code
stringlengths
2
1.05M
/* * Copyright 2003-2006, 2009, 2017, United States Government, as represented by the Administrator of the * National Aeronautics and Space Administration. All rights reserved. * * The NASAWorldWind/WebWorldWind platform is 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. */ define([ '../KmlElements', '../KmlObject' ], function(KmlElements, KmlObject){ /** * @augment KmlObject * @param options * @constructor * @alias KmlChange */ var KmlChange = function(options) { KmlObject.call(this, options); }; KmlChange.prototype = Object.create(KmlObject.prototype); Object.defineProperties(KmlChange.prototype, { /** * All shapes which should be changed with the location where they should be changed. * @memberof KmlChange.prototype * @readonly * @type {KmlObject[]} */ shapes: { get: function(){ return this._factory.all(this); } } }); /** * @inheritDoc */ KmlChange.prototype.getTagNames = function() { return ['Change']; }; KmlElements.addKey(KmlChange.prototype.getTagNames()[0], KmlChange); return KmlChange; });
"use strict"; var http = require('http'); var sapnwrfc = require('../sapnwrfc'); var connectionParams = { ashost: "192.168.0.20", sysid: "NPL", sysnr: "42", user: "DEVELOPER", passwd: "", client: "001" }; var funcParams = { QUESTION: 'How are you' } http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); var con = new sapnwrfc.Connection; con.Open(connectionParams, function(err) { if (err) { res.end(err.message); return; } res.write("Version: " + con.GetVersion() + "\n"); var func = con.Lookup('STFC_STRING'); func.Invoke(funcParams, function(err, result) { if (err) { res.end(err.message); return; } console.log(result); res.write(result.MYANSWER + "\n"); res.write("\nJSON Schema:\n"); res.end(JSON.stringify(func.MetaData(), null, 2)); }); }); }).listen(3000, '127.0.0.1'); console.log('Server running at http://127.0.0.1:3000/');
/* * Scroller * http://github.com/zynga/scroller * * Copyright 2011, Zynga Inc. * Licensed under the MIT License. * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt * * Based on the work of: Unify Project (unify-project.org) * http://unify-project.org * Copyright 2011, Deutsche Telekom AG * License: MIT + Apache (V2) */ var core = require('./Animate'); var Scroller; (function() { var NOOP = function(){}; /** * A pure logic 'component' for 'virtual' scrolling/zooming. */ Scroller = function(callback, options) { this.__callback = callback; this.options = { /** Enable scrolling on x-axis */ scrollingX: true, /** Enable scrolling on y-axis */ scrollingY: true, /** Enable animations for deceleration, snap back, zooming and scrolling */ animating: true, /** duration for animations triggered by scrollTo/zoomTo */ animationDuration: 250, /** Enable bouncing (content can be slowly moved outside and jumps back after releasing) */ bouncing: true, /** Enable locking to the main axis if user moves only slightly on one of them at start */ locking: true, /** Enable pagination mode (switching between full page content panes) */ paging: false, /** Enable snapping of content to a configured pixel grid */ snapping: false, /** Enable zooming of content via API, fingers and mouse wheel */ zooming: false, /** Minimum zoom level */ minZoom: 0.5, /** Maximum zoom level */ maxZoom: 3, /** Multiply or decrease scrolling speed **/ speedMultiplier: 1, /** Callback that is fired on the later of touch end or deceleration end, provided that another scrolling action has not begun. Used to know when to fade out a scrollbar. */ scrollingComplete: NOOP, /** Increase or decrease the amount of friction applied to deceleration **/ decelerationRate: 0.95, /** This configures the amount of change applied to deceleration when reaching boundaries **/ penetrationDeceleration : 0.03, /** This configures the amount of change applied to acceleration when reaching boundaries **/ penetrationAcceleration : 0.08 }; for (var key in options) { this.options[key] = options[key]; } }; // Easing Equations (c) 2003 Robert Penner, all rights reserved. // Open source under the BSD License. /** * @param pos {Number} position between 0 (start of effect) and 1 (end of effect) **/ var easeOutCubic = function(pos) { return (Math.pow((pos - 1), 3) + 1); }; /** * @param pos {Number} position between 0 (start of effect) and 1 (end of effect) **/ var easeInOutCubic = function(pos) { if ((pos /= 0.5) < 1) { return 0.5 * Math.pow(pos, 3); } return 0.5 * (Math.pow((pos - 2), 3) + 2); }; var members = { /* --------------------------------------------------------------------------- INTERNAL FIELDS :: STATUS --------------------------------------------------------------------------- */ /** {Boolean} Whether only a single finger is used in touch handling */ __isSingleTouch: false, /** {Boolean} Whether a touch event sequence is in progress */ __isTracking: false, /** {Boolean} Whether a deceleration animation went to completion. */ __didDecelerationComplete: false, /** * {Boolean} Whether a gesture zoom/rotate event is in progress. Activates when * a gesturestart event happens. This has higher priority than dragging. */ __isGesturing: false, /** * {Boolean} Whether the user has moved by such a distance that we have enabled * dragging mode. Hint: It's only enabled after some pixels of movement to * not interrupt with clicks etc. */ __isDragging: false, /** * {Boolean} Not touching and dragging anymore, and smoothly animating the * touch sequence using deceleration. */ __isDecelerating: false, /** * {Boolean} Smoothly animating the currently configured change */ __isAnimating: false, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: DIMENSIONS --------------------------------------------------------------------------- */ /** {Integer} Available outer left position (from document perspective) */ __clientLeft: 0, /** {Integer} Available outer top position (from document perspective) */ __clientTop: 0, /** {Integer} Available outer width */ __clientWidth: 0, /** {Integer} Available outer height */ __clientHeight: 0, /** {Integer} Outer width of content */ __contentWidth: 0, /** {Integer} Outer height of content */ __contentHeight: 0, /** {Integer} Snapping width for content */ __snapWidth: 100, /** {Integer} Snapping height for content */ __snapHeight: 100, /** {Integer} Height to assign to refresh area */ __refreshHeight: null, /** {Boolean} Whether the refresh process is enabled when the event is released now */ __refreshActive: false, /** {Function} Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release */ __refreshActivate: null, /** {Function} Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled */ __refreshDeactivate: null, /** {Function} Callback to execute to start the actual refresh. Call {@link #refreshFinish} when done */ __refreshStart: null, /** {Number} Zoom level */ __zoomLevel: 1, /** {Number} Scroll position on x-axis */ __scrollLeft: 0, /** {Number} Scroll position on y-axis */ __scrollTop: 0, /** {Integer} Maximum allowed scroll position on x-axis */ __maxScrollLeft: 0, /** {Integer} Maximum allowed scroll position on y-axis */ __maxScrollTop: 0, /* {Number} Scheduled left position (final position when animating) */ __scheduledLeft: 0, /* {Number} Scheduled top position (final position when animating) */ __scheduledTop: 0, /* {Number} Scheduled zoom level (final scale when animating) */ __scheduledZoom: 0, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: LAST POSITIONS --------------------------------------------------------------------------- */ /** {Number} Left position of finger at start */ __lastTouchLeft: null, /** {Number} Top position of finger at start */ __lastTouchTop: null, /** {Date} Timestamp of last move of finger. Used to limit tracking range for deceleration speed. */ __lastTouchMove: null, /** {Array} List of positions, uses three indexes for each state: left, top, timestamp */ __positions: null, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: DECELERATION SUPPORT --------------------------------------------------------------------------- */ /** {Integer} Minimum left scroll position during deceleration */ __minDecelerationScrollLeft: null, /** {Integer} Minimum top scroll position during deceleration */ __minDecelerationScrollTop: null, /** {Integer} Maximum left scroll position during deceleration */ __maxDecelerationScrollLeft: null, /** {Integer} Maximum top scroll position during deceleration */ __maxDecelerationScrollTop: null, /** {Number} Current factor to modify horizontal scroll position with on every step */ __decelerationVelocityX: null, /** {Number} Current factor to modify vertical scroll position with on every step */ __decelerationVelocityY: null, /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ /** * Configures the dimensions of the client (outer) and content (inner) elements. * Requires the available space for the outer element and the outer size of the inner element. * All values which are falsy (null or zero etc.) are ignored and the old value is kept. * * @param clientWidth {Integer ? null} Inner width of outer element * @param clientHeight {Integer ? null} Inner height of outer element * @param contentWidth {Integer ? null} Outer width of inner element * @param contentHeight {Integer ? null} Outer height of inner element */ setDimensions: function(clientWidth, clientHeight, contentWidth, contentHeight) { var self = this; // Only update values which are defined if (clientWidth === +clientWidth) { self.__clientWidth = clientWidth; } if (clientHeight === +clientHeight) { self.__clientHeight = clientHeight; } if (contentWidth === +contentWidth) { self.__contentWidth = contentWidth; } if (contentHeight === +contentHeight) { self.__contentHeight = contentHeight; } // Refresh maximums self.__computeScrollMax(); // Refresh scroll position self.scrollTo(self.__scrollLeft, self.__scrollTop, true); }, /** * Sets the client coordinates in relation to the document. * * @param left {Integer ? 0} Left position of outer element * @param top {Integer ? 0} Top position of outer element */ setPosition: function(left, top) { var self = this; self.__clientLeft = left || 0; self.__clientTop = top || 0; }, /** * Configures the snapping (when snapping is active) * * @param width {Integer} Snapping width * @param height {Integer} Snapping height */ setSnapSize: function(width, height) { var self = this; self.__snapWidth = width; self.__snapHeight = height; }, /** * Activates pull-to-refresh. A special zone on the top of the list to start a list refresh whenever * the user event is released during visibility of this zone. This was introduced by some apps on iOS like * the official Twitter client. * * @param height {Integer} Height of pull-to-refresh zone on top of rendered list * @param activateCallback {Function} Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release. * @param deactivateCallback {Function} Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled. * @param startCallback {Function} Callback to execute to start the real async refresh action. Call {@link #finishPullToRefresh} after finish of refresh. */ activatePullToRefresh: function(height, activateCallback, deactivateCallback, startCallback) { var self = this; self.__refreshHeight = height; self.__refreshActivate = activateCallback; self.__refreshDeactivate = deactivateCallback; self.__refreshStart = startCallback; }, /** * Starts pull-to-refresh manually. */ triggerPullToRefresh: function() { // Use publish instead of scrollTo to allow scrolling to out of boundary position // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled this.__publish(this.__scrollLeft, -this.__refreshHeight, this.__zoomLevel, true); if (this.__refreshStart) { this.__refreshStart(); } }, /** * Signalizes that pull-to-refresh is finished. */ finishPullToRefresh: function() { var self = this; self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } self.scrollTo(self.__scrollLeft, self.__scrollTop, true); }, /** * Returns the scroll position and zooming values * * @return {Map} `left` and `top` scroll position and `zoom` level */ getValues: function() { var self = this; return { left: self.__scrollLeft, top: self.__scrollTop, zoom: self.__zoomLevel }; }, /** * Returns the maximum scroll values * * @return {Map} `left` and `top` maximum scroll values */ getScrollMax: function() { var self = this; return { left: self.__maxScrollLeft, top: self.__maxScrollTop }; }, /** * Zooms to the given level. Supports optional animation. Zooms * the center when no coordinates are given. * * @param level {Number} Level to zoom to * @param animate {Boolean ? false} Whether to use animation * @param originLeft {Number ? null} Zoom in at given left coordinate * @param originTop {Number ? null} Zoom in at given top coordinate * @param callback {Function ? null} A callback that gets fired when the zoom is complete. */ zoomTo: function(level, animate, originLeft, originTop, callback) { var self = this; if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } // Add callback if exists if(callback) { self.__zoomComplete = callback; } // Stop deceleration if (self.__isDecelerating) { core.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } var oldLevel = self.__zoomLevel; // Normalize input origin to center of viewport if not defined if (originLeft == null) { originLeft = self.__clientWidth / 2; } if (originTop == null) { originTop = self.__clientHeight / 2; } // Limit level according to configuration level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom); // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(level); // Recompute left and top coordinates based on new zoom level var left = ((originLeft + self.__scrollLeft) * level / oldLevel) - originLeft; var top = ((originTop + self.__scrollTop) * level / oldLevel) - originTop; // Limit x-axis if (left > self.__maxScrollLeft) { left = self.__maxScrollLeft; } else if (left < 0) { left = 0; } // Limit y-axis if (top > self.__maxScrollTop) { top = self.__maxScrollTop; } else if (top < 0) { top = 0; } // Push values out self.__publish(left, top, level, animate); }, /** * Zooms the content by the given factor. * * @param factor {Number} Zoom by given factor * @param animate {Boolean ? false} Whether to use animation * @param originLeft {Number ? 0} Zoom in at given left coordinate * @param originTop {Number ? 0} Zoom in at given top coordinate * @param callback {Function ? null} A callback that gets fired when the zoom is complete. */ zoomBy: function(factor, animate, originLeft, originTop, callback) { var self = this; self.zoomTo(self.__zoomLevel * factor, animate, originLeft, originTop, callback); }, /** * Scrolls to the given position. Respect limitations and snapping automatically. * * @param left {Number?null} Horizontal scroll position, keeps current if value is <code>null</code> * @param top {Number?null} Vertical scroll position, keeps current if value is <code>null</code> * @param animate {Boolean?false} Whether the scrolling should happen using an animation * @param zoom {Number?null} Zoom level to go to */ scrollTo: function(left, top, animate, zoom) { var self = this; // Stop deceleration if (self.__isDecelerating) { core.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } // Correct coordinates based on new zoom level if (zoom != null && zoom !== self.__zoomLevel) { if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } left *= zoom; top *= zoom; // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(zoom); } else { // Keep zoom when not defined zoom = self.__zoomLevel; } if (!self.options.scrollingX) { left = self.__scrollLeft; } else { if (self.options.paging) { left = Math.round(left / self.__clientWidth) * self.__clientWidth; } else if (self.options.snapping) { left = Math.round(left / self.__snapWidth) * self.__snapWidth; } } if (!self.options.scrollingY) { top = self.__scrollTop; } else { if (self.options.paging) { top = Math.round(top / self.__clientHeight) * self.__clientHeight; } else if (self.options.snapping) { top = Math.round(top / self.__snapHeight) * self.__snapHeight; } } // Limit for allowed ranges left = Math.max(Math.min(self.__maxScrollLeft, left), 0); top = Math.max(Math.min(self.__maxScrollTop, top), 0); // Don't animate when no change detected, still call publish to make sure // that rendered position is really in-sync with internal data if (left === self.__scrollLeft && top === self.__scrollTop) { animate = false; } // Publish new values self.__publish(left, top, zoom, animate); }, /** * Scroll by the given offset * * @param left {Number ? 0} Scroll x-axis by given offset * @param top {Number ? 0} Scroll x-axis by given offset * @param animate {Boolean ? false} Whether to animate the given change */ scrollBy: function(left, top, animate) { var self = this; var startLeft = self.__isAnimating ? self.__scheduledLeft : self.__scrollLeft; var startTop = self.__isAnimating ? self.__scheduledTop : self.__scrollTop; self.scrollTo(startLeft + (left || 0), startTop + (top || 0), animate); }, /* --------------------------------------------------------------------------- EVENT CALLBACKS --------------------------------------------------------------------------- */ /** * Mouse wheel handler for zooming support */ doMouseZoom: function(wheelDelta, timeStamp, pageX, pageY) { var self = this; var change = wheelDelta > 0 ? 0.97 : 1.03; return self.zoomTo(self.__zoomLevel * change, false, pageX - self.__clientLeft, pageY - self.__clientTop); }, /** * Touch start handler for scrolling support */ doTouchStart: function(touches, timeStamp) { // Array-like check is enough here if (touches.length == null) { throw new Error("Invalid touch list: " + touches); } if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { throw new Error("Invalid timestamp value: " + timeStamp); } var self = this; // Reset interruptedAnimation flag self.__interruptedAnimation = true; // Stop deceleration if (self.__isDecelerating) { core.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; self.__interruptedAnimation = true; } // Stop animation if (self.__isAnimating) { core.effect.Animate.stop(self.__isAnimating); self.__isAnimating = false; self.__interruptedAnimation = true; } // Use center point when dealing with two fingers var currentTouchLeft, currentTouchTop; var isSingleTouch = touches.length === 1; if (isSingleTouch) { currentTouchLeft = touches[0].pageX; currentTouchTop = touches[0].pageY; } else { currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2; currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2; } // Store initial positions self.__initialTouchLeft = currentTouchLeft; self.__initialTouchTop = currentTouchTop; // Store current zoom level self.__zoomLevelStart = self.__zoomLevel; // Store initial touch positions self.__lastTouchLeft = currentTouchLeft; self.__lastTouchTop = currentTouchTop; // Store initial move time stamp self.__lastTouchMove = timeStamp; // Reset initial scale self.__lastScale = 1; // Reset locking flags self.__enableScrollX = !isSingleTouch && self.options.scrollingX; self.__enableScrollY = !isSingleTouch && self.options.scrollingY; // Reset tracking flag self.__isTracking = true; // Reset deceleration complete flag self.__didDecelerationComplete = false; // Dragging starts directly with two fingers, otherwise lazy with an offset self.__isDragging = !isSingleTouch; // Some features are disabled in multi touch scenarios self.__isSingleTouch = isSingleTouch; // Clearing data structure self.__positions = []; }, /** * Touch move handler for scrolling support */ doTouchMove: function(touches, timeStamp, scale) { // Array-like check is enough here if (touches.length == null) { throw new Error("Invalid touch list: " + touches); } if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { throw new Error("Invalid timestamp value: " + timeStamp); } var self = this; // Ignore event when tracking is not enabled (event might be outside of element) if (!self.__isTracking) { return; } var currentTouchLeft, currentTouchTop; // Compute move based around of center of fingers if (touches.length === 2) { currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2; currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2; } else { currentTouchLeft = touches[0].pageX; currentTouchTop = touches[0].pageY; } var positions = self.__positions; // Are we already is dragging mode? if (self.__isDragging) { // Compute move distance var moveX = currentTouchLeft - self.__lastTouchLeft; var moveY = currentTouchTop - self.__lastTouchTop; // Read previous scroll position and zooming var scrollLeft = self.__scrollLeft; var scrollTop = self.__scrollTop; var level = self.__zoomLevel; // Work with scaling if (scale != null && self.options.zooming) { var oldLevel = level; // Recompute level based on previous scale and new scale level = level / self.__lastScale * scale; // Limit level according to configuration level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom); // Only do further compution when change happened if (oldLevel !== level) { // Compute relative event position to container var currentTouchLeftRel = currentTouchLeft - self.__clientLeft; var currentTouchTopRel = currentTouchTop - self.__clientTop; // Recompute left and top coordinates based on new zoom level scrollLeft = ((currentTouchLeftRel + scrollLeft) * level / oldLevel) - currentTouchLeftRel; scrollTop = ((currentTouchTopRel + scrollTop) * level / oldLevel) - currentTouchTopRel; // Recompute max scroll values self.__computeScrollMax(level); } } if (self.__enableScrollX) { scrollLeft -= moveX * this.options.speedMultiplier; var maxScrollLeft = self.__maxScrollLeft; if (scrollLeft > maxScrollLeft || scrollLeft < 0) { // Slow down on the edges if (self.options.bouncing) { scrollLeft += (moveX / 2 * this.options.speedMultiplier); } else if (scrollLeft > maxScrollLeft) { scrollLeft = maxScrollLeft; } else { scrollLeft = 0; } } } // Compute new vertical scroll position if (self.__enableScrollY) { scrollTop -= moveY * this.options.speedMultiplier; var maxScrollTop = self.__maxScrollTop; if (scrollTop > maxScrollTop || scrollTop < 0) { // Slow down on the edges if (self.options.bouncing) { scrollTop += (moveY / 2 * this.options.speedMultiplier); // Support pull-to-refresh (only when only y is scrollable) if (!self.__enableScrollX && self.__refreshHeight != null) { if (!self.__refreshActive && scrollTop <= -self.__refreshHeight) { self.__refreshActive = true; if (self.__refreshActivate) { self.__refreshActivate(); } } else if (self.__refreshActive && scrollTop > -self.__refreshHeight) { self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } } } } else if (scrollTop > maxScrollTop) { scrollTop = maxScrollTop; } else { scrollTop = 0; } } } // Keep list from growing infinitely (holding min 10, max 20 measure points) if (positions.length > 60) { positions.splice(0, 30); } // Track scroll movement for decleration positions.push(scrollLeft, scrollTop, timeStamp); // Sync scroll position self.__publish(scrollLeft, scrollTop, level); // Otherwise figure out whether we are switching into dragging mode now. } else { var minimumTrackingForScroll = self.options.locking ? 3 : 0; var minimumTrackingForDrag = 5; var distanceX = Math.abs(currentTouchLeft - self.__initialTouchLeft); var distanceY = Math.abs(currentTouchTop - self.__initialTouchTop); self.__enableScrollX = self.options.scrollingX && distanceX >= minimumTrackingForScroll; self.__enableScrollY = self.options.scrollingY && distanceY >= minimumTrackingForScroll; positions.push(self.__scrollLeft, self.__scrollTop, timeStamp); self.__isDragging = (self.__enableScrollX || self.__enableScrollY) && (distanceX >= minimumTrackingForDrag || distanceY >= minimumTrackingForDrag); if (self.__isDragging) { self.__interruptedAnimation = false; } } // Update last touch positions and time stamp for next event self.__lastTouchLeft = currentTouchLeft; self.__lastTouchTop = currentTouchTop; self.__lastTouchMove = timeStamp; self.__lastScale = scale; }, /** * Touch end handler for scrolling support */ doTouchEnd: function(timeStamp) { if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { throw new Error("Invalid timestamp value: " + timeStamp); } var self = this; // Ignore event when tracking is not enabled (no touchstart event on element) // This is required as this listener ('touchmove') sits on the document and not on the element itself. if (!self.__isTracking) { return; } // Not touching anymore (when two finger hit the screen there are two touch end events) self.__isTracking = false; // Be sure to reset the dragging flag now. Here we also detect whether // the finger has moved fast enough to switch into a deceleration animation. if (self.__isDragging) { // Reset dragging flag self.__isDragging = false; // Start deceleration // Verify that the last move detected was in some relevant time frame if (self.__isSingleTouch && self.options.animating && (timeStamp - self.__lastTouchMove) <= 100) { // Then figure out what the scroll position was about 100ms ago var positions = self.__positions; var endPos = positions.length - 1; var startPos = endPos; // Move pointer to position measured 100ms ago for (var i = endPos; i > 0 && positions[i] > (self.__lastTouchMove - 100); i -= 3) { startPos = i; } // If we haven't received consecutive touchmove events within a 100ms // timeframe, attempt a best-effort based on the first position. This // typically happens when an expensive operation occurs on the main // thread during scrolling, such as image decoding. if (startPos === endPos && positions.length > 5) { startPos = 2; } // If start and stop position is identical in a 100ms timeframe, // we cannot compute any useful deceleration. if (startPos !== endPos) { // Compute relative movement between these two points var timeOffset = positions[endPos] - positions[startPos]; var movedLeft = self.__scrollLeft - positions[startPos - 2]; var movedTop = self.__scrollTop - positions[startPos - 1]; // Based on 50ms compute the movement to apply for each render step self.__decelerationVelocityX = movedLeft / timeOffset * (1000 / 60); self.__decelerationVelocityY = movedTop / timeOffset * (1000 / 60); // How much velocity is required to start the deceleration var minVelocityToStartDeceleration = self.options.paging || self.options.snapping ? 4 : 1; // Verify that we have enough velocity to start deceleration if (Math.abs(self.__decelerationVelocityX) > minVelocityToStartDeceleration || Math.abs(self.__decelerationVelocityY) > minVelocityToStartDeceleration) { // Deactivate pull-to-refresh when decelerating if (!self.__refreshActive) { self.__startDeceleration(timeStamp); } } } else { self.options.scrollingComplete(); } } else if ((timeStamp - self.__lastTouchMove) > 100) { self.options.scrollingComplete(); } } // If this was a slower move it is per default non decelerated, but this // still means that we want snap back to the bounds which is done here. // This is placed outside the condition above to improve edge case stability // e.g. touchend fired without enabled dragging. This should normally do not // have modified the scroll positions or even showed the scrollbars though. if (!self.__isDecelerating) { if (self.__refreshActive && self.__refreshStart) { // Use publish instead of scrollTo to allow scrolling to out of boundary position // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled self.__publish(self.__scrollLeft, -self.__refreshHeight, self.__zoomLevel, true); if (self.__refreshStart) { self.__refreshStart(); } } else { if (self.__interruptedAnimation || self.__isDragging) { self.options.scrollingComplete(); } self.scrollTo(self.__scrollLeft, self.__scrollTop, true, self.__zoomLevel); // Directly signalize deactivation (nothing todo on refresh?) if (self.__refreshActive) { self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } } } } // Fully cleanup list self.__positions.length = 0; }, /* --------------------------------------------------------------------------- PRIVATE API --------------------------------------------------------------------------- */ /** * Applies the scroll position to the content element * * @param left {Number} Left scroll position * @param top {Number} Top scroll position * @param animate {Boolean?false} Whether animation should be used to move to the new coordinates */ __publish: function(left, top, zoom, animate) { var self = this; // Remember whether we had an animation, then we try to continue based on the current "drive" of the animation var wasAnimating = self.__isAnimating; if (wasAnimating) { core.effect.Animate.stop(wasAnimating); self.__isAnimating = false; } if (animate && self.options.animating) { // Keep scheduled positions for scrollBy/zoomBy functionality self.__scheduledLeft = left; self.__scheduledTop = top; self.__scheduledZoom = zoom; var oldLeft = self.__scrollLeft; var oldTop = self.__scrollTop; var oldZoom = self.__zoomLevel; var diffLeft = left - oldLeft; var diffTop = top - oldTop; var diffZoom = zoom - oldZoom; var step = function(percent, now, render) { if (render) { self.__scrollLeft = oldLeft + (diffLeft * percent); self.__scrollTop = oldTop + (diffTop * percent); self.__zoomLevel = oldZoom + (diffZoom * percent); // Push values out if (self.__callback) { self.__callback(self.__scrollLeft, self.__scrollTop, self.__zoomLevel); } } }; var verify = function(id) { return self.__isAnimating === id; }; var completed = function(renderedFramesPerSecond, animationId, wasFinished) { if (animationId === self.__isAnimating) { self.__isAnimating = false; } if (self.__didDecelerationComplete || wasFinished) { self.options.scrollingComplete(); } if (self.options.zooming) { self.__computeScrollMax(); if(self.__zoomComplete) { self.__zoomComplete(); self.__zoomComplete = null; } } }; // When continuing based on previous animation we choose an ease-out animation instead of ease-in-out self.__isAnimating = core.effect.Animate.start(step, verify, completed, self.options.animationDuration, wasAnimating ? easeOutCubic : easeInOutCubic); } else { self.__scheduledLeft = self.__scrollLeft = left; self.__scheduledTop = self.__scrollTop = top; self.__scheduledZoom = self.__zoomLevel = zoom; // Push values out if (self.__callback) { self.__callback(left, top, zoom); } // Fix max scroll ranges if (self.options.zooming) { self.__computeScrollMax(); if(self.__zoomComplete) { self.__zoomComplete(); self.__zoomComplete = null; } } } }, /** * Recomputes scroll minimum values based on client dimensions and content dimensions. */ __computeScrollMax: function(zoomLevel) { var self = this; if (zoomLevel == null) { zoomLevel = self.__zoomLevel; } self.__maxScrollLeft = Math.max((self.__contentWidth * zoomLevel) - self.__clientWidth, 0); self.__maxScrollTop = Math.max((self.__contentHeight * zoomLevel) - self.__clientHeight, 0); }, /* --------------------------------------------------------------------------- ANIMATION (DECELERATION) SUPPORT --------------------------------------------------------------------------- */ /** * Called when a touch sequence end and the speed of the finger was high enough * to switch into deceleration mode. */ __startDeceleration: function(timeStamp) { var self = this; if (self.options.paging) { var scrollLeft = Math.max(Math.min(self.__scrollLeft, self.__maxScrollLeft), 0); var scrollTop = Math.max(Math.min(self.__scrollTop, self.__maxScrollTop), 0); var clientWidth = self.__clientWidth; var clientHeight = self.__clientHeight; // We limit deceleration not to the min/max values of the allowed range, but to the size of the visible client area. // Each page should have exactly the size of the client area. self.__minDecelerationScrollLeft = Math.floor(scrollLeft / clientWidth) * clientWidth; self.__minDecelerationScrollTop = Math.floor(scrollTop / clientHeight) * clientHeight; self.__maxDecelerationScrollLeft = Math.ceil(scrollLeft / clientWidth) * clientWidth; self.__maxDecelerationScrollTop = Math.ceil(scrollTop / clientHeight) * clientHeight; } else { self.__minDecelerationScrollLeft = 0; self.__minDecelerationScrollTop = 0; self.__maxDecelerationScrollLeft = self.__maxScrollLeft; self.__maxDecelerationScrollTop = self.__maxScrollTop; } // Wrap class method var step = function(percent, now, render) { self.__stepThroughDeceleration(render); }; // How much velocity is required to keep the deceleration running var minVelocityToKeepDecelerating = self.options.snapping ? 4 : 0.1; // Detect whether it's still worth to continue animating steps // If we are already slow enough to not being user perceivable anymore, we stop the whole process here. var verify = function() { var shouldContinue = Math.abs(self.__decelerationVelocityX) >= minVelocityToKeepDecelerating || Math.abs(self.__decelerationVelocityY) >= minVelocityToKeepDecelerating; if (!shouldContinue) { self.__didDecelerationComplete = true; } return shouldContinue; }; var completed = function(renderedFramesPerSecond, animationId, wasFinished) { self.__isDecelerating = false; if (self.__didDecelerationComplete) { self.options.scrollingComplete(); } // Animate to grid when snapping is active, otherwise just fix out-of-boundary positions self.scrollTo(self.__scrollLeft, self.__scrollTop, self.options.snapping); }; // Start animation and switch on flag self.__isDecelerating = core.effect.Animate.start(step, verify, completed); }, /** * Called on every step of the animation * * @param inMemory {Boolean?false} Whether to not render the current step, but keep it in memory only. Used internally only! */ __stepThroughDeceleration: function(render) { var self = this; // // COMPUTE NEXT SCROLL POSITION // // Add deceleration to scroll position var scrollLeft = self.__scrollLeft + self.__decelerationVelocityX; var scrollTop = self.__scrollTop + self.__decelerationVelocityY; // // HARD LIMIT SCROLL POSITION FOR NON BOUNCING MODE // if (!self.options.bouncing) { var scrollLeftFixed = Math.max(Math.min(self.__maxDecelerationScrollLeft, scrollLeft), self.__minDecelerationScrollLeft); if (scrollLeftFixed !== scrollLeft) { scrollLeft = scrollLeftFixed; self.__decelerationVelocityX = 0; } var scrollTopFixed = Math.max(Math.min(self.__maxDecelerationScrollTop, scrollTop), self.__minDecelerationScrollTop); if (scrollTopFixed !== scrollTop) { scrollTop = scrollTopFixed; self.__decelerationVelocityY = 0; } } // // UPDATE SCROLL POSITION // if (render) { self.__publish(scrollLeft, scrollTop, self.__zoomLevel); } else { self.__scrollLeft = scrollLeft; self.__scrollTop = scrollTop; } // // SLOW DOWN // // Slow down velocity on every iteration if (!self.options.paging) { // This is the factor applied to every iteration of the animation // to slow down the process. This should emulate natural behavior where // objects slow down when the initiator of the movement is removed var frictionFactor = self.options.decelerationRate; self.__decelerationVelocityX *= frictionFactor; self.__decelerationVelocityY *= frictionFactor; } // // BOUNCING SUPPORT // if (self.options.bouncing) { var scrollOutsideX = 0; var scrollOutsideY = 0; // This configures the amount of change applied to deceleration/acceleration when reaching boundaries var penetrationDeceleration = self.options.penetrationDeceleration; var penetrationAcceleration = self.options.penetrationAcceleration; // Check limits if (scrollLeft < self.__minDecelerationScrollLeft) { scrollOutsideX = self.__minDecelerationScrollLeft - scrollLeft; } else if (scrollLeft > self.__maxDecelerationScrollLeft) { scrollOutsideX = self.__maxDecelerationScrollLeft - scrollLeft; } if (scrollTop < self.__minDecelerationScrollTop) { scrollOutsideY = self.__minDecelerationScrollTop - scrollTop; } else if (scrollTop > self.__maxDecelerationScrollTop) { scrollOutsideY = self.__maxDecelerationScrollTop - scrollTop; } // Slow down until slow enough, then flip back to snap position if (scrollOutsideX !== 0) { if (scrollOutsideX * self.__decelerationVelocityX <= 0) { self.__decelerationVelocityX += scrollOutsideX * penetrationDeceleration; } else { self.__decelerationVelocityX = scrollOutsideX * penetrationAcceleration; } } if (scrollOutsideY !== 0) { if (scrollOutsideY * self.__decelerationVelocityY <= 0) { self.__decelerationVelocityY += scrollOutsideY * penetrationDeceleration; } else { self.__decelerationVelocityY = scrollOutsideY * penetrationAcceleration; } } } } }; // Copy over members to prototype for (var key in members) { Scroller.prototype[key] = members[key]; } module.exports = Scroller; })();
// The contents of individual model .js files will be concatenated into dist/models.js (function() { // Protects views where AngularJS is not loaded from errors if ( typeof angular == 'undefined' ) { return; }; var module = angular.module('AirportModel', ['restangular']); module.factory('AirportRestangular', function(Restangular) { return Restangular.withConfig(function(RestangularConfigurer) { RestangularConfigurer.setBaseUrl('http://localhost/data'); RestangularConfigurer.setRequestSuffix('.json'); RestangularConfigurer.setRestangularFields({ id: "airport_id" }); }); }); })();
const moment = require('moment'); const HeaderDivider = '='.repeat(20); class PlainTextGameChatFormatter { constructor(gameChat) { this.gameChat = gameChat; } get messages() { return this.gameChat.messages; } format() { return this.messages.map(messageProps => this.formatMessage(messageProps)).join('\n'); } formatMessage(messageProps) { return `${moment(messageProps.date).format('YYYY-MM-DD HH:mm:ss')} ${this.formatMessageFragment(messageProps.message)}`; } formatMessageFragment(messageProps) { let result = ''; for(const [key, fragment] of Object.entries(messageProps)) { if(fragment === null || fragment === undefined) { continue; } if(key === 'alert') { let message = this.formatMessageFragment(fragment.message); switch(fragment.type) { case 'endofround': case 'phasestart': case 'startofround': result += `${HeaderDivider} ${message} ${HeaderDivider}`; break; case 'success': case 'info': case 'danger': case 'warning': result += `${fragment.type.toUpperCase()} ${message}`; break; default: result += message; break; } } else if(fragment.message) { result += this.formatMessageFragment(fragment.message); } else if(fragment.argType === 'card') { result += fragment.label; } else if(fragment.name && fragment.argType === 'player') { result += `${fragment.name}:`; } else if(fragment.argType === 'nonAvatarPlayer') { result += fragment.name; } else { result += fragment.toString(); } } return result; } } module.exports = PlainTextGameChatFormatter;
'use strict'; /** * @ngdoc function * @name iibHeatMapApp.controller:ChartCtrl * @description * # ChartCtrl * Controller of the iibHeatMapApp */ angular.module('iibHeatMapApp') .controller('ChartCtrl', function($scope, $routeParams, INode) { $scope.resource = {}; $scope.selectedElement = ""; $scope.showResources = false; $scope.chartType = $routeParams.type; INode.one('topology').get().then(function(data) { $scope.topology = data; }); // used for the navbar active selection $scope.viewChart = true; $scope.getResources = function(inodeId, iserver, application, messageflow, type, name) { console.log("scope"); $scope.resource = {}; $scope.resourceLoading = true; $scope.selectedElement = name; $scope.resource.type = type; var route = "iservers"; if (iserver !== null) { route += "/" + iserver; } if (application !== null) { route += "/applications/" + application; } if (messageflow !== null) { route += "/messageflows/" + messageflow; } INode.one(inodeId).customGET(route).then(function(data) { $scope.resourceLoading = false; if (data.status === 404) { $scope.message = "Integration Node not found"; } else { $scope.showResources = true; $scope.resource = data; $scope.resource.type = type; console.log($scope.resource); } }); }; });
import { Debug } from '../core/debug.js'; import { math } from '../math/math.js'; import { Mat4 } from '../math/mat4.js'; import { FILTER_NEAREST, PIXELFORMAT_RGBA32F } from '../graphics/constants.js'; import { Texture } from '../graphics/texture.js'; /** @typedef {import('./graph-node.js').GraphNode} GraphNode */ /** @typedef {import('./skin.js').Skin} Skin */ const _invMatrix = new Mat4(); /** * A skin instance is responsible for generating the matrix palette that is used to skin vertices * from object space to world space. */ class SkinInstance { /** * An array of nodes representing each bone in this skin instance. * * @type {GraphNode[]} */ bones; /** * Create a new SkinInstance instance. * * @param {Skin} skin - The skin that will provide the inverse bind pose matrices to generate * the final matrix palette. */ constructor(skin) { this._dirty = true; // optional root bone - used for cache lookup, not used for skinning this._rootBone = null; // sequential index of when the bone update was performed the last time this._skinUpdateIndex = -1; // true if bones need to be updated before the frustum culling (bones are needed to update bounds of the MeshInstance) this._updateBeforeCull = true; if (skin) { this.initSkin(skin); } } set rootBone(rootBone) { this._rootBone = rootBone; } get rootBone() { return this._rootBone; } init(device, numBones) { if (device.supportsBoneTextures) { // texture size - roughly square that fits all bones, width is multiply of 3 to simplify shader math const numPixels = numBones * 3; let width = Math.ceil(Math.sqrt(numPixels)); width = math.roundUp(width, 3); const height = Math.ceil(numPixels / width); this.boneTexture = new Texture(device, { width: width, height: height, format: PIXELFORMAT_RGBA32F, mipmaps: false, minFilter: FILTER_NEAREST, magFilter: FILTER_NEAREST }); this.boneTexture.name = 'skin'; this.matrixPalette = this.boneTexture.lock(); } else { this.matrixPalette = new Float32Array(numBones * 12); } } destroy() { if (this.boneTexture) { this.boneTexture.destroy(); this.boneTexture = null; } } // resolved skin bones to a hierarchy with the rootBone at its root. // entity parameter specifies the entity used if the bone match is not found in the hierarchy - usually the entity the render component is attached to resolve(rootBone, entity) { this.rootBone = rootBone; // Resolve bone IDs to actual graph nodes of the hierarchy const skin = this.skin; const bones = []; for (let j = 0; j < skin.boneNames.length; j++) { const boneName = skin.boneNames[j]; let bone = rootBone.findByName(boneName); if (!bone) { Debug.error(`Failed to find bone [${boneName}] in the entity hierarchy, RenderComponent on ${entity.name}, rootBone: ${rootBone.entity.name}`); bone = entity; } bones.push(bone); } this.bones = bones; } initSkin(skin) { this.skin = skin; // Unique per clone this.bones = []; const numBones = skin.inverseBindPose.length; this.init(skin.device, numBones); this.matrices = []; for (let i = 0; i < numBones; i++) { this.matrices[i] = new Mat4(); } } uploadBones(device) { // TODO: this is a bit strange looking. Change the Texture API to do a reupload if (device.supportsBoneTextures) { this.boneTexture.lock(); this.boneTexture.unlock(); } } _updateMatrices(rootNode, skinUpdateIndex) { // if not already up to date if (this._skinUpdateIndex !== skinUpdateIndex) { this._skinUpdateIndex = skinUpdateIndex; _invMatrix.copy(rootNode.getWorldTransform()).invert(); for (let i = this.bones.length - 1; i >= 0; i--) { this.matrices[i].mulAffine2(_invMatrix, this.bones[i].getWorldTransform()); // world space -> rootNode space this.matrices[i].mulAffine2(this.matrices[i], this.skin.inverseBindPose[i]); // rootNode space -> bind space } } } updateMatrices(rootNode, skinUpdateIndex) { if (this._updateBeforeCull) { this._updateMatrices(rootNode, skinUpdateIndex); } } updateMatrixPalette(rootNode, skinUpdateIndex) { // make sure matrices are up to date this._updateMatrices(rootNode, skinUpdateIndex); // copy matrices to palette const mp = this.matrixPalette; const count = this.bones.length; for (let i = 0; i < count; i++) { const pe = this.matrices[i].data; // Copy the matrix into the palette, ready to be sent to the vertex shader, transpose matrix from 4x4 to 4x3 format as well const base = i * 12; mp[base] = pe[0]; mp[base + 1] = pe[4]; mp[base + 2] = pe[8]; mp[base + 3] = pe[12]; mp[base + 4] = pe[1]; mp[base + 5] = pe[5]; mp[base + 6] = pe[9]; mp[base + 7] = pe[13]; mp[base + 8] = pe[2]; mp[base + 9] = pe[6]; mp[base + 10] = pe[10]; mp[base + 11] = pe[14]; } this.uploadBones(this.skin.device); } } export { SkinInstance };
import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { hasPermission } from '../../../authorization'; import { LivechatVisitors } from '../../../models'; Meteor.publish('livechat:visitors', function(date) { if (!this.userId) { return this.error(new Meteor.Error('error-not-authorized', 'Not authorized', { publish: 'livechat:visitors' })); } if (!hasPermission(this.userId, 'view-livechat-manager')) { return this.error(new Meteor.Error('error-not-authorized', 'Not authorized', { publish: 'livechat:visitors' })); } date = { gte: new Date(date.gte), lt: new Date(date.lt), }; check(date.gte, Date); check(date.lt, Date); const self = this; const handle = LivechatVisitors.getVisitorsBetweenDate(date).observeChanges({ added(id, fields) { self.added('livechatVisitors', id, fields); }, changed(id, fields) { self.changed('livechatVisitors', id, fields); }, removed(id) { self.removed('livechatVisitors', id); }, }); self.ready(); self.onStop(function() { handle.stop(); }); });
module.exports = { getLocation: function (index, inputStream) { var n = index + 1, line = null, column = -1; while (--n >= 0 && inputStream.charAt(n) !== '\n') { column++; } if (typeof index === 'number') { line = (inputStream.slice(0, index).match(/\n/g) || "").length; } return { line: line, column: column }; } };
/***************************************************************** KROKI Web Application Flat UI - JavaScript implementation Author: Milorad Filipovic [mfili@uns.ac.rs] Copyrigth (c) 2014 KROKI Team, Chair of Informatics Faculty of Technical Sciences Novi Sad, Serbia https://github.com/KROKIteam *****************************************************************/ $(document).ready(function(e) { //number of miliseconds that popup messages are being visible for var delay = 2000; //speed of fade out and fade in effects var fadeSpeed = 300; //window (div.windows) that is currently being dragged var dragged = null; //offsets for dragging forms var ox = 0; var oy = 0; //remember username so it can be switched with logout text var username = $("#logoutLink").text(); //if the username is shorter than the word "Logout", keep the minimal width of the link if(username.length < 6) { $("#logoutLink").outerWidth(88); } //delete dummy text generated by KROKI menu generator for empty divs $(".arrow-down").empty(); $(".arrow-right").empty(); //cache container and body for later use var container = $("#container"); var body = $("body"); //if the confirm dialog is shown, remember which form to refresh after hiding the overlay var formToRefresh; /************************************************************************************************************************** MENU EFFECTS **************************************************************************************************************************/ //PAGE LOAD ANIMATION //Slide down the navigation $("nav").animate({height: calculateNavigationHeight()}, "slow", function() { $("#mainMenu").css("visibility","visible").hide().fadeIn("fast", function() { $("#logoutDiv").fadeIn("slow"); }); }); //MAKE MAIN MENU ITEMS INVERT COLORS ON MOUSE HOVER $(".mainMenuItems").hover(function(e) { if($(this).find("ul.L1SubMenu").css('visibility') == 'hidden') { $(this).addClass("hover"); } }, function(e) { if($(this).find("ul.L1SubMenu").css('visibility') == 'hidden') { $(this).removeClass("hover"); } }); //OPEN SUBMENU ON CLICK // $(".menu") is a <div> within main menu list elements which contains text and down arrow // so getting parent of $(".menu") we get the actual <li> element $(".mainMenuItems").click(function(e) { //if corresponding submenu is not allready open, open it while closing all other submenus if($(this).find("ul.L1SubMenu").css('visibility') == 'hidden') { $(".mainMenuItems").each(function(index, element) { $(this).removeClass("hover"); $(this).find("ul.L1SubMenu").css("visibility","hidden"); $(this).find("ul.L2SubMenu").hide(); }); $(this).addClass("hover"); $(this).find("ul.L1SubMenu").css("visibility","visible"); }else { //if a submenu is open, just close it on click //$(this).addClass("hover"); $(this).find("ul.L1SubMenu").css("visibility","hidden"); } }); //INVERT SUBMENU ITEMS COLORS ON MOUSE HOVER $("li.subMenuItem").hover(function(e) { e.stopPropagation(); $(this).addClass("hover-li"); $(this).find("span").addClass("arrow-right-hover"); }, function(e) { e.stopPropagation(); $(this).removeClass("hover-li"); $(this).find("span").removeClass("arrow-right-hover"); }); //SHOW HIGHER LEVEL SUBMENUS ON CLICK $(".subMenuLink").click(function(e) { e.stopPropagation(); // if submenu is not visible, click opens it if(!$(this).find("ul.L2SubMenu").is(":visible")) { // first close all others $(this).parent().find("ul.L2SubMenu").each(function(index, element) { $(this).hide(); }); $(this).children("ul.L2SubMenu").first().show(); }else { //if submenu is allready opened, it is closed on click $(this).children("ul.L2SubMenu").first().hide(); } }); //SHOW "LOGOUT" TEXT WHEN HOVERING OVER USERNAME $("#logoutLink").hover(function() { //keep original width if username is longer than "Logout" so link doesn't shrink if(username.length > 6) { $(this).outerWidth($(this).outerWidth()) } $(this).text("Logout"); }, function(){ $(this).text(username); }); //if a window is resized, keep headers and fixed div aligned $(window).resize(function(e) { container.find(".standardForms").each(function(index, element) { updateBounds($(this)); }); $("nav").height(calculateNavigationHeight()); }); /************************************************************************************************************************** FORM EFFECTS **************************************************************************************************************************/ /* GUI components that are used to open standard forms have the 'activator' css class, 'data-activate', 'data-label' and 'data-paneltype' attributes. Clicking these components displays corresponding standard panels in standard form. Currently, activators are: a) main menu items, b)lookup buttons and c)next links */ $(document).on("click", ".activator", function(e) { e.stopPropagation(); var activator = $(this); var activate = "/show/" + $(this).attr("data-activate"); var label = $(this).attr("data-label"); var panelType = $(this).attr("data-paneltype"); var showback = false; resourceId = $(this).attr("data-activate"); //ACTIVATOR SPECIFIC OPERATIONS: //if activator is menu item, return menu to inital state if(activator.hasClass(".subMenuItem")) { // Hide all the submenus $(".mainMenuItems").each(function(index, element) { $(this).removeClass("hover"); $(this).find("ul.L1SubMenu").css("visibility","hidden"); $(this).find("ul.L2SubMenu").hide(); }); activator.closest("li.mainMenuItems").removeClass("hover"); } //if activator is next link, change activate link to get the child panel instead of standard panel if(activator.hasClass("panelLinks")) { var form = activator.closest("div.standardForms"); var tableDiv = form.find("div.tableDiv"); var selectedRow = tableDiv.find(".mainTable tbody tr.selectedTr"); var returnTo = null; var zoomName = null; resourceId = $(this).attr("data-resourceId"); if(selectedRow.length > 0) { var id = selectedRow.find("#idCell").text(); activate = $(this).attr("data-activate") + "/" + id; panelType = "next-panel"; }else { // If nothing is selected, show unfiltered data in new form label = $(this).attr("data-labelClean"); activate = "/show/" + resourceId; } activator.closest(".nextPopup").hide(); } //if activator is lookup button, show back button //and set 'data-returnTo' attribute to caller form ID if(activator.hasClass("zoomInputs")) { showback = true; var form = activator.closest("div.standardForms"); var activatorColumn = activator.closest("td.inputColumn"); zoomName = activatorColumn.find("input[name]").attr("name"); returnTo = form.attr("id"); } //finally, pass data to method that creates forms makeNewWindow(activate, label, panelType, showback, returnTo, zoomName, resourceId); }); //CLOSE FORM ON 'X' BUTTON CLICK container.on("click", ".headerButtons", function(e) { e.stopPropagation(); var window = $(this).parent().parent(); //TODO: Handle parent child window closing var form = window.find("div.standardForms:first"); closeForm(form); }); //FOCUS FORM ON CLICK container.on("click", ".windows", function() { focus($(this)); }); //DRAG FORMS WHEN DRAGGING HEADERS // mousedown on .formheaders - make current form draggable container.on("mousedown", ".windowHeaders", function(e) { dragged = $(this).parent(); focus(dragged); //coordinates of a mouse var ex = e.pageX; var ey = e.pageY; //coordinates of the form var position = dragged.position(); var fx = position.left; var fy = position.top; //offsets of these coordinates ox = ex - fx; oy = ey - fy; //offsets are calculated here to avoid calculation on mouse move //since the offsets stay the same during the dragging process }); // mouseup - stop dragging forms $("html").mouseup(function() { dragged = null; }); $("html").mousemove(function(e) { if(dragged != null) { var ex = e.pageX; var ey = e.pageY; dragged.offset({ left: ex - ox, top: ey - oy }); } }); //FUNCTION THAT CREATES HTML WINDOWS function makeNewWindow(activate, label, panelType, showback, returnTo, zoomName, resourceId) { //make div.window var newWindow = $(document.createElement("div")); //add unique ID for each window newWindow.addClass("windows"); //make div.windowHeaders and it's contents var newWindowHeader = $(document.createElement("div")); newWindowHeader.addClass("windowHeaders"); var newWindowName = $(document.createElement("div")); newWindowName.addClass("windowName"); newWindowName.text(label); var newHeaderButtonDiv = $(document.createElement("div")); newHeaderButtonDiv.addClass("headerButtons"); newHeaderButtonDiv.attr("title", "Close window"); var newHeaderButtonImage = $(document.createElement("img")); newHeaderButtonImage.attr("src", "/files/images/icons-white/close.png"); if(returnTo != null) { newWindow.attr("data-returnTo", returnTo); } if(zoomName != null) { newWindow.attr("data-zoomName", zoomName); } newHeaderButtonDiv.append(newHeaderButtonImage); newWindowHeader.append(newWindowName); newWindowHeader.append(newHeaderButtonDiv); //var activateLink = "/show/" + activate; var activateSplit = activate.split("/"); //make div.windowBody newWindowBody = $(document.createElement("div")); newWindowBody.addClass("windowBody"); newWindow.append(newWindowHeader) newWindow.append(newWindowBody); newWindowBody.bind('scroll', function() { updateBounds(newWindowBody); }); container.append(newWindow); //if the form that needs to ne displayed is parent-child form //get containing panels with ajax call to /getInfo/panelName //and get data for each form by envoking standard panel ajax call to server if(panelType == "PARENTCHILDPANEL") { //get JSON data from server $.getJSON("/getInfo/" + resourceId, function(data) { //Create <div> element for each contained panel for(var i=0; i<data.panels.length; i++) { var activate = data.panels[i].activate; var associationEnd = data.panels[i].assoiciation_end; var newStandardForm = $(document.createElement("div")); newStandardForm.attr("id", generateUUID()); newStandardForm.addClass("standardForms"); newStandardForm.attr("data-activate", "/show/" + activate); newStandardForm.attr("data-assocend", associationEnd); newStandardForm.css({"height": (100/data.panels.length) + "%"}); newStandardForm.attr("data-resourceId", activate); newWindowBody.append(newStandardForm); loadDataToForm(newStandardForm, true, false); updateBounds(newWindowBody); $(".datepicker").datepicker({ changeMonth: true, changeYear: true, dateFormat: "dd.mm.yy.", yearRange: "1900:2100" }); var newHeight = (data.panels.length) * 200; if(newHeight < $("#container").height()) { alert("New New: " + newHeight); newWindow.height(newHeight); }else { newWindow.height("85%"); newWindow.css({ "top": 60, "left": 20, }); } } }); }else { var newStandardForm = $(document.createElement("div")); newStandardForm.addClass("standardForms"); newStandardForm.attr("id", generateUUID()); newStandardForm.attr("data-activate", activate); newStandardForm.attr("data-resourceId", resourceId); newWindowBody.append(newStandardForm); loadDataToForm(newStandardForm, false, showback); } forms = newWindow.find("div.standardForms").length; if(forms > 2) { var newHeight = forms*200; if(newHeight < $("#container").height()) { newWindow.height(newHeight); }else { newWindow.height("85%"); newWindow.css({ "top": 60, "left": 20, }); } } updateBounds(newWindowBody); } /************************************************************************************************************************** TABLE EFFECTS ***************************************************************************************************************************/ // SELECT TABLE ROWS ON MOUSE CLICK // Only one row can be selected at a time container.on("click", ".mainTable tbody tr", function() { var form = $(this).closest(".standardForms"); var window = $(this).closest(".windows"); $(this).parent().find("tr").removeClass("selectedTr"); $(this).addClass("selectedTr"); form.find("#btnPrev").removeAttr("disabled"); form.find("#btnNext").removeAttr("disabled"); form.find("#btnDelete").removeAttr("disabled"); form.find("#btnNextForms").removeAttr("disabled"); form.find("#btnZoomBack").removeAttr("disabled"); form.find("a.panelLinks").removeClass("disabled"); //if the table is on parent-child panel, filter data on table below and select first row if(window.find(".standardForms").length > 1) { var parentId = form.attr("data-resourceId"); var childForm = form.next(); var childId = childForm.attr("data-resourceId"); var rowId = $(this).find("#idCell").text(); var assocEnd = childForm.attr("data-assocend"); //call server method only if child form exists below this form if(childForm.length > 0) { $.ajax({ url: "/showChildren/" + childId + "/" + assocEnd + "/" + rowId, type: 'GET', encoding:"UTF-8", contentType: "text/html; charset=UTF-8", success: function(data) { childForm.html(data); childForm.find("button#btnZoomBack").remove(); var firstRow = childForm.find(".mainTable tbody tr:first-child"); if(firstRow.length > 0) { firstRow.trigger("click"); }else { childForm.next().find(".tablePanel").empty(); } updateBounds(childForm); }, error: function(XMLHttpRequest, textStatus, errorThrown) { $("#messagePopup").html("<p>" + errorThrown + "</p>"); $("#messagePopup").attr("class", "messageError"); $("#messagePopup").prepend("<div></div>"); $("#messagePopup").slideToggle(300).delay(delay).slideToggle(500); } }); } } }); //"SWITCH VIEW" BUTTON: // - Shows forms for adding new and editing existent rows in table container.on("click", "#btnSwitch", function(e) { var tableDiv = $(this).closest("div.tableDiv"); var selectedRow = tableDiv.find(".mainTable tbody tr.selectedTr"); var formBody = $(this).closest(".windowBody"); var form = $(this).closest("div.standardForms"); //if a row is selected, edit form needs to be displayed, //otherwise, an empty form for adding is shown if(selectedRow.length > 0) { var id = selectedRow.find("#idCell").text(); var resName = form.attr("data-resourceId"); var pid = -1; //if the form has been opened as child form, submit parent id if(form.attr("data-activate").indexOf("showChildren") != -1) { var activateLink = form.attr("data-activate").split("/"); pid = activateLink[activateLink.length-1]; } //since edit form is fetched from server on each click, remove previous one formBody.remove(".inputForm[name=editForm]"); $.ajax({ url: "/edit/" + resName + "/" + id + "/" + pid, type: 'GET', encoding:"UTF-8", contentType: "text/html; charset=UTF-8", success: function(data) { form.append(data); form.find(".nextPopup").hide(); // initialize jQuery UI datepickers $(".datepicker").datepicker({ changeMonth: true, changeYear: true, dateFormat: "dd.mm.yy.", yearRange: "1900:2100" }); form.fadeOut(fadeSpeed, function(e) { form.find(".tableDiv").hide(); form.find(".operationsDiv").hide(); form.find(".inputForm[name=editForm]").show(); form.fadeIn(fadeSpeed); }); }, error: function(XMLHttpRequest, textStatus, errorThrown) { $("#messagePopup").html("<p>" + errorThrown + "</p>"); $("#messagePopup").attr("class", "messageError"); $("#messagePopup").prepend("<div></div>"); $("#messagePopup").slideToggle(300).delay(delay).slideToggle(500); } }); }else { form.find(".nextPopup").hide(); form.fadeOut(fadeSpeed, function(e) { form.find(".tableDiv").hide(); form.find(".operationsDiv").hide(); form.find(".inputForm[name=addForm]").show(); form.fadeIn(fadeSpeed); }); } }); // FIRST, LAST, PREVIOUS AND NEXT BUTTONS IMPLEMENTATIONS container.on("click", "#btnFirst", function(e) { var form = $(this).closest("div.standardForms"); var tableDiv = $(this).closest("div.tableDiv"); var firstTR = tableDiv.find(".mainTable tbody tr:first-child"); if(firstTR.length > 0) { /*tableDiv.find(".mainTable tbody tr").removeClass("selectedTr"); //select first element firstTR.addClass("selectedTr");*/ firstTR.trigger("click"); //scroll to top tableDiv.find(".tablePanel").scrollTop(0); form.find("#btnPrev").removeAttr("disabled"); form.find("#btnNext").removeAttr("disabled"); form.find("#btnDelete").removeAttr("disabled"); form.find("#btnNextForms").removeAttr("disabled"); } }); container.on("click", "#btnPrev", function(e) { var tableDiv = $(this).closest("div.tableDiv"); var tablePanel = tableDiv.find(".tablePanel"); var selectedRow = tableDiv.find(".mainTable tbody tr.selectedTr"); if(selectedRow.length > 0) { if(selectedRow.prev().length > 0) { var position = selectedRow.prev().position(); selectedRow.prev().trigger("click"); //detect whent the selected row gets out of the view port, and scroll so it gets on top if(position.top < tablePanel.position().top) { tablePanel.scrollTop((selectedRow.next().index()-2) * selectedRow.next().outerHeight()); } } } }); container.on("click", "#btnNext", function(e) { var tableDiv = $(this).closest("div.tableDiv"); var tablePanel = tableDiv.find(".tablePanel"); var selectedRow = tableDiv.find(".mainTable tbody tr.selectedTr"); if(selectedRow.length > 0) { if(selectedRow.next().length > 0) { var position = selectedRow.next().position(); selectedRow.next().trigger("click"); //detect whent the selected row gets out of the view port, and scroll so it gets on top if((position.top + selectedRow.next().outerHeight()) > (tablePanel.position().top + tablePanel.outerHeight()) ) { tablePanel.scrollTop((selectedRow.next().index()+2) * selectedRow.next().outerHeight()); } } } }); container.on("click", "#btnLast", function(e) { var form = $(this).closest("div.standardForms"); var tableDiv = $(this).closest("div.tableDiv"); var lastTR = tableDiv.find(".mainTable tbody tr:last-child"); if(lastTR.length > 0) { //select last element lastTR.trigger("click"); //scroll to bottom var position = lastTR.position(); tableDiv.find(".tablePanel").scrollTop(position.top); form.find("#btnPrev").removeAttr("disabled"); form.find("#btnNext").removeAttr("disabled"); form.find("#btnDelete").removeAttr("disabled"); form.find("#btnNextForms").removeAttr("disabled"); } }); /* SHOW NEXT POPUP BUTTON CLICK */ container.on("click", "#btnNextForms", function(e) { var form = $(this).closest("div.standardForms"); var popup = form.find(".nextPopup"); var tableDiv = $(this).closest("div.tableDiv"); var selectedRow = tableDiv.find(".mainTable tbody tr.selectedTr"); popup.css({ 'position': 'absolute', 'left': $(this).position().left, 'top': $(this).position().top + $(this).height() + 10 }); popup.fadeToggle(); }); container.on("click", "#btnRefresh", function(e) { var form = $(this).closest("div.standardForms"); refreshFormData(form); }); container.on("click", "#btnAdd", function(e) { var tableDiv = $(this).closest("div.tableDiv"); var selectedRow = tableDiv.find(".mainTable tbody tr.selectedTr"); var formBody = $(this).closest(".windowBody"); var form = $(this).closest("div.standardForms"); form.find(".nextPopup").hide(); form.fadeOut("slow", function(e) { form.find(".tableDiv").hide(); form.find(".operationsDiv").hide(); form.find(".inputForm[name=addForm]").show(); form.fadeIn("slow"); }); }); container.on("click", "#btnDelete", function(e) { var form = $(this).closest("div.standardForms"); var tableDiv = form.find("div.tableDiv"); var selectedRow = tableDiv.find(".mainTable tbody tr.selectedTr"); if(selectedRow.length > 0) { var id = selectedRow.find("#idCell").text(); var presName = form.attr("data-resourceId"); formToRefresh = form; showConfirmDialog("Confirm delete", "/delete/" + presName + "/" + id, "Are you sure you wish to delete the selected row?"); } }); //OK and Cancel buttons on confirm dialogs $("#cancelConfirm").click(function(e) { $("#overlay").hide(); }); $("#cconfirmBtn").click(function(e) { $("#overlay").hide(); var link = $(this).closest("#confirmDialog").attr("data-confirmLink"); var params = "?names=" if(link == "printForm") { var confirmDialog = $(this).closest("#confirmDialog"); var resourceid = $("#confirmDialog").attr("data-resourceid"); if($('#confirmDialog input:checkbox:checked').length > 0) { $('#confirmDialog input:checkbox:checked').each(function() { params += $(this).attr("name") + ";" }); link += params + "&resource=" + resourceid; $.ajax({ url: link, type: 'GET', encoding:"UTF-8", contentType: "text/html; charset=UTF-8", success: function(data) { console.log("RESPONSE: " + data) $("#messagePopup").html(data); var clas = $("#messagePopup").find("p").attr("data-cssClass"); $("#messagePopup").attr("class", clas); $("#messagePopup").prepend("<div></div>"); $("#messagePopup").slideToggle(300).delay(delay).slideToggle(500); var pdfURI = "" window.open('/static/' + resourceid + '.pdf', '_blank'); }, error: function(XMLHttpRequest, textStatus, errorThrown) { $("#messagePopup").html("<p>" + errorThrown + "</p>"); $("#messagePopup").attr("class", "messageError"); $("#messagePopup").prepend("<div></div>"); $("#messagePopup").slideToggle(300).delay(delay).slideToggle(500); } }); }else { alert("Please select at least one column to print.") } }else { if(link != "justClose") { $.ajax({ url: link, type: 'GET', encoding:"UTF-8", contentType: "text/html; charset=UTF-8", success: function(data) { $("#messagePopup").html(data); var clas = $("#messagePopup").find("p").attr("data-cssClass"); $("#messagePopup").attr("class", clas); $("#messagePopup").prepend("<div></div>"); $("#messagePopup").slideToggle(300).delay(delay).slideToggle(500); refreshFormData(formToRefresh); }, error: function(XMLHttpRequest, textStatus, errorThrown) { $("#messagePopup").html("<p>" + errorThrown + "</p>"); $("#messagePopup").attr("class", "messageError"); $("#messagePopup").prepend("<div></div>"); $("#messagePopup").slideToggle(300).delay(delay).slideToggle(500); } }); } } }); function showConfirmDialog(name, confirmLink, text, form) { $("#confirmDialog .windowName").text(name); $("#confirmDialog").attr("data-confirmLink", confirmLink); $("#confirmDialog p").empty(); $("#confirmDialog p").text(text); // DEFAULT PRINT FORM // Show check boxes for columns that need to be printed if (typeof form !== "undefined" && confirmLink == "printForm") { var printContainer = $(document.createElement("div")); $("#confirmDialog").attr("data-resourceid", form.attr("data-resourceid")); form.find(".inputFormFields tr").each(function() { var label = $(this).find('td.labelColumn').text(); var name = $(this).find('*[name]:first').attr('name'); var checkboxLabel = $(document.createElement("label")); var printCheckBox = $(document.createElement("input")); printCheckBox.addClass("printCheckBox"); printCheckBox.attr("type", "checkbox"); printCheckBox.attr("name", name); printCheckBox.attr("id", name); printCheckBox.attr("value", name); printCheckBox.attr("checked", "checked"); var checkboxLabel = $(document.createElement("label")); checkboxLabel.addClass("printLabel"); checkboxLabel.attr("for", name); checkboxLabel.text(label); printContainer.append(printCheckBox); printContainer.append(checkboxLabel); }); var count = printContainer.find("input").length; if(count > 3) { $("#confirmDialog").css({height: 42*count + "px"}); }else { $("#confirmDialog").css({height: "170px"}); } $("#confirmDialog p").append(printContainer); }else { $("#confirmDialog").css({height: "170px"}); } $("#overlay").show(); } // Return from zoom button container.on("click", "#btnZoomBack", function(e) { var form = $(this).closest("div.standardForms"); var window = $(this).closest("div.windows"); var tableDiv = form.find("div.tableDiv"); var selectedRow = tableDiv.find(".mainTable tbody tr.selectedTr"); if(selectedRow.length > 0) { closeForm(form); var id = selectedRow.find("#idCell").text(); var zoomName = window.attr("data-zoomname"); var returnTo = window.attr("data-returnto"); var caller = getForm(returnTo); var callerPanel = caller.attr("data-resourceId"); $.getJSON("/getZooms/" + callerPanel + "/" + zoomName + "/" + id, function(data) { for(var i = 0; i < data.zoomValues.length; i++) { var zoomName = data.zoomValues[i].name; var zoomValue = data.zoomValues[i].value; // Get visible input since, one is always hidden, depending on which form is in use (add or edit) var zoomInput = caller.find("#" + zoomName + ":visible"); console.log("Menjam :" + zoomInput.attr("id") + " iz " + zoomInput.closest("form.inputForm").attr("name")); console.log(zoomInput.val() + " --> " + zoomValue); zoomInput.val(zoomValue); } }); } }); // OPERATION BUTTON CLICKS container.on("click", ".operationButton[data-operation]", function(e) { var name = $(this).text(); var link = $(this).attr("data-confirmLink"); var text = $(this).attr("data-confirmText"); var form = $(this.closest(".standardForms")); showConfirmDialog(name, link, text, form); }); /************************************************************************************************************************** INPUT PANEL EFFECTS **************************************************************************************************************************/ container.on("click", "#button-cancel", function(e) { e.preventDefault(); var form = $(this).closest("div.standardForms"); form.fadeOut("slow", function(e) { refreshFormData(form); form.find(".tableDiv").show(); form.find(".operationsDiv").show(); form.find(".inputForm").hide(); form.fadeIn(fadeSpeed); }); form.trigger("reset"); }); container.on("click", "#button-ok", function(e) { e.preventDefault(); var form = $(this).closest(".inputForm"); var act = form.attr('action'); var method = form.attr('method'); $.ajax({ type: method, url: act, data: form.serialize(), encoding:"UTF-8", contentType: "text/html; charset=UTF-8", success: function (data) { $("#messagePopup").html(data); var clas = $("#messagePopup").find("p").attr("data-cssClass"); $("#messagePopup").attr("class", clas); $("#messagePopup").prepend("<div></div>"); $("#messagePopup").slideToggle(300).delay(delay).slideToggle(500); if(clas == "messageOk") { if(form.attr("name") == "addForm") { form.trigger("reset"); form.find(".inputFormFields tr:first-child input").focus(); } } }, error: function(XMLHttpRequest, textStatus, errorThrown) { $("#messagePopup").html("<p>" + errorThrown + "</p>"); $("#messagePopup").attr("class", "messageError"); $("#messagePopup").prepend("<div></div>"); $("#messagePopup").slideToggle(300).delay(delay).slideToggle(500); } }); }); }); //---------------------------------------------------------------------// UTIL FUNCTIONS /* * Fetches the data from server to form element * */ function loadDataToForm(form, displayTitle, showback) { var activateLink = form.attr("data-activate"); var window = form.closest(".windows"); $.ajax({ url: activateLink, type: 'GET', encoding:"UTF-8", contentType: "text/html; charset=UTF-8", success: function(data) { form.html(data); window.show(); focus(window); if(!displayTitle) { form.find("h1").remove(); } if(!showback) { form.find("button#btnZoomBack").remove(); } /* * Set the bounds of table head fixator div and its contents */ updateBounds(form); // initialize jQuery UI datepickers $(".datepicker").datepicker({ changeMonth: true, changeYear: true, dateFormat: "dd.mm.yy.", yearRange: "1900:2100" }); /* * If number of columns is more than 6, add 200 pixels for each * and 200 px in height for each standard form */ newWindow = form.closest(".windows"); var columns = newWindow.find("th").length; var siblings = newWindow.find(".standardForms").length; if(columns > 6) { var newWidth = columns*200; if(newWidth<$("#container").width()) { newWindow.width(newWidth); newWindow.css("width", "98%"); }else { //newWindow.style.width("98%"); newWindow.css({ "width": "98%", "top": 60, "left": 20 }); } } if(siblings > 1) { form.find(".operationsDiv").css("max-height", "100%"); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { window.remove(); delete window; $("#messagePopup").html("<p><b>ERROR:</b> " + errorThrown + "</p>"); $("#messagePopup").attr("class", "messageError"); $("#messagePopup").prepend("<div></div>"); $("#messagePopup").slideToggle(300).delay(2000).slideToggle(500); } }); } //Form is focused by applying 'focused' css class //which adds drop-shadow effect to it and puts the form in front of the others. //Only one form can be focused at a time. function focus(form) { $(".windows").each(function(index, element) { $(this).removeClass("focused"); $(this).addClass("unfocused"); }); form.removeClass("unfocused"); form.addClass("focused"); } /* * Refresh form data from database */ function refreshFormData(form) { if(typeof form !== "undefined") { var win = form.closest("div.windows"); form.fadeOut("fast", function() { var showTitle = false; var showback = false; if((win.find(".standardForms").length) > 1) { showTitle = true; } if((form.find("button#btnZoomBack").length) > 0) { showback = true; } loadDataToForm(form, showTitle, showback); $(this).fadeIn("fast", function(e) { if(form.next().length > 0) { refreshFormData(form.next()); } }); }); } } //Updates the bounds of fixed table headers and main navigation dimensions on resize and scroll events function updateBounds(form) { if(form != null) { form.find(".tablePanel").each(function(index, element) { var thead = $(this).find("thead:first"); var fixator = $(this).find(".theadFixator:first"); fixator.offset({ top: $(this).offset().top, left: $(this).offset().left }); fixator.height(thead.height()); fixator.width(thead.width()); thead.find(".innerTHDiv").each(function(index, element) { var span = $(this).parent().find("span:first"); $(this).offset({ top: fixator.offset().top, left: $(this).offset().left }); $(this).css("padding-left", (span.offset().left - span.parent().offset().left)); }); }); } } //calculate main navigation height based on calculated items widht function calculateNavigationHeight() { var menuItemsWidth = 0; var mainMenuWidth = $("#mainMenu").width(); $(".mainMenuItems").each(function(index, element) { menuItemsWidth += $(this).width(); }); var rows = 1; if(menuItemsWidth > mainMenuWidth) { rows = Math.round(menuItemsWidth/mainMenuWidth) + 1; } return rows*40; } // Generate UUID-like uniqe ID for each form function generateUUID() { var d = new Date().getTime(); var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = (d + Math.random()*16)%16 | 0; d = Math.floor(d/16); return (c=='x' ? r : (r&0x7|0x8)).toString(16); }); return uuid; }; function getForm(id) { var form = null; $("div.standardForms").each(function(index, element) { if( $(this).attr("id") == id ) { form = $(this); return false; } }); return form; }; //Closes the form and all it's associated forms function closeForm(form) { //close all zoomed forms first var formID = form.attr("id"); var formWindow = form.closest("div.windows"); $("div.standardForms").each(function(index, element) { if( $(this).attr("data-returnTo") == formID ) { closeForm($(this)); } }); formWindow.remove(); delete formWindow; }
/** * Loads the panel for managing access policies. * * @class MODx.panel.AccessPolicies * @extends MODx.FormPanel * @param {Object} config An object of configuration properties * @xtype modx-panel-access-policies */ MODx.panel.AccessPolicies = function(config) { config = config || {}; Ext.applyIf(config,{ id: 'modx-panel-access-policies' ,bodyStyle: '' ,defaults: { collapsible: false ,autoHeight: true } ,items: [{ html: '<h2>'+_('policies')+'</h2>' ,border: false ,id: 'modx-policies-header' ,cls: 'modx-page-header' },{ layout: 'form' ,cls: 'main-wrapper' ,items: [{ html: '<p>'+_('policy_management_msg')+'</p>' ,border: false },{ xtype: 'modx-grid-access-policy' ,preventRender: true }] }] }); MODx.panel.AccessPolicies.superclass.constructor.call(this,config); }; Ext.extend(MODx.panel.AccessPolicies,MODx.FormPanel); Ext.reg('modx-panel-access-policies',MODx.panel.AccessPolicies); /** * Loads a grid of modAccessPolicies. * * @class MODx.grid.AccessPolicy * @extends MODx.grid.Grid * @param {Object} config An object of options. * @xtype modx-grid-access-policy */ MODx.grid.AccessPolicy = function(config) { config = config || {}; this.sm = new Ext.grid.CheckboxSelectionModel(); Ext.applyIf(config,{ id: 'modx-grid-access-policy' ,url: MODx.config.connectors_url+'security/access/policy.php' ,fields: ['id','name','description','class','data','parent','template','template_name','active_permissions','total_permissions','active_of','cls'] ,paging: true ,autosave: true ,remoteSort: true ,sm: this.sm ,columns: [this.sm,{ header: _('policy_name') ,dataIndex: 'name' ,width: 200 ,editor: { xtype: 'textfield' ,allowBlank: false } ,sortable: true },{ header: _('description') ,dataIndex: 'description' ,width: 375 ,editor: { xtype: 'textfield' } },{ header: _('policy_template') ,dataIndex: 'template_name' ,width: 375 },{ header: _('active_permissions') ,dataIndex: 'active_of' ,width: 100 ,editable: false }] ,tbar: [{ text: _('policy_create') ,scope: this ,handler: this.createPolicy },'-',{ text: _('import') ,scope: this ,handler: this.importPolicy },'-',{ text: _('bulk_actions') ,menu: [{ text: _('policy_remove_multiple') ,handler: this.removeSelected ,scope: this }] },'->',{ xtype: 'textfield' ,name: 'search' ,id: 'modx-policy-search' ,emptyText: _('search_ellipsis') ,listeners: { 'change': {fn: this.search, scope: this} ,'render': {fn: function(cmp) { new Ext.KeyMap(cmp.getEl(), { key: Ext.EventObject.ENTER ,fn: function() { this.fireEvent('change',this.getValue()); this.blur(); return true;} ,scope: cmp }); },scope:this} } },{ xtype: 'button' ,id: 'modx-sacpol-filter-clear' ,text: _('filter_clear') ,listeners: { 'click': {fn: this.clearFilter, scope: this} } }] }); MODx.grid.AccessPolicy.superclass.constructor.call(this,config); }; Ext.extend(MODx.grid.AccessPolicy,MODx.grid.Grid,{ search: function(tf,newValue,oldValue) { var nv = newValue || tf; this.getStore().baseParams.query = Ext.isEmpty(nv) || Ext.isObject(nv) ? '' : nv; this.getBottomToolbar().changePage(1); this.refresh(); return true; } ,clearFilter: function() { this.getStore().baseParams = { action: 'getList' }; Ext.getCmp('modx-policy-search').reset(); this.getBottomToolbar().changePage(1); this.refresh(); } ,editPolicy: function(itm,e) { location.href = '?a='+MODx.action['security/access/policy/update']+'&id='+this.menu.record.id; } ,createPolicy: function(btn,e) { var r = this.menu.record; if (!this.windows.apc) { this.windows.apc = MODx.load({ xtype: 'modx-window-access-policy-create' ,record: r ,plugin: this.config.plugin ,listeners: { 'success': {fn:function(r) { this.refresh(); },scope:this} } }); } this.windows.apc.reset(); this.windows.apc.show(e.target); } ,exportPolicy: function(btn,e) { var id = this.menu.record.id; MODx.Ajax.request({ url: this.config.url ,params: { action: 'export' ,id: id } ,listeners: { 'success': {fn:function(r) { location.href = this.config.url+'?action=export&download=1&id='+id+'&HTTP_MODAUTH='+MODx.siteId; },scope:this} } }); } ,importPolicy: function(btn,e) { var r = {}; if (!this.windows.importPolicy) { this.windows.importPolicy = MODx.load({ xtype: 'modx-window-policy-import' ,record: r ,listeners: { 'success': {fn:function(o) { this.refresh(); },scope:this} } }); } this.windows.importPolicy.reset(); this.windows.importPolicy.setValues(r); this.windows.importPolicy.show(e.target); } ,getMenu: function() { var r = this.getSelectionModel().getSelected(); var p = r.data.cls; var m = []; if (this.getSelectionModel().getCount() > 1) { m.push({ text: _('policy_remove_multiple') ,handler: this.removeSelected }); } else { if (p.indexOf('pedit') != -1) { m.push({ text: _('policy_update') ,handler: this.editPolicy }); m.push({ text: _('policy_duplicate') ,handler: this.confirm.createDelegate(this,["duplicate","policy_duplicate_confirm"]) }); } if (m.length > 0) { m.push('-'); } m.push({ text: _('policy_export') ,handler: this.exportPolicy }); if (p.indexOf('premove') != -1) { if (m.length > 0) m.push('-'); m.push({ text: _('policy_remove') ,handler: this.confirm.createDelegate(this,["remove","policy_remove_confirm"]) }); } } if (m.length > 0) { this.addContextMenuItem(m); } } ,removeSelected: function() { var cs = this.getSelectedAsList(); if (cs === false) return false; MODx.msg.confirm({ title: _('policy_remove_multiple') ,text: _('policy_remove_multiple_confirm') ,url: this.config.url ,params: { action: 'removeMultiple' ,policies: cs } ,listeners: { 'success': {fn:function(r) { this.getSelectionModel().clearSelections(true); this.refresh(); },scope:this} } }); return true; } }); Ext.reg('modx-grid-access-policy',MODx.grid.AccessPolicy); /** * Generates a window for creating Access Policies. * * @class MODx.window.CreateAccessPolicy * @extends MODx.Window * @param {Object} config An object of options. * @xtype modx-window-access-policy-create */ MODx.window.CreateAccessPolicy = function(config) { config = config || {}; this.ident = config.ident || 'cacp'+Ext.id(); Ext.applyIf(config,{ width: 500 ,title: _('policy_create') ,url: MODx.config.connectors_url+'security/access/policy.php' ,action: 'create' ,fields: [{ fieldLabel: _('name') ,description: MODx.expandHelp ? '' : _('policy_desc_name') ,name: 'name' ,id: 'modx-'+this.ident+'-name' ,xtype: 'textfield' ,anchor: '100%' },{ xtype: MODx.expandHelp ? 'label' : 'hidden' ,forId: 'modx-'+this.ident+'-name' ,html: _('policy_desc_name') ,cls: 'desc-under' },{ fieldLabel: _('policy_template') ,description: MODx.expandHelp ? '' : _('policy_desc_template') ,name: 'template' ,hiddenName: 'template' ,id: 'modx-'+this.ident+'-template' ,xtype: 'modx-combo-access-policy-template' ,anchor: '100%' },{ xtype: MODx.expandHelp ? 'label' : 'hidden' ,forId: 'modx-'+this.ident+'-template' ,html: _('policy_desc_template') ,cls: 'desc-under' },{ fieldLabel: _('description') ,description: MODx.expandHelp ? '' : _('policy_desc_description') ,name: 'description' ,id: 'modx-'+this.ident+'-description' ,xtype: 'textarea' ,anchor: '100%' ,height: 50 },{ xtype: MODx.expandHelp ? 'label' : 'hidden' ,forId: 'modx-'+this.ident+'-description' ,html: _('policy_desc_description') ,cls: 'desc-under' },{ name: 'class' ,id: 'modx-'+this.ident+'-class' ,xtype: 'hidden' },{ name: 'id' ,id: 'modx-'+this.ident+'-id' ,xtype: 'hidden' }] ,keys: [] }); MODx.window.CreateAccessPolicy.superclass.constructor.call(this,config); }; Ext.extend(MODx.window.CreateAccessPolicy,MODx.Window); Ext.reg('modx-window-access-policy-create',MODx.window.CreateAccessPolicy); MODx.combo.AccessPolicyTemplate = function(config) { config = config || {}; Ext.applyIf(config,{ name: 'template' ,hiddenName: 'template' ,fields: ['id','name','description'] ,forceSelection: true ,typeAhead: false ,editable: false ,allowBlank: false ,listWidth: 300 ,pageSize: 20 ,url: MODx.config.connectors_url+'security/access/policy/template.php' ,tpl: new Ext.XTemplate('<tpl for="."><div class="x-combo-list-item"><span style="font-weight: bold">{name}</span>' ,'<p style="margin: 0; font-size: 11px; color: gray;">{description}</p></div></tpl>') }); MODx.combo.AccessPolicyTemplate.superclass.constructor.call(this,config); }; Ext.extend(MODx.combo.AccessPolicyTemplate,MODx.combo.ComboBox); Ext.reg('modx-combo-access-policy-template',MODx.combo.AccessPolicyTemplate); MODx.window.ImportPolicy = function(config) { config = config || {}; this.ident = config.ident || 'imppol-'+Ext.id(); Ext.applyIf(config,{ title: _('policy_import') ,id: 'modx-window-policy-import' ,url: MODx.config.connectors_url+'security/access/policy.php' ,action: 'import' ,fileUpload: true ,saveBtnText: _('import') ,fields: [{ html: _('policy_import_msg') ,id: this.ident+'-desc' ,border: false ,cls: 'panel-desc' ,style: 'margin-bottom: 10px;' },{ xtype: 'textfield' ,fieldLabel: _('file') ,name: 'file' ,id: this.ident+'-file' ,anchor: '100%' ,inputType: 'file' }] }); MODx.window.ImportPolicy.superclass.constructor.call(this,config); }; Ext.extend(MODx.window.ImportPolicy,MODx.Window); Ext.reg('modx-window-policy-import',MODx.window.ImportPolicy);
var ChildRouter = (function () { function ChildRouter() { } ChildRouter.prototype.configureRouter = function (config, router) { this.router = router; config.map([ { route: ['', 'welcome'], moduleId: './welcome', nav: true, title: 'Welcome' }, { route: 'flickr', moduleId: './flickr', nav: true, title: 'Flickr' }, { route: 'child-router', moduleId: './child-router', nav: true, title: 'Child Router' } ]); }; return ChildRouter; })(); exports.ChildRouter = ChildRouter;
define(['jquery', 'ajax', 'handlebars', 'todo.template'], function ($, AJAX, Handlebars, Template) { 'use strict'; var $todoListContainer = $('.main'); var $todoList = $('.todo-list'); var BASE_URL = 'http://128.199.76.9:8002/fairesy'; var cache = {}; function init() { loadTodosOnFirstPage(); $todoList.on('click', '.toggle', completeTodo); } function loadTodosOnFirstPage() { AJAX.get(BASE_URL + '/page?start=0&limit=3') .done(function (allTodo) { $todoList.append(allTodo.map(function (todo) { return compileTodoFromTemplate(todo.id, todo.todo, todo.completed); }).join('')); }); } function completeTodo(event) { var $target = $(event.target).closest('li'); var targetId = $target.data('id'); $target.toggleClass('completed'); var completed = $target.hasClass('completed') ? 1 : 0; AJAX.put(BASE_URL, targetId, { completed: completed }) .done(function () { }); } function compileTodoFromTemplate(todoId, todoName, completed) { var todoTemplate = Handlebars.compile(Template.todo); var compiledTodo = todoTemplate({ completed: completed === 1 ? 'completed' : '', checked: completed === 1 ? 'checked' : '', 'todo-id': todoId, 'todo-name': todoName, }); return compiledTodo; } function renderEachPage(selectedIndex, max) { var start = max * (selectedIndex - 1);//(한 페이지당 불러오는 개수=limit)x(index-1) var URLforEachIndex = 'http://128.199.76.9:8002/fairesy/page?start=' + start + '&limit=' + max; if (!cache[selectedIndex]) { cache[selectedIndex] = AJAX.get(URLforEachIndex).promise(); } cache[selectedIndex].done(function (todosForCurrentIndex) { $todoList.empty(); $todoList.append(todosForCurrentIndex.map(function (todo) { return compileTodoFromTemplate(todo.id, todo.todo, todo.completed); }).join('')); }); } return { init: init, renderEachPage: renderEachPage, }; });
import rng from './rng.js'; import bytesToUuid from './bytesToUuid.js'; // **`v1()` - Generate time-based UUID** // // Inspired by https://github.com/LiosK/UUID.js // and http://docs.python.org/library/uuid.html var _nodeId; var _clockseq; // Previous uuid creation time var _lastMSecs = 0; var _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details function v1(options, buf, offset) { var i = buf && offset || 0; var b = buf || []; options = options || {}; var node = options.node || _nodeId; var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not // specified. We do this lazily to minimize issues related to insufficient // system entropy. See #189 if (node == null || clockseq == null) { var seedBytes = options.random || (options.rng || rng)(); if (node == null) { // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; } if (clockseq == null) { // Per 4.2.2, randomize (14 bit) clockseq clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; } } // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. var msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) var dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression if (dt < 0 && options.clockseq === undefined) { clockseq = clockseq + 1 & 0x3fff; } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { nsecs = 0; } // Per 4.2.1.2 Throw error if too many uuids are requested if (nsecs >= 10000) { throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); } _lastMSecs = msecs; _lastNSecs = nsecs; _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs += 12219292800000; // `time_low` var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; b[i++] = tl >>> 24 & 0xff; b[i++] = tl >>> 16 & 0xff; b[i++] = tl >>> 8 & 0xff; b[i++] = tl & 0xff; // `time_mid` var tmh = msecs / 0x100000000 * 10000 & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; b[i++] = tmh & 0xff; // `time_high_and_version` b[i++] = tmh >>> 24 & 0xf | 0x10; // include version b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` b[i++] = clockseq & 0xff; // `node` for (var n = 0; n < 6; ++n) { b[i + n] = node[n]; } return buf || bytesToUuid(b); } export default v1;
"use strict"; const Cmdlet = require('./Cmdlet'); const Parameters = require('./Parameters'); class Command extends Cmdlet { static defineAspect (name, value) { if (name === 'parameters') { var parameters = this.parameters; parameters.addAll(value); let switches = this.switches; for (let param of parameters) { if (param.switch) { let name = param.name; if (switches.get(name)) { throw new Error(`Parameter ${name} already defined as a switch`); } switches.add(param); } } } else { super.defineAspect(name, value); } } static defineItemHelp (name, text) { let ok = super.defineItemHelp(name, text); let item = this.parameters.get(name); if (item) { item.help = text; ok = true; } return ok; } static get parameters () { return Parameters.get(this); } static getAspects (includePrivate = true) { return Object.assign(super.getAspects(includePrivate), { command: true, parameters: this.parameters.items.map((p) => { if (!p.private || includePrivate) return p; }) }); } //----------------------------------------------------------- constructor () { super(); // The next positional parameter to accept this._paramPos = 0; } get parameters () { return this.constructor.parameters; } applyDefaults (params) { super.applyDefaults(params); this.parameters.applyDefaults(params); } beforeExecute (params) { super.beforeExecute(params); let me = this; me.parameters.getToConfirm(params || this.params).forEach((item) => me.ask(item)); } processArg (arg, args) { let param = this.parameters.at(this._paramPos); if (!param) { // We've run out of parameters so let the base class take over... return super.processArg(arg, args); } let value = param.convert(arg); if (value === null) { if (param.required && !(param.name in this.params)) { this.raise(`Invalid value for "${param.name}" (expected ${param.type}): "${arg}"`); } // Since this param is optional or we have at least one valid argument // for it, skip to the next candidate and try it (this is the only way to // advance past a vargs param): ++this._paramPos; args.unpull(arg); } else { param.set(this.params, value); // We'll park on a vargs parameter until we hit an non-parsable arg... if (!param.vargs) { ++this._paramPos; } } return this.configure(args); } updateFromAnswers (answers, params) { super.updateFromAnswers(answers, params); for (let paramName of Object.keys(answers)) { let entry = this.parameters.lookup(paramName); if (entry) { entry.setRaw(params, answers[paramName]); delete answers[paramName]; } } } //--------------------------------------------------------------- // Private } Object.assign(Command, { isCommand: true, _parameters: new Parameters(Command) }); Object.assign(Command.prototype, { isCommand: true }); module.exports = Command;
import path from 'path'; import { mount } from 'enzyme'; import { createSerializer as enzymeSerializer } from 'enzyme-to-json'; import { createSerializer as emotionSerializer } from 'jest-emotion'; import initStoryshots from '../dist/ts3.9'; initStoryshots({ framework: 'react', configPath: path.join(__dirname, '..', '.storybook'), renderer: mount, snapshotSerializers: [enzymeSerializer(), emotionSerializer()], });
import { runtime, theme, tw } from "./_/chunks/chunk-XFJPXPDR.js"; // src/index.ts import { defineConfig } from "@twind/core"; import autoprefix from "@twind/preset-autoprefix"; import tailwind from "@twind/preset-tailwind"; export * from "@twind/core"; if (typeof document != "undefined" && document.currentScript) { autoSetupTimeoutRef = setTimeout(setup); } var autoSetupTimeoutRef; function setup(config = {}, target) { clearTimeout(autoSetupTimeoutRef); return runtime(defineConfig({ ...config, presets: [autoprefix(), ...config.presets || [], tailwind()] }), target); } export { setup, theme, tw }; //# sourceMappingURL=twind.esnext.js.map
const Assets = require('assets'); const { dirname } = require('path'); const functions = require('postcss-functions'); const util = require('util'); const quote = require('./quote'); const unescapeCss = require('./unescape-css'); const unquote = require('./unquote'); const generateFileUniqueId = require('./__utils__/generateFileUniqueId'); const cachedDimensions = {}; function formatUrl(url) { return util.format('url(%s)', quote(url)); } function formatSize(measurements) { return util.format('%dpx %dpx', measurements.width, measurements.height); } function formatWidth(measurements) { return util.format('%dpx', measurements.width); } function formatHeight(measurements) { return util.format('%dpx', measurements.height); } module.exports = (params = {}) => { if (params.relative === undefined) { params.relative = false; // eslint-disable-line no-param-reassign } const resolver = new Assets(params); function measure(path, density) { let cached = null; let id = ''; let getSizePromise = null; return resolver.path(path).then((resolvedPath) => { if (params.cache) { cached = cachedDimensions[resolvedPath]; id = generateFileUniqueId(resolvedPath); } if (cached && id && cached[id]) { getSizePromise = Promise.resolve(cached[id]); } else { getSizePromise = resolver.size(path).then((size) => { if (params.cache && id) { cachedDimensions[resolvedPath] = {}; cachedDimensions[resolvedPath][id] = size; } return size; }); } return getSizePromise.then((size) => { if (density !== undefined) { return { width: Number((size.width / density).toFixed(4)), height: Number((size.height / density).toFixed(4)), }; } return size; }); }); } return { // Initialize functions plugin as if it was this plugin ...functions({ functions: { resolve: function resolve(path) { const normalizedPath = unquote(unescapeCss(path)); return resolver.url(normalizedPath).then(formatUrl); }, inline: function inline(path) { const normalizedPath = unquote(unescapeCss(path)); return resolver.data(normalizedPath).then(formatUrl); }, size: function size(path, density) { const normalizedPath = unquote(unescapeCss(path)); return measure(normalizedPath, density).then(formatSize); }, width: function width(path, density) { const normalizedPath = unquote(unescapeCss(path)); return measure(normalizedPath, density).then(formatWidth); }, height: function height(path, density) { const normalizedPath = unquote(unescapeCss(path)); return measure(normalizedPath, density).then(formatHeight); }, }, }), // Override with our own features and name postcssPlugin: 'postcss-assets', Once(root) { let inputDir; if (root.source.input.file) { inputDir = dirname(root.source.input.file); resolver.options.loadPaths = resolver.options.loadPaths || []; resolver.options.loadPaths.unshift(inputDir); if (params.relative === true) { resolver.options.relativeTo = inputDir; } } if (typeof params.relative === 'string') { resolver.options.relativeTo = params.relative; } }, }; }; module.exports.postcss = true;
const NODE_ENV = process.env.NODE_ENV || 'development'; const envConfigs = require('./configs'); module.exports = { /** * why? you can see: * https://fb.me/react-minification * http://stackoverflow.com/questions/30030031 */ 'process.env': { NODE_ENV: JSON.stringify(NODE_ENV), }, env: NODE_ENV, __DEV__: NODE_ENV === 'development', __PRO__: NODE_ENV === 'production', config: Object.assign(envConfigs.defaults, envConfigs[NODE_ENV] || {}), };
import React from 'react'; import { findDOMNode, render } from 'react-dom'; import TestUtils from 'react-addons-test-utils'; const removeNewlines = (string) => (string.replace(/(\r\n|\n|\r)/gm, '')) import Style from '../src/index.js'; describe('Style-12', () => { it('removes single and double quotes from CSS declaration bodies', () => { const wrapper = TestUtils.renderIntoDocument( <div> <Style> {` @media all and (orientation: portrait) { #box { background-image: url('http://google.com/'); font-family: 'Helvetica', "Arial"; } } `} <div id="box"></div> </Style> </div> ); const rootNode = findDOMNode(wrapper).children[0]; const styleNode = rootNode.children[0]; const scopedClass = rootNode.className.split(' ').slice(-1)[0]; expect(rootNode.className).toEqual(`${scopedClass}`); expect( removeNewlines(styleNode.textContent) ) .toEqual(` @media all and (orientation: portrait) { #box.${scopedClass} , .${scopedClass} #box { background-image: url('http:\/\/google.com/'); font-family: 'Helvetica', "Arial"; }}`); }); });
// flow-typed signature: 1b2e7734ed6bcd099c4a5feec9fb792c // flow-typed version: <<STUB>>/redux-devtools-dock-monitor_v1.1.1/flow_v0.43.0 /** * This is an autogenerated libdef stub for: * * 'redux-devtools-dock-monitor' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'redux-devtools-dock-monitor' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'redux-devtools-dock-monitor/lib/actions' { declare module.exports: any; } declare module 'redux-devtools-dock-monitor/lib/constants' { declare module.exports: any; } declare module 'redux-devtools-dock-monitor/lib/DockMonitor' { declare module.exports: any; } declare module 'redux-devtools-dock-monitor/lib/index' { declare module.exports: any; } declare module 'redux-devtools-dock-monitor/lib/reducers' { declare module.exports: any; } declare module 'redux-devtools-dock-monitor/src/actions' { declare module.exports: any; } declare module 'redux-devtools-dock-monitor/src/constants' { declare module.exports: any; } declare module 'redux-devtools-dock-monitor/src/DockMonitor' { declare module.exports: any; } declare module 'redux-devtools-dock-monitor/src/index' { declare module.exports: any; } declare module 'redux-devtools-dock-monitor/src/reducers' { declare module.exports: any; } // Filename aliases declare module 'redux-devtools-dock-monitor/lib/actions.js' { declare module.exports: $Exports<'redux-devtools-dock-monitor/lib/actions'>; } declare module 'redux-devtools-dock-monitor/lib/constants.js' { declare module.exports: $Exports<'redux-devtools-dock-monitor/lib/constants'>; } declare module 'redux-devtools-dock-monitor/lib/DockMonitor.js' { declare module.exports: $Exports<'redux-devtools-dock-monitor/lib/DockMonitor'>; } declare module 'redux-devtools-dock-monitor/lib/index.js' { declare module.exports: $Exports<'redux-devtools-dock-monitor/lib/index'>; } declare module 'redux-devtools-dock-monitor/lib/reducers.js' { declare module.exports: $Exports<'redux-devtools-dock-monitor/lib/reducers'>; } declare module 'redux-devtools-dock-monitor/src/actions.js' { declare module.exports: $Exports<'redux-devtools-dock-monitor/src/actions'>; } declare module 'redux-devtools-dock-monitor/src/constants.js' { declare module.exports: $Exports<'redux-devtools-dock-monitor/src/constants'>; } declare module 'redux-devtools-dock-monitor/src/DockMonitor.js' { declare module.exports: $Exports<'redux-devtools-dock-monitor/src/DockMonitor'>; } declare module 'redux-devtools-dock-monitor/src/index.js' { declare module.exports: $Exports<'redux-devtools-dock-monitor/src/index'>; } declare module 'redux-devtools-dock-monitor/src/reducers.js' { declare module.exports: $Exports<'redux-devtools-dock-monitor/src/reducers'>; }
import moment from 'moment'; import Pipeline from './Pipeline'; /** * Sort pipelines by date and filter out pipelines without data * * @param {Array} pipelines The pipelines to sort * @param {Array} disabledPipelines Pipelines that are disabled * @param {string} sortOrder The sort order, 'buildtime' or 'status' * @param {string} filterRegex Regular expression to filter for * @return {Array} Sorted pipelines */ export const sortAndFilterPipelines = (pipelines, disabledPipelines, sortOrder, filterRegex) => { const pipelineIsValid = p => p && p.name const pipelineIsNotDisabled = p => disabledPipelines.indexOf(p.name) < 0 const pipelineMatchesRegex = p => p.name.match(filterRegex) const activePipelines = pipelines.filter(pipelineIsValid) .filter(pipelineIsNotDisabled) .filter(pipelineMatchesRegex); // Add "time ago" moment string activePipelines.forEach((pipeline) => { pipeline.timeago = moment(pipeline.buildtime).fromNow(); }); const sortByBuildTime = (a, b) => { return a.buildtime > b.buildtime ? -1 : 1; }; if (sortOrder === 'buildtime') { return activePipelines.sort(sortByBuildTime); } else { return activePipelines.sort((a, b) => { const aStatus = Pipeline.status(a); const bStatus = Pipeline.status(b); if (aStatus === bStatus) { return sortByBuildTime(a, b); } const statusIndex = { building: -1, failed: 0, cancelled: 1, passed: 2, paused: 3, unknown: 3, } return statusIndex[aStatus] - statusIndex[bStatus] ; }); } }
import Ember from 'ember'; import { city_object } from '../utils/city'; export function cityName(cid/*, hash*/) { return city_object[cid] ? city_object[cid].name : ''; } export default Ember.Helper.helper(cityName);
import DS from 'ember-data'; /** * This model describes the driver as it exists * on a single trip * @type {DS.model} */ export default DS.Model.extend({ name: DS.attr('string'), driverScore: DS.attr('number') });
'use strict'; // Use application configuration module to register a new module ApplicationConfiguration.registerModule('tj-hair');
/*! * Chart.js v3.6.2 * https://www.chartjs.org * (c) 2021 Chart.js Contributors * Released under the MIT License */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Chart = factory()); }(this, (function () { 'use strict'; function fontString(pixelSize, fontStyle, fontFamily) { return fontStyle + ' ' + pixelSize + 'px ' + fontFamily; } const requestAnimFrame = (function() { if (typeof window === 'undefined') { return function(callback) { return callback(); }; } return window.requestAnimationFrame; }()); function throttled(fn, thisArg, updateFn) { const updateArgs = updateFn || ((args) => Array.prototype.slice.call(args)); let ticking = false; let args = []; return function(...rest) { args = updateArgs(rest); if (!ticking) { ticking = true; requestAnimFrame.call(window, () => { ticking = false; fn.apply(thisArg, args); }); } }; } function debounce(fn, delay) { let timeout; return function(...args) { if (delay) { clearTimeout(timeout); timeout = setTimeout(fn, delay, args); } else { fn.apply(this, args); } return delay; }; } const _toLeftRightCenter = (align) => align === 'start' ? 'left' : align === 'end' ? 'right' : 'center'; const _alignStartEnd = (align, start, end) => align === 'start' ? start : align === 'end' ? end : (start + end) / 2; const _textX = (align, left, right, rtl) => { const check = rtl ? 'left' : 'right'; return align === check ? right : align === 'center' ? (left + right) / 2 : left; }; class Animator { constructor() { this._request = null; this._charts = new Map(); this._running = false; this._lastDate = undefined; } _notify(chart, anims, date, type) { const callbacks = anims.listeners[type]; const numSteps = anims.duration; callbacks.forEach(fn => fn({ chart, initial: anims.initial, numSteps, currentStep: Math.min(date - anims.start, numSteps) })); } _refresh() { if (this._request) { return; } this._running = true; this._request = requestAnimFrame.call(window, () => { this._update(); this._request = null; if (this._running) { this._refresh(); } }); } _update(date = Date.now()) { let remaining = 0; this._charts.forEach((anims, chart) => { if (!anims.running || !anims.items.length) { return; } const items = anims.items; let i = items.length - 1; let draw = false; let item; for (; i >= 0; --i) { item = items[i]; if (item._active) { if (item._total > anims.duration) { anims.duration = item._total; } item.tick(date); draw = true; } else { items[i] = items[items.length - 1]; items.pop(); } } if (draw) { chart.draw(); this._notify(chart, anims, date, 'progress'); } if (!items.length) { anims.running = false; this._notify(chart, anims, date, 'complete'); anims.initial = false; } remaining += items.length; }); this._lastDate = date; if (remaining === 0) { this._running = false; } } _getAnims(chart) { const charts = this._charts; let anims = charts.get(chart); if (!anims) { anims = { running: false, initial: true, items: [], listeners: { complete: [], progress: [] } }; charts.set(chart, anims); } return anims; } listen(chart, event, cb) { this._getAnims(chart).listeners[event].push(cb); } add(chart, items) { if (!items || !items.length) { return; } this._getAnims(chart).items.push(...items); } has(chart) { return this._getAnims(chart).items.length > 0; } start(chart) { const anims = this._charts.get(chart); if (!anims) { return; } anims.running = true; anims.start = Date.now(); anims.duration = anims.items.reduce((acc, cur) => Math.max(acc, cur._duration), 0); this._refresh(); } running(chart) { if (!this._running) { return false; } const anims = this._charts.get(chart); if (!anims || !anims.running || !anims.items.length) { return false; } return true; } stop(chart) { const anims = this._charts.get(chart); if (!anims || !anims.items.length) { return; } const items = anims.items; let i = items.length - 1; for (; i >= 0; --i) { items[i].cancel(); } anims.items = []; this._notify(chart, anims, Date.now(), 'complete'); } remove(chart) { return this._charts.delete(chart); } } var animator = new Animator(); /*! * @kurkle/color v0.1.9 * https://github.com/kurkle/color#readme * (c) 2020 Jukka Kurkela * Released under the MIT License */ const map$1 = {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, A: 10, B: 11, C: 12, D: 13, E: 14, F: 15, a: 10, b: 11, c: 12, d: 13, e: 14, f: 15}; const hex = '0123456789ABCDEF'; const h1 = (b) => hex[b & 0xF]; const h2 = (b) => hex[(b & 0xF0) >> 4] + hex[b & 0xF]; const eq = (b) => (((b & 0xF0) >> 4) === (b & 0xF)); function isShort(v) { return eq(v.r) && eq(v.g) && eq(v.b) && eq(v.a); } function hexParse(str) { var len = str.length; var ret; if (str[0] === '#') { if (len === 4 || len === 5) { ret = { r: 255 & map$1[str[1]] * 17, g: 255 & map$1[str[2]] * 17, b: 255 & map$1[str[3]] * 17, a: len === 5 ? map$1[str[4]] * 17 : 255 }; } else if (len === 7 || len === 9) { ret = { r: map$1[str[1]] << 4 | map$1[str[2]], g: map$1[str[3]] << 4 | map$1[str[4]], b: map$1[str[5]] << 4 | map$1[str[6]], a: len === 9 ? (map$1[str[7]] << 4 | map$1[str[8]]) : 255 }; } } return ret; } function hexString(v) { var f = isShort(v) ? h1 : h2; return v ? '#' + f(v.r) + f(v.g) + f(v.b) + (v.a < 255 ? f(v.a) : '') : v; } function round(v) { return v + 0.5 | 0; } const lim = (v, l, h) => Math.max(Math.min(v, h), l); function p2b(v) { return lim(round(v * 2.55), 0, 255); } function n2b(v) { return lim(round(v * 255), 0, 255); } function b2n(v) { return lim(round(v / 2.55) / 100, 0, 1); } function n2p(v) { return lim(round(v * 100), 0, 100); } const RGB_RE = /^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/; function rgbParse(str) { const m = RGB_RE.exec(str); let a = 255; let r, g, b; if (!m) { return; } if (m[7] !== r) { const v = +m[7]; a = 255 & (m[8] ? p2b(v) : v * 255); } r = +m[1]; g = +m[3]; b = +m[5]; r = 255 & (m[2] ? p2b(r) : r); g = 255 & (m[4] ? p2b(g) : g); b = 255 & (m[6] ? p2b(b) : b); return { r: r, g: g, b: b, a: a }; } function rgbString(v) { return v && ( v.a < 255 ? `rgba(${v.r}, ${v.g}, ${v.b}, ${b2n(v.a)})` : `rgb(${v.r}, ${v.g}, ${v.b})` ); } const HUE_RE = /^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/; function hsl2rgbn(h, s, l) { const a = s * Math.min(l, 1 - l); const f = (n, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1); return [f(0), f(8), f(4)]; } function hsv2rgbn(h, s, v) { const f = (n, k = (n + h / 60) % 6) => v - v * s * Math.max(Math.min(k, 4 - k, 1), 0); return [f(5), f(3), f(1)]; } function hwb2rgbn(h, w, b) { const rgb = hsl2rgbn(h, 1, 0.5); let i; if (w + b > 1) { i = 1 / (w + b); w *= i; b *= i; } for (i = 0; i < 3; i++) { rgb[i] *= 1 - w - b; rgb[i] += w; } return rgb; } function rgb2hsl(v) { const range = 255; const r = v.r / range; const g = v.g / range; const b = v.b / range; const max = Math.max(r, g, b); const min = Math.min(r, g, b); const l = (max + min) / 2; let h, s, d; if (max !== min) { d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); h = max === r ? ((g - b) / d) + (g < b ? 6 : 0) : max === g ? (b - r) / d + 2 : (r - g) / d + 4; h = h * 60 + 0.5; } return [h | 0, s || 0, l]; } function calln(f, a, b, c) { return ( Array.isArray(a) ? f(a[0], a[1], a[2]) : f(a, b, c) ).map(n2b); } function hsl2rgb(h, s, l) { return calln(hsl2rgbn, h, s, l); } function hwb2rgb(h, w, b) { return calln(hwb2rgbn, h, w, b); } function hsv2rgb(h, s, v) { return calln(hsv2rgbn, h, s, v); } function hue(h) { return (h % 360 + 360) % 360; } function hueParse(str) { const m = HUE_RE.exec(str); let a = 255; let v; if (!m) { return; } if (m[5] !== v) { a = m[6] ? p2b(+m[5]) : n2b(+m[5]); } const h = hue(+m[2]); const p1 = +m[3] / 100; const p2 = +m[4] / 100; if (m[1] === 'hwb') { v = hwb2rgb(h, p1, p2); } else if (m[1] === 'hsv') { v = hsv2rgb(h, p1, p2); } else { v = hsl2rgb(h, p1, p2); } return { r: v[0], g: v[1], b: v[2], a: a }; } function rotate(v, deg) { var h = rgb2hsl(v); h[0] = hue(h[0] + deg); h = hsl2rgb(h); v.r = h[0]; v.g = h[1]; v.b = h[2]; } function hslString(v) { if (!v) { return; } const a = rgb2hsl(v); const h = a[0]; const s = n2p(a[1]); const l = n2p(a[2]); return v.a < 255 ? `hsla(${h}, ${s}%, ${l}%, ${b2n(v.a)})` : `hsl(${h}, ${s}%, ${l}%)`; } const map$1$1 = { x: 'dark', Z: 'light', Y: 're', X: 'blu', W: 'gr', V: 'medium', U: 'slate', A: 'ee', T: 'ol', S: 'or', B: 'ra', C: 'lateg', D: 'ights', R: 'in', Q: 'turquois', E: 'hi', P: 'ro', O: 'al', N: 'le', M: 'de', L: 'yello', F: 'en', K: 'ch', G: 'arks', H: 'ea', I: 'ightg', J: 'wh' }; const names = { OiceXe: 'f0f8ff', antiquewEte: 'faebd7', aqua: 'ffff', aquamarRe: '7fffd4', azuY: 'f0ffff', beige: 'f5f5dc', bisque: 'ffe4c4', black: '0', blanKedOmond: 'ffebcd', Xe: 'ff', XeviTet: '8a2be2', bPwn: 'a52a2a', burlywood: 'deb887', caMtXe: '5f9ea0', KartYuse: '7fff00', KocTate: 'd2691e', cSO: 'ff7f50', cSnflowerXe: '6495ed', cSnsilk: 'fff8dc', crimson: 'dc143c', cyan: 'ffff', xXe: '8b', xcyan: '8b8b', xgTMnPd: 'b8860b', xWay: 'a9a9a9', xgYF: '6400', xgYy: 'a9a9a9', xkhaki: 'bdb76b', xmagFta: '8b008b', xTivegYF: '556b2f', xSange: 'ff8c00', xScEd: '9932cc', xYd: '8b0000', xsOmon: 'e9967a', xsHgYF: '8fbc8f', xUXe: '483d8b', xUWay: '2f4f4f', xUgYy: '2f4f4f', xQe: 'ced1', xviTet: '9400d3', dAppRk: 'ff1493', dApskyXe: 'bfff', dimWay: '696969', dimgYy: '696969', dodgerXe: '1e90ff', fiYbrick: 'b22222', flSOwEte: 'fffaf0', foYstWAn: '228b22', fuKsia: 'ff00ff', gaRsbSo: 'dcdcdc', ghostwEte: 'f8f8ff', gTd: 'ffd700', gTMnPd: 'daa520', Way: '808080', gYF: '8000', gYFLw: 'adff2f', gYy: '808080', honeyMw: 'f0fff0', hotpRk: 'ff69b4', RdianYd: 'cd5c5c', Rdigo: '4b0082', ivSy: 'fffff0', khaki: 'f0e68c', lavFMr: 'e6e6fa', lavFMrXsh: 'fff0f5', lawngYF: '7cfc00', NmoncEffon: 'fffacd', ZXe: 'add8e6', ZcSO: 'f08080', Zcyan: 'e0ffff', ZgTMnPdLw: 'fafad2', ZWay: 'd3d3d3', ZgYF: '90ee90', ZgYy: 'd3d3d3', ZpRk: 'ffb6c1', ZsOmon: 'ffa07a', ZsHgYF: '20b2aa', ZskyXe: '87cefa', ZUWay: '778899', ZUgYy: '778899', ZstAlXe: 'b0c4de', ZLw: 'ffffe0', lime: 'ff00', limegYF: '32cd32', lRF: 'faf0e6', magFta: 'ff00ff', maPon: '800000', VaquamarRe: '66cdaa', VXe: 'cd', VScEd: 'ba55d3', VpurpN: '9370db', VsHgYF: '3cb371', VUXe: '7b68ee', VsprRggYF: 'fa9a', VQe: '48d1cc', VviTetYd: 'c71585', midnightXe: '191970', mRtcYam: 'f5fffa', mistyPse: 'ffe4e1', moccasR: 'ffe4b5', navajowEte: 'ffdead', navy: '80', Tdlace: 'fdf5e6', Tive: '808000', TivedBb: '6b8e23', Sange: 'ffa500', SangeYd: 'ff4500', ScEd: 'da70d6', pOegTMnPd: 'eee8aa', pOegYF: '98fb98', pOeQe: 'afeeee', pOeviTetYd: 'db7093', papayawEp: 'ffefd5', pHKpuff: 'ffdab9', peru: 'cd853f', pRk: 'ffc0cb', plum: 'dda0dd', powMrXe: 'b0e0e6', purpN: '800080', YbeccapurpN: '663399', Yd: 'ff0000', Psybrown: 'bc8f8f', PyOXe: '4169e1', saddNbPwn: '8b4513', sOmon: 'fa8072', sandybPwn: 'f4a460', sHgYF: '2e8b57', sHshell: 'fff5ee', siFna: 'a0522d', silver: 'c0c0c0', skyXe: '87ceeb', UXe: '6a5acd', UWay: '708090', UgYy: '708090', snow: 'fffafa', sprRggYF: 'ff7f', stAlXe: '4682b4', tan: 'd2b48c', teO: '8080', tEstN: 'd8bfd8', tomato: 'ff6347', Qe: '40e0d0', viTet: 'ee82ee', JHt: 'f5deb3', wEte: 'ffffff', wEtesmoke: 'f5f5f5', Lw: 'ffff00', LwgYF: '9acd32' }; function unpack() { const unpacked = {}; const keys = Object.keys(names); const tkeys = Object.keys(map$1$1); let i, j, k, ok, nk; for (i = 0; i < keys.length; i++) { ok = nk = keys[i]; for (j = 0; j < tkeys.length; j++) { k = tkeys[j]; nk = nk.replace(k, map$1$1[k]); } k = parseInt(names[ok], 16); unpacked[nk] = [k >> 16 & 0xFF, k >> 8 & 0xFF, k & 0xFF]; } return unpacked; } let names$1; function nameParse(str) { if (!names$1) { names$1 = unpack(); names$1.transparent = [0, 0, 0, 0]; } const a = names$1[str.toLowerCase()]; return a && { r: a[0], g: a[1], b: a[2], a: a.length === 4 ? a[3] : 255 }; } function modHSL(v, i, ratio) { if (v) { let tmp = rgb2hsl(v); tmp[i] = Math.max(0, Math.min(tmp[i] + tmp[i] * ratio, i === 0 ? 360 : 1)); tmp = hsl2rgb(tmp); v.r = tmp[0]; v.g = tmp[1]; v.b = tmp[2]; } } function clone$1(v, proto) { return v ? Object.assign(proto || {}, v) : v; } function fromObject(input) { var v = {r: 0, g: 0, b: 0, a: 255}; if (Array.isArray(input)) { if (input.length >= 3) { v = {r: input[0], g: input[1], b: input[2], a: 255}; if (input.length > 3) { v.a = n2b(input[3]); } } } else { v = clone$1(input, {r: 0, g: 0, b: 0, a: 1}); v.a = n2b(v.a); } return v; } function functionParse(str) { if (str.charAt(0) === 'r') { return rgbParse(str); } return hueParse(str); } class Color { constructor(input) { if (input instanceof Color) { return input; } const type = typeof input; let v; if (type === 'object') { v = fromObject(input); } else if (type === 'string') { v = hexParse(input) || nameParse(input) || functionParse(input); } this._rgb = v; this._valid = !!v; } get valid() { return this._valid; } get rgb() { var v = clone$1(this._rgb); if (v) { v.a = b2n(v.a); } return v; } set rgb(obj) { this._rgb = fromObject(obj); } rgbString() { return this._valid ? rgbString(this._rgb) : this._rgb; } hexString() { return this._valid ? hexString(this._rgb) : this._rgb; } hslString() { return this._valid ? hslString(this._rgb) : this._rgb; } mix(color, weight) { const me = this; if (color) { const c1 = me.rgb; const c2 = color.rgb; let w2; const p = weight === w2 ? 0.5 : weight; const w = 2 * p - 1; const a = c1.a - c2.a; const w1 = ((w * a === -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0; w2 = 1 - w1; c1.r = 0xFF & w1 * c1.r + w2 * c2.r + 0.5; c1.g = 0xFF & w1 * c1.g + w2 * c2.g + 0.5; c1.b = 0xFF & w1 * c1.b + w2 * c2.b + 0.5; c1.a = p * c1.a + (1 - p) * c2.a; me.rgb = c1; } return me; } clone() { return new Color(this.rgb); } alpha(a) { this._rgb.a = n2b(a); return this; } clearer(ratio) { const rgb = this._rgb; rgb.a *= 1 - ratio; return this; } greyscale() { const rgb = this._rgb; const val = round(rgb.r * 0.3 + rgb.g * 0.59 + rgb.b * 0.11); rgb.r = rgb.g = rgb.b = val; return this; } opaquer(ratio) { const rgb = this._rgb; rgb.a *= 1 + ratio; return this; } negate() { const v = this._rgb; v.r = 255 - v.r; v.g = 255 - v.g; v.b = 255 - v.b; return this; } lighten(ratio) { modHSL(this._rgb, 2, ratio); return this; } darken(ratio) { modHSL(this._rgb, 2, -ratio); return this; } saturate(ratio) { modHSL(this._rgb, 1, ratio); return this; } desaturate(ratio) { modHSL(this._rgb, 1, -ratio); return this; } rotate(deg) { rotate(this._rgb, deg); return this; } } function index_esm(input) { return new Color(input); } const isPatternOrGradient = (value) => value instanceof CanvasGradient || value instanceof CanvasPattern; function color(value) { return isPatternOrGradient(value) ? value : index_esm(value); } function getHoverColor(value) { return isPatternOrGradient(value) ? value : index_esm(value).saturate(0.5).darken(0.1).hexString(); } function noop() {} const uid = (function() { let id = 0; return function() { return id++; }; }()); function isNullOrUndef(value) { return value === null || typeof value === 'undefined'; } function isArray(value) { if (Array.isArray && Array.isArray(value)) { return true; } const type = Object.prototype.toString.call(value); if (type.substr(0, 7) === '[object' && type.substr(-6) === 'Array]') { return true; } return false; } function isObject(value) { return value !== null && Object.prototype.toString.call(value) === '[object Object]'; } const isNumberFinite = (value) => (typeof value === 'number' || value instanceof Number) && isFinite(+value); function finiteOrDefault(value, defaultValue) { return isNumberFinite(value) ? value : defaultValue; } function valueOrDefault(value, defaultValue) { return typeof value === 'undefined' ? defaultValue : value; } const toPercentage = (value, dimension) => typeof value === 'string' && value.endsWith('%') ? parseFloat(value) / 100 : value / dimension; const toDimension = (value, dimension) => typeof value === 'string' && value.endsWith('%') ? parseFloat(value) / 100 * dimension : +value; function callback(fn, args, thisArg) { if (fn && typeof fn.call === 'function') { return fn.apply(thisArg, args); } } function each(loopable, fn, thisArg, reverse) { let i, len, keys; if (isArray(loopable)) { len = loopable.length; if (reverse) { for (i = len - 1; i >= 0; i--) { fn.call(thisArg, loopable[i], i); } } else { for (i = 0; i < len; i++) { fn.call(thisArg, loopable[i], i); } } } else if (isObject(loopable)) { keys = Object.keys(loopable); len = keys.length; for (i = 0; i < len; i++) { fn.call(thisArg, loopable[keys[i]], keys[i]); } } } function _elementsEqual(a0, a1) { let i, ilen, v0, v1; if (!a0 || !a1 || a0.length !== a1.length) { return false; } for (i = 0, ilen = a0.length; i < ilen; ++i) { v0 = a0[i]; v1 = a1[i]; if (v0.datasetIndex !== v1.datasetIndex || v0.index !== v1.index) { return false; } } return true; } function clone(source) { if (isArray(source)) { return source.map(clone); } if (isObject(source)) { const target = Object.create(null); const keys = Object.keys(source); const klen = keys.length; let k = 0; for (; k < klen; ++k) { target[keys[k]] = clone(source[keys[k]]); } return target; } return source; } function isValidKey(key) { return ['__proto__', 'prototype', 'constructor'].indexOf(key) === -1; } function _merger(key, target, source, options) { if (!isValidKey(key)) { return; } const tval = target[key]; const sval = source[key]; if (isObject(tval) && isObject(sval)) { merge(tval, sval, options); } else { target[key] = clone(sval); } } function merge(target, source, options) { const sources = isArray(source) ? source : [source]; const ilen = sources.length; if (!isObject(target)) { return target; } options = options || {}; const merger = options.merger || _merger; for (let i = 0; i < ilen; ++i) { source = sources[i]; if (!isObject(source)) { continue; } const keys = Object.keys(source); for (let k = 0, klen = keys.length; k < klen; ++k) { merger(keys[k], target, source, options); } } return target; } function mergeIf(target, source) { return merge(target, source, {merger: _mergerIf}); } function _mergerIf(key, target, source) { if (!isValidKey(key)) { return; } const tval = target[key]; const sval = source[key]; if (isObject(tval) && isObject(sval)) { mergeIf(tval, sval); } else if (!Object.prototype.hasOwnProperty.call(target, key)) { target[key] = clone(sval); } } function _deprecated(scope, value, previous, current) { if (value !== undefined) { console.warn(scope + ': "' + previous + '" is deprecated. Please use "' + current + '" instead'); } } const emptyString = ''; const dot = '.'; function indexOfDotOrLength(key, start) { const idx = key.indexOf(dot, start); return idx === -1 ? key.length : idx; } function resolveObjectKey(obj, key) { if (key === emptyString) { return obj; } let pos = 0; let idx = indexOfDotOrLength(key, pos); while (obj && idx > pos) { obj = obj[key.substr(pos, idx - pos)]; pos = idx + 1; idx = indexOfDotOrLength(key, pos); } return obj; } function _capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } const defined = (value) => typeof value !== 'undefined'; const isFunction = (value) => typeof value === 'function'; const setsEqual = (a, b) => { if (a.size !== b.size) { return false; } for (const item of a) { if (!b.has(item)) { return false; } } return true; }; const overrides = Object.create(null); const descriptors = Object.create(null); function getScope$1(node, key) { if (!key) { return node; } const keys = key.split('.'); for (let i = 0, n = keys.length; i < n; ++i) { const k = keys[i]; node = node[k] || (node[k] = Object.create(null)); } return node; } function set(root, scope, values) { if (typeof scope === 'string') { return merge(getScope$1(root, scope), values); } return merge(getScope$1(root, ''), scope); } class Defaults { constructor(_descriptors) { this.animation = undefined; this.backgroundColor = 'rgba(0,0,0,0.1)'; this.borderColor = 'rgba(0,0,0,0.1)'; this.color = '#666'; this.datasets = {}; this.devicePixelRatio = (context) => context.chart.platform.getDevicePixelRatio(); this.elements = {}; this.events = [ 'mousemove', 'mouseout', 'click', 'touchstart', 'touchmove' ]; this.font = { family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif", size: 12, style: 'normal', lineHeight: 1.2, weight: null }; this.hover = {}; this.hoverBackgroundColor = (ctx, options) => getHoverColor(options.backgroundColor); this.hoverBorderColor = (ctx, options) => getHoverColor(options.borderColor); this.hoverColor = (ctx, options) => getHoverColor(options.color); this.indexAxis = 'x'; this.interaction = { mode: 'nearest', intersect: true }; this.maintainAspectRatio = true; this.onHover = null; this.onClick = null; this.parsing = true; this.plugins = {}; this.responsive = true; this.scale = undefined; this.scales = {}; this.showLine = true; this.describe(_descriptors); } set(scope, values) { return set(this, scope, values); } get(scope) { return getScope$1(this, scope); } describe(scope, values) { return set(descriptors, scope, values); } override(scope, values) { return set(overrides, scope, values); } route(scope, name, targetScope, targetName) { const scopeObject = getScope$1(this, scope); const targetScopeObject = getScope$1(this, targetScope); const privateName = '_' + name; Object.defineProperties(scopeObject, { [privateName]: { value: scopeObject[name], writable: true }, [name]: { enumerable: true, get() { const local = this[privateName]; const target = targetScopeObject[targetName]; if (isObject(local)) { return Object.assign({}, target, local); } return valueOrDefault(local, target); }, set(value) { this[privateName] = value; } } }); } } var defaults = new Defaults({ _scriptable: (name) => !name.startsWith('on'), _indexable: (name) => name !== 'events', hover: { _fallback: 'interaction' }, interaction: { _scriptable: false, _indexable: false, } }); const PI = Math.PI; const TAU = 2 * PI; const PITAU = TAU + PI; const INFINITY = Number.POSITIVE_INFINITY; const RAD_PER_DEG = PI / 180; const HALF_PI = PI / 2; const QUARTER_PI = PI / 4; const TWO_THIRDS_PI = PI * 2 / 3; const log10 = Math.log10; const sign = Math.sign; function niceNum(range) { const roundedRange = Math.round(range); range = almostEquals(range, roundedRange, range / 1000) ? roundedRange : range; const niceRange = Math.pow(10, Math.floor(log10(range))); const fraction = range / niceRange; const niceFraction = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10; return niceFraction * niceRange; } function _factorize(value) { const result = []; const sqrt = Math.sqrt(value); let i; for (i = 1; i < sqrt; i++) { if (value % i === 0) { result.push(i); result.push(value / i); } } if (sqrt === (sqrt | 0)) { result.push(sqrt); } result.sort((a, b) => a - b).pop(); return result; } function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function almostEquals(x, y, epsilon) { return Math.abs(x - y) < epsilon; } function almostWhole(x, epsilon) { const rounded = Math.round(x); return ((rounded - epsilon) <= x) && ((rounded + epsilon) >= x); } function _setMinAndMaxByKey(array, target, property) { let i, ilen, value; for (i = 0, ilen = array.length; i < ilen; i++) { value = array[i][property]; if (!isNaN(value)) { target.min = Math.min(target.min, value); target.max = Math.max(target.max, value); } } } function toRadians(degrees) { return degrees * (PI / 180); } function toDegrees(radians) { return radians * (180 / PI); } function _decimalPlaces(x) { if (!isNumberFinite(x)) { return; } let e = 1; let p = 0; while (Math.round(x * e) / e !== x) { e *= 10; p++; } return p; } function getAngleFromPoint(centrePoint, anglePoint) { const distanceFromXCenter = anglePoint.x - centrePoint.x; const distanceFromYCenter = anglePoint.y - centrePoint.y; const radialDistanceFromCenter = Math.sqrt(distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter); let angle = Math.atan2(distanceFromYCenter, distanceFromXCenter); if (angle < (-0.5 * PI)) { angle += TAU; } return { angle, distance: radialDistanceFromCenter }; } function distanceBetweenPoints(pt1, pt2) { return Math.sqrt(Math.pow(pt2.x - pt1.x, 2) + Math.pow(pt2.y - pt1.y, 2)); } function _angleDiff(a, b) { return (a - b + PITAU) % TAU - PI; } function _normalizeAngle(a) { return (a % TAU + TAU) % TAU; } function _angleBetween(angle, start, end, sameAngleIsFullCircle) { const a = _normalizeAngle(angle); const s = _normalizeAngle(start); const e = _normalizeAngle(end); const angleToStart = _normalizeAngle(s - a); const angleToEnd = _normalizeAngle(e - a); const startToAngle = _normalizeAngle(a - s); const endToAngle = _normalizeAngle(a - e); return a === s || a === e || (sameAngleIsFullCircle && s === e) || (angleToStart > angleToEnd && startToAngle < endToAngle); } function _limitValue(value, min, max) { return Math.max(min, Math.min(max, value)); } function _int16Range(value) { return _limitValue(value, -32768, 32767); } function _isBetween(value, start, end, epsilon = 1e-6) { return value >= Math.min(start, end) - epsilon && value <= Math.max(start, end) + epsilon; } function toFontString(font) { if (!font || isNullOrUndef(font.size) || isNullOrUndef(font.family)) { return null; } return (font.style ? font.style + ' ' : '') + (font.weight ? font.weight + ' ' : '') + font.size + 'px ' + font.family; } function _measureText(ctx, data, gc, longest, string) { let textWidth = data[string]; if (!textWidth) { textWidth = data[string] = ctx.measureText(string).width; gc.push(string); } if (textWidth > longest) { longest = textWidth; } return longest; } function _longestText(ctx, font, arrayOfThings, cache) { cache = cache || {}; let data = cache.data = cache.data || {}; let gc = cache.garbageCollect = cache.garbageCollect || []; if (cache.font !== font) { data = cache.data = {}; gc = cache.garbageCollect = []; cache.font = font; } ctx.save(); ctx.font = font; let longest = 0; const ilen = arrayOfThings.length; let i, j, jlen, thing, nestedThing; for (i = 0; i < ilen; i++) { thing = arrayOfThings[i]; if (thing !== undefined && thing !== null && isArray(thing) !== true) { longest = _measureText(ctx, data, gc, longest, thing); } else if (isArray(thing)) { for (j = 0, jlen = thing.length; j < jlen; j++) { nestedThing = thing[j]; if (nestedThing !== undefined && nestedThing !== null && !isArray(nestedThing)) { longest = _measureText(ctx, data, gc, longest, nestedThing); } } } } ctx.restore(); const gcLen = gc.length / 2; if (gcLen > arrayOfThings.length) { for (i = 0; i < gcLen; i++) { delete data[gc[i]]; } gc.splice(0, gcLen); } return longest; } function _alignPixel(chart, pixel, width) { const devicePixelRatio = chart.currentDevicePixelRatio; const halfWidth = width !== 0 ? Math.max(width / 2, 0.5) : 0; return Math.round((pixel - halfWidth) * devicePixelRatio) / devicePixelRatio + halfWidth; } function clearCanvas(canvas, ctx) { ctx = ctx || canvas.getContext('2d'); ctx.save(); ctx.resetTransform(); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.restore(); } function drawPoint(ctx, options, x, y) { let type, xOffset, yOffset, size, cornerRadius; const style = options.pointStyle; const rotation = options.rotation; const radius = options.radius; let rad = (rotation || 0) * RAD_PER_DEG; if (style && typeof style === 'object') { type = style.toString(); if (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]') { ctx.save(); ctx.translate(x, y); ctx.rotate(rad); ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height); ctx.restore(); return; } } if (isNaN(radius) || radius <= 0) { return; } ctx.beginPath(); switch (style) { default: ctx.arc(x, y, radius, 0, TAU); ctx.closePath(); break; case 'triangle': ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius); rad += TWO_THIRDS_PI; ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius); rad += TWO_THIRDS_PI; ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius); ctx.closePath(); break; case 'rectRounded': cornerRadius = radius * 0.516; size = radius - cornerRadius; xOffset = Math.cos(rad + QUARTER_PI) * size; yOffset = Math.sin(rad + QUARTER_PI) * size; ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI); ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad); ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI); ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI); ctx.closePath(); break; case 'rect': if (!rotation) { size = Math.SQRT1_2 * radius; ctx.rect(x - size, y - size, 2 * size, 2 * size); break; } rad += QUARTER_PI; case 'rectRot': xOffset = Math.cos(rad) * radius; yOffset = Math.sin(rad) * radius; ctx.moveTo(x - xOffset, y - yOffset); ctx.lineTo(x + yOffset, y - xOffset); ctx.lineTo(x + xOffset, y + yOffset); ctx.lineTo(x - yOffset, y + xOffset); ctx.closePath(); break; case 'crossRot': rad += QUARTER_PI; case 'cross': xOffset = Math.cos(rad) * radius; yOffset = Math.sin(rad) * radius; ctx.moveTo(x - xOffset, y - yOffset); ctx.lineTo(x + xOffset, y + yOffset); ctx.moveTo(x + yOffset, y - xOffset); ctx.lineTo(x - yOffset, y + xOffset); break; case 'star': xOffset = Math.cos(rad) * radius; yOffset = Math.sin(rad) * radius; ctx.moveTo(x - xOffset, y - yOffset); ctx.lineTo(x + xOffset, y + yOffset); ctx.moveTo(x + yOffset, y - xOffset); ctx.lineTo(x - yOffset, y + xOffset); rad += QUARTER_PI; xOffset = Math.cos(rad) * radius; yOffset = Math.sin(rad) * radius; ctx.moveTo(x - xOffset, y - yOffset); ctx.lineTo(x + xOffset, y + yOffset); ctx.moveTo(x + yOffset, y - xOffset); ctx.lineTo(x - yOffset, y + xOffset); break; case 'line': xOffset = Math.cos(rad) * radius; yOffset = Math.sin(rad) * radius; ctx.moveTo(x - xOffset, y - yOffset); ctx.lineTo(x + xOffset, y + yOffset); break; case 'dash': ctx.moveTo(x, y); ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius); break; } ctx.fill(); if (options.borderWidth > 0) { ctx.stroke(); } } function _isPointInArea(point, area, margin) { margin = margin || 0.5; return !area || (point && point.x > area.left - margin && point.x < area.right + margin && point.y > area.top - margin && point.y < area.bottom + margin); } function clipArea(ctx, area) { ctx.save(); ctx.beginPath(); ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top); ctx.clip(); } function unclipArea(ctx) { ctx.restore(); } function _steppedLineTo(ctx, previous, target, flip, mode) { if (!previous) { return ctx.lineTo(target.x, target.y); } if (mode === 'middle') { const midpoint = (previous.x + target.x) / 2.0; ctx.lineTo(midpoint, previous.y); ctx.lineTo(midpoint, target.y); } else if (mode === 'after' !== !!flip) { ctx.lineTo(previous.x, target.y); } else { ctx.lineTo(target.x, previous.y); } ctx.lineTo(target.x, target.y); } function _bezierCurveTo(ctx, previous, target, flip) { if (!previous) { return ctx.lineTo(target.x, target.y); } ctx.bezierCurveTo( flip ? previous.cp1x : previous.cp2x, flip ? previous.cp1y : previous.cp2y, flip ? target.cp2x : target.cp1x, flip ? target.cp2y : target.cp1y, target.x, target.y); } function renderText(ctx, text, x, y, font, opts = {}) { const lines = isArray(text) ? text : [text]; const stroke = opts.strokeWidth > 0 && opts.strokeColor !== ''; let i, line; ctx.save(); ctx.font = font.string; setRenderOpts(ctx, opts); for (i = 0; i < lines.length; ++i) { line = lines[i]; if (stroke) { if (opts.strokeColor) { ctx.strokeStyle = opts.strokeColor; } if (!isNullOrUndef(opts.strokeWidth)) { ctx.lineWidth = opts.strokeWidth; } ctx.strokeText(line, x, y, opts.maxWidth); } ctx.fillText(line, x, y, opts.maxWidth); decorateText(ctx, x, y, line, opts); y += font.lineHeight; } ctx.restore(); } function setRenderOpts(ctx, opts) { if (opts.translation) { ctx.translate(opts.translation[0], opts.translation[1]); } if (!isNullOrUndef(opts.rotation)) { ctx.rotate(opts.rotation); } if (opts.color) { ctx.fillStyle = opts.color; } if (opts.textAlign) { ctx.textAlign = opts.textAlign; } if (opts.textBaseline) { ctx.textBaseline = opts.textBaseline; } } function decorateText(ctx, x, y, line, opts) { if (opts.strikethrough || opts.underline) { const metrics = ctx.measureText(line); const left = x - metrics.actualBoundingBoxLeft; const right = x + metrics.actualBoundingBoxRight; const top = y - metrics.actualBoundingBoxAscent; const bottom = y + metrics.actualBoundingBoxDescent; const yDecoration = opts.strikethrough ? (top + bottom) / 2 : bottom; ctx.strokeStyle = ctx.fillStyle; ctx.beginPath(); ctx.lineWidth = opts.decorationWidth || 2; ctx.moveTo(left, yDecoration); ctx.lineTo(right, yDecoration); ctx.stroke(); } } function addRoundedRectPath(ctx, rect) { const {x, y, w, h, radius} = rect; ctx.arc(x + radius.topLeft, y + radius.topLeft, radius.topLeft, -HALF_PI, PI, true); ctx.lineTo(x, y + h - radius.bottomLeft); ctx.arc(x + radius.bottomLeft, y + h - radius.bottomLeft, radius.bottomLeft, PI, HALF_PI, true); ctx.lineTo(x + w - radius.bottomRight, y + h); ctx.arc(x + w - radius.bottomRight, y + h - radius.bottomRight, radius.bottomRight, HALF_PI, 0, true); ctx.lineTo(x + w, y + radius.topRight); ctx.arc(x + w - radius.topRight, y + radius.topRight, radius.topRight, 0, -HALF_PI, true); ctx.lineTo(x + radius.topLeft, y); } function _lookup(table, value, cmp) { cmp = cmp || ((index) => table[index] < value); let hi = table.length - 1; let lo = 0; let mid; while (hi - lo > 1) { mid = (lo + hi) >> 1; if (cmp(mid)) { lo = mid; } else { hi = mid; } } return {lo, hi}; } const _lookupByKey = (table, key, value) => _lookup(table, value, index => table[index][key] < value); const _rlookupByKey = (table, key, value) => _lookup(table, value, index => table[index][key] >= value); function _filterBetween(values, min, max) { let start = 0; let end = values.length; while (start < end && values[start] < min) { start++; } while (end > start && values[end - 1] > max) { end--; } return start > 0 || end < values.length ? values.slice(start, end) : values; } const arrayEvents = ['push', 'pop', 'shift', 'splice', 'unshift']; function listenArrayEvents(array, listener) { if (array._chartjs) { array._chartjs.listeners.push(listener); return; } Object.defineProperty(array, '_chartjs', { configurable: true, enumerable: false, value: { listeners: [listener] } }); arrayEvents.forEach((key) => { const method = '_onData' + _capitalize(key); const base = array[key]; Object.defineProperty(array, key, { configurable: true, enumerable: false, value(...args) { const res = base.apply(this, args); array._chartjs.listeners.forEach((object) => { if (typeof object[method] === 'function') { object[method](...args); } }); return res; } }); }); } function unlistenArrayEvents(array, listener) { const stub = array._chartjs; if (!stub) { return; } const listeners = stub.listeners; const index = listeners.indexOf(listener); if (index !== -1) { listeners.splice(index, 1); } if (listeners.length > 0) { return; } arrayEvents.forEach((key) => { delete array[key]; }); delete array._chartjs; } function _arrayUnique(items) { const set = new Set(); let i, ilen; for (i = 0, ilen = items.length; i < ilen; ++i) { set.add(items[i]); } if (set.size === ilen) { return items; } return Array.from(set); } function _isDomSupported() { return typeof window !== 'undefined' && typeof document !== 'undefined'; } function _getParentNode(domNode) { let parent = domNode.parentNode; if (parent && parent.toString() === '[object ShadowRoot]') { parent = parent.host; } return parent; } function parseMaxStyle(styleValue, node, parentProperty) { let valueInPixels; if (typeof styleValue === 'string') { valueInPixels = parseInt(styleValue, 10); if (styleValue.indexOf('%') !== -1) { valueInPixels = valueInPixels / 100 * node.parentNode[parentProperty]; } } else { valueInPixels = styleValue; } return valueInPixels; } const getComputedStyle = (element) => window.getComputedStyle(element, null); function getStyle(el, property) { return getComputedStyle(el).getPropertyValue(property); } const positions = ['top', 'right', 'bottom', 'left']; function getPositionedStyle(styles, style, suffix) { const result = {}; suffix = suffix ? '-' + suffix : ''; for (let i = 0; i < 4; i++) { const pos = positions[i]; result[pos] = parseFloat(styles[style + '-' + pos + suffix]) || 0; } result.width = result.left + result.right; result.height = result.top + result.bottom; return result; } const useOffsetPos = (x, y, target) => (x > 0 || y > 0) && (!target || !target.shadowRoot); function getCanvasPosition(evt, canvas) { const e = evt.native || evt; const touches = e.touches; const source = touches && touches.length ? touches[0] : e; const {offsetX, offsetY} = source; let box = false; let x, y; if (useOffsetPos(offsetX, offsetY, e.target)) { x = offsetX; y = offsetY; } else { const rect = canvas.getBoundingClientRect(); x = source.clientX - rect.left; y = source.clientY - rect.top; box = true; } return {x, y, box}; } function getRelativePosition$1(evt, chart) { const {canvas, currentDevicePixelRatio} = chart; const style = getComputedStyle(canvas); const borderBox = style.boxSizing === 'border-box'; const paddings = getPositionedStyle(style, 'padding'); const borders = getPositionedStyle(style, 'border', 'width'); const {x, y, box} = getCanvasPosition(evt, canvas); const xOffset = paddings.left + (box && borders.left); const yOffset = paddings.top + (box && borders.top); let {width, height} = chart; if (borderBox) { width -= paddings.width + borders.width; height -= paddings.height + borders.height; } return { x: Math.round((x - xOffset) / width * canvas.width / currentDevicePixelRatio), y: Math.round((y - yOffset) / height * canvas.height / currentDevicePixelRatio) }; } function getContainerSize(canvas, width, height) { let maxWidth, maxHeight; if (width === undefined || height === undefined) { const container = _getParentNode(canvas); if (!container) { width = canvas.clientWidth; height = canvas.clientHeight; } else { const rect = container.getBoundingClientRect(); const containerStyle = getComputedStyle(container); const containerBorder = getPositionedStyle(containerStyle, 'border', 'width'); const containerPadding = getPositionedStyle(containerStyle, 'padding'); width = rect.width - containerPadding.width - containerBorder.width; height = rect.height - containerPadding.height - containerBorder.height; maxWidth = parseMaxStyle(containerStyle.maxWidth, container, 'clientWidth'); maxHeight = parseMaxStyle(containerStyle.maxHeight, container, 'clientHeight'); } } return { width, height, maxWidth: maxWidth || INFINITY, maxHeight: maxHeight || INFINITY }; } const round1 = v => Math.round(v * 10) / 10; function getMaximumSize(canvas, bbWidth, bbHeight, aspectRatio) { const style = getComputedStyle(canvas); const margins = getPositionedStyle(style, 'margin'); const maxWidth = parseMaxStyle(style.maxWidth, canvas, 'clientWidth') || INFINITY; const maxHeight = parseMaxStyle(style.maxHeight, canvas, 'clientHeight') || INFINITY; const containerSize = getContainerSize(canvas, bbWidth, bbHeight); let {width, height} = containerSize; if (style.boxSizing === 'content-box') { const borders = getPositionedStyle(style, 'border', 'width'); const paddings = getPositionedStyle(style, 'padding'); width -= paddings.width + borders.width; height -= paddings.height + borders.height; } width = Math.max(0, width - margins.width); height = Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height - margins.height); width = round1(Math.min(width, maxWidth, containerSize.maxWidth)); height = round1(Math.min(height, maxHeight, containerSize.maxHeight)); if (width && !height) { height = round1(width / 2); } return { width, height }; } function retinaScale(chart, forceRatio, forceStyle) { const pixelRatio = forceRatio || 1; const deviceHeight = Math.floor(chart.height * pixelRatio); const deviceWidth = Math.floor(chart.width * pixelRatio); chart.height = deviceHeight / pixelRatio; chart.width = deviceWidth / pixelRatio; const canvas = chart.canvas; if (canvas.style && (forceStyle || (!canvas.style.height && !canvas.style.width))) { canvas.style.height = `${chart.height}px`; canvas.style.width = `${chart.width}px`; } if (chart.currentDevicePixelRatio !== pixelRatio || canvas.height !== deviceHeight || canvas.width !== deviceWidth) { chart.currentDevicePixelRatio = pixelRatio; canvas.height = deviceHeight; canvas.width = deviceWidth; chart.ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); return true; } return false; } const supportsEventListenerOptions = (function() { let passiveSupported = false; try { const options = { get passive() { passiveSupported = true; return false; } }; window.addEventListener('test', null, options); window.removeEventListener('test', null, options); } catch (e) { } return passiveSupported; }()); function readUsedSize(element, property) { const value = getStyle(element, property); const matches = value && value.match(/^(\d+)(\.\d+)?px$/); return matches ? +matches[1] : undefined; } function getRelativePosition(e, chart) { if ('native' in e) { return { x: e.x, y: e.y }; } return getRelativePosition$1(e, chart); } function evaluateAllVisibleItems(chart, handler) { const metasets = chart.getSortedVisibleDatasetMetas(); let index, data, element; for (let i = 0, ilen = metasets.length; i < ilen; ++i) { ({index, data} = metasets[i]); for (let j = 0, jlen = data.length; j < jlen; ++j) { element = data[j]; if (!element.skip) { handler(element, index, j); } } } } function binarySearch(metaset, axis, value, intersect) { const {controller, data, _sorted} = metaset; const iScale = controller._cachedMeta.iScale; if (iScale && axis === iScale.axis && _sorted && data.length) { const lookupMethod = iScale._reversePixels ? _rlookupByKey : _lookupByKey; if (!intersect) { return lookupMethod(data, axis, value); } else if (controller._sharedOptions) { const el = data[0]; const range = typeof el.getRange === 'function' && el.getRange(axis); if (range) { const start = lookupMethod(data, axis, value - range); const end = lookupMethod(data, axis, value + range); return {lo: start.lo, hi: end.hi}; } } } return {lo: 0, hi: data.length - 1}; } function optimizedEvaluateItems(chart, axis, position, handler, intersect) { const metasets = chart.getSortedVisibleDatasetMetas(); const value = position[axis]; for (let i = 0, ilen = metasets.length; i < ilen; ++i) { const {index, data} = metasets[i]; const {lo, hi} = binarySearch(metasets[i], axis, value, intersect); for (let j = lo; j <= hi; ++j) { const element = data[j]; if (!element.skip) { handler(element, index, j); } } } } function getDistanceMetricForAxis(axis) { const useX = axis.indexOf('x') !== -1; const useY = axis.indexOf('y') !== -1; return function(pt1, pt2) { const deltaX = useX ? Math.abs(pt1.x - pt2.x) : 0; const deltaY = useY ? Math.abs(pt1.y - pt2.y) : 0; return Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)); }; } function getIntersectItems(chart, position, axis, useFinalPosition) { const items = []; if (!_isPointInArea(position, chart.chartArea, chart._minPadding)) { return items; } const evaluationFunc = function(element, datasetIndex, index) { if (element.inRange(position.x, position.y, useFinalPosition)) { items.push({element, datasetIndex, index}); } }; optimizedEvaluateItems(chart, axis, position, evaluationFunc, true); return items; } function getNearestItems(chart, position, axis, intersect, useFinalPosition) { const distanceMetric = getDistanceMetricForAxis(axis); let minDistance = Number.POSITIVE_INFINITY; let items = []; if (!_isPointInArea(position, chart.chartArea, chart._minPadding)) { return items; } const evaluationFunc = function(element, datasetIndex, index) { if (intersect && !element.inRange(position.x, position.y, useFinalPosition)) { return; } const center = element.getCenterPoint(useFinalPosition); if (!_isPointInArea(center, chart.chartArea, chart._minPadding) && !element.inRange(position.x, position.y, useFinalPosition)) { return; } const distance = distanceMetric(position, center); if (distance < minDistance) { items = [{element, datasetIndex, index}]; minDistance = distance; } else if (distance === minDistance) { items.push({element, datasetIndex, index}); } }; optimizedEvaluateItems(chart, axis, position, evaluationFunc); return items; } function getAxisItems(chart, e, options, useFinalPosition) { const position = getRelativePosition(e, chart); const items = []; const axis = options.axis; const rangeMethod = axis === 'x' ? 'inXRange' : 'inYRange'; let intersectsItem = false; evaluateAllVisibleItems(chart, (element, datasetIndex, index) => { if (element[rangeMethod](position[axis], useFinalPosition)) { items.push({element, datasetIndex, index}); } if (element.inRange(position.x, position.y, useFinalPosition)) { intersectsItem = true; } }); if (options.intersect && !intersectsItem) { return []; } return items; } var Interaction = { modes: { index(chart, e, options, useFinalPosition) { const position = getRelativePosition(e, chart); const axis = options.axis || 'x'; const items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition) : getNearestItems(chart, position, axis, false, useFinalPosition); const elements = []; if (!items.length) { return []; } chart.getSortedVisibleDatasetMetas().forEach((meta) => { const index = items[0].index; const element = meta.data[index]; if (element && !element.skip) { elements.push({element, datasetIndex: meta.index, index}); } }); return elements; }, dataset(chart, e, options, useFinalPosition) { const position = getRelativePosition(e, chart); const axis = options.axis || 'xy'; let items = options.intersect ? getIntersectItems(chart, position, axis, useFinalPosition) : getNearestItems(chart, position, axis, false, useFinalPosition); if (items.length > 0) { const datasetIndex = items[0].datasetIndex; const data = chart.getDatasetMeta(datasetIndex).data; items = []; for (let i = 0; i < data.length; ++i) { items.push({element: data[i], datasetIndex, index: i}); } } return items; }, point(chart, e, options, useFinalPosition) { const position = getRelativePosition(e, chart); const axis = options.axis || 'xy'; return getIntersectItems(chart, position, axis, useFinalPosition); }, nearest(chart, e, options, useFinalPosition) { const position = getRelativePosition(e, chart); const axis = options.axis || 'xy'; return getNearestItems(chart, position, axis, options.intersect, useFinalPosition); }, x(chart, e, options, useFinalPosition) { return getAxisItems(chart, e, {axis: 'x', intersect: options.intersect}, useFinalPosition); }, y(chart, e, options, useFinalPosition) { return getAxisItems(chart, e, {axis: 'y', intersect: options.intersect}, useFinalPosition); } } }; const LINE_HEIGHT = new RegExp(/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/); const FONT_STYLE = new RegExp(/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/); function toLineHeight(value, size) { const matches = ('' + value).match(LINE_HEIGHT); if (!matches || matches[1] === 'normal') { return size * 1.2; } value = +matches[2]; switch (matches[3]) { case 'px': return value; case '%': value /= 100; break; } return size * value; } const numberOrZero$1 = v => +v || 0; function _readValueToProps(value, props) { const ret = {}; const objProps = isObject(props); const keys = objProps ? Object.keys(props) : props; const read = isObject(value) ? objProps ? prop => valueOrDefault(value[prop], value[props[prop]]) : prop => value[prop] : () => value; for (const prop of keys) { ret[prop] = numberOrZero$1(read(prop)); } return ret; } function toTRBL(value) { return _readValueToProps(value, {top: 'y', right: 'x', bottom: 'y', left: 'x'}); } function toTRBLCorners(value) { return _readValueToProps(value, ['topLeft', 'topRight', 'bottomLeft', 'bottomRight']); } function toPadding(value) { const obj = toTRBL(value); obj.width = obj.left + obj.right; obj.height = obj.top + obj.bottom; return obj; } function toFont(options, fallback) { options = options || {}; fallback = fallback || defaults.font; let size = valueOrDefault(options.size, fallback.size); if (typeof size === 'string') { size = parseInt(size, 10); } let style = valueOrDefault(options.style, fallback.style); if (style && !('' + style).match(FONT_STYLE)) { console.warn('Invalid font style specified: "' + style + '"'); style = ''; } const font = { family: valueOrDefault(options.family, fallback.family), lineHeight: toLineHeight(valueOrDefault(options.lineHeight, fallback.lineHeight), size), size, style, weight: valueOrDefault(options.weight, fallback.weight), string: '' }; font.string = toFontString(font); return font; } function resolve(inputs, context, index, info) { let cacheable = true; let i, ilen, value; for (i = 0, ilen = inputs.length; i < ilen; ++i) { value = inputs[i]; if (value === undefined) { continue; } if (context !== undefined && typeof value === 'function') { value = value(context); cacheable = false; } if (index !== undefined && isArray(value)) { value = value[index % value.length]; cacheable = false; } if (value !== undefined) { if (info && !cacheable) { info.cacheable = false; } return value; } } } function _addGrace(minmax, grace, beginAtZero) { const {min, max} = minmax; const change = toDimension(grace, (max - min) / 2); const keepZero = (value, add) => beginAtZero && value === 0 ? 0 : value + add; return { min: keepZero(min, -Math.abs(change)), max: keepZero(max, change) }; } function createContext(parentContext, context) { return Object.assign(Object.create(parentContext), context); } const STATIC_POSITIONS = ['left', 'top', 'right', 'bottom']; function filterByPosition(array, position) { return array.filter(v => v.pos === position); } function filterDynamicPositionByAxis(array, axis) { return array.filter(v => STATIC_POSITIONS.indexOf(v.pos) === -1 && v.box.axis === axis); } function sortByWeight(array, reverse) { return array.sort((a, b) => { const v0 = reverse ? b : a; const v1 = reverse ? a : b; return v0.weight === v1.weight ? v0.index - v1.index : v0.weight - v1.weight; }); } function wrapBoxes(boxes) { const layoutBoxes = []; let i, ilen, box, pos, stack, stackWeight; for (i = 0, ilen = (boxes || []).length; i < ilen; ++i) { box = boxes[i]; ({position: pos, options: {stack, stackWeight = 1}} = box); layoutBoxes.push({ index: i, box, pos, horizontal: box.isHorizontal(), weight: box.weight, stack: stack && (pos + stack), stackWeight }); } return layoutBoxes; } function buildStacks(layouts) { const stacks = {}; for (const wrap of layouts) { const {stack, pos, stackWeight} = wrap; if (!stack || !STATIC_POSITIONS.includes(pos)) { continue; } const _stack = stacks[stack] || (stacks[stack] = {count: 0, placed: 0, weight: 0, size: 0}); _stack.count++; _stack.weight += stackWeight; } return stacks; } function setLayoutDims(layouts, params) { const stacks = buildStacks(layouts); const {vBoxMaxWidth, hBoxMaxHeight} = params; let i, ilen, layout; for (i = 0, ilen = layouts.length; i < ilen; ++i) { layout = layouts[i]; const {fullSize} = layout.box; const stack = stacks[layout.stack]; const factor = stack && layout.stackWeight / stack.weight; if (layout.horizontal) { layout.width = factor ? factor * vBoxMaxWidth : fullSize && params.availableWidth; layout.height = hBoxMaxHeight; } else { layout.width = vBoxMaxWidth; layout.height = factor ? factor * hBoxMaxHeight : fullSize && params.availableHeight; } } return stacks; } function buildLayoutBoxes(boxes) { const layoutBoxes = wrapBoxes(boxes); const fullSize = sortByWeight(layoutBoxes.filter(wrap => wrap.box.fullSize), true); const left = sortByWeight(filterByPosition(layoutBoxes, 'left'), true); const right = sortByWeight(filterByPosition(layoutBoxes, 'right')); const top = sortByWeight(filterByPosition(layoutBoxes, 'top'), true); const bottom = sortByWeight(filterByPosition(layoutBoxes, 'bottom')); const centerHorizontal = filterDynamicPositionByAxis(layoutBoxes, 'x'); const centerVertical = filterDynamicPositionByAxis(layoutBoxes, 'y'); return { fullSize, leftAndTop: left.concat(top), rightAndBottom: right.concat(centerVertical).concat(bottom).concat(centerHorizontal), chartArea: filterByPosition(layoutBoxes, 'chartArea'), vertical: left.concat(right).concat(centerVertical), horizontal: top.concat(bottom).concat(centerHorizontal) }; } function getCombinedMax(maxPadding, chartArea, a, b) { return Math.max(maxPadding[a], chartArea[a]) + Math.max(maxPadding[b], chartArea[b]); } function updateMaxPadding(maxPadding, boxPadding) { maxPadding.top = Math.max(maxPadding.top, boxPadding.top); maxPadding.left = Math.max(maxPadding.left, boxPadding.left); maxPadding.bottom = Math.max(maxPadding.bottom, boxPadding.bottom); maxPadding.right = Math.max(maxPadding.right, boxPadding.right); } function updateDims(chartArea, params, layout, stacks) { const {pos, box} = layout; const maxPadding = chartArea.maxPadding; if (!isObject(pos)) { if (layout.size) { chartArea[pos] -= layout.size; } const stack = stacks[layout.stack] || {size: 0, count: 1}; stack.size = Math.max(stack.size, layout.horizontal ? box.height : box.width); layout.size = stack.size / stack.count; chartArea[pos] += layout.size; } if (box.getPadding) { updateMaxPadding(maxPadding, box.getPadding()); } const newWidth = Math.max(0, params.outerWidth - getCombinedMax(maxPadding, chartArea, 'left', 'right')); const newHeight = Math.max(0, params.outerHeight - getCombinedMax(maxPadding, chartArea, 'top', 'bottom')); const widthChanged = newWidth !== chartArea.w; const heightChanged = newHeight !== chartArea.h; chartArea.w = newWidth; chartArea.h = newHeight; return layout.horizontal ? {same: widthChanged, other: heightChanged} : {same: heightChanged, other: widthChanged}; } function handleMaxPadding(chartArea) { const maxPadding = chartArea.maxPadding; function updatePos(pos) { const change = Math.max(maxPadding[pos] - chartArea[pos], 0); chartArea[pos] += change; return change; } chartArea.y += updatePos('top'); chartArea.x += updatePos('left'); updatePos('right'); updatePos('bottom'); } function getMargins(horizontal, chartArea) { const maxPadding = chartArea.maxPadding; function marginForPositions(positions) { const margin = {left: 0, top: 0, right: 0, bottom: 0}; positions.forEach((pos) => { margin[pos] = Math.max(chartArea[pos], maxPadding[pos]); }); return margin; } return horizontal ? marginForPositions(['left', 'right']) : marginForPositions(['top', 'bottom']); } function fitBoxes(boxes, chartArea, params, stacks) { const refitBoxes = []; let i, ilen, layout, box, refit, changed; for (i = 0, ilen = boxes.length, refit = 0; i < ilen; ++i) { layout = boxes[i]; box = layout.box; box.update( layout.width || chartArea.w, layout.height || chartArea.h, getMargins(layout.horizontal, chartArea) ); const {same, other} = updateDims(chartArea, params, layout, stacks); refit |= same && refitBoxes.length; changed = changed || other; if (!box.fullSize) { refitBoxes.push(layout); } } return refit && fitBoxes(refitBoxes, chartArea, params, stacks) || changed; } function setBoxDims(box, left, top, width, height) { box.top = top; box.left = left; box.right = left + width; box.bottom = top + height; box.width = width; box.height = height; } function placeBoxes(boxes, chartArea, params, stacks) { const userPadding = params.padding; let {x, y} = chartArea; for (const layout of boxes) { const box = layout.box; const stack = stacks[layout.stack] || {count: 1, placed: 0, weight: 1}; const weight = (layout.stackWeight / stack.weight) || 1; if (layout.horizontal) { const width = chartArea.w * weight; const height = stack.size || box.height; if (defined(stack.start)) { y = stack.start; } if (box.fullSize) { setBoxDims(box, userPadding.left, y, params.outerWidth - userPadding.right - userPadding.left, height); } else { setBoxDims(box, chartArea.left + stack.placed, y, width, height); } stack.start = y; stack.placed += width; y = box.bottom; } else { const height = chartArea.h * weight; const width = stack.size || box.width; if (defined(stack.start)) { x = stack.start; } if (box.fullSize) { setBoxDims(box, x, userPadding.top, width, params.outerHeight - userPadding.bottom - userPadding.top); } else { setBoxDims(box, x, chartArea.top + stack.placed, width, height); } stack.start = x; stack.placed += height; x = box.right; } } chartArea.x = x; chartArea.y = y; } defaults.set('layout', { autoPadding: true, padding: { top: 0, right: 0, bottom: 0, left: 0 } }); var layouts = { addBox(chart, item) { if (!chart.boxes) { chart.boxes = []; } item.fullSize = item.fullSize || false; item.position = item.position || 'top'; item.weight = item.weight || 0; item._layers = item._layers || function() { return [{ z: 0, draw(chartArea) { item.draw(chartArea); } }]; }; chart.boxes.push(item); }, removeBox(chart, layoutItem) { const index = chart.boxes ? chart.boxes.indexOf(layoutItem) : -1; if (index !== -1) { chart.boxes.splice(index, 1); } }, configure(chart, item, options) { item.fullSize = options.fullSize; item.position = options.position; item.weight = options.weight; }, update(chart, width, height, minPadding) { if (!chart) { return; } const padding = toPadding(chart.options.layout.padding); const availableWidth = Math.max(width - padding.width, 0); const availableHeight = Math.max(height - padding.height, 0); const boxes = buildLayoutBoxes(chart.boxes); const verticalBoxes = boxes.vertical; const horizontalBoxes = boxes.horizontal; each(chart.boxes, box => { if (typeof box.beforeLayout === 'function') { box.beforeLayout(); } }); const visibleVerticalBoxCount = verticalBoxes.reduce((total, wrap) => wrap.box.options && wrap.box.options.display === false ? total : total + 1, 0) || 1; const params = Object.freeze({ outerWidth: width, outerHeight: height, padding, availableWidth, availableHeight, vBoxMaxWidth: availableWidth / 2 / visibleVerticalBoxCount, hBoxMaxHeight: availableHeight / 2 }); const maxPadding = Object.assign({}, padding); updateMaxPadding(maxPadding, toPadding(minPadding)); const chartArea = Object.assign({ maxPadding, w: availableWidth, h: availableHeight, x: padding.left, y: padding.top }, padding); const stacks = setLayoutDims(verticalBoxes.concat(horizontalBoxes), params); fitBoxes(boxes.fullSize, chartArea, params, stacks); fitBoxes(verticalBoxes, chartArea, params, stacks); if (fitBoxes(horizontalBoxes, chartArea, params, stacks)) { fitBoxes(verticalBoxes, chartArea, params, stacks); } handleMaxPadding(chartArea); placeBoxes(boxes.leftAndTop, chartArea, params, stacks); chartArea.x += chartArea.w; chartArea.y += chartArea.h; placeBoxes(boxes.rightAndBottom, chartArea, params, stacks); chart.chartArea = { left: chartArea.left, top: chartArea.top, right: chartArea.left + chartArea.w, bottom: chartArea.top + chartArea.h, height: chartArea.h, width: chartArea.w, }; each(boxes.chartArea, (layout) => { const box = layout.box; Object.assign(box, chart.chartArea); box.update(chartArea.w, chartArea.h, {left: 0, top: 0, right: 0, bottom: 0}); }); } }; function _createResolver(scopes, prefixes = [''], rootScopes = scopes, fallback, getTarget = () => scopes[0]) { if (!defined(fallback)) { fallback = _resolve('_fallback', scopes); } const cache = { [Symbol.toStringTag]: 'Object', _cacheable: true, _scopes: scopes, _rootScopes: rootScopes, _fallback: fallback, _getTarget: getTarget, override: (scope) => _createResolver([scope, ...scopes], prefixes, rootScopes, fallback), }; return new Proxy(cache, { deleteProperty(target, prop) { delete target[prop]; delete target._keys; delete scopes[0][prop]; return true; }, get(target, prop) { return _cached(target, prop, () => _resolveWithPrefixes(prop, prefixes, scopes, target)); }, getOwnPropertyDescriptor(target, prop) { return Reflect.getOwnPropertyDescriptor(target._scopes[0], prop); }, getPrototypeOf() { return Reflect.getPrototypeOf(scopes[0]); }, has(target, prop) { return getKeysFromAllScopes(target).includes(prop); }, ownKeys(target) { return getKeysFromAllScopes(target); }, set(target, prop, value) { const storage = target._storage || (target._storage = getTarget()); target[prop] = storage[prop] = value; delete target._keys; return true; } }); } function _attachContext(proxy, context, subProxy, descriptorDefaults) { const cache = { _cacheable: false, _proxy: proxy, _context: context, _subProxy: subProxy, _stack: new Set(), _descriptors: _descriptors(proxy, descriptorDefaults), setContext: (ctx) => _attachContext(proxy, ctx, subProxy, descriptorDefaults), override: (scope) => _attachContext(proxy.override(scope), context, subProxy, descriptorDefaults) }; return new Proxy(cache, { deleteProperty(target, prop) { delete target[prop]; delete proxy[prop]; return true; }, get(target, prop, receiver) { return _cached(target, prop, () => _resolveWithContext(target, prop, receiver)); }, getOwnPropertyDescriptor(target, prop) { return target._descriptors.allKeys ? Reflect.has(proxy, prop) ? {enumerable: true, configurable: true} : undefined : Reflect.getOwnPropertyDescriptor(proxy, prop); }, getPrototypeOf() { return Reflect.getPrototypeOf(proxy); }, has(target, prop) { return Reflect.has(proxy, prop); }, ownKeys() { return Reflect.ownKeys(proxy); }, set(target, prop, value) { proxy[prop] = value; delete target[prop]; return true; } }); } function _descriptors(proxy, defaults = {scriptable: true, indexable: true}) { const {_scriptable = defaults.scriptable, _indexable = defaults.indexable, _allKeys = defaults.allKeys} = proxy; return { allKeys: _allKeys, scriptable: _scriptable, indexable: _indexable, isScriptable: isFunction(_scriptable) ? _scriptable : () => _scriptable, isIndexable: isFunction(_indexable) ? _indexable : () => _indexable }; } const readKey = (prefix, name) => prefix ? prefix + _capitalize(name) : name; const needsSubResolver = (prop, value) => isObject(value) && prop !== 'adapters' && (Object.getPrototypeOf(value) === null || value.constructor === Object); function _cached(target, prop, resolve) { if (Object.prototype.hasOwnProperty.call(target, prop)) { return target[prop]; } const value = resolve(); target[prop] = value; return value; } function _resolveWithContext(target, prop, receiver) { const {_proxy, _context, _subProxy, _descriptors: descriptors} = target; let value = _proxy[prop]; if (isFunction(value) && descriptors.isScriptable(prop)) { value = _resolveScriptable(prop, value, target, receiver); } if (isArray(value) && value.length) { value = _resolveArray(prop, value, target, descriptors.isIndexable); } if (needsSubResolver(prop, value)) { value = _attachContext(value, _context, _subProxy && _subProxy[prop], descriptors); } return value; } function _resolveScriptable(prop, value, target, receiver) { const {_proxy, _context, _subProxy, _stack} = target; if (_stack.has(prop)) { throw new Error('Recursion detected: ' + Array.from(_stack).join('->') + '->' + prop); } _stack.add(prop); value = value(_context, _subProxy || receiver); _stack.delete(prop); if (needsSubResolver(prop, value)) { value = createSubResolver(_proxy._scopes, _proxy, prop, value); } return value; } function _resolveArray(prop, value, target, isIndexable) { const {_proxy, _context, _subProxy, _descriptors: descriptors} = target; if (defined(_context.index) && isIndexable(prop)) { value = value[_context.index % value.length]; } else if (isObject(value[0])) { const arr = value; const scopes = _proxy._scopes.filter(s => s !== arr); value = []; for (const item of arr) { const resolver = createSubResolver(scopes, _proxy, prop, item); value.push(_attachContext(resolver, _context, _subProxy && _subProxy[prop], descriptors)); } } return value; } function resolveFallback(fallback, prop, value) { return isFunction(fallback) ? fallback(prop, value) : fallback; } const getScope = (key, parent) => key === true ? parent : typeof key === 'string' ? resolveObjectKey(parent, key) : undefined; function addScopes(set, parentScopes, key, parentFallback) { for (const parent of parentScopes) { const scope = getScope(key, parent); if (scope) { set.add(scope); const fallback = resolveFallback(scope._fallback, key, scope); if (defined(fallback) && fallback !== key && fallback !== parentFallback) { return fallback; } } else if (scope === false && defined(parentFallback) && key !== parentFallback) { return null; } } return false; } function createSubResolver(parentScopes, resolver, prop, value) { const rootScopes = resolver._rootScopes; const fallback = resolveFallback(resolver._fallback, prop, value); const allScopes = [...parentScopes, ...rootScopes]; const set = new Set(); set.add(value); let key = addScopesFromKey(set, allScopes, prop, fallback || prop); if (key === null) { return false; } if (defined(fallback) && fallback !== prop) { key = addScopesFromKey(set, allScopes, fallback, key); if (key === null) { return false; } } return _createResolver(Array.from(set), [''], rootScopes, fallback, () => subGetTarget(resolver, prop, value)); } function addScopesFromKey(set, allScopes, key, fallback) { while (key) { key = addScopes(set, allScopes, key, fallback); } return key; } function subGetTarget(resolver, prop, value) { const parent = resolver._getTarget(); if (!(prop in parent)) { parent[prop] = {}; } const target = parent[prop]; if (isArray(target) && isObject(value)) { return value; } return target; } function _resolveWithPrefixes(prop, prefixes, scopes, proxy) { let value; for (const prefix of prefixes) { value = _resolve(readKey(prefix, prop), scopes); if (defined(value)) { return needsSubResolver(prop, value) ? createSubResolver(scopes, proxy, prop, value) : value; } } } function _resolve(key, scopes) { for (const scope of scopes) { if (!scope) { continue; } const value = scope[key]; if (defined(value)) { return value; } } } function getKeysFromAllScopes(target) { let keys = target._keys; if (!keys) { keys = target._keys = resolveKeysFromAllScopes(target._scopes); } return keys; } function resolveKeysFromAllScopes(scopes) { const set = new Set(); for (const scope of scopes) { for (const key of Object.keys(scope).filter(k => !k.startsWith('_'))) { set.add(key); } } return Array.from(set); } const EPSILON = Number.EPSILON || 1e-14; const getPoint = (points, i) => i < points.length && !points[i].skip && points[i]; const getValueAxis = (indexAxis) => indexAxis === 'x' ? 'y' : 'x'; function splineCurve(firstPoint, middlePoint, afterPoint, t) { const previous = firstPoint.skip ? middlePoint : firstPoint; const current = middlePoint; const next = afterPoint.skip ? middlePoint : afterPoint; const d01 = distanceBetweenPoints(current, previous); const d12 = distanceBetweenPoints(next, current); let s01 = d01 / (d01 + d12); let s12 = d12 / (d01 + d12); s01 = isNaN(s01) ? 0 : s01; s12 = isNaN(s12) ? 0 : s12; const fa = t * s01; const fb = t * s12; return { previous: { x: current.x - fa * (next.x - previous.x), y: current.y - fa * (next.y - previous.y) }, next: { x: current.x + fb * (next.x - previous.x), y: current.y + fb * (next.y - previous.y) } }; } function monotoneAdjust(points, deltaK, mK) { const pointsLen = points.length; let alphaK, betaK, tauK, squaredMagnitude, pointCurrent; let pointAfter = getPoint(points, 0); for (let i = 0; i < pointsLen - 1; ++i) { pointCurrent = pointAfter; pointAfter = getPoint(points, i + 1); if (!pointCurrent || !pointAfter) { continue; } if (almostEquals(deltaK[i], 0, EPSILON)) { mK[i] = mK[i + 1] = 0; continue; } alphaK = mK[i] / deltaK[i]; betaK = mK[i + 1] / deltaK[i]; squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2); if (squaredMagnitude <= 9) { continue; } tauK = 3 / Math.sqrt(squaredMagnitude); mK[i] = alphaK * tauK * deltaK[i]; mK[i + 1] = betaK * tauK * deltaK[i]; } } function monotoneCompute(points, mK, indexAxis = 'x') { const valueAxis = getValueAxis(indexAxis); const pointsLen = points.length; let delta, pointBefore, pointCurrent; let pointAfter = getPoint(points, 0); for (let i = 0; i < pointsLen; ++i) { pointBefore = pointCurrent; pointCurrent = pointAfter; pointAfter = getPoint(points, i + 1); if (!pointCurrent) { continue; } const iPixel = pointCurrent[indexAxis]; const vPixel = pointCurrent[valueAxis]; if (pointBefore) { delta = (iPixel - pointBefore[indexAxis]) / 3; pointCurrent[`cp1${indexAxis}`] = iPixel - delta; pointCurrent[`cp1${valueAxis}`] = vPixel - delta * mK[i]; } if (pointAfter) { delta = (pointAfter[indexAxis] - iPixel) / 3; pointCurrent[`cp2${indexAxis}`] = iPixel + delta; pointCurrent[`cp2${valueAxis}`] = vPixel + delta * mK[i]; } } } function splineCurveMonotone(points, indexAxis = 'x') { const valueAxis = getValueAxis(indexAxis); const pointsLen = points.length; const deltaK = Array(pointsLen).fill(0); const mK = Array(pointsLen); let i, pointBefore, pointCurrent; let pointAfter = getPoint(points, 0); for (i = 0; i < pointsLen; ++i) { pointBefore = pointCurrent; pointCurrent = pointAfter; pointAfter = getPoint(points, i + 1); if (!pointCurrent) { continue; } if (pointAfter) { const slopeDelta = pointAfter[indexAxis] - pointCurrent[indexAxis]; deltaK[i] = slopeDelta !== 0 ? (pointAfter[valueAxis] - pointCurrent[valueAxis]) / slopeDelta : 0; } mK[i] = !pointBefore ? deltaK[i] : !pointAfter ? deltaK[i - 1] : (sign(deltaK[i - 1]) !== sign(deltaK[i])) ? 0 : (deltaK[i - 1] + deltaK[i]) / 2; } monotoneAdjust(points, deltaK, mK); monotoneCompute(points, mK, indexAxis); } function capControlPoint(pt, min, max) { return Math.max(Math.min(pt, max), min); } function capBezierPoints(points, area) { let i, ilen, point, inArea, inAreaPrev; let inAreaNext = _isPointInArea(points[0], area); for (i = 0, ilen = points.length; i < ilen; ++i) { inAreaPrev = inArea; inArea = inAreaNext; inAreaNext = i < ilen - 1 && _isPointInArea(points[i + 1], area); if (!inArea) { continue; } point = points[i]; if (inAreaPrev) { point.cp1x = capControlPoint(point.cp1x, area.left, area.right); point.cp1y = capControlPoint(point.cp1y, area.top, area.bottom); } if (inAreaNext) { point.cp2x = capControlPoint(point.cp2x, area.left, area.right); point.cp2y = capControlPoint(point.cp2y, area.top, area.bottom); } } } function _updateBezierControlPoints(points, options, area, loop, indexAxis) { let i, ilen, point, controlPoints; if (options.spanGaps) { points = points.filter((pt) => !pt.skip); } if (options.cubicInterpolationMode === 'monotone') { splineCurveMonotone(points, indexAxis); } else { let prev = loop ? points[points.length - 1] : points[0]; for (i = 0, ilen = points.length; i < ilen; ++i) { point = points[i]; controlPoints = splineCurve( prev, point, points[Math.min(i + 1, ilen - (loop ? 0 : 1)) % ilen], options.tension ); point.cp1x = controlPoints.previous.x; point.cp1y = controlPoints.previous.y; point.cp2x = controlPoints.next.x; point.cp2y = controlPoints.next.y; prev = point; } } if (options.capBezierPoints) { capBezierPoints(points, area); } } const atEdge = (t) => t === 0 || t === 1; const elasticIn = (t, s, p) => -(Math.pow(2, 10 * (t -= 1)) * Math.sin((t - s) * TAU / p)); const elasticOut = (t, s, p) => Math.pow(2, -10 * t) * Math.sin((t - s) * TAU / p) + 1; const effects = { linear: t => t, easeInQuad: t => t * t, easeOutQuad: t => -t * (t - 2), easeInOutQuad: t => ((t /= 0.5) < 1) ? 0.5 * t * t : -0.5 * ((--t) * (t - 2) - 1), easeInCubic: t => t * t * t, easeOutCubic: t => (t -= 1) * t * t + 1, easeInOutCubic: t => ((t /= 0.5) < 1) ? 0.5 * t * t * t : 0.5 * ((t -= 2) * t * t + 2), easeInQuart: t => t * t * t * t, easeOutQuart: t => -((t -= 1) * t * t * t - 1), easeInOutQuart: t => ((t /= 0.5) < 1) ? 0.5 * t * t * t * t : -0.5 * ((t -= 2) * t * t * t - 2), easeInQuint: t => t * t * t * t * t, easeOutQuint: t => (t -= 1) * t * t * t * t + 1, easeInOutQuint: t => ((t /= 0.5) < 1) ? 0.5 * t * t * t * t * t : 0.5 * ((t -= 2) * t * t * t * t + 2), easeInSine: t => -Math.cos(t * HALF_PI) + 1, easeOutSine: t => Math.sin(t * HALF_PI), easeInOutSine: t => -0.5 * (Math.cos(PI * t) - 1), easeInExpo: t => (t === 0) ? 0 : Math.pow(2, 10 * (t - 1)), easeOutExpo: t => (t === 1) ? 1 : -Math.pow(2, -10 * t) + 1, easeInOutExpo: t => atEdge(t) ? t : t < 0.5 ? 0.5 * Math.pow(2, 10 * (t * 2 - 1)) : 0.5 * (-Math.pow(2, -10 * (t * 2 - 1)) + 2), easeInCirc: t => (t >= 1) ? t : -(Math.sqrt(1 - t * t) - 1), easeOutCirc: t => Math.sqrt(1 - (t -= 1) * t), easeInOutCirc: t => ((t /= 0.5) < 1) ? -0.5 * (Math.sqrt(1 - t * t) - 1) : 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1), easeInElastic: t => atEdge(t) ? t : elasticIn(t, 0.075, 0.3), easeOutElastic: t => atEdge(t) ? t : elasticOut(t, 0.075, 0.3), easeInOutElastic(t) { const s = 0.1125; const p = 0.45; return atEdge(t) ? t : t < 0.5 ? 0.5 * elasticIn(t * 2, s, p) : 0.5 + 0.5 * elasticOut(t * 2 - 1, s, p); }, easeInBack(t) { const s = 1.70158; return t * t * ((s + 1) * t - s); }, easeOutBack(t) { const s = 1.70158; return (t -= 1) * t * ((s + 1) * t + s) + 1; }, easeInOutBack(t) { let s = 1.70158; if ((t /= 0.5) < 1) { return 0.5 * (t * t * (((s *= (1.525)) + 1) * t - s)); } return 0.5 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2); }, easeInBounce: t => 1 - effects.easeOutBounce(1 - t), easeOutBounce(t) { const m = 7.5625; const d = 2.75; if (t < (1 / d)) { return m * t * t; } if (t < (2 / d)) { return m * (t -= (1.5 / d)) * t + 0.75; } if (t < (2.5 / d)) { return m * (t -= (2.25 / d)) * t + 0.9375; } return m * (t -= (2.625 / d)) * t + 0.984375; }, easeInOutBounce: t => (t < 0.5) ? effects.easeInBounce(t * 2) * 0.5 : effects.easeOutBounce(t * 2 - 1) * 0.5 + 0.5, }; function _pointInLine(p1, p2, t, mode) { return { x: p1.x + t * (p2.x - p1.x), y: p1.y + t * (p2.y - p1.y) }; } function _steppedInterpolation(p1, p2, t, mode) { return { x: p1.x + t * (p2.x - p1.x), y: mode === 'middle' ? t < 0.5 ? p1.y : p2.y : mode === 'after' ? t < 1 ? p1.y : p2.y : t > 0 ? p2.y : p1.y }; } function _bezierInterpolation(p1, p2, t, mode) { const cp1 = {x: p1.cp2x, y: p1.cp2y}; const cp2 = {x: p2.cp1x, y: p2.cp1y}; const a = _pointInLine(p1, cp1, t); const b = _pointInLine(cp1, cp2, t); const c = _pointInLine(cp2, p2, t); const d = _pointInLine(a, b, t); const e = _pointInLine(b, c, t); return _pointInLine(d, e, t); } const intlCache = new Map(); function getNumberFormat(locale, options) { options = options || {}; const cacheKey = locale + JSON.stringify(options); let formatter = intlCache.get(cacheKey); if (!formatter) { formatter = new Intl.NumberFormat(locale, options); intlCache.set(cacheKey, formatter); } return formatter; } function formatNumber(num, locale, options) { return getNumberFormat(locale, options).format(num); } const getRightToLeftAdapter = function(rectX, width) { return { x(x) { return rectX + rectX + width - x; }, setWidth(w) { width = w; }, textAlign(align) { if (align === 'center') { return align; } return align === 'right' ? 'left' : 'right'; }, xPlus(x, value) { return x - value; }, leftForLtr(x, itemWidth) { return x - itemWidth; }, }; }; const getLeftToRightAdapter = function() { return { x(x) { return x; }, setWidth(w) { }, textAlign(align) { return align; }, xPlus(x, value) { return x + value; }, leftForLtr(x, _itemWidth) { return x; }, }; }; function getRtlAdapter(rtl, rectX, width) { return rtl ? getRightToLeftAdapter(rectX, width) : getLeftToRightAdapter(); } function overrideTextDirection(ctx, direction) { let style, original; if (direction === 'ltr' || direction === 'rtl') { style = ctx.canvas.style; original = [ style.getPropertyValue('direction'), style.getPropertyPriority('direction'), ]; style.setProperty('direction', direction, 'important'); ctx.prevTextDirection = original; } } function restoreTextDirection(ctx, original) { if (original !== undefined) { delete ctx.prevTextDirection; ctx.canvas.style.setProperty('direction', original[0], original[1]); } } function propertyFn(property) { if (property === 'angle') { return { between: _angleBetween, compare: _angleDiff, normalize: _normalizeAngle, }; } return { between: _isBetween, compare: (a, b) => a - b, normalize: x => x }; } function normalizeSegment({start, end, count, loop, style}) { return { start: start % count, end: end % count, loop: loop && (end - start + 1) % count === 0, style }; } function getSegment(segment, points, bounds) { const {property, start: startBound, end: endBound} = bounds; const {between, normalize} = propertyFn(property); const count = points.length; let {start, end, loop} = segment; let i, ilen; if (loop) { start += count; end += count; for (i = 0, ilen = count; i < ilen; ++i) { if (!between(normalize(points[start % count][property]), startBound, endBound)) { break; } start--; end--; } start %= count; end %= count; } if (end < start) { end += count; } return {start, end, loop, style: segment.style}; } function _boundSegment(segment, points, bounds) { if (!bounds) { return [segment]; } const {property, start: startBound, end: endBound} = bounds; const count = points.length; const {compare, between, normalize} = propertyFn(property); const {start, end, loop, style} = getSegment(segment, points, bounds); const result = []; let inside = false; let subStart = null; let value, point, prevValue; const startIsBefore = () => between(startBound, prevValue, value) && compare(startBound, prevValue) !== 0; const endIsBefore = () => compare(endBound, value) === 0 || between(endBound, prevValue, value); const shouldStart = () => inside || startIsBefore(); const shouldStop = () => !inside || endIsBefore(); for (let i = start, prev = start; i <= end; ++i) { point = points[i % count]; if (point.skip) { continue; } value = normalize(point[property]); if (value === prevValue) { continue; } inside = between(value, startBound, endBound); if (subStart === null && shouldStart()) { subStart = compare(value, startBound) === 0 ? i : prev; } if (subStart !== null && shouldStop()) { result.push(normalizeSegment({start: subStart, end: i, loop, count, style})); subStart = null; } prev = i; prevValue = value; } if (subStart !== null) { result.push(normalizeSegment({start: subStart, end, loop, count, style})); } return result; } function _boundSegments(line, bounds) { const result = []; const segments = line.segments; for (let i = 0; i < segments.length; i++) { const sub = _boundSegment(segments[i], line.points, bounds); if (sub.length) { result.push(...sub); } } return result; } function findStartAndEnd(points, count, loop, spanGaps) { let start = 0; let end = count - 1; if (loop && !spanGaps) { while (start < count && !points[start].skip) { start++; } } while (start < count && points[start].skip) { start++; } start %= count; if (loop) { end += start; } while (end > start && points[end % count].skip) { end--; } end %= count; return {start, end}; } function solidSegments(points, start, max, loop) { const count = points.length; const result = []; let last = start; let prev = points[start]; let end; for (end = start + 1; end <= max; ++end) { const cur = points[end % count]; if (cur.skip || cur.stop) { if (!prev.skip) { loop = false; result.push({start: start % count, end: (end - 1) % count, loop}); start = last = cur.stop ? end : null; } } else { last = end; if (prev.skip) { start = end; } } prev = cur; } if (last !== null) { result.push({start: start % count, end: last % count, loop}); } return result; } function _computeSegments(line, segmentOptions) { const points = line.points; const spanGaps = line.options.spanGaps; const count = points.length; if (!count) { return []; } const loop = !!line._loop; const {start, end} = findStartAndEnd(points, count, loop, spanGaps); if (spanGaps === true) { return splitByStyles(line, [{start, end, loop}], points, segmentOptions); } const max = end < start ? end + count : end; const completeLoop = !!line._fullLoop && start === 0 && end === count - 1; return splitByStyles(line, solidSegments(points, start, max, completeLoop), points, segmentOptions); } function splitByStyles(line, segments, points, segmentOptions) { if (!segmentOptions || !segmentOptions.setContext || !points) { return segments; } return doSplitByStyles(line, segments, points, segmentOptions); } function doSplitByStyles(line, segments, points, segmentOptions) { const chartContext = line._chart.getContext(); const baseStyle = readStyle(line.options); const {_datasetIndex: datasetIndex, options: {spanGaps}} = line; const count = points.length; const result = []; let prevStyle = baseStyle; let start = segments[0].start; let i = start; function addStyle(s, e, l, st) { const dir = spanGaps ? -1 : 1; if (s === e) { return; } s += count; while (points[s % count].skip) { s -= dir; } while (points[e % count].skip) { e += dir; } if (s % count !== e % count) { result.push({start: s % count, end: e % count, loop: l, style: st}); prevStyle = st; start = e % count; } } for (const segment of segments) { start = spanGaps ? start : segment.start; let prev = points[start % count]; let style; for (i = start + 1; i <= segment.end; i++) { const pt = points[i % count]; style = readStyle(segmentOptions.setContext(createContext(chartContext, { type: 'segment', p0: prev, p1: pt, p0DataIndex: (i - 1) % count, p1DataIndex: i % count, datasetIndex }))); if (styleChanged(style, prevStyle)) { addStyle(start, i - 1, segment.loop, prevStyle); } prev = pt; prevStyle = style; } if (start < i - 1) { addStyle(start, i - 1, segment.loop, prevStyle); } } return result; } function readStyle(options) { return { backgroundColor: options.backgroundColor, borderCapStyle: options.borderCapStyle, borderDash: options.borderDash, borderDashOffset: options.borderDashOffset, borderJoinStyle: options.borderJoinStyle, borderWidth: options.borderWidth, borderColor: options.borderColor }; } function styleChanged(style, prevStyle) { return prevStyle && JSON.stringify(style) !== JSON.stringify(prevStyle); } var helpers = /*#__PURE__*/Object.freeze({ __proto__: null, easingEffects: effects, color: color, getHoverColor: getHoverColor, noop: noop, uid: uid, isNullOrUndef: isNullOrUndef, isArray: isArray, isObject: isObject, isFinite: isNumberFinite, finiteOrDefault: finiteOrDefault, valueOrDefault: valueOrDefault, toPercentage: toPercentage, toDimension: toDimension, callback: callback, each: each, _elementsEqual: _elementsEqual, clone: clone, _merger: _merger, merge: merge, mergeIf: mergeIf, _mergerIf: _mergerIf, _deprecated: _deprecated, resolveObjectKey: resolveObjectKey, _capitalize: _capitalize, defined: defined, isFunction: isFunction, setsEqual: setsEqual, toFontString: toFontString, _measureText: _measureText, _longestText: _longestText, _alignPixel: _alignPixel, clearCanvas: clearCanvas, drawPoint: drawPoint, _isPointInArea: _isPointInArea, clipArea: clipArea, unclipArea: unclipArea, _steppedLineTo: _steppedLineTo, _bezierCurveTo: _bezierCurveTo, renderText: renderText, addRoundedRectPath: addRoundedRectPath, _lookup: _lookup, _lookupByKey: _lookupByKey, _rlookupByKey: _rlookupByKey, _filterBetween: _filterBetween, listenArrayEvents: listenArrayEvents, unlistenArrayEvents: unlistenArrayEvents, _arrayUnique: _arrayUnique, _createResolver: _createResolver, _attachContext: _attachContext, _descriptors: _descriptors, splineCurve: splineCurve, splineCurveMonotone: splineCurveMonotone, _updateBezierControlPoints: _updateBezierControlPoints, _isDomSupported: _isDomSupported, _getParentNode: _getParentNode, getStyle: getStyle, getRelativePosition: getRelativePosition$1, getMaximumSize: getMaximumSize, retinaScale: retinaScale, supportsEventListenerOptions: supportsEventListenerOptions, readUsedSize: readUsedSize, fontString: fontString, requestAnimFrame: requestAnimFrame, throttled: throttled, debounce: debounce, _toLeftRightCenter: _toLeftRightCenter, _alignStartEnd: _alignStartEnd, _textX: _textX, _pointInLine: _pointInLine, _steppedInterpolation: _steppedInterpolation, _bezierInterpolation: _bezierInterpolation, formatNumber: formatNumber, toLineHeight: toLineHeight, _readValueToProps: _readValueToProps, toTRBL: toTRBL, toTRBLCorners: toTRBLCorners, toPadding: toPadding, toFont: toFont, resolve: resolve, _addGrace: _addGrace, createContext: createContext, PI: PI, TAU: TAU, PITAU: PITAU, INFINITY: INFINITY, RAD_PER_DEG: RAD_PER_DEG, HALF_PI: HALF_PI, QUARTER_PI: QUARTER_PI, TWO_THIRDS_PI: TWO_THIRDS_PI, log10: log10, sign: sign, niceNum: niceNum, _factorize: _factorize, isNumber: isNumber, almostEquals: almostEquals, almostWhole: almostWhole, _setMinAndMaxByKey: _setMinAndMaxByKey, toRadians: toRadians, toDegrees: toDegrees, _decimalPlaces: _decimalPlaces, getAngleFromPoint: getAngleFromPoint, distanceBetweenPoints: distanceBetweenPoints, _angleDiff: _angleDiff, _normalizeAngle: _normalizeAngle, _angleBetween: _angleBetween, _limitValue: _limitValue, _int16Range: _int16Range, _isBetween: _isBetween, getRtlAdapter: getRtlAdapter, overrideTextDirection: overrideTextDirection, restoreTextDirection: restoreTextDirection, _boundSegment: _boundSegment, _boundSegments: _boundSegments, _computeSegments: _computeSegments }); class BasePlatform { acquireContext(canvas, aspectRatio) {} releaseContext(context) { return false; } addEventListener(chart, type, listener) {} removeEventListener(chart, type, listener) {} getDevicePixelRatio() { return 1; } getMaximumSize(element, width, height, aspectRatio) { width = Math.max(0, width || element.width); height = height || element.height; return { width, height: Math.max(0, aspectRatio ? Math.floor(width / aspectRatio) : height) }; } isAttached(canvas) { return true; } updateConfig(config) { } } class BasicPlatform extends BasePlatform { acquireContext(item) { return item && item.getContext && item.getContext('2d') || null; } updateConfig(config) { config.options.animation = false; } } const EXPANDO_KEY = '$chartjs'; const EVENT_TYPES = { touchstart: 'mousedown', touchmove: 'mousemove', touchend: 'mouseup', pointerenter: 'mouseenter', pointerdown: 'mousedown', pointermove: 'mousemove', pointerup: 'mouseup', pointerleave: 'mouseout', pointerout: 'mouseout' }; const isNullOrEmpty = value => value === null || value === ''; function initCanvas(canvas, aspectRatio) { const style = canvas.style; const renderHeight = canvas.getAttribute('height'); const renderWidth = canvas.getAttribute('width'); canvas[EXPANDO_KEY] = { initial: { height: renderHeight, width: renderWidth, style: { display: style.display, height: style.height, width: style.width } } }; style.display = style.display || 'block'; style.boxSizing = style.boxSizing || 'border-box'; if (isNullOrEmpty(renderWidth)) { const displayWidth = readUsedSize(canvas, 'width'); if (displayWidth !== undefined) { canvas.width = displayWidth; } } if (isNullOrEmpty(renderHeight)) { if (canvas.style.height === '') { canvas.height = canvas.width / (aspectRatio || 2); } else { const displayHeight = readUsedSize(canvas, 'height'); if (displayHeight !== undefined) { canvas.height = displayHeight; } } } return canvas; } const eventListenerOptions = supportsEventListenerOptions ? {passive: true} : false; function addListener(node, type, listener) { node.addEventListener(type, listener, eventListenerOptions); } function removeListener(chart, type, listener) { chart.canvas.removeEventListener(type, listener, eventListenerOptions); } function fromNativeEvent(event, chart) { const type = EVENT_TYPES[event.type] || event.type; const {x, y} = getRelativePosition$1(event, chart); return { type, chart, native: event, x: x !== undefined ? x : null, y: y !== undefined ? y : null, }; } function nodeListContains(nodeList, canvas) { for (const node of nodeList) { if (node === canvas || node.contains(canvas)) { return true; } } } function createAttachObserver(chart, type, listener) { const canvas = chart.canvas; const observer = new MutationObserver(entries => { let trigger = false; for (const entry of entries) { trigger = trigger || nodeListContains(entry.addedNodes, canvas); trigger = trigger && !nodeListContains(entry.removedNodes, canvas); } if (trigger) { listener(); } }); observer.observe(document, {childList: true, subtree: true}); return observer; } function createDetachObserver(chart, type, listener) { const canvas = chart.canvas; const observer = new MutationObserver(entries => { let trigger = false; for (const entry of entries) { trigger = trigger || nodeListContains(entry.removedNodes, canvas); trigger = trigger && !nodeListContains(entry.addedNodes, canvas); } if (trigger) { listener(); } }); observer.observe(document, {childList: true, subtree: true}); return observer; } const drpListeningCharts = new Map(); let oldDevicePixelRatio = 0; function onWindowResize() { const dpr = window.devicePixelRatio; if (dpr === oldDevicePixelRatio) { return; } oldDevicePixelRatio = dpr; drpListeningCharts.forEach((resize, chart) => { if (chart.currentDevicePixelRatio !== dpr) { resize(); } }); } function listenDevicePixelRatioChanges(chart, resize) { if (!drpListeningCharts.size) { window.addEventListener('resize', onWindowResize); } drpListeningCharts.set(chart, resize); } function unlistenDevicePixelRatioChanges(chart) { drpListeningCharts.delete(chart); if (!drpListeningCharts.size) { window.removeEventListener('resize', onWindowResize); } } function createResizeObserver(chart, type, listener) { const canvas = chart.canvas; const container = canvas && _getParentNode(canvas); if (!container) { return; } const resize = throttled((width, height) => { const w = container.clientWidth; listener(width, height); if (w < container.clientWidth) { listener(); } }, window); const observer = new ResizeObserver(entries => { const entry = entries[0]; const width = entry.contentRect.width; const height = entry.contentRect.height; if (width === 0 && height === 0) { return; } resize(width, height); }); observer.observe(container); listenDevicePixelRatioChanges(chart, resize); return observer; } function releaseObserver(chart, type, observer) { if (observer) { observer.disconnect(); } if (type === 'resize') { unlistenDevicePixelRatioChanges(chart); } } function createProxyAndListen(chart, type, listener) { const canvas = chart.canvas; const proxy = throttled((event) => { if (chart.ctx !== null) { listener(fromNativeEvent(event, chart)); } }, chart, (args) => { const event = args[0]; return [event, event.offsetX, event.offsetY]; }); addListener(canvas, type, proxy); return proxy; } class DomPlatform extends BasePlatform { acquireContext(canvas, aspectRatio) { const context = canvas && canvas.getContext && canvas.getContext('2d'); if (context && context.canvas === canvas) { initCanvas(canvas, aspectRatio); return context; } return null; } releaseContext(context) { const canvas = context.canvas; if (!canvas[EXPANDO_KEY]) { return false; } const initial = canvas[EXPANDO_KEY].initial; ['height', 'width'].forEach((prop) => { const value = initial[prop]; if (isNullOrUndef(value)) { canvas.removeAttribute(prop); } else { canvas.setAttribute(prop, value); } }); const style = initial.style || {}; Object.keys(style).forEach((key) => { canvas.style[key] = style[key]; }); canvas.width = canvas.width; delete canvas[EXPANDO_KEY]; return true; } addEventListener(chart, type, listener) { this.removeEventListener(chart, type); const proxies = chart.$proxies || (chart.$proxies = {}); const handlers = { attach: createAttachObserver, detach: createDetachObserver, resize: createResizeObserver }; const handler = handlers[type] || createProxyAndListen; proxies[type] = handler(chart, type, listener); } removeEventListener(chart, type) { const proxies = chart.$proxies || (chart.$proxies = {}); const proxy = proxies[type]; if (!proxy) { return; } const handlers = { attach: releaseObserver, detach: releaseObserver, resize: releaseObserver }; const handler = handlers[type] || removeListener; handler(chart, type, proxy); proxies[type] = undefined; } getDevicePixelRatio() { return window.devicePixelRatio; } getMaximumSize(canvas, width, height, aspectRatio) { return getMaximumSize(canvas, width, height, aspectRatio); } isAttached(canvas) { const container = _getParentNode(canvas); return !!(container && container.isConnected); } } function _detectPlatform(canvas) { if (!_isDomSupported() || (typeof OffscreenCanvas !== 'undefined' && canvas instanceof OffscreenCanvas)) { return BasicPlatform; } return DomPlatform; } var platforms = /*#__PURE__*/Object.freeze({ __proto__: null, _detectPlatform: _detectPlatform, BasePlatform: BasePlatform, BasicPlatform: BasicPlatform, DomPlatform: DomPlatform }); const transparent = 'transparent'; const interpolators = { boolean(from, to, factor) { return factor > 0.5 ? to : from; }, color(from, to, factor) { const c0 = color(from || transparent); const c1 = c0.valid && color(to || transparent); return c1 && c1.valid ? c1.mix(c0, factor).hexString() : to; }, number(from, to, factor) { return from + (to - from) * factor; } }; class Animation { constructor(cfg, target, prop, to) { const currentValue = target[prop]; to = resolve([cfg.to, to, currentValue, cfg.from]); const from = resolve([cfg.from, currentValue, to]); this._active = true; this._fn = cfg.fn || interpolators[cfg.type || typeof from]; this._easing = effects[cfg.easing] || effects.linear; this._start = Math.floor(Date.now() + (cfg.delay || 0)); this._duration = this._total = Math.floor(cfg.duration); this._loop = !!cfg.loop; this._target = target; this._prop = prop; this._from = from; this._to = to; this._promises = undefined; } active() { return this._active; } update(cfg, to, date) { if (this._active) { this._notify(false); const currentValue = this._target[this._prop]; const elapsed = date - this._start; const remain = this._duration - elapsed; this._start = date; this._duration = Math.floor(Math.max(remain, cfg.duration)); this._total += elapsed; this._loop = !!cfg.loop; this._to = resolve([cfg.to, to, currentValue, cfg.from]); this._from = resolve([cfg.from, currentValue, to]); } } cancel() { if (this._active) { this.tick(Date.now()); this._active = false; this._notify(false); } } tick(date) { const elapsed = date - this._start; const duration = this._duration; const prop = this._prop; const from = this._from; const loop = this._loop; const to = this._to; let factor; this._active = from !== to && (loop || (elapsed < duration)); if (!this._active) { this._target[prop] = to; this._notify(true); return; } if (elapsed < 0) { this._target[prop] = from; return; } factor = (elapsed / duration) % 2; factor = loop && factor > 1 ? 2 - factor : factor; factor = this._easing(Math.min(1, Math.max(0, factor))); this._target[prop] = this._fn(from, to, factor); } wait() { const promises = this._promises || (this._promises = []); return new Promise((res, rej) => { promises.push({res, rej}); }); } _notify(resolved) { const method = resolved ? 'res' : 'rej'; const promises = this._promises || []; for (let i = 0; i < promises.length; i++) { promises[i][method](); } } } const numbers = ['x', 'y', 'borderWidth', 'radius', 'tension']; const colors = ['color', 'borderColor', 'backgroundColor']; defaults.set('animation', { delay: undefined, duration: 1000, easing: 'easeOutQuart', fn: undefined, from: undefined, loop: undefined, to: undefined, type: undefined, }); const animationOptions = Object.keys(defaults.animation); defaults.describe('animation', { _fallback: false, _indexable: false, _scriptable: (name) => name !== 'onProgress' && name !== 'onComplete' && name !== 'fn', }); defaults.set('animations', { colors: { type: 'color', properties: colors }, numbers: { type: 'number', properties: numbers }, }); defaults.describe('animations', { _fallback: 'animation', }); defaults.set('transitions', { active: { animation: { duration: 400 } }, resize: { animation: { duration: 0 } }, show: { animations: { colors: { from: 'transparent' }, visible: { type: 'boolean', duration: 0 }, } }, hide: { animations: { colors: { to: 'transparent' }, visible: { type: 'boolean', easing: 'linear', fn: v => v | 0 }, } } }); class Animations { constructor(chart, config) { this._chart = chart; this._properties = new Map(); this.configure(config); } configure(config) { if (!isObject(config)) { return; } const animatedProps = this._properties; Object.getOwnPropertyNames(config).forEach(key => { const cfg = config[key]; if (!isObject(cfg)) { return; } const resolved = {}; for (const option of animationOptions) { resolved[option] = cfg[option]; } (isArray(cfg.properties) && cfg.properties || [key]).forEach((prop) => { if (prop === key || !animatedProps.has(prop)) { animatedProps.set(prop, resolved); } }); }); } _animateOptions(target, values) { const newOptions = values.options; const options = resolveTargetOptions(target, newOptions); if (!options) { return []; } const animations = this._createAnimations(options, newOptions); if (newOptions.$shared) { awaitAll(target.options.$animations, newOptions).then(() => { target.options = newOptions; }, () => { }); } return animations; } _createAnimations(target, values) { const animatedProps = this._properties; const animations = []; const running = target.$animations || (target.$animations = {}); const props = Object.keys(values); const date = Date.now(); let i; for (i = props.length - 1; i >= 0; --i) { const prop = props[i]; if (prop.charAt(0) === '$') { continue; } if (prop === 'options') { animations.push(...this._animateOptions(target, values)); continue; } const value = values[prop]; let animation = running[prop]; const cfg = animatedProps.get(prop); if (animation) { if (cfg && animation.active()) { animation.update(cfg, value, date); continue; } else { animation.cancel(); } } if (!cfg || !cfg.duration) { target[prop] = value; continue; } running[prop] = animation = new Animation(cfg, target, prop, value); animations.push(animation); } return animations; } update(target, values) { if (this._properties.size === 0) { Object.assign(target, values); return; } const animations = this._createAnimations(target, values); if (animations.length) { animator.add(this._chart, animations); return true; } } } function awaitAll(animations, properties) { const running = []; const keys = Object.keys(properties); for (let i = 0; i < keys.length; i++) { const anim = animations[keys[i]]; if (anim && anim.active()) { running.push(anim.wait()); } } return Promise.all(running); } function resolveTargetOptions(target, newOptions) { if (!newOptions) { return; } let options = target.options; if (!options) { target.options = newOptions; return; } if (options.$shared) { target.options = options = Object.assign({}, options, {$shared: false, $animations: {}}); } return options; } function scaleClip(scale, allowedOverflow) { const opts = scale && scale.options || {}; const reverse = opts.reverse; const min = opts.min === undefined ? allowedOverflow : 0; const max = opts.max === undefined ? allowedOverflow : 0; return { start: reverse ? max : min, end: reverse ? min : max }; } function defaultClip(xScale, yScale, allowedOverflow) { if (allowedOverflow === false) { return false; } const x = scaleClip(xScale, allowedOverflow); const y = scaleClip(yScale, allowedOverflow); return { top: y.end, right: x.end, bottom: y.start, left: x.start }; } function toClip(value) { let t, r, b, l; if (isObject(value)) { t = value.top; r = value.right; b = value.bottom; l = value.left; } else { t = r = b = l = value; } return { top: t, right: r, bottom: b, left: l, disabled: value === false }; } function getSortedDatasetIndices(chart, filterVisible) { const keys = []; const metasets = chart._getSortedDatasetMetas(filterVisible); let i, ilen; for (i = 0, ilen = metasets.length; i < ilen; ++i) { keys.push(metasets[i].index); } return keys; } function applyStack(stack, value, dsIndex, options = {}) { const keys = stack.keys; const singleMode = options.mode === 'single'; let i, ilen, datasetIndex, otherValue; if (value === null) { return; } for (i = 0, ilen = keys.length; i < ilen; ++i) { datasetIndex = +keys[i]; if (datasetIndex === dsIndex) { if (options.all) { continue; } break; } otherValue = stack.values[datasetIndex]; if (isNumberFinite(otherValue) && (singleMode || (value === 0 || sign(value) === sign(otherValue)))) { value += otherValue; } } return value; } function convertObjectDataToArray(data) { const keys = Object.keys(data); const adata = new Array(keys.length); let i, ilen, key; for (i = 0, ilen = keys.length; i < ilen; ++i) { key = keys[i]; adata[i] = { x: key, y: data[key] }; } return adata; } function isStacked(scale, meta) { const stacked = scale && scale.options.stacked; return stacked || (stacked === undefined && meta.stack !== undefined); } function getStackKey(indexScale, valueScale, meta) { return `${indexScale.id}.${valueScale.id}.${meta.stack || meta.type}`; } function getUserBounds(scale) { const {min, max, minDefined, maxDefined} = scale.getUserBounds(); return { min: minDefined ? min : Number.NEGATIVE_INFINITY, max: maxDefined ? max : Number.POSITIVE_INFINITY }; } function getOrCreateStack(stacks, stackKey, indexValue) { const subStack = stacks[stackKey] || (stacks[stackKey] = {}); return subStack[indexValue] || (subStack[indexValue] = {}); } function getLastIndexInStack(stack, vScale, positive, type) { for (const meta of vScale.getMatchingVisibleMetas(type).reverse()) { const value = stack[meta.index]; if ((positive && value > 0) || (!positive && value < 0)) { return meta.index; } } return null; } function updateStacks(controller, parsed) { const {chart, _cachedMeta: meta} = controller; const stacks = chart._stacks || (chart._stacks = {}); const {iScale, vScale, index: datasetIndex} = meta; const iAxis = iScale.axis; const vAxis = vScale.axis; const key = getStackKey(iScale, vScale, meta); const ilen = parsed.length; let stack; for (let i = 0; i < ilen; ++i) { const item = parsed[i]; const {[iAxis]: index, [vAxis]: value} = item; const itemStacks = item._stacks || (item._stacks = {}); stack = itemStacks[vAxis] = getOrCreateStack(stacks, key, index); stack[datasetIndex] = value; stack._top = getLastIndexInStack(stack, vScale, true, meta.type); stack._bottom = getLastIndexInStack(stack, vScale, false, meta.type); } } function getFirstScaleId(chart, axis) { const scales = chart.scales; return Object.keys(scales).filter(key => scales[key].axis === axis).shift(); } function createDatasetContext(parent, index) { return createContext(parent, { active: false, dataset: undefined, datasetIndex: index, index, mode: 'default', type: 'dataset' } ); } function createDataContext(parent, index, element) { return createContext(parent, { active: false, dataIndex: index, parsed: undefined, raw: undefined, element, index, mode: 'default', type: 'data' }); } function clearStacks(meta, items) { const datasetIndex = meta.controller.index; const axis = meta.vScale && meta.vScale.axis; if (!axis) { return; } items = items || meta._parsed; for (const parsed of items) { const stacks = parsed._stacks; if (!stacks || stacks[axis] === undefined || stacks[axis][datasetIndex] === undefined) { return; } delete stacks[axis][datasetIndex]; } } const isDirectUpdateMode = (mode) => mode === 'reset' || mode === 'none'; const cloneIfNotShared = (cached, shared) => shared ? cached : Object.assign({}, cached); const createStack = (canStack, meta, chart) => canStack && !meta.hidden && meta._stacked && {keys: getSortedDatasetIndices(chart, true), values: null}; class DatasetController { constructor(chart, datasetIndex) { this.chart = chart; this._ctx = chart.ctx; this.index = datasetIndex; this._cachedDataOpts = {}; this._cachedMeta = this.getMeta(); this._type = this._cachedMeta.type; this.options = undefined; this._parsing = false; this._data = undefined; this._objectData = undefined; this._sharedOptions = undefined; this._drawStart = undefined; this._drawCount = undefined; this.enableOptionSharing = false; this.$context = undefined; this._syncList = []; this.initialize(); } initialize() { const meta = this._cachedMeta; this.configure(); this.linkScales(); meta._stacked = isStacked(meta.vScale, meta); this.addElements(); } updateIndex(datasetIndex) { if (this.index !== datasetIndex) { clearStacks(this._cachedMeta); } this.index = datasetIndex; } linkScales() { const chart = this.chart; const meta = this._cachedMeta; const dataset = this.getDataset(); const chooseId = (axis, x, y, r) => axis === 'x' ? x : axis === 'r' ? r : y; const xid = meta.xAxisID = valueOrDefault(dataset.xAxisID, getFirstScaleId(chart, 'x')); const yid = meta.yAxisID = valueOrDefault(dataset.yAxisID, getFirstScaleId(chart, 'y')); const rid = meta.rAxisID = valueOrDefault(dataset.rAxisID, getFirstScaleId(chart, 'r')); const indexAxis = meta.indexAxis; const iid = meta.iAxisID = chooseId(indexAxis, xid, yid, rid); const vid = meta.vAxisID = chooseId(indexAxis, yid, xid, rid); meta.xScale = this.getScaleForId(xid); meta.yScale = this.getScaleForId(yid); meta.rScale = this.getScaleForId(rid); meta.iScale = this.getScaleForId(iid); meta.vScale = this.getScaleForId(vid); } getDataset() { return this.chart.data.datasets[this.index]; } getMeta() { return this.chart.getDatasetMeta(this.index); } getScaleForId(scaleID) { return this.chart.scales[scaleID]; } _getOtherScale(scale) { const meta = this._cachedMeta; return scale === meta.iScale ? meta.vScale : meta.iScale; } reset() { this._update('reset'); } _destroy() { const meta = this._cachedMeta; if (this._data) { unlistenArrayEvents(this._data, this); } if (meta._stacked) { clearStacks(meta); } } _dataCheck() { const dataset = this.getDataset(); const data = dataset.data || (dataset.data = []); const _data = this._data; if (isObject(data)) { this._data = convertObjectDataToArray(data); } else if (_data !== data) { if (_data) { unlistenArrayEvents(_data, this); const meta = this._cachedMeta; clearStacks(meta); meta._parsed = []; } if (data && Object.isExtensible(data)) { listenArrayEvents(data, this); } this._syncList = []; this._data = data; } } addElements() { const meta = this._cachedMeta; this._dataCheck(); if (this.datasetElementType) { meta.dataset = new this.datasetElementType(); } } buildOrUpdateElements(resetNewElements) { const meta = this._cachedMeta; const dataset = this.getDataset(); let stackChanged = false; this._dataCheck(); const oldStacked = meta._stacked; meta._stacked = isStacked(meta.vScale, meta); if (meta.stack !== dataset.stack) { stackChanged = true; clearStacks(meta); meta.stack = dataset.stack; } this._resyncElements(resetNewElements); if (stackChanged || oldStacked !== meta._stacked) { updateStacks(this, meta._parsed); } } configure() { const config = this.chart.config; const scopeKeys = config.datasetScopeKeys(this._type); const scopes = config.getOptionScopes(this.getDataset(), scopeKeys, true); this.options = config.createResolver(scopes, this.getContext()); this._parsing = this.options.parsing; this._cachedDataOpts = {}; } parse(start, count) { const {_cachedMeta: meta, _data: data} = this; const {iScale, _stacked} = meta; const iAxis = iScale.axis; let sorted = start === 0 && count === data.length ? true : meta._sorted; let prev = start > 0 && meta._parsed[start - 1]; let i, cur, parsed; if (this._parsing === false) { meta._parsed = data; meta._sorted = true; parsed = data; } else { if (isArray(data[start])) { parsed = this.parseArrayData(meta, data, start, count); } else if (isObject(data[start])) { parsed = this.parseObjectData(meta, data, start, count); } else { parsed = this.parsePrimitiveData(meta, data, start, count); } const isNotInOrderComparedToPrev = () => cur[iAxis] === null || (prev && cur[iAxis] < prev[iAxis]); for (i = 0; i < count; ++i) { meta._parsed[i + start] = cur = parsed[i]; if (sorted) { if (isNotInOrderComparedToPrev()) { sorted = false; } prev = cur; } } meta._sorted = sorted; } if (_stacked) { updateStacks(this, parsed); } } parsePrimitiveData(meta, data, start, count) { const {iScale, vScale} = meta; const iAxis = iScale.axis; const vAxis = vScale.axis; const labels = iScale.getLabels(); const singleScale = iScale === vScale; const parsed = new Array(count); let i, ilen, index; for (i = 0, ilen = count; i < ilen; ++i) { index = i + start; parsed[i] = { [iAxis]: singleScale || iScale.parse(labels[index], index), [vAxis]: vScale.parse(data[index], index) }; } return parsed; } parseArrayData(meta, data, start, count) { const {xScale, yScale} = meta; const parsed = new Array(count); let i, ilen, index, item; for (i = 0, ilen = count; i < ilen; ++i) { index = i + start; item = data[index]; parsed[i] = { x: xScale.parse(item[0], index), y: yScale.parse(item[1], index) }; } return parsed; } parseObjectData(meta, data, start, count) { const {xScale, yScale} = meta; const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing; const parsed = new Array(count); let i, ilen, index, item; for (i = 0, ilen = count; i < ilen; ++i) { index = i + start; item = data[index]; parsed[i] = { x: xScale.parse(resolveObjectKey(item, xAxisKey), index), y: yScale.parse(resolveObjectKey(item, yAxisKey), index) }; } return parsed; } getParsed(index) { return this._cachedMeta._parsed[index]; } getDataElement(index) { return this._cachedMeta.data[index]; } applyStack(scale, parsed, mode) { const chart = this.chart; const meta = this._cachedMeta; const value = parsed[scale.axis]; const stack = { keys: getSortedDatasetIndices(chart, true), values: parsed._stacks[scale.axis] }; return applyStack(stack, value, meta.index, {mode}); } updateRangeFromParsed(range, scale, parsed, stack) { const parsedValue = parsed[scale.axis]; let value = parsedValue === null ? NaN : parsedValue; const values = stack && parsed._stacks[scale.axis]; if (stack && values) { stack.values = values; value = applyStack(stack, parsedValue, this._cachedMeta.index); } range.min = Math.min(range.min, value); range.max = Math.max(range.max, value); } getMinMax(scale, canStack) { const meta = this._cachedMeta; const _parsed = meta._parsed; const sorted = meta._sorted && scale === meta.iScale; const ilen = _parsed.length; const otherScale = this._getOtherScale(scale); const stack = createStack(canStack, meta, this.chart); const range = {min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY}; const {min: otherMin, max: otherMax} = getUserBounds(otherScale); let i, parsed; function _skip() { parsed = _parsed[i]; const otherValue = parsed[otherScale.axis]; return !isNumberFinite(parsed[scale.axis]) || otherMin > otherValue || otherMax < otherValue; } for (i = 0; i < ilen; ++i) { if (_skip()) { continue; } this.updateRangeFromParsed(range, scale, parsed, stack); if (sorted) { break; } } if (sorted) { for (i = ilen - 1; i >= 0; --i) { if (_skip()) { continue; } this.updateRangeFromParsed(range, scale, parsed, stack); break; } } return range; } getAllParsedValues(scale) { const parsed = this._cachedMeta._parsed; const values = []; let i, ilen, value; for (i = 0, ilen = parsed.length; i < ilen; ++i) { value = parsed[i][scale.axis]; if (isNumberFinite(value)) { values.push(value); } } return values; } getMaxOverflow() { return false; } getLabelAndValue(index) { const meta = this._cachedMeta; const iScale = meta.iScale; const vScale = meta.vScale; const parsed = this.getParsed(index); return { label: iScale ? '' + iScale.getLabelForValue(parsed[iScale.axis]) : '', value: vScale ? '' + vScale.getLabelForValue(parsed[vScale.axis]) : '' }; } _update(mode) { const meta = this._cachedMeta; this.update(mode || 'default'); meta._clip = toClip(valueOrDefault(this.options.clip, defaultClip(meta.xScale, meta.yScale, this.getMaxOverflow()))); } update(mode) {} draw() { const ctx = this._ctx; const chart = this.chart; const meta = this._cachedMeta; const elements = meta.data || []; const area = chart.chartArea; const active = []; const start = this._drawStart || 0; const count = this._drawCount || (elements.length - start); let i; if (meta.dataset) { meta.dataset.draw(ctx, area, start, count); } for (i = start; i < start + count; ++i) { const element = elements[i]; if (element.hidden) { continue; } if (element.active) { active.push(element); } else { element.draw(ctx, area); } } for (i = 0; i < active.length; ++i) { active[i].draw(ctx, area); } } getStyle(index, active) { const mode = active ? 'active' : 'default'; return index === undefined && this._cachedMeta.dataset ? this.resolveDatasetElementOptions(mode) : this.resolveDataElementOptions(index || 0, mode); } getContext(index, active, mode) { const dataset = this.getDataset(); let context; if (index >= 0 && index < this._cachedMeta.data.length) { const element = this._cachedMeta.data[index]; context = element.$context || (element.$context = createDataContext(this.getContext(), index, element)); context.parsed = this.getParsed(index); context.raw = dataset.data[index]; context.index = context.dataIndex = index; } else { context = this.$context || (this.$context = createDatasetContext(this.chart.getContext(), this.index)); context.dataset = dataset; context.index = context.datasetIndex = this.index; } context.active = !!active; context.mode = mode; return context; } resolveDatasetElementOptions(mode) { return this._resolveElementOptions(this.datasetElementType.id, mode); } resolveDataElementOptions(index, mode) { return this._resolveElementOptions(this.dataElementType.id, mode, index); } _resolveElementOptions(elementType, mode = 'default', index) { const active = mode === 'active'; const cache = this._cachedDataOpts; const cacheKey = elementType + '-' + mode; const cached = cache[cacheKey]; const sharing = this.enableOptionSharing && defined(index); if (cached) { return cloneIfNotShared(cached, sharing); } const config = this.chart.config; const scopeKeys = config.datasetElementScopeKeys(this._type, elementType); const prefixes = active ? [`${elementType}Hover`, 'hover', elementType, ''] : [elementType, '']; const scopes = config.getOptionScopes(this.getDataset(), scopeKeys); const names = Object.keys(defaults.elements[elementType]); const context = () => this.getContext(index, active); const values = config.resolveNamedOptions(scopes, names, context, prefixes); if (values.$shared) { values.$shared = sharing; cache[cacheKey] = Object.freeze(cloneIfNotShared(values, sharing)); } return values; } _resolveAnimations(index, transition, active) { const chart = this.chart; const cache = this._cachedDataOpts; const cacheKey = `animation-${transition}`; const cached = cache[cacheKey]; if (cached) { return cached; } let options; if (chart.options.animation !== false) { const config = this.chart.config; const scopeKeys = config.datasetAnimationScopeKeys(this._type, transition); const scopes = config.getOptionScopes(this.getDataset(), scopeKeys); options = config.createResolver(scopes, this.getContext(index, active, transition)); } const animations = new Animations(chart, options && options.animations); if (options && options._cacheable) { cache[cacheKey] = Object.freeze(animations); } return animations; } getSharedOptions(options) { if (!options.$shared) { return; } return this._sharedOptions || (this._sharedOptions = Object.assign({}, options)); } includeOptions(mode, sharedOptions) { return !sharedOptions || isDirectUpdateMode(mode) || this.chart._animationsDisabled; } updateElement(element, index, properties, mode) { if (isDirectUpdateMode(mode)) { Object.assign(element, properties); } else { this._resolveAnimations(index, mode).update(element, properties); } } updateSharedOptions(sharedOptions, mode, newOptions) { if (sharedOptions && !isDirectUpdateMode(mode)) { this._resolveAnimations(undefined, mode).update(sharedOptions, newOptions); } } _setStyle(element, index, mode, active) { element.active = active; const options = this.getStyle(index, active); this._resolveAnimations(index, mode, active).update(element, { options: (!active && this.getSharedOptions(options)) || options }); } removeHoverStyle(element, datasetIndex, index) { this._setStyle(element, index, 'active', false); } setHoverStyle(element, datasetIndex, index) { this._setStyle(element, index, 'active', true); } _removeDatasetHoverStyle() { const element = this._cachedMeta.dataset; if (element) { this._setStyle(element, undefined, 'active', false); } } _setDatasetHoverStyle() { const element = this._cachedMeta.dataset; if (element) { this._setStyle(element, undefined, 'active', true); } } _resyncElements(resetNewElements) { const data = this._data; const elements = this._cachedMeta.data; for (const [method, arg1, arg2] of this._syncList) { this[method](arg1, arg2); } this._syncList = []; const numMeta = elements.length; const numData = data.length; const count = Math.min(numData, numMeta); if (count) { this.parse(0, count); } if (numData > numMeta) { this._insertElements(numMeta, numData - numMeta, resetNewElements); } else if (numData < numMeta) { this._removeElements(numData, numMeta - numData); } } _insertElements(start, count, resetNewElements = true) { const meta = this._cachedMeta; const data = meta.data; const end = start + count; let i; const move = (arr) => { arr.length += count; for (i = arr.length - 1; i >= end; i--) { arr[i] = arr[i - count]; } }; move(data); for (i = start; i < end; ++i) { data[i] = new this.dataElementType(); } if (this._parsing) { move(meta._parsed); } this.parse(start, count); if (resetNewElements) { this.updateElements(data, start, count, 'reset'); } } updateElements(element, start, count, mode) {} _removeElements(start, count) { const meta = this._cachedMeta; if (this._parsing) { const removed = meta._parsed.splice(start, count); if (meta._stacked) { clearStacks(meta, removed); } } meta.data.splice(start, count); } _sync(args) { if (this._parsing) { this._syncList.push(args); } else { const [method, arg1, arg2] = args; this[method](arg1, arg2); } this.chart._dataChanges.push([this.index, ...args]); } _onDataPush() { const count = arguments.length; this._sync(['_insertElements', this.getDataset().data.length - count, count]); } _onDataPop() { this._sync(['_removeElements', this._cachedMeta.data.length - 1, 1]); } _onDataShift() { this._sync(['_removeElements', 0, 1]); } _onDataSplice(start, count) { if (count) { this._sync(['_removeElements', start, count]); } const newCount = arguments.length - 2; if (newCount) { this._sync(['_insertElements', start, newCount]); } } _onDataUnshift() { this._sync(['_insertElements', 0, arguments.length]); } } DatasetController.defaults = {}; DatasetController.prototype.datasetElementType = null; DatasetController.prototype.dataElementType = null; class Element { constructor() { this.x = undefined; this.y = undefined; this.active = false; this.options = undefined; this.$animations = undefined; } tooltipPosition(useFinalPosition) { const {x, y} = this.getProps(['x', 'y'], useFinalPosition); return {x, y}; } hasValue() { return isNumber(this.x) && isNumber(this.y); } getProps(props, final) { const anims = this.$animations; if (!final || !anims) { return this; } const ret = {}; props.forEach(prop => { ret[prop] = anims[prop] && anims[prop].active() ? anims[prop]._to : this[prop]; }); return ret; } } Element.defaults = {}; Element.defaultRoutes = undefined; const formatters = { values(value) { return isArray(value) ? value : '' + value; }, numeric(tickValue, index, ticks) { if (tickValue === 0) { return '0'; } const locale = this.chart.options.locale; let notation; let delta = tickValue; if (ticks.length > 1) { const maxTick = Math.max(Math.abs(ticks[0].value), Math.abs(ticks[ticks.length - 1].value)); if (maxTick < 1e-4 || maxTick > 1e+15) { notation = 'scientific'; } delta = calculateDelta(tickValue, ticks); } const logDelta = log10(Math.abs(delta)); const numDecimal = Math.max(Math.min(-1 * Math.floor(logDelta), 20), 0); const options = {notation, minimumFractionDigits: numDecimal, maximumFractionDigits: numDecimal}; Object.assign(options, this.options.ticks.format); return formatNumber(tickValue, locale, options); }, logarithmic(tickValue, index, ticks) { if (tickValue === 0) { return '0'; } const remain = tickValue / (Math.pow(10, Math.floor(log10(tickValue)))); if (remain === 1 || remain === 2 || remain === 5) { return formatters.numeric.call(this, tickValue, index, ticks); } return ''; } }; function calculateDelta(tickValue, ticks) { let delta = ticks.length > 3 ? ticks[2].value - ticks[1].value : ticks[1].value - ticks[0].value; if (Math.abs(delta) >= 1 && tickValue !== Math.floor(tickValue)) { delta = tickValue - Math.floor(tickValue); } return delta; } var Ticks = {formatters}; defaults.set('scale', { display: true, offset: false, reverse: false, beginAtZero: false, bounds: 'ticks', grace: 0, grid: { display: true, lineWidth: 1, drawBorder: true, drawOnChartArea: true, drawTicks: true, tickLength: 8, tickWidth: (_ctx, options) => options.lineWidth, tickColor: (_ctx, options) => options.color, offset: false, borderDash: [], borderDashOffset: 0.0, borderWidth: 1 }, title: { display: false, text: '', padding: { top: 4, bottom: 4 } }, ticks: { minRotation: 0, maxRotation: 50, mirror: false, textStrokeWidth: 0, textStrokeColor: '', padding: 3, display: true, autoSkip: true, autoSkipPadding: 3, labelOffset: 0, callback: Ticks.formatters.values, minor: {}, major: {}, align: 'center', crossAlign: 'near', showLabelBackdrop: false, backdropColor: 'rgba(255, 255, 255, 0.75)', backdropPadding: 2, } }); defaults.route('scale.ticks', 'color', '', 'color'); defaults.route('scale.grid', 'color', '', 'borderColor'); defaults.route('scale.grid', 'borderColor', '', 'borderColor'); defaults.route('scale.title', 'color', '', 'color'); defaults.describe('scale', { _fallback: false, _scriptable: (name) => !name.startsWith('before') && !name.startsWith('after') && name !== 'callback' && name !== 'parser', _indexable: (name) => name !== 'borderDash' && name !== 'tickBorderDash', }); defaults.describe('scales', { _fallback: 'scale', }); defaults.describe('scale.ticks', { _scriptable: (name) => name !== 'backdropPadding' && name !== 'callback', _indexable: (name) => name !== 'backdropPadding', }); function autoSkip(scale, ticks) { const tickOpts = scale.options.ticks; const ticksLimit = tickOpts.maxTicksLimit || determineMaxTicks(scale); const majorIndices = tickOpts.major.enabled ? getMajorIndices(ticks) : []; const numMajorIndices = majorIndices.length; const first = majorIndices[0]; const last = majorIndices[numMajorIndices - 1]; const newTicks = []; if (numMajorIndices > ticksLimit) { skipMajors(ticks, newTicks, majorIndices, numMajorIndices / ticksLimit); return newTicks; } const spacing = calculateSpacing(majorIndices, ticks, ticksLimit); if (numMajorIndices > 0) { let i, ilen; const avgMajorSpacing = numMajorIndices > 1 ? Math.round((last - first) / (numMajorIndices - 1)) : null; skip(ticks, newTicks, spacing, isNullOrUndef(avgMajorSpacing) ? 0 : first - avgMajorSpacing, first); for (i = 0, ilen = numMajorIndices - 1; i < ilen; i++) { skip(ticks, newTicks, spacing, majorIndices[i], majorIndices[i + 1]); } skip(ticks, newTicks, spacing, last, isNullOrUndef(avgMajorSpacing) ? ticks.length : last + avgMajorSpacing); return newTicks; } skip(ticks, newTicks, spacing); return newTicks; } function determineMaxTicks(scale) { const offset = scale.options.offset; const tickLength = scale._tickSize(); const maxScale = scale._length / tickLength + (offset ? 0 : 1); const maxChart = scale._maxLength / tickLength; return Math.floor(Math.min(maxScale, maxChart)); } function calculateSpacing(majorIndices, ticks, ticksLimit) { const evenMajorSpacing = getEvenSpacing(majorIndices); const spacing = ticks.length / ticksLimit; if (!evenMajorSpacing) { return Math.max(spacing, 1); } const factors = _factorize(evenMajorSpacing); for (let i = 0, ilen = factors.length - 1; i < ilen; i++) { const factor = factors[i]; if (factor > spacing) { return factor; } } return Math.max(spacing, 1); } function getMajorIndices(ticks) { const result = []; let i, ilen; for (i = 0, ilen = ticks.length; i < ilen; i++) { if (ticks[i].major) { result.push(i); } } return result; } function skipMajors(ticks, newTicks, majorIndices, spacing) { let count = 0; let next = majorIndices[0]; let i; spacing = Math.ceil(spacing); for (i = 0; i < ticks.length; i++) { if (i === next) { newTicks.push(ticks[i]); count++; next = majorIndices[count * spacing]; } } } function skip(ticks, newTicks, spacing, majorStart, majorEnd) { const start = valueOrDefault(majorStart, 0); const end = Math.min(valueOrDefault(majorEnd, ticks.length), ticks.length); let count = 0; let length, i, next; spacing = Math.ceil(spacing); if (majorEnd) { length = majorEnd - majorStart; spacing = length / Math.floor(length / spacing); } next = start; while (next < 0) { count++; next = Math.round(start + count * spacing); } for (i = Math.max(start, 0); i < end; i++) { if (i === next) { newTicks.push(ticks[i]); count++; next = Math.round(start + count * spacing); } } } function getEvenSpacing(arr) { const len = arr.length; let i, diff; if (len < 2) { return false; } for (diff = arr[0], i = 1; i < len; ++i) { if (arr[i] - arr[i - 1] !== diff) { return false; } } return diff; } const reverseAlign = (align) => align === 'left' ? 'right' : align === 'right' ? 'left' : align; const offsetFromEdge = (scale, edge, offset) => edge === 'top' || edge === 'left' ? scale[edge] + offset : scale[edge] - offset; function sample(arr, numItems) { const result = []; const increment = arr.length / numItems; const len = arr.length; let i = 0; for (; i < len; i += increment) { result.push(arr[Math.floor(i)]); } return result; } function getPixelForGridLine(scale, index, offsetGridLines) { const length = scale.ticks.length; const validIndex = Math.min(index, length - 1); const start = scale._startPixel; const end = scale._endPixel; const epsilon = 1e-6; let lineValue = scale.getPixelForTick(validIndex); let offset; if (offsetGridLines) { if (length === 1) { offset = Math.max(lineValue - start, end - lineValue); } else if (index === 0) { offset = (scale.getPixelForTick(1) - lineValue) / 2; } else { offset = (lineValue - scale.getPixelForTick(validIndex - 1)) / 2; } lineValue += validIndex < index ? offset : -offset; if (lineValue < start - epsilon || lineValue > end + epsilon) { return; } } return lineValue; } function garbageCollect(caches, length) { each(caches, (cache) => { const gc = cache.gc; const gcLen = gc.length / 2; let i; if (gcLen > length) { for (i = 0; i < gcLen; ++i) { delete cache.data[gc[i]]; } gc.splice(0, gcLen); } }); } function getTickMarkLength(options) { return options.drawTicks ? options.tickLength : 0; } function getTitleHeight(options, fallback) { if (!options.display) { return 0; } const font = toFont(options.font, fallback); const padding = toPadding(options.padding); const lines = isArray(options.text) ? options.text.length : 1; return (lines * font.lineHeight) + padding.height; } function createScaleContext(parent, scale) { return createContext(parent, { scale, type: 'scale' }); } function createTickContext(parent, index, tick) { return createContext(parent, { tick, index, type: 'tick' }); } function titleAlign(align, position, reverse) { let ret = _toLeftRightCenter(align); if ((reverse && position !== 'right') || (!reverse && position === 'right')) { ret = reverseAlign(ret); } return ret; } function titleArgs(scale, offset, position, align) { const {top, left, bottom, right, chart} = scale; const {chartArea, scales} = chart; let rotation = 0; let maxWidth, titleX, titleY; const height = bottom - top; const width = right - left; if (scale.isHorizontal()) { titleX = _alignStartEnd(align, left, right); if (isObject(position)) { const positionAxisID = Object.keys(position)[0]; const value = position[positionAxisID]; titleY = scales[positionAxisID].getPixelForValue(value) + height - offset; } else if (position === 'center') { titleY = (chartArea.bottom + chartArea.top) / 2 + height - offset; } else { titleY = offsetFromEdge(scale, position, offset); } maxWidth = right - left; } else { if (isObject(position)) { const positionAxisID = Object.keys(position)[0]; const value = position[positionAxisID]; titleX = scales[positionAxisID].getPixelForValue(value) - width + offset; } else if (position === 'center') { titleX = (chartArea.left + chartArea.right) / 2 - width + offset; } else { titleX = offsetFromEdge(scale, position, offset); } titleY = _alignStartEnd(align, bottom, top); rotation = position === 'left' ? -HALF_PI : HALF_PI; } return {titleX, titleY, maxWidth, rotation}; } class Scale extends Element { constructor(cfg) { super(); this.id = cfg.id; this.type = cfg.type; this.options = undefined; this.ctx = cfg.ctx; this.chart = cfg.chart; this.top = undefined; this.bottom = undefined; this.left = undefined; this.right = undefined; this.width = undefined; this.height = undefined; this._margins = { left: 0, right: 0, top: 0, bottom: 0 }; this.maxWidth = undefined; this.maxHeight = undefined; this.paddingTop = undefined; this.paddingBottom = undefined; this.paddingLeft = undefined; this.paddingRight = undefined; this.axis = undefined; this.labelRotation = undefined; this.min = undefined; this.max = undefined; this._range = undefined; this.ticks = []; this._gridLineItems = null; this._labelItems = null; this._labelSizes = null; this._length = 0; this._maxLength = 0; this._longestTextCache = {}; this._startPixel = undefined; this._endPixel = undefined; this._reversePixels = false; this._userMax = undefined; this._userMin = undefined; this._suggestedMax = undefined; this._suggestedMin = undefined; this._ticksLength = 0; this._borderValue = 0; this._cache = {}; this._dataLimitsCached = false; this.$context = undefined; } init(options) { this.options = options.setContext(this.getContext()); this.axis = options.axis; this._userMin = this.parse(options.min); this._userMax = this.parse(options.max); this._suggestedMin = this.parse(options.suggestedMin); this._suggestedMax = this.parse(options.suggestedMax); } parse(raw, index) { return raw; } getUserBounds() { let {_userMin, _userMax, _suggestedMin, _suggestedMax} = this; _userMin = finiteOrDefault(_userMin, Number.POSITIVE_INFINITY); _userMax = finiteOrDefault(_userMax, Number.NEGATIVE_INFINITY); _suggestedMin = finiteOrDefault(_suggestedMin, Number.POSITIVE_INFINITY); _suggestedMax = finiteOrDefault(_suggestedMax, Number.NEGATIVE_INFINITY); return { min: finiteOrDefault(_userMin, _suggestedMin), max: finiteOrDefault(_userMax, _suggestedMax), minDefined: isNumberFinite(_userMin), maxDefined: isNumberFinite(_userMax) }; } getMinMax(canStack) { let {min, max, minDefined, maxDefined} = this.getUserBounds(); let range; if (minDefined && maxDefined) { return {min, max}; } const metas = this.getMatchingVisibleMetas(); for (let i = 0, ilen = metas.length; i < ilen; ++i) { range = metas[i].controller.getMinMax(this, canStack); if (!minDefined) { min = Math.min(min, range.min); } if (!maxDefined) { max = Math.max(max, range.max); } } min = maxDefined && min > max ? max : min; max = minDefined && min > max ? min : max; return { min: finiteOrDefault(min, finiteOrDefault(max, min)), max: finiteOrDefault(max, finiteOrDefault(min, max)) }; } getPadding() { return { left: this.paddingLeft || 0, top: this.paddingTop || 0, right: this.paddingRight || 0, bottom: this.paddingBottom || 0 }; } getTicks() { return this.ticks; } getLabels() { const data = this.chart.data; return this.options.labels || (this.isHorizontal() ? data.xLabels : data.yLabels) || data.labels || []; } beforeLayout() { this._cache = {}; this._dataLimitsCached = false; } beforeUpdate() { callback(this.options.beforeUpdate, [this]); } update(maxWidth, maxHeight, margins) { const {beginAtZero, grace, ticks: tickOpts} = this.options; const sampleSize = tickOpts.sampleSize; this.beforeUpdate(); this.maxWidth = maxWidth; this.maxHeight = maxHeight; this._margins = margins = Object.assign({ left: 0, right: 0, top: 0, bottom: 0 }, margins); this.ticks = null; this._labelSizes = null; this._gridLineItems = null; this._labelItems = null; this.beforeSetDimensions(); this.setDimensions(); this.afterSetDimensions(); this._maxLength = this.isHorizontal() ? this.width + margins.left + margins.right : this.height + margins.top + margins.bottom; if (!this._dataLimitsCached) { this.beforeDataLimits(); this.determineDataLimits(); this.afterDataLimits(); this._range = _addGrace(this, grace, beginAtZero); this._dataLimitsCached = true; } this.beforeBuildTicks(); this.ticks = this.buildTicks() || []; this.afterBuildTicks(); const samplingEnabled = sampleSize < this.ticks.length; this._convertTicksToLabels(samplingEnabled ? sample(this.ticks, sampleSize) : this.ticks); this.configure(); this.beforeCalculateLabelRotation(); this.calculateLabelRotation(); this.afterCalculateLabelRotation(); if (tickOpts.display && (tickOpts.autoSkip || tickOpts.source === 'auto')) { this.ticks = autoSkip(this, this.ticks); this._labelSizes = null; } if (samplingEnabled) { this._convertTicksToLabels(this.ticks); } this.beforeFit(); this.fit(); this.afterFit(); this.afterUpdate(); } configure() { let reversePixels = this.options.reverse; let startPixel, endPixel; if (this.isHorizontal()) { startPixel = this.left; endPixel = this.right; } else { startPixel = this.top; endPixel = this.bottom; reversePixels = !reversePixels; } this._startPixel = startPixel; this._endPixel = endPixel; this._reversePixels = reversePixels; this._length = endPixel - startPixel; this._alignToPixels = this.options.alignToPixels; } afterUpdate() { callback(this.options.afterUpdate, [this]); } beforeSetDimensions() { callback(this.options.beforeSetDimensions, [this]); } setDimensions() { if (this.isHorizontal()) { this.width = this.maxWidth; this.left = 0; this.right = this.width; } else { this.height = this.maxHeight; this.top = 0; this.bottom = this.height; } this.paddingLeft = 0; this.paddingTop = 0; this.paddingRight = 0; this.paddingBottom = 0; } afterSetDimensions() { callback(this.options.afterSetDimensions, [this]); } _callHooks(name) { this.chart.notifyPlugins(name, this.getContext()); callback(this.options[name], [this]); } beforeDataLimits() { this._callHooks('beforeDataLimits'); } determineDataLimits() {} afterDataLimits() { this._callHooks('afterDataLimits'); } beforeBuildTicks() { this._callHooks('beforeBuildTicks'); } buildTicks() { return []; } afterBuildTicks() { this._callHooks('afterBuildTicks'); } beforeTickToLabelConversion() { callback(this.options.beforeTickToLabelConversion, [this]); } generateTickLabels(ticks) { const tickOpts = this.options.ticks; let i, ilen, tick; for (i = 0, ilen = ticks.length; i < ilen; i++) { tick = ticks[i]; tick.label = callback(tickOpts.callback, [tick.value, i, ticks], this); } } afterTickToLabelConversion() { callback(this.options.afterTickToLabelConversion, [this]); } beforeCalculateLabelRotation() { callback(this.options.beforeCalculateLabelRotation, [this]); } calculateLabelRotation() { const options = this.options; const tickOpts = options.ticks; const numTicks = this.ticks.length; const minRotation = tickOpts.minRotation || 0; const maxRotation = tickOpts.maxRotation; let labelRotation = minRotation; let tickWidth, maxHeight, maxLabelDiagonal; if (!this._isVisible() || !tickOpts.display || minRotation >= maxRotation || numTicks <= 1 || !this.isHorizontal()) { this.labelRotation = minRotation; return; } const labelSizes = this._getLabelSizes(); const maxLabelWidth = labelSizes.widest.width; const maxLabelHeight = labelSizes.highest.height; const maxWidth = _limitValue(this.chart.width - maxLabelWidth, 0, this.maxWidth); tickWidth = options.offset ? this.maxWidth / numTicks : maxWidth / (numTicks - 1); if (maxLabelWidth + 6 > tickWidth) { tickWidth = maxWidth / (numTicks - (options.offset ? 0.5 : 1)); maxHeight = this.maxHeight - getTickMarkLength(options.grid) - tickOpts.padding - getTitleHeight(options.title, this.chart.options.font); maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight); labelRotation = toDegrees(Math.min( Math.asin(_limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)), Math.asin(_limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(_limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1)) )); labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation)); } this.labelRotation = labelRotation; } afterCalculateLabelRotation() { callback(this.options.afterCalculateLabelRotation, [this]); } beforeFit() { callback(this.options.beforeFit, [this]); } fit() { const minSize = { width: 0, height: 0 }; const {chart, options: {ticks: tickOpts, title: titleOpts, grid: gridOpts}} = this; const display = this._isVisible(); const isHorizontal = this.isHorizontal(); if (display) { const titleHeight = getTitleHeight(titleOpts, chart.options.font); if (isHorizontal) { minSize.width = this.maxWidth; minSize.height = getTickMarkLength(gridOpts) + titleHeight; } else { minSize.height = this.maxHeight; minSize.width = getTickMarkLength(gridOpts) + titleHeight; } if (tickOpts.display && this.ticks.length) { const {first, last, widest, highest} = this._getLabelSizes(); const tickPadding = tickOpts.padding * 2; const angleRadians = toRadians(this.labelRotation); const cos = Math.cos(angleRadians); const sin = Math.sin(angleRadians); if (isHorizontal) { const labelHeight = tickOpts.mirror ? 0 : sin * widest.width + cos * highest.height; minSize.height = Math.min(this.maxHeight, minSize.height + labelHeight + tickPadding); } else { const labelWidth = tickOpts.mirror ? 0 : cos * widest.width + sin * highest.height; minSize.width = Math.min(this.maxWidth, minSize.width + labelWidth + tickPadding); } this._calculatePadding(first, last, sin, cos); } } this._handleMargins(); if (isHorizontal) { this.width = this._length = chart.width - this._margins.left - this._margins.right; this.height = minSize.height; } else { this.width = minSize.width; this.height = this._length = chart.height - this._margins.top - this._margins.bottom; } } _calculatePadding(first, last, sin, cos) { const {ticks: {align, padding}, position} = this.options; const isRotated = this.labelRotation !== 0; const labelsBelowTicks = position !== 'top' && this.axis === 'x'; if (this.isHorizontal()) { const offsetLeft = this.getPixelForTick(0) - this.left; const offsetRight = this.right - this.getPixelForTick(this.ticks.length - 1); let paddingLeft = 0; let paddingRight = 0; if (isRotated) { if (labelsBelowTicks) { paddingLeft = cos * first.width; paddingRight = sin * last.height; } else { paddingLeft = sin * first.height; paddingRight = cos * last.width; } } else if (align === 'start') { paddingRight = last.width; } else if (align === 'end') { paddingLeft = first.width; } else { paddingLeft = first.width / 2; paddingRight = last.width / 2; } this.paddingLeft = Math.max((paddingLeft - offsetLeft + padding) * this.width / (this.width - offsetLeft), 0); this.paddingRight = Math.max((paddingRight - offsetRight + padding) * this.width / (this.width - offsetRight), 0); } else { let paddingTop = last.height / 2; let paddingBottom = first.height / 2; if (align === 'start') { paddingTop = 0; paddingBottom = first.height; } else if (align === 'end') { paddingTop = last.height; paddingBottom = 0; } this.paddingTop = paddingTop + padding; this.paddingBottom = paddingBottom + padding; } } _handleMargins() { if (this._margins) { this._margins.left = Math.max(this.paddingLeft, this._margins.left); this._margins.top = Math.max(this.paddingTop, this._margins.top); this._margins.right = Math.max(this.paddingRight, this._margins.right); this._margins.bottom = Math.max(this.paddingBottom, this._margins.bottom); } } afterFit() { callback(this.options.afterFit, [this]); } isHorizontal() { const {axis, position} = this.options; return position === 'top' || position === 'bottom' || axis === 'x'; } isFullSize() { return this.options.fullSize; } _convertTicksToLabels(ticks) { this.beforeTickToLabelConversion(); this.generateTickLabels(ticks); let i, ilen; for (i = 0, ilen = ticks.length; i < ilen; i++) { if (isNullOrUndef(ticks[i].label)) { ticks.splice(i, 1); ilen--; i--; } } this.afterTickToLabelConversion(); } _getLabelSizes() { let labelSizes = this._labelSizes; if (!labelSizes) { const sampleSize = this.options.ticks.sampleSize; let ticks = this.ticks; if (sampleSize < ticks.length) { ticks = sample(ticks, sampleSize); } this._labelSizes = labelSizes = this._computeLabelSizes(ticks, ticks.length); } return labelSizes; } _computeLabelSizes(ticks, length) { const {ctx, _longestTextCache: caches} = this; const widths = []; const heights = []; let widestLabelSize = 0; let highestLabelSize = 0; let i, j, jlen, label, tickFont, fontString, cache, lineHeight, width, height, nestedLabel; for (i = 0; i < length; ++i) { label = ticks[i].label; tickFont = this._resolveTickFontOptions(i); ctx.font = fontString = tickFont.string; cache = caches[fontString] = caches[fontString] || {data: {}, gc: []}; lineHeight = tickFont.lineHeight; width = height = 0; if (!isNullOrUndef(label) && !isArray(label)) { width = _measureText(ctx, cache.data, cache.gc, width, label); height = lineHeight; } else if (isArray(label)) { for (j = 0, jlen = label.length; j < jlen; ++j) { nestedLabel = label[j]; if (!isNullOrUndef(nestedLabel) && !isArray(nestedLabel)) { width = _measureText(ctx, cache.data, cache.gc, width, nestedLabel); height += lineHeight; } } } widths.push(width); heights.push(height); widestLabelSize = Math.max(width, widestLabelSize); highestLabelSize = Math.max(height, highestLabelSize); } garbageCollect(caches, length); const widest = widths.indexOf(widestLabelSize); const highest = heights.indexOf(highestLabelSize); const valueAt = (idx) => ({width: widths[idx] || 0, height: heights[idx] || 0}); return { first: valueAt(0), last: valueAt(length - 1), widest: valueAt(widest), highest: valueAt(highest), widths, heights, }; } getLabelForValue(value) { return value; } getPixelForValue(value, index) { return NaN; } getValueForPixel(pixel) {} getPixelForTick(index) { const ticks = this.ticks; if (index < 0 || index > ticks.length - 1) { return null; } return this.getPixelForValue(ticks[index].value); } getPixelForDecimal(decimal) { if (this._reversePixels) { decimal = 1 - decimal; } const pixel = this._startPixel + decimal * this._length; return _int16Range(this._alignToPixels ? _alignPixel(this.chart, pixel, 0) : pixel); } getDecimalForPixel(pixel) { const decimal = (pixel - this._startPixel) / this._length; return this._reversePixels ? 1 - decimal : decimal; } getBasePixel() { return this.getPixelForValue(this.getBaseValue()); } getBaseValue() { const {min, max} = this; return min < 0 && max < 0 ? max : min > 0 && max > 0 ? min : 0; } getContext(index) { const ticks = this.ticks || []; if (index >= 0 && index < ticks.length) { const tick = ticks[index]; return tick.$context || (tick.$context = createTickContext(this.getContext(), index, tick)); } return this.$context || (this.$context = createScaleContext(this.chart.getContext(), this)); } _tickSize() { const optionTicks = this.options.ticks; const rot = toRadians(this.labelRotation); const cos = Math.abs(Math.cos(rot)); const sin = Math.abs(Math.sin(rot)); const labelSizes = this._getLabelSizes(); const padding = optionTicks.autoSkipPadding || 0; const w = labelSizes ? labelSizes.widest.width + padding : 0; const h = labelSizes ? labelSizes.highest.height + padding : 0; return this.isHorizontal() ? h * cos > w * sin ? w / cos : h / sin : h * sin < w * cos ? h / cos : w / sin; } _isVisible() { const display = this.options.display; if (display !== 'auto') { return !!display; } return this.getMatchingVisibleMetas().length > 0; } _computeGridLineItems(chartArea) { const axis = this.axis; const chart = this.chart; const options = this.options; const {grid, position} = options; const offset = grid.offset; const isHorizontal = this.isHorizontal(); const ticks = this.ticks; const ticksLength = ticks.length + (offset ? 1 : 0); const tl = getTickMarkLength(grid); const items = []; const borderOpts = grid.setContext(this.getContext()); const axisWidth = borderOpts.drawBorder ? borderOpts.borderWidth : 0; const axisHalfWidth = axisWidth / 2; const alignBorderValue = function(pixel) { return _alignPixel(chart, pixel, axisWidth); }; let borderValue, i, lineValue, alignedLineValue; let tx1, ty1, tx2, ty2, x1, y1, x2, y2; if (position === 'top') { borderValue = alignBorderValue(this.bottom); ty1 = this.bottom - tl; ty2 = borderValue - axisHalfWidth; y1 = alignBorderValue(chartArea.top) + axisHalfWidth; y2 = chartArea.bottom; } else if (position === 'bottom') { borderValue = alignBorderValue(this.top); y1 = chartArea.top; y2 = alignBorderValue(chartArea.bottom) - axisHalfWidth; ty1 = borderValue + axisHalfWidth; ty2 = this.top + tl; } else if (position === 'left') { borderValue = alignBorderValue(this.right); tx1 = this.right - tl; tx2 = borderValue - axisHalfWidth; x1 = alignBorderValue(chartArea.left) + axisHalfWidth; x2 = chartArea.right; } else if (position === 'right') { borderValue = alignBorderValue(this.left); x1 = chartArea.left; x2 = alignBorderValue(chartArea.right) - axisHalfWidth; tx1 = borderValue + axisHalfWidth; tx2 = this.left + tl; } else if (axis === 'x') { if (position === 'center') { borderValue = alignBorderValue((chartArea.top + chartArea.bottom) / 2 + 0.5); } else if (isObject(position)) { const positionAxisID = Object.keys(position)[0]; const value = position[positionAxisID]; borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value)); } y1 = chartArea.top; y2 = chartArea.bottom; ty1 = borderValue + axisHalfWidth; ty2 = ty1 + tl; } else if (axis === 'y') { if (position === 'center') { borderValue = alignBorderValue((chartArea.left + chartArea.right) / 2); } else if (isObject(position)) { const positionAxisID = Object.keys(position)[0]; const value = position[positionAxisID]; borderValue = alignBorderValue(this.chart.scales[positionAxisID].getPixelForValue(value)); } tx1 = borderValue - axisHalfWidth; tx2 = tx1 - tl; x1 = chartArea.left; x2 = chartArea.right; } const limit = valueOrDefault(options.ticks.maxTicksLimit, ticksLength); const step = Math.max(1, Math.ceil(ticksLength / limit)); for (i = 0; i < ticksLength; i += step) { const optsAtIndex = grid.setContext(this.getContext(i)); const lineWidth = optsAtIndex.lineWidth; const lineColor = optsAtIndex.color; const borderDash = grid.borderDash || []; const borderDashOffset = optsAtIndex.borderDashOffset; const tickWidth = optsAtIndex.tickWidth; const tickColor = optsAtIndex.tickColor; const tickBorderDash = optsAtIndex.tickBorderDash || []; const tickBorderDashOffset = optsAtIndex.tickBorderDashOffset; lineValue = getPixelForGridLine(this, i, offset); if (lineValue === undefined) { continue; } alignedLineValue = _alignPixel(chart, lineValue, lineWidth); if (isHorizontal) { tx1 = tx2 = x1 = x2 = alignedLineValue; } else { ty1 = ty2 = y1 = y2 = alignedLineValue; } items.push({ tx1, ty1, tx2, ty2, x1, y1, x2, y2, width: lineWidth, color: lineColor, borderDash, borderDashOffset, tickWidth, tickColor, tickBorderDash, tickBorderDashOffset, }); } this._ticksLength = ticksLength; this._borderValue = borderValue; return items; } _computeLabelItems(chartArea) { const axis = this.axis; const options = this.options; const {position, ticks: optionTicks} = options; const isHorizontal = this.isHorizontal(); const ticks = this.ticks; const {align, crossAlign, padding, mirror} = optionTicks; const tl = getTickMarkLength(options.grid); const tickAndPadding = tl + padding; const hTickAndPadding = mirror ? -padding : tickAndPadding; const rotation = -toRadians(this.labelRotation); const items = []; let i, ilen, tick, label, x, y, textAlign, pixel, font, lineHeight, lineCount, textOffset; let textBaseline = 'middle'; if (position === 'top') { y = this.bottom - hTickAndPadding; textAlign = this._getXAxisLabelAlignment(); } else if (position === 'bottom') { y = this.top + hTickAndPadding; textAlign = this._getXAxisLabelAlignment(); } else if (position === 'left') { const ret = this._getYAxisLabelAlignment(tl); textAlign = ret.textAlign; x = ret.x; } else if (position === 'right') { const ret = this._getYAxisLabelAlignment(tl); textAlign = ret.textAlign; x = ret.x; } else if (axis === 'x') { if (position === 'center') { y = ((chartArea.top + chartArea.bottom) / 2) + tickAndPadding; } else if (isObject(position)) { const positionAxisID = Object.keys(position)[0]; const value = position[positionAxisID]; y = this.chart.scales[positionAxisID].getPixelForValue(value) + tickAndPadding; } textAlign = this._getXAxisLabelAlignment(); } else if (axis === 'y') { if (position === 'center') { x = ((chartArea.left + chartArea.right) / 2) - tickAndPadding; } else if (isObject(position)) { const positionAxisID = Object.keys(position)[0]; const value = position[positionAxisID]; x = this.chart.scales[positionAxisID].getPixelForValue(value); } textAlign = this._getYAxisLabelAlignment(tl).textAlign; } if (axis === 'y') { if (align === 'start') { textBaseline = 'top'; } else if (align === 'end') { textBaseline = 'bottom'; } } const labelSizes = this._getLabelSizes(); for (i = 0, ilen = ticks.length; i < ilen; ++i) { tick = ticks[i]; label = tick.label; const optsAtIndex = optionTicks.setContext(this.getContext(i)); pixel = this.getPixelForTick(i) + optionTicks.labelOffset; font = this._resolveTickFontOptions(i); lineHeight = font.lineHeight; lineCount = isArray(label) ? label.length : 1; const halfCount = lineCount / 2; const color = optsAtIndex.color; const strokeColor = optsAtIndex.textStrokeColor; const strokeWidth = optsAtIndex.textStrokeWidth; if (isHorizontal) { x = pixel; if (position === 'top') { if (crossAlign === 'near' || rotation !== 0) { textOffset = -lineCount * lineHeight + lineHeight / 2; } else if (crossAlign === 'center') { textOffset = -labelSizes.highest.height / 2 - halfCount * lineHeight + lineHeight; } else { textOffset = -labelSizes.highest.height + lineHeight / 2; } } else { if (crossAlign === 'near' || rotation !== 0) { textOffset = lineHeight / 2; } else if (crossAlign === 'center') { textOffset = labelSizes.highest.height / 2 - halfCount * lineHeight; } else { textOffset = labelSizes.highest.height - lineCount * lineHeight; } } if (mirror) { textOffset *= -1; } } else { y = pixel; textOffset = (1 - lineCount) * lineHeight / 2; } let backdrop; if (optsAtIndex.showLabelBackdrop) { const labelPadding = toPadding(optsAtIndex.backdropPadding); const height = labelSizes.heights[i]; const width = labelSizes.widths[i]; let top = y + textOffset - labelPadding.top; let left = x - labelPadding.left; switch (textBaseline) { case 'middle': top -= height / 2; break; case 'bottom': top -= height; break; } switch (textAlign) { case 'center': left -= width / 2; break; case 'right': left -= width; break; } backdrop = { left, top, width: width + labelPadding.width, height: height + labelPadding.height, color: optsAtIndex.backdropColor, }; } items.push({ rotation, label, font, color, strokeColor, strokeWidth, textOffset, textAlign, textBaseline, translation: [x, y], backdrop, }); } return items; } _getXAxisLabelAlignment() { const {position, ticks} = this.options; const rotation = -toRadians(this.labelRotation); if (rotation) { return position === 'top' ? 'left' : 'right'; } let align = 'center'; if (ticks.align === 'start') { align = 'left'; } else if (ticks.align === 'end') { align = 'right'; } return align; } _getYAxisLabelAlignment(tl) { const {position, ticks: {crossAlign, mirror, padding}} = this.options; const labelSizes = this._getLabelSizes(); const tickAndPadding = tl + padding; const widest = labelSizes.widest.width; let textAlign; let x; if (position === 'left') { if (mirror) { x = this.right + padding; if (crossAlign === 'near') { textAlign = 'left'; } else if (crossAlign === 'center') { textAlign = 'center'; x += (widest / 2); } else { textAlign = 'right'; x += widest; } } else { x = this.right - tickAndPadding; if (crossAlign === 'near') { textAlign = 'right'; } else if (crossAlign === 'center') { textAlign = 'center'; x -= (widest / 2); } else { textAlign = 'left'; x = this.left; } } } else if (position === 'right') { if (mirror) { x = this.left + padding; if (crossAlign === 'near') { textAlign = 'right'; } else if (crossAlign === 'center') { textAlign = 'center'; x -= (widest / 2); } else { textAlign = 'left'; x -= widest; } } else { x = this.left + tickAndPadding; if (crossAlign === 'near') { textAlign = 'left'; } else if (crossAlign === 'center') { textAlign = 'center'; x += widest / 2; } else { textAlign = 'right'; x = this.right; } } } else { textAlign = 'right'; } return {textAlign, x}; } _computeLabelArea() { if (this.options.ticks.mirror) { return; } const chart = this.chart; const position = this.options.position; if (position === 'left' || position === 'right') { return {top: 0, left: this.left, bottom: chart.height, right: this.right}; } if (position === 'top' || position === 'bottom') { return {top: this.top, left: 0, bottom: this.bottom, right: chart.width}; } } drawBackground() { const {ctx, options: {backgroundColor}, left, top, width, height} = this; if (backgroundColor) { ctx.save(); ctx.fillStyle = backgroundColor; ctx.fillRect(left, top, width, height); ctx.restore(); } } getLineWidthForValue(value) { const grid = this.options.grid; if (!this._isVisible() || !grid.display) { return 0; } const ticks = this.ticks; const index = ticks.findIndex(t => t.value === value); if (index >= 0) { const opts = grid.setContext(this.getContext(index)); return opts.lineWidth; } return 0; } drawGrid(chartArea) { const grid = this.options.grid; const ctx = this.ctx; const items = this._gridLineItems || (this._gridLineItems = this._computeGridLineItems(chartArea)); let i, ilen; const drawLine = (p1, p2, style) => { if (!style.width || !style.color) { return; } ctx.save(); ctx.lineWidth = style.width; ctx.strokeStyle = style.color; ctx.setLineDash(style.borderDash || []); ctx.lineDashOffset = style.borderDashOffset; ctx.beginPath(); ctx.moveTo(p1.x, p1.y); ctx.lineTo(p2.x, p2.y); ctx.stroke(); ctx.restore(); }; if (grid.display) { for (i = 0, ilen = items.length; i < ilen; ++i) { const item = items[i]; if (grid.drawOnChartArea) { drawLine( {x: item.x1, y: item.y1}, {x: item.x2, y: item.y2}, item ); } if (grid.drawTicks) { drawLine( {x: item.tx1, y: item.ty1}, {x: item.tx2, y: item.ty2}, { color: item.tickColor, width: item.tickWidth, borderDash: item.tickBorderDash, borderDashOffset: item.tickBorderDashOffset } ); } } } } drawBorder() { const {chart, ctx, options: {grid}} = this; const borderOpts = grid.setContext(this.getContext()); const axisWidth = grid.drawBorder ? borderOpts.borderWidth : 0; if (!axisWidth) { return; } const lastLineWidth = grid.setContext(this.getContext(0)).lineWidth; const borderValue = this._borderValue; let x1, x2, y1, y2; if (this.isHorizontal()) { x1 = _alignPixel(chart, this.left, axisWidth) - axisWidth / 2; x2 = _alignPixel(chart, this.right, lastLineWidth) + lastLineWidth / 2; y1 = y2 = borderValue; } else { y1 = _alignPixel(chart, this.top, axisWidth) - axisWidth / 2; y2 = _alignPixel(chart, this.bottom, lastLineWidth) + lastLineWidth / 2; x1 = x2 = borderValue; } ctx.save(); ctx.lineWidth = borderOpts.borderWidth; ctx.strokeStyle = borderOpts.borderColor; ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); ctx.restore(); } drawLabels(chartArea) { const optionTicks = this.options.ticks; if (!optionTicks.display) { return; } const ctx = this.ctx; const area = this._computeLabelArea(); if (area) { clipArea(ctx, area); } const items = this._labelItems || (this._labelItems = this._computeLabelItems(chartArea)); let i, ilen; for (i = 0, ilen = items.length; i < ilen; ++i) { const item = items[i]; const tickFont = item.font; const label = item.label; if (item.backdrop) { ctx.fillStyle = item.backdrop.color; ctx.fillRect(item.backdrop.left, item.backdrop.top, item.backdrop.width, item.backdrop.height); } let y = item.textOffset; renderText(ctx, label, 0, y, tickFont, item); } if (area) { unclipArea(ctx); } } drawTitle() { const {ctx, options: {position, title, reverse}} = this; if (!title.display) { return; } const font = toFont(title.font); const padding = toPadding(title.padding); const align = title.align; let offset = font.lineHeight / 2; if (position === 'bottom' || position === 'center' || isObject(position)) { offset += padding.bottom; if (isArray(title.text)) { offset += font.lineHeight * (title.text.length - 1); } } else { offset += padding.top; } const {titleX, titleY, maxWidth, rotation} = titleArgs(this, offset, position, align); renderText(ctx, title.text, 0, 0, font, { color: title.color, maxWidth, rotation, textAlign: titleAlign(align, position, reverse), textBaseline: 'middle', translation: [titleX, titleY], }); } draw(chartArea) { if (!this._isVisible()) { return; } this.drawBackground(); this.drawGrid(chartArea); this.drawBorder(); this.drawTitle(); this.drawLabels(chartArea); } _layers() { const opts = this.options; const tz = opts.ticks && opts.ticks.z || 0; const gz = valueOrDefault(opts.grid && opts.grid.z, -1); if (!this._isVisible() || this.draw !== Scale.prototype.draw) { return [{ z: tz, draw: (chartArea) => { this.draw(chartArea); } }]; } return [{ z: gz, draw: (chartArea) => { this.drawBackground(); this.drawGrid(chartArea); this.drawTitle(); } }, { z: gz + 1, draw: () => { this.drawBorder(); } }, { z: tz, draw: (chartArea) => { this.drawLabels(chartArea); } }]; } getMatchingVisibleMetas(type) { const metas = this.chart.getSortedVisibleDatasetMetas(); const axisID = this.axis + 'AxisID'; const result = []; let i, ilen; for (i = 0, ilen = metas.length; i < ilen; ++i) { const meta = metas[i]; if (meta[axisID] === this.id && (!type || meta.type === type)) { result.push(meta); } } return result; } _resolveTickFontOptions(index) { const opts = this.options.ticks.setContext(this.getContext(index)); return toFont(opts.font); } _maxDigits() { const fontSize = this._resolveTickFontOptions(0).lineHeight; return (this.isHorizontal() ? this.width : this.height) / fontSize; } } class TypedRegistry { constructor(type, scope, override) { this.type = type; this.scope = scope; this.override = override; this.items = Object.create(null); } isForType(type) { return Object.prototype.isPrototypeOf.call(this.type.prototype, type.prototype); } register(item) { const proto = Object.getPrototypeOf(item); let parentScope; if (isIChartComponent(proto)) { parentScope = this.register(proto); } const items = this.items; const id = item.id; const scope = this.scope + '.' + id; if (!id) { throw new Error('class does not have id: ' + item); } if (id in items) { return scope; } items[id] = item; registerDefaults(item, scope, parentScope); if (this.override) { defaults.override(item.id, item.overrides); } return scope; } get(id) { return this.items[id]; } unregister(item) { const items = this.items; const id = item.id; const scope = this.scope; if (id in items) { delete items[id]; } if (scope && id in defaults[scope]) { delete defaults[scope][id]; if (this.override) { delete overrides[id]; } } } } function registerDefaults(item, scope, parentScope) { const itemDefaults = merge(Object.create(null), [ parentScope ? defaults.get(parentScope) : {}, defaults.get(scope), item.defaults ]); defaults.set(scope, itemDefaults); if (item.defaultRoutes) { routeDefaults(scope, item.defaultRoutes); } if (item.descriptors) { defaults.describe(scope, item.descriptors); } } function routeDefaults(scope, routes) { Object.keys(routes).forEach(property => { const propertyParts = property.split('.'); const sourceName = propertyParts.pop(); const sourceScope = [scope].concat(propertyParts).join('.'); const parts = routes[property].split('.'); const targetName = parts.pop(); const targetScope = parts.join('.'); defaults.route(sourceScope, sourceName, targetScope, targetName); }); } function isIChartComponent(proto) { return 'id' in proto && 'defaults' in proto; } class Registry { constructor() { this.controllers = new TypedRegistry(DatasetController, 'datasets', true); this.elements = new TypedRegistry(Element, 'elements'); this.plugins = new TypedRegistry(Object, 'plugins'); this.scales = new TypedRegistry(Scale, 'scales'); this._typedRegistries = [this.controllers, this.scales, this.elements]; } add(...args) { this._each('register', args); } remove(...args) { this._each('unregister', args); } addControllers(...args) { this._each('register', args, this.controllers); } addElements(...args) { this._each('register', args, this.elements); } addPlugins(...args) { this._each('register', args, this.plugins); } addScales(...args) { this._each('register', args, this.scales); } getController(id) { return this._get(id, this.controllers, 'controller'); } getElement(id) { return this._get(id, this.elements, 'element'); } getPlugin(id) { return this._get(id, this.plugins, 'plugin'); } getScale(id) { return this._get(id, this.scales, 'scale'); } removeControllers(...args) { this._each('unregister', args, this.controllers); } removeElements(...args) { this._each('unregister', args, this.elements); } removePlugins(...args) { this._each('unregister', args, this.plugins); } removeScales(...args) { this._each('unregister', args, this.scales); } _each(method, args, typedRegistry) { [...args].forEach(arg => { const reg = typedRegistry || this._getRegistryForType(arg); if (typedRegistry || reg.isForType(arg) || (reg === this.plugins && arg.id)) { this._exec(method, reg, arg); } else { each(arg, item => { const itemReg = typedRegistry || this._getRegistryForType(item); this._exec(method, itemReg, item); }); } }); } _exec(method, registry, component) { const camelMethod = _capitalize(method); callback(component['before' + camelMethod], [], component); registry[method](component); callback(component['after' + camelMethod], [], component); } _getRegistryForType(type) { for (let i = 0; i < this._typedRegistries.length; i++) { const reg = this._typedRegistries[i]; if (reg.isForType(type)) { return reg; } } return this.plugins; } _get(id, typedRegistry, type) { const item = typedRegistry.get(id); if (item === undefined) { throw new Error('"' + id + '" is not a registered ' + type + '.'); } return item; } } var registry = new Registry(); class PluginService { constructor() { this._init = []; } notify(chart, hook, args, filter) { if (hook === 'beforeInit') { this._init = this._createDescriptors(chart, true); this._notify(this._init, chart, 'install'); } const descriptors = filter ? this._descriptors(chart).filter(filter) : this._descriptors(chart); const result = this._notify(descriptors, chart, hook, args); if (hook === 'destroy') { this._notify(descriptors, chart, 'stop'); this._notify(this._init, chart, 'uninstall'); } return result; } _notify(descriptors, chart, hook, args) { args = args || {}; for (const descriptor of descriptors) { const plugin = descriptor.plugin; const method = plugin[hook]; const params = [chart, args, descriptor.options]; if (callback(method, params, plugin) === false && args.cancelable) { return false; } } return true; } invalidate() { if (!isNullOrUndef(this._cache)) { this._oldCache = this._cache; this._cache = undefined; } } _descriptors(chart) { if (this._cache) { return this._cache; } const descriptors = this._cache = this._createDescriptors(chart); this._notifyStateChanges(chart); return descriptors; } _createDescriptors(chart, all) { const config = chart && chart.config; const options = valueOrDefault(config.options && config.options.plugins, {}); const plugins = allPlugins(config); return options === false && !all ? [] : createDescriptors(chart, plugins, options, all); } _notifyStateChanges(chart) { const previousDescriptors = this._oldCache || []; const descriptors = this._cache; const diff = (a, b) => a.filter(x => !b.some(y => x.plugin.id === y.plugin.id)); this._notify(diff(previousDescriptors, descriptors), chart, 'stop'); this._notify(diff(descriptors, previousDescriptors), chart, 'start'); } } function allPlugins(config) { const plugins = []; const keys = Object.keys(registry.plugins.items); for (let i = 0; i < keys.length; i++) { plugins.push(registry.getPlugin(keys[i])); } const local = config.plugins || []; for (let i = 0; i < local.length; i++) { const plugin = local[i]; if (plugins.indexOf(plugin) === -1) { plugins.push(plugin); } } return plugins; } function getOpts(options, all) { if (!all && options === false) { return null; } if (options === true) { return {}; } return options; } function createDescriptors(chart, plugins, options, all) { const result = []; const context = chart.getContext(); for (let i = 0; i < plugins.length; i++) { const plugin = plugins[i]; const id = plugin.id; const opts = getOpts(options[id], all); if (opts === null) { continue; } result.push({ plugin, options: pluginOpts(chart.config, plugin, opts, context) }); } return result; } function pluginOpts(config, plugin, opts, context) { const keys = config.pluginScopeKeys(plugin); const scopes = config.getOptionScopes(opts, keys); return config.createResolver(scopes, context, [''], {scriptable: false, indexable: false, allKeys: true}); } function getIndexAxis(type, options) { const datasetDefaults = defaults.datasets[type] || {}; const datasetOptions = (options.datasets || {})[type] || {}; return datasetOptions.indexAxis || options.indexAxis || datasetDefaults.indexAxis || 'x'; } function getAxisFromDefaultScaleID(id, indexAxis) { let axis = id; if (id === '_index_') { axis = indexAxis; } else if (id === '_value_') { axis = indexAxis === 'x' ? 'y' : 'x'; } return axis; } function getDefaultScaleIDFromAxis(axis, indexAxis) { return axis === indexAxis ? '_index_' : '_value_'; } function axisFromPosition(position) { if (position === 'top' || position === 'bottom') { return 'x'; } if (position === 'left' || position === 'right') { return 'y'; } } function determineAxis(id, scaleOptions) { if (id === 'x' || id === 'y') { return id; } return scaleOptions.axis || axisFromPosition(scaleOptions.position) || id.charAt(0).toLowerCase(); } function mergeScaleConfig(config, options) { const chartDefaults = overrides[config.type] || {scales: {}}; const configScales = options.scales || {}; const chartIndexAxis = getIndexAxis(config.type, options); const firstIDs = Object.create(null); const scales = Object.create(null); Object.keys(configScales).forEach(id => { const scaleConf = configScales[id]; if (!isObject(scaleConf)) { return console.error(`Invalid scale configuration for scale: ${id}`); } if (scaleConf._proxy) { return console.warn(`Ignoring resolver passed as options for scale: ${id}`); } const axis = determineAxis(id, scaleConf); const defaultId = getDefaultScaleIDFromAxis(axis, chartIndexAxis); const defaultScaleOptions = chartDefaults.scales || {}; firstIDs[axis] = firstIDs[axis] || id; scales[id] = mergeIf(Object.create(null), [{axis}, scaleConf, defaultScaleOptions[axis], defaultScaleOptions[defaultId]]); }); config.data.datasets.forEach(dataset => { const type = dataset.type || config.type; const indexAxis = dataset.indexAxis || getIndexAxis(type, options); const datasetDefaults = overrides[type] || {}; const defaultScaleOptions = datasetDefaults.scales || {}; Object.keys(defaultScaleOptions).forEach(defaultID => { const axis = getAxisFromDefaultScaleID(defaultID, indexAxis); const id = dataset[axis + 'AxisID'] || firstIDs[axis] || axis; scales[id] = scales[id] || Object.create(null); mergeIf(scales[id], [{axis}, configScales[id], defaultScaleOptions[defaultID]]); }); }); Object.keys(scales).forEach(key => { const scale = scales[key]; mergeIf(scale, [defaults.scales[scale.type], defaults.scale]); }); return scales; } function initOptions(config) { const options = config.options || (config.options = {}); options.plugins = valueOrDefault(options.plugins, {}); options.scales = mergeScaleConfig(config, options); } function initData(data) { data = data || {}; data.datasets = data.datasets || []; data.labels = data.labels || []; return data; } function initConfig(config) { config = config || {}; config.data = initData(config.data); initOptions(config); return config; } const keyCache = new Map(); const keysCached = new Set(); function cachedKeys(cacheKey, generate) { let keys = keyCache.get(cacheKey); if (!keys) { keys = generate(); keyCache.set(cacheKey, keys); keysCached.add(keys); } return keys; } const addIfFound = (set, obj, key) => { const opts = resolveObjectKey(obj, key); if (opts !== undefined) { set.add(opts); } }; class Config { constructor(config) { this._config = initConfig(config); this._scopeCache = new Map(); this._resolverCache = new Map(); } get platform() { return this._config.platform; } get type() { return this._config.type; } set type(type) { this._config.type = type; } get data() { return this._config.data; } set data(data) { this._config.data = initData(data); } get options() { return this._config.options; } set options(options) { this._config.options = options; } get plugins() { return this._config.plugins; } update() { const config = this._config; this.clearCache(); initOptions(config); } clearCache() { this._scopeCache.clear(); this._resolverCache.clear(); } datasetScopeKeys(datasetType) { return cachedKeys(datasetType, () => [[ `datasets.${datasetType}`, '' ]]); } datasetAnimationScopeKeys(datasetType, transition) { return cachedKeys(`${datasetType}.transition.${transition}`, () => [ [ `datasets.${datasetType}.transitions.${transition}`, `transitions.${transition}`, ], [ `datasets.${datasetType}`, '' ] ]); } datasetElementScopeKeys(datasetType, elementType) { return cachedKeys(`${datasetType}-${elementType}`, () => [[ `datasets.${datasetType}.elements.${elementType}`, `datasets.${datasetType}`, `elements.${elementType}`, '' ]]); } pluginScopeKeys(plugin) { const id = plugin.id; const type = this.type; return cachedKeys(`${type}-plugin-${id}`, () => [[ `plugins.${id}`, ...plugin.additionalOptionScopes || [], ]]); } _cachedScopes(mainScope, resetCache) { const _scopeCache = this._scopeCache; let cache = _scopeCache.get(mainScope); if (!cache || resetCache) { cache = new Map(); _scopeCache.set(mainScope, cache); } return cache; } getOptionScopes(mainScope, keyLists, resetCache) { const {options, type} = this; const cache = this._cachedScopes(mainScope, resetCache); const cached = cache.get(keyLists); if (cached) { return cached; } const scopes = new Set(); keyLists.forEach(keys => { if (mainScope) { scopes.add(mainScope); keys.forEach(key => addIfFound(scopes, mainScope, key)); } keys.forEach(key => addIfFound(scopes, options, key)); keys.forEach(key => addIfFound(scopes, overrides[type] || {}, key)); keys.forEach(key => addIfFound(scopes, defaults, key)); keys.forEach(key => addIfFound(scopes, descriptors, key)); }); const array = Array.from(scopes); if (array.length === 0) { array.push(Object.create(null)); } if (keysCached.has(keyLists)) { cache.set(keyLists, array); } return array; } chartOptionScopes() { const {options, type} = this; return [ options, overrides[type] || {}, defaults.datasets[type] || {}, {type}, defaults, descriptors ]; } resolveNamedOptions(scopes, names, context, prefixes = ['']) { const result = {$shared: true}; const {resolver, subPrefixes} = getResolver(this._resolverCache, scopes, prefixes); let options = resolver; if (needContext(resolver, names)) { result.$shared = false; context = isFunction(context) ? context() : context; const subResolver = this.createResolver(scopes, context, subPrefixes); options = _attachContext(resolver, context, subResolver); } for (const prop of names) { result[prop] = options[prop]; } return result; } createResolver(scopes, context, prefixes = [''], descriptorDefaults) { const {resolver} = getResolver(this._resolverCache, scopes, prefixes); return isObject(context) ? _attachContext(resolver, context, undefined, descriptorDefaults) : resolver; } } function getResolver(resolverCache, scopes, prefixes) { let cache = resolverCache.get(scopes); if (!cache) { cache = new Map(); resolverCache.set(scopes, cache); } const cacheKey = prefixes.join(); let cached = cache.get(cacheKey); if (!cached) { const resolver = _createResolver(scopes, prefixes); cached = { resolver, subPrefixes: prefixes.filter(p => !p.toLowerCase().includes('hover')) }; cache.set(cacheKey, cached); } return cached; } const hasFunction = value => isObject(value) && Object.getOwnPropertyNames(value).reduce((acc, key) => acc || isFunction(value[key]), false); function needContext(proxy, names) { const {isScriptable, isIndexable} = _descriptors(proxy); for (const prop of names) { const scriptable = isScriptable(prop); const indexable = isIndexable(prop); const value = (indexable || scriptable) && proxy[prop]; if ((scriptable && (isFunction(value) || hasFunction(value))) || (indexable && isArray(value))) { return true; } } return false; } var version = "3.6.2"; const KNOWN_POSITIONS = ['top', 'bottom', 'left', 'right', 'chartArea']; function positionIsHorizontal(position, axis) { return position === 'top' || position === 'bottom' || (KNOWN_POSITIONS.indexOf(position) === -1 && axis === 'x'); } function compare2Level(l1, l2) { return function(a, b) { return a[l1] === b[l1] ? a[l2] - b[l2] : a[l1] - b[l1]; }; } function onAnimationsComplete(context) { const chart = context.chart; const animationOptions = chart.options.animation; chart.notifyPlugins('afterRender'); callback(animationOptions && animationOptions.onComplete, [context], chart); } function onAnimationProgress(context) { const chart = context.chart; const animationOptions = chart.options.animation; callback(animationOptions && animationOptions.onProgress, [context], chart); } function getCanvas(item) { if (_isDomSupported() && typeof item === 'string') { item = document.getElementById(item); } else if (item && item.length) { item = item[0]; } if (item && item.canvas) { item = item.canvas; } return item; } const instances = {}; const getChart = (key) => { const canvas = getCanvas(key); return Object.values(instances).filter((c) => c.canvas === canvas).pop(); }; function moveNumericKeys(obj, start, move) { const keys = Object.keys(obj); for (const key of keys) { const intKey = +key; if (intKey >= start) { const value = obj[key]; delete obj[key]; if (move > 0 || intKey > start) { obj[intKey + move] = value; } } } } class Chart { constructor(item, userConfig) { const config = this.config = new Config(userConfig); const initialCanvas = getCanvas(item); const existingChart = getChart(initialCanvas); if (existingChart) { throw new Error( 'Canvas is already in use. Chart with ID \'' + existingChart.id + '\'' + ' must be destroyed before the canvas can be reused.' ); } const options = config.createResolver(config.chartOptionScopes(), this.getContext()); this.platform = new (config.platform || _detectPlatform(initialCanvas))(); this.platform.updateConfig(config); const context = this.platform.acquireContext(initialCanvas, options.aspectRatio); const canvas = context && context.canvas; const height = canvas && canvas.height; const width = canvas && canvas.width; this.id = uid(); this.ctx = context; this.canvas = canvas; this.width = width; this.height = height; this._options = options; this._aspectRatio = this.aspectRatio; this._layers = []; this._metasets = []; this._stacks = undefined; this.boxes = []; this.currentDevicePixelRatio = undefined; this.chartArea = undefined; this._active = []; this._lastEvent = undefined; this._listeners = {}; this._responsiveListeners = undefined; this._sortedMetasets = []; this.scales = {}; this._plugins = new PluginService(); this.$proxies = {}; this._hiddenIndices = {}; this.attached = false; this._animationsDisabled = undefined; this.$context = undefined; this._doResize = debounce(mode => this.update(mode), options.resizeDelay || 0); this._dataChanges = []; instances[this.id] = this; if (!context || !canvas) { console.error("Failed to create chart: can't acquire context from the given item"); return; } animator.listen(this, 'complete', onAnimationsComplete); animator.listen(this, 'progress', onAnimationProgress); this._initialize(); if (this.attached) { this.update(); } } get aspectRatio() { const {options: {aspectRatio, maintainAspectRatio}, width, height, _aspectRatio} = this; if (!isNullOrUndef(aspectRatio)) { return aspectRatio; } if (maintainAspectRatio && _aspectRatio) { return _aspectRatio; } return height ? width / height : null; } get data() { return this.config.data; } set data(data) { this.config.data = data; } get options() { return this._options; } set options(options) { this.config.options = options; } _initialize() { this.notifyPlugins('beforeInit'); if (this.options.responsive) { this.resize(); } else { retinaScale(this, this.options.devicePixelRatio); } this.bindEvents(); this.notifyPlugins('afterInit'); return this; } clear() { clearCanvas(this.canvas, this.ctx); return this; } stop() { animator.stop(this); return this; } resize(width, height) { if (!animator.running(this)) { this._resize(width, height); } else { this._resizeBeforeDraw = {width, height}; } } _resize(width, height) { const options = this.options; const canvas = this.canvas; const aspectRatio = options.maintainAspectRatio && this.aspectRatio; const newSize = this.platform.getMaximumSize(canvas, width, height, aspectRatio); const newRatio = options.devicePixelRatio || this.platform.getDevicePixelRatio(); const mode = this.width ? 'resize' : 'attach'; this.width = newSize.width; this.height = newSize.height; this._aspectRatio = this.aspectRatio; if (!retinaScale(this, newRatio, true)) { return; } this.notifyPlugins('resize', {size: newSize}); callback(options.onResize, [this, newSize], this); if (this.attached) { if (this._doResize(mode)) { this.render(); } } } ensureScalesHaveIDs() { const options = this.options; const scalesOptions = options.scales || {}; each(scalesOptions, (axisOptions, axisID) => { axisOptions.id = axisID; }); } buildOrUpdateScales() { const options = this.options; const scaleOpts = options.scales; const scales = this.scales; const updated = Object.keys(scales).reduce((obj, id) => { obj[id] = false; return obj; }, {}); let items = []; if (scaleOpts) { items = items.concat( Object.keys(scaleOpts).map((id) => { const scaleOptions = scaleOpts[id]; const axis = determineAxis(id, scaleOptions); const isRadial = axis === 'r'; const isHorizontal = axis === 'x'; return { options: scaleOptions, dposition: isRadial ? 'chartArea' : isHorizontal ? 'bottom' : 'left', dtype: isRadial ? 'radialLinear' : isHorizontal ? 'category' : 'linear' }; }) ); } each(items, (item) => { const scaleOptions = item.options; const id = scaleOptions.id; const axis = determineAxis(id, scaleOptions); const scaleType = valueOrDefault(scaleOptions.type, item.dtype); if (scaleOptions.position === undefined || positionIsHorizontal(scaleOptions.position, axis) !== positionIsHorizontal(item.dposition)) { scaleOptions.position = item.dposition; } updated[id] = true; let scale = null; if (id in scales && scales[id].type === scaleType) { scale = scales[id]; } else { const scaleClass = registry.getScale(scaleType); scale = new scaleClass({ id, type: scaleType, ctx: this.ctx, chart: this }); scales[scale.id] = scale; } scale.init(scaleOptions, options); }); each(updated, (hasUpdated, id) => { if (!hasUpdated) { delete scales[id]; } }); each(scales, (scale) => { layouts.configure(this, scale, scale.options); layouts.addBox(this, scale); }); } _updateMetasets() { const metasets = this._metasets; const numData = this.data.datasets.length; const numMeta = metasets.length; metasets.sort((a, b) => a.index - b.index); if (numMeta > numData) { for (let i = numData; i < numMeta; ++i) { this._destroyDatasetMeta(i); } metasets.splice(numData, numMeta - numData); } this._sortedMetasets = metasets.slice(0).sort(compare2Level('order', 'index')); } _removeUnreferencedMetasets() { const {_metasets: metasets, data: {datasets}} = this; if (metasets.length > datasets.length) { delete this._stacks; } metasets.forEach((meta, index) => { if (datasets.filter(x => x === meta._dataset).length === 0) { this._destroyDatasetMeta(index); } }); } buildOrUpdateControllers() { const newControllers = []; const datasets = this.data.datasets; let i, ilen; this._removeUnreferencedMetasets(); for (i = 0, ilen = datasets.length; i < ilen; i++) { const dataset = datasets[i]; let meta = this.getDatasetMeta(i); const type = dataset.type || this.config.type; if (meta.type && meta.type !== type) { this._destroyDatasetMeta(i); meta = this.getDatasetMeta(i); } meta.type = type; meta.indexAxis = dataset.indexAxis || getIndexAxis(type, this.options); meta.order = dataset.order || 0; meta.index = i; meta.label = '' + dataset.label; meta.visible = this.isDatasetVisible(i); if (meta.controller) { meta.controller.updateIndex(i); meta.controller.linkScales(); } else { const ControllerClass = registry.getController(type); const {datasetElementType, dataElementType} = defaults.datasets[type]; Object.assign(ControllerClass.prototype, { dataElementType: registry.getElement(dataElementType), datasetElementType: datasetElementType && registry.getElement(datasetElementType) }); meta.controller = new ControllerClass(this, i); newControllers.push(meta.controller); } } this._updateMetasets(); return newControllers; } _resetElements() { each(this.data.datasets, (dataset, datasetIndex) => { this.getDatasetMeta(datasetIndex).controller.reset(); }, this); } reset() { this._resetElements(); this.notifyPlugins('reset'); } update(mode) { const config = this.config; config.update(); const options = this._options = config.createResolver(config.chartOptionScopes(), this.getContext()); const animsDisabled = this._animationsDisabled = !options.animation; this._updateScales(); this._checkEventBindings(); this._updateHiddenIndices(); this._plugins.invalidate(); if (this.notifyPlugins('beforeUpdate', {mode, cancelable: true}) === false) { return; } const newControllers = this.buildOrUpdateControllers(); this.notifyPlugins('beforeElementsUpdate'); let minPadding = 0; for (let i = 0, ilen = this.data.datasets.length; i < ilen; i++) { const {controller} = this.getDatasetMeta(i); const reset = !animsDisabled && newControllers.indexOf(controller) === -1; controller.buildOrUpdateElements(reset); minPadding = Math.max(+controller.getMaxOverflow(), minPadding); } minPadding = this._minPadding = options.layout.autoPadding ? minPadding : 0; this._updateLayout(minPadding); if (!animsDisabled) { each(newControllers, (controller) => { controller.reset(); }); } this._updateDatasets(mode); this.notifyPlugins('afterUpdate', {mode}); this._layers.sort(compare2Level('z', '_idx')); if (this._lastEvent) { this._eventHandler(this._lastEvent, true); } this.render(); } _updateScales() { each(this.scales, (scale) => { layouts.removeBox(this, scale); }); this.ensureScalesHaveIDs(); this.buildOrUpdateScales(); } _checkEventBindings() { const options = this.options; const existingEvents = new Set(Object.keys(this._listeners)); const newEvents = new Set(options.events); if (!setsEqual(existingEvents, newEvents) || !!this._responsiveListeners !== options.responsive) { this.unbindEvents(); this.bindEvents(); } } _updateHiddenIndices() { const {_hiddenIndices} = this; const changes = this._getUniformDataChanges() || []; for (const {method, start, count} of changes) { const move = method === '_removeElements' ? -count : count; moveNumericKeys(_hiddenIndices, start, move); } } _getUniformDataChanges() { const _dataChanges = this._dataChanges; if (!_dataChanges || !_dataChanges.length) { return; } this._dataChanges = []; const datasetCount = this.data.datasets.length; const makeSet = (idx) => new Set( _dataChanges .filter(c => c[0] === idx) .map((c, i) => i + ',' + c.splice(1).join(',')) ); const changeSet = makeSet(0); for (let i = 1; i < datasetCount; i++) { if (!setsEqual(changeSet, makeSet(i))) { return; } } return Array.from(changeSet) .map(c => c.split(',')) .map(a => ({method: a[1], start: +a[2], count: +a[3]})); } _updateLayout(minPadding) { if (this.notifyPlugins('beforeLayout', {cancelable: true}) === false) { return; } layouts.update(this, this.width, this.height, minPadding); const area = this.chartArea; const noArea = area.width <= 0 || area.height <= 0; this._layers = []; each(this.boxes, (box) => { if (noArea && box.position === 'chartArea') { return; } if (box.configure) { box.configure(); } this._layers.push(...box._layers()); }, this); this._layers.forEach((item, index) => { item._idx = index; }); this.notifyPlugins('afterLayout'); } _updateDatasets(mode) { if (this.notifyPlugins('beforeDatasetsUpdate', {mode, cancelable: true}) === false) { return; } for (let i = 0, ilen = this.data.datasets.length; i < ilen; ++i) { this.getDatasetMeta(i).controller.configure(); } for (let i = 0, ilen = this.data.datasets.length; i < ilen; ++i) { this._updateDataset(i, isFunction(mode) ? mode({datasetIndex: i}) : mode); } this.notifyPlugins('afterDatasetsUpdate', {mode}); } _updateDataset(index, mode) { const meta = this.getDatasetMeta(index); const args = {meta, index, mode, cancelable: true}; if (this.notifyPlugins('beforeDatasetUpdate', args) === false) { return; } meta.controller._update(mode); args.cancelable = false; this.notifyPlugins('afterDatasetUpdate', args); } render() { if (this.notifyPlugins('beforeRender', {cancelable: true}) === false) { return; } if (animator.has(this)) { if (this.attached && !animator.running(this)) { animator.start(this); } } else { this.draw(); onAnimationsComplete({chart: this}); } } draw() { let i; if (this._resizeBeforeDraw) { const {width, height} = this._resizeBeforeDraw; this._resize(width, height); this._resizeBeforeDraw = null; } this.clear(); if (this.width <= 0 || this.height <= 0) { return; } if (this.notifyPlugins('beforeDraw', {cancelable: true}) === false) { return; } const layers = this._layers; for (i = 0; i < layers.length && layers[i].z <= 0; ++i) { layers[i].draw(this.chartArea); } this._drawDatasets(); for (; i < layers.length; ++i) { layers[i].draw(this.chartArea); } this.notifyPlugins('afterDraw'); } _getSortedDatasetMetas(filterVisible) { const metasets = this._sortedMetasets; const result = []; let i, ilen; for (i = 0, ilen = metasets.length; i < ilen; ++i) { const meta = metasets[i]; if (!filterVisible || meta.visible) { result.push(meta); } } return result; } getSortedVisibleDatasetMetas() { return this._getSortedDatasetMetas(true); } _drawDatasets() { if (this.notifyPlugins('beforeDatasetsDraw', {cancelable: true}) === false) { return; } const metasets = this.getSortedVisibleDatasetMetas(); for (let i = metasets.length - 1; i >= 0; --i) { this._drawDataset(metasets[i]); } this.notifyPlugins('afterDatasetsDraw'); } _drawDataset(meta) { const ctx = this.ctx; const clip = meta._clip; const useClip = !clip.disabled; const area = this.chartArea; const args = { meta, index: meta.index, cancelable: true }; if (this.notifyPlugins('beforeDatasetDraw', args) === false) { return; } if (useClip) { clipArea(ctx, { left: clip.left === false ? 0 : area.left - clip.left, right: clip.right === false ? this.width : area.right + clip.right, top: clip.top === false ? 0 : area.top - clip.top, bottom: clip.bottom === false ? this.height : area.bottom + clip.bottom }); } meta.controller.draw(); if (useClip) { unclipArea(ctx); } args.cancelable = false; this.notifyPlugins('afterDatasetDraw', args); } getElementsAtEventForMode(e, mode, options, useFinalPosition) { const method = Interaction.modes[mode]; if (typeof method === 'function') { return method(this, e, options, useFinalPosition); } return []; } getDatasetMeta(datasetIndex) { const dataset = this.data.datasets[datasetIndex]; const metasets = this._metasets; let meta = metasets.filter(x => x && x._dataset === dataset).pop(); if (!meta) { meta = { type: null, data: [], dataset: null, controller: null, hidden: null, xAxisID: null, yAxisID: null, order: dataset && dataset.order || 0, index: datasetIndex, _dataset: dataset, _parsed: [], _sorted: false }; metasets.push(meta); } return meta; } getContext() { return this.$context || (this.$context = createContext(null, {chart: this, type: 'chart'})); } getVisibleDatasetCount() { return this.getSortedVisibleDatasetMetas().length; } isDatasetVisible(datasetIndex) { const dataset = this.data.datasets[datasetIndex]; if (!dataset) { return false; } const meta = this.getDatasetMeta(datasetIndex); return typeof meta.hidden === 'boolean' ? !meta.hidden : !dataset.hidden; } setDatasetVisibility(datasetIndex, visible) { const meta = this.getDatasetMeta(datasetIndex); meta.hidden = !visible; } toggleDataVisibility(index) { this._hiddenIndices[index] = !this._hiddenIndices[index]; } getDataVisibility(index) { return !this._hiddenIndices[index]; } _updateVisibility(datasetIndex, dataIndex, visible) { const mode = visible ? 'show' : 'hide'; const meta = this.getDatasetMeta(datasetIndex); const anims = meta.controller._resolveAnimations(undefined, mode); if (defined(dataIndex)) { meta.data[dataIndex].hidden = !visible; this.update(); } else { this.setDatasetVisibility(datasetIndex, visible); anims.update(meta, {visible}); this.update((ctx) => ctx.datasetIndex === datasetIndex ? mode : undefined); } } hide(datasetIndex, dataIndex) { this._updateVisibility(datasetIndex, dataIndex, false); } show(datasetIndex, dataIndex) { this._updateVisibility(datasetIndex, dataIndex, true); } _destroyDatasetMeta(datasetIndex) { const meta = this._metasets[datasetIndex]; if (meta && meta.controller) { meta.controller._destroy(); } delete this._metasets[datasetIndex]; } _stop() { let i, ilen; this.stop(); animator.remove(this); for (i = 0, ilen = this.data.datasets.length; i < ilen; ++i) { this._destroyDatasetMeta(i); } } destroy() { const {canvas, ctx} = this; this._stop(); this.config.clearCache(); if (canvas) { this.unbindEvents(); clearCanvas(canvas, ctx); this.platform.releaseContext(ctx); this.canvas = null; this.ctx = null; } this.notifyPlugins('destroy'); delete instances[this.id]; } toBase64Image(...args) { return this.canvas.toDataURL(...args); } bindEvents() { this.bindUserEvents(); if (this.options.responsive) { this.bindResponsiveEvents(); } else { this.attached = true; } } bindUserEvents() { const listeners = this._listeners; const platform = this.platform; const _add = (type, listener) => { platform.addEventListener(this, type, listener); listeners[type] = listener; }; const listener = (e, x, y) => { e.offsetX = x; e.offsetY = y; this._eventHandler(e); }; each(this.options.events, (type) => _add(type, listener)); } bindResponsiveEvents() { if (!this._responsiveListeners) { this._responsiveListeners = {}; } const listeners = this._responsiveListeners; const platform = this.platform; const _add = (type, listener) => { platform.addEventListener(this, type, listener); listeners[type] = listener; }; const _remove = (type, listener) => { if (listeners[type]) { platform.removeEventListener(this, type, listener); delete listeners[type]; } }; const listener = (width, height) => { if (this.canvas) { this.resize(width, height); } }; let detached; const attached = () => { _remove('attach', attached); this.attached = true; this.resize(); _add('resize', listener); _add('detach', detached); }; detached = () => { this.attached = false; _remove('resize', listener); this._stop(); this._resize(0, 0); _add('attach', attached); }; if (platform.isAttached(this.canvas)) { attached(); } else { detached(); } } unbindEvents() { each(this._listeners, (listener, type) => { this.platform.removeEventListener(this, type, listener); }); this._listeners = {}; each(this._responsiveListeners, (listener, type) => { this.platform.removeEventListener(this, type, listener); }); this._responsiveListeners = undefined; } updateHoverStyle(items, mode, enabled) { const prefix = enabled ? 'set' : 'remove'; let meta, item, i, ilen; if (mode === 'dataset') { meta = this.getDatasetMeta(items[0].datasetIndex); meta.controller['_' + prefix + 'DatasetHoverStyle'](); } for (i = 0, ilen = items.length; i < ilen; ++i) { item = items[i]; const controller = item && this.getDatasetMeta(item.datasetIndex).controller; if (controller) { controller[prefix + 'HoverStyle'](item.element, item.datasetIndex, item.index); } } } getActiveElements() { return this._active || []; } setActiveElements(activeElements) { const lastActive = this._active || []; const active = activeElements.map(({datasetIndex, index}) => { const meta = this.getDatasetMeta(datasetIndex); if (!meta) { throw new Error('No dataset found at index ' + datasetIndex); } return { datasetIndex, element: meta.data[index], index, }; }); const changed = !_elementsEqual(active, lastActive); if (changed) { this._active = active; this._updateHoverStyles(active, lastActive); } } notifyPlugins(hook, args, filter) { return this._plugins.notify(this, hook, args, filter); } _updateHoverStyles(active, lastActive, replay) { const hoverOptions = this.options.hover; const diff = (a, b) => a.filter(x => !b.some(y => x.datasetIndex === y.datasetIndex && x.index === y.index)); const deactivated = diff(lastActive, active); const activated = replay ? active : diff(active, lastActive); if (deactivated.length) { this.updateHoverStyle(deactivated, hoverOptions.mode, false); } if (activated.length && hoverOptions.mode) { this.updateHoverStyle(activated, hoverOptions.mode, true); } } _eventHandler(e, replay) { const args = {event: e, replay, cancelable: true}; const eventFilter = (plugin) => (plugin.options.events || this.options.events).includes(e.native.type); if (this.notifyPlugins('beforeEvent', args, eventFilter) === false) { return; } const changed = this._handleEvent(e, replay); args.cancelable = false; this.notifyPlugins('afterEvent', args, eventFilter); if (changed || args.changed) { this.render(); } return this; } _handleEvent(e, replay) { const {_active: lastActive = [], options} = this; const hoverOptions = options.hover; const useFinalPosition = replay; let active = []; let changed = false; let lastEvent = null; if (e.type !== 'mouseout') { active = this.getElementsAtEventForMode(e, hoverOptions.mode, hoverOptions, useFinalPosition); lastEvent = e.type === 'click' ? this._lastEvent : e; } this._lastEvent = null; if (_isPointInArea(e, this.chartArea, this._minPadding)) { callback(options.onHover, [e, active, this], this); if (e.type === 'mouseup' || e.type === 'click' || e.type === 'contextmenu') { callback(options.onClick, [e, active, this], this); } } changed = !_elementsEqual(active, lastActive); if (changed || replay) { this._active = active; this._updateHoverStyles(active, lastActive, replay); } this._lastEvent = lastEvent; return changed; } } const invalidatePlugins = () => each(Chart.instances, (chart) => chart._plugins.invalidate()); const enumerable = true; Object.defineProperties(Chart, { defaults: { enumerable, value: defaults }, instances: { enumerable, value: instances }, overrides: { enumerable, value: overrides }, registry: { enumerable, value: registry }, version: { enumerable, value: version }, getChart: { enumerable, value: getChart }, register: { enumerable, value: (...items) => { registry.add(...items); invalidatePlugins(); } }, unregister: { enumerable, value: (...items) => { registry.remove(...items); invalidatePlugins(); } } }); function abstract() { throw new Error('This method is not implemented: Check that a complete date adapter is provided.'); } class DateAdapter { constructor(options) { this.options = options || {}; } formats() { return abstract(); } parse(value, format) { return abstract(); } format(timestamp, format) { return abstract(); } add(timestamp, amount, unit) { return abstract(); } diff(a, b, unit) { return abstract(); } startOf(timestamp, unit, weekday) { return abstract(); } endOf(timestamp, unit) { return abstract(); } } DateAdapter.override = function(members) { Object.assign(DateAdapter.prototype, members); }; var _adapters = { _date: DateAdapter }; function getAllScaleValues(scale, type) { if (!scale._cache.$bar) { const visibleMetas = scale.getMatchingVisibleMetas(type); let values = []; for (let i = 0, ilen = visibleMetas.length; i < ilen; i++) { values = values.concat(visibleMetas[i].controller.getAllParsedValues(scale)); } scale._cache.$bar = _arrayUnique(values.sort((a, b) => a - b)); } return scale._cache.$bar; } function computeMinSampleSize(meta) { const scale = meta.iScale; const values = getAllScaleValues(scale, meta.type); let min = scale._length; let i, ilen, curr, prev; const updateMinAndPrev = () => { if (curr === 32767 || curr === -32768) { return; } if (defined(prev)) { min = Math.min(min, Math.abs(curr - prev) || min); } prev = curr; }; for (i = 0, ilen = values.length; i < ilen; ++i) { curr = scale.getPixelForValue(values[i]); updateMinAndPrev(); } prev = undefined; for (i = 0, ilen = scale.ticks.length; i < ilen; ++i) { curr = scale.getPixelForTick(i); updateMinAndPrev(); } return min; } function computeFitCategoryTraits(index, ruler, options, stackCount) { const thickness = options.barThickness; let size, ratio; if (isNullOrUndef(thickness)) { size = ruler.min * options.categoryPercentage; ratio = options.barPercentage; } else { size = thickness * stackCount; ratio = 1; } return { chunk: size / stackCount, ratio, start: ruler.pixels[index] - (size / 2) }; } function computeFlexCategoryTraits(index, ruler, options, stackCount) { const pixels = ruler.pixels; const curr = pixels[index]; let prev = index > 0 ? pixels[index - 1] : null; let next = index < pixels.length - 1 ? pixels[index + 1] : null; const percent = options.categoryPercentage; if (prev === null) { prev = curr - (next === null ? ruler.end - ruler.start : next - curr); } if (next === null) { next = curr + curr - prev; } const start = curr - (curr - Math.min(prev, next)) / 2 * percent; const size = Math.abs(next - prev) / 2 * percent; return { chunk: size / stackCount, ratio: options.barPercentage, start }; } function parseFloatBar(entry, item, vScale, i) { const startValue = vScale.parse(entry[0], i); const endValue = vScale.parse(entry[1], i); const min = Math.min(startValue, endValue); const max = Math.max(startValue, endValue); let barStart = min; let barEnd = max; if (Math.abs(min) > Math.abs(max)) { barStart = max; barEnd = min; } item[vScale.axis] = barEnd; item._custom = { barStart, barEnd, start: startValue, end: endValue, min, max }; } function parseValue(entry, item, vScale, i) { if (isArray(entry)) { parseFloatBar(entry, item, vScale, i); } else { item[vScale.axis] = vScale.parse(entry, i); } return item; } function parseArrayOrPrimitive(meta, data, start, count) { const iScale = meta.iScale; const vScale = meta.vScale; const labels = iScale.getLabels(); const singleScale = iScale === vScale; const parsed = []; let i, ilen, item, entry; for (i = start, ilen = start + count; i < ilen; ++i) { entry = data[i]; item = {}; item[iScale.axis] = singleScale || iScale.parse(labels[i], i); parsed.push(parseValue(entry, item, vScale, i)); } return parsed; } function isFloatBar(custom) { return custom && custom.barStart !== undefined && custom.barEnd !== undefined; } function barSign(size, vScale, actualBase) { if (size !== 0) { return sign(size); } return (vScale.isHorizontal() ? 1 : -1) * (vScale.min >= actualBase ? 1 : -1); } function borderProps(properties) { let reverse, start, end, top, bottom; if (properties.horizontal) { reverse = properties.base > properties.x; start = 'left'; end = 'right'; } else { reverse = properties.base < properties.y; start = 'bottom'; end = 'top'; } if (reverse) { top = 'end'; bottom = 'start'; } else { top = 'start'; bottom = 'end'; } return {start, end, reverse, top, bottom}; } function setBorderSkipped(properties, options, stack, index) { let edge = options.borderSkipped; const res = {}; if (!edge) { properties.borderSkipped = res; return; } const {start, end, reverse, top, bottom} = borderProps(properties); if (edge === 'middle' && stack) { properties.enableBorderRadius = true; if ((stack._top || 0) === index) { edge = top; } else if ((stack._bottom || 0) === index) { edge = bottom; } else { res[parseEdge(bottom, start, end, reverse)] = true; edge = top; } } res[parseEdge(edge, start, end, reverse)] = true; properties.borderSkipped = res; } function parseEdge(edge, a, b, reverse) { if (reverse) { edge = swap(edge, a, b); edge = startEnd(edge, b, a); } else { edge = startEnd(edge, a, b); } return edge; } function swap(orig, v1, v2) { return orig === v1 ? v2 : orig === v2 ? v1 : orig; } function startEnd(v, start, end) { return v === 'start' ? start : v === 'end' ? end : v; } function setInflateAmount(properties, {inflateAmount}, ratio) { properties.inflateAmount = inflateAmount === 'auto' ? ratio === 1 ? 0.33 : 0 : inflateAmount; } class BarController extends DatasetController { parsePrimitiveData(meta, data, start, count) { return parseArrayOrPrimitive(meta, data, start, count); } parseArrayData(meta, data, start, count) { return parseArrayOrPrimitive(meta, data, start, count); } parseObjectData(meta, data, start, count) { const {iScale, vScale} = meta; const {xAxisKey = 'x', yAxisKey = 'y'} = this._parsing; const iAxisKey = iScale.axis === 'x' ? xAxisKey : yAxisKey; const vAxisKey = vScale.axis === 'x' ? xAxisKey : yAxisKey; const parsed = []; let i, ilen, item, obj; for (i = start, ilen = start + count; i < ilen; ++i) { obj = data[i]; item = {}; item[iScale.axis] = iScale.parse(resolveObjectKey(obj, iAxisKey), i); parsed.push(parseValue(resolveObjectKey(obj, vAxisKey), item, vScale, i)); } return parsed; } updateRangeFromParsed(range, scale, parsed, stack) { super.updateRangeFromParsed(range, scale, parsed, stack); const custom = parsed._custom; if (custom && scale === this._cachedMeta.vScale) { range.min = Math.min(range.min, custom.min); range.max = Math.max(range.max, custom.max); } } getMaxOverflow() { return 0; } getLabelAndValue(index) { const meta = this._cachedMeta; const {iScale, vScale} = meta; const parsed = this.getParsed(index); const custom = parsed._custom; const value = isFloatBar(custom) ? '[' + custom.start + ', ' + custom.end + ']' : '' + vScale.getLabelForValue(parsed[vScale.axis]); return { label: '' + iScale.getLabelForValue(parsed[iScale.axis]), value }; } initialize() { this.enableOptionSharing = true; super.initialize(); const meta = this._cachedMeta; meta.stack = this.getDataset().stack; } update(mode) { const meta = this._cachedMeta; this.updateElements(meta.data, 0, meta.data.length, mode); } updateElements(bars, start, count, mode) { const reset = mode === 'reset'; const {index, _cachedMeta: {vScale}} = this; const base = vScale.getBasePixel(); const horizontal = vScale.isHorizontal(); const ruler = this._getRuler(); const firstOpts = this.resolveDataElementOptions(start, mode); const sharedOptions = this.getSharedOptions(firstOpts); const includeOptions = this.includeOptions(mode, sharedOptions); this.updateSharedOptions(sharedOptions, mode, firstOpts); for (let i = start; i < start + count; i++) { const parsed = this.getParsed(i); const vpixels = reset || isNullOrUndef(parsed[vScale.axis]) ? {base, head: base} : this._calculateBarValuePixels(i); const ipixels = this._calculateBarIndexPixels(i, ruler); const stack = (parsed._stacks || {})[vScale.axis]; const properties = { horizontal, base: vpixels.base, enableBorderRadius: !stack || isFloatBar(parsed._custom) || (index === stack._top || index === stack._bottom), x: horizontal ? vpixels.head : ipixels.center, y: horizontal ? ipixels.center : vpixels.head, height: horizontal ? ipixels.size : Math.abs(vpixels.size), width: horizontal ? Math.abs(vpixels.size) : ipixels.size }; if (includeOptions) { properties.options = sharedOptions || this.resolveDataElementOptions(i, bars[i].active ? 'active' : mode); } const options = properties.options || bars[i].options; setBorderSkipped(properties, options, stack, index); setInflateAmount(properties, options, ruler.ratio); this.updateElement(bars[i], i, properties, mode); } } _getStacks(last, dataIndex) { const meta = this._cachedMeta; const iScale = meta.iScale; const metasets = iScale.getMatchingVisibleMetas(this._type); const stacked = iScale.options.stacked; const ilen = metasets.length; const stacks = []; let i, item; for (i = 0; i < ilen; ++i) { item = metasets[i]; if (!item.controller.options.grouped) { continue; } if (typeof dataIndex !== 'undefined') { const val = item.controller.getParsed(dataIndex)[ item.controller._cachedMeta.vScale.axis ]; if (isNullOrUndef(val) || isNaN(val)) { continue; } } if (stacked === false || stacks.indexOf(item.stack) === -1 || (stacked === undefined && item.stack === undefined)) { stacks.push(item.stack); } if (item.index === last) { break; } } if (!stacks.length) { stacks.push(undefined); } return stacks; } _getStackCount(index) { return this._getStacks(undefined, index).length; } _getStackIndex(datasetIndex, name, dataIndex) { const stacks = this._getStacks(datasetIndex, dataIndex); const index = (name !== undefined) ? stacks.indexOf(name) : -1; return (index === -1) ? stacks.length - 1 : index; } _getRuler() { const opts = this.options; const meta = this._cachedMeta; const iScale = meta.iScale; const pixels = []; let i, ilen; for (i = 0, ilen = meta.data.length; i < ilen; ++i) { pixels.push(iScale.getPixelForValue(this.getParsed(i)[iScale.axis], i)); } const barThickness = opts.barThickness; const min = barThickness || computeMinSampleSize(meta); return { min, pixels, start: iScale._startPixel, end: iScale._endPixel, stackCount: this._getStackCount(), scale: iScale, grouped: opts.grouped, ratio: barThickness ? 1 : opts.categoryPercentage * opts.barPercentage }; } _calculateBarValuePixels(index) { const {_cachedMeta: {vScale, _stacked}, options: {base: baseValue, minBarLength}} = this; const actualBase = baseValue || 0; const parsed = this.getParsed(index); const custom = parsed._custom; const floating = isFloatBar(custom); let value = parsed[vScale.axis]; let start = 0; let length = _stacked ? this.applyStack(vScale, parsed, _stacked) : value; let head, size; if (length !== value) { start = length - value; length = value; } if (floating) { value = custom.barStart; length = custom.barEnd - custom.barStart; if (value !== 0 && sign(value) !== sign(custom.barEnd)) { start = 0; } start += value; } const startValue = !isNullOrUndef(baseValue) && !floating ? baseValue : start; let base = vScale.getPixelForValue(startValue); if (this.chart.getDataVisibility(index)) { head = vScale.getPixelForValue(start + length); } else { head = base; } size = head - base; if (Math.abs(size) < minBarLength) { size = barSign(size, vScale, actualBase) * minBarLength; if (value === actualBase) { base -= size / 2; } head = base + size; } if (base === vScale.getPixelForValue(actualBase)) { const halfGrid = sign(size) * vScale.getLineWidthForValue(actualBase) / 2; base += halfGrid; size -= halfGrid; } return { size, base, head, center: head + size / 2 }; } _calculateBarIndexPixels(index, ruler) { const scale = ruler.scale; const options = this.options; const skipNull = options.skipNull; const maxBarThickness = valueOrDefault(options.maxBarThickness, Infinity); let center, size; if (ruler.grouped) { const stackCount = skipNull ? this._getStackCount(index) : ruler.stackCount; const range = options.barThickness === 'flex' ? computeFlexCategoryTraits(index, ruler, options, stackCount) : computeFitCategoryTraits(index, ruler, options, stackCount); const stackIndex = this._getStackIndex(this.index, this._cachedMeta.stack, skipNull ? index : undefined); center = range.start + (range.chunk * stackIndex) + (range.chunk / 2); size = Math.min(maxBarThickness, range.chunk * range.ratio); } else { center = scale.getPixelForValue(this.getParsed(index)[scale.axis], index); size = Math.min(maxBarThickness, ruler.min * ruler.ratio); } return { base: center - size / 2, head: center + size / 2, center, size }; } draw() { const meta = this._cachedMeta; const vScale = meta.vScale; const rects = meta.data; const ilen = rects.length; let i = 0; for (; i < ilen; ++i) { if (this.getParsed(i)[vScale.axis] !== null) { rects[i].draw(this._ctx); } } } } BarController.id = 'bar'; BarController.defaults = { datasetElementType: false, dataElementType: 'bar', categoryPercentage: 0.8, barPercentage: 0.9, grouped: true, animations: { numbers: { type: 'number', properties: ['x', 'y', 'base', 'width', 'height'] } } }; BarController.overrides = { scales: { _index_: { type: 'category', offset: true, grid: { offset: true } }, _value_: { type: 'linear', beginAtZero: true, } } }; class BubbleController extends DatasetController { initialize() { this.enableOptionSharing = true; super.initialize(); } parsePrimitiveData(meta, data, start, count) { const parsed = super.parsePrimitiveData(meta, data, start, count); for (let i = 0; i < parsed.length; i++) { parsed[i]._custom = this.resolveDataElementOptions(i + start).radius; } return parsed; } parseArrayData(meta, data, start, count) { const parsed = super.parseArrayData(meta, data, start, count); for (let i = 0; i < parsed.length; i++) { const item = data[start + i]; parsed[i]._custom = valueOrDefault(item[2], this.resolveDataElementOptions(i + start).radius); } return parsed; } parseObjectData(meta, data, start, count) { const parsed = super.parseObjectData(meta, data, start, count); for (let i = 0; i < parsed.length; i++) { const item = data[start + i]; parsed[i]._custom = valueOrDefault(item && item.r && +item.r, this.resolveDataElementOptions(i + start).radius); } return parsed; } getMaxOverflow() { const data = this._cachedMeta.data; let max = 0; for (let i = data.length - 1; i >= 0; --i) { max = Math.max(max, data[i].size(this.resolveDataElementOptions(i)) / 2); } return max > 0 && max; } getLabelAndValue(index) { const meta = this._cachedMeta; const {xScale, yScale} = meta; const parsed = this.getParsed(index); const x = xScale.getLabelForValue(parsed.x); const y = yScale.getLabelForValue(parsed.y); const r = parsed._custom; return { label: meta.label, value: '(' + x + ', ' + y + (r ? ', ' + r : '') + ')' }; } update(mode) { const points = this._cachedMeta.data; this.updateElements(points, 0, points.length, mode); } updateElements(points, start, count, mode) { const reset = mode === 'reset'; const {iScale, vScale} = this._cachedMeta; const firstOpts = this.resolveDataElementOptions(start, mode); const sharedOptions = this.getSharedOptions(firstOpts); const includeOptions = this.includeOptions(mode, sharedOptions); const iAxis = iScale.axis; const vAxis = vScale.axis; for (let i = start; i < start + count; i++) { const point = points[i]; const parsed = !reset && this.getParsed(i); const properties = {}; const iPixel = properties[iAxis] = reset ? iScale.getPixelForDecimal(0.5) : iScale.getPixelForValue(parsed[iAxis]); const vPixel = properties[vAxis] = reset ? vScale.getBasePixel() : vScale.getPixelForValue(parsed[vAxis]); properties.skip = isNaN(iPixel) || isNaN(vPixel); if (includeOptions) { properties.options = this.resolveDataElementOptions(i, point.active ? 'active' : mode); if (reset) { properties.options.radius = 0; } } this.updateElement(point, i, properties, mode); } this.updateSharedOptions(sharedOptions, mode, firstOpts); } resolveDataElementOptions(index, mode) { const parsed = this.getParsed(index); let values = super.resolveDataElementOptions(index, mode); if (values.$shared) { values = Object.assign({}, values, {$shared: false}); } const radius = values.radius; if (mode !== 'active') { values.radius = 0; } values.radius += valueOrDefault(parsed && parsed._custom, radius); return values; } } BubbleController.id = 'bubble'; BubbleController.defaults = { datasetElementType: false, dataElementType: 'point', animations: { numbers: { type: 'number', properties: ['x', 'y', 'borderWidth', 'radius'] } } }; BubbleController.overrides = { scales: { x: { type: 'linear' }, y: { type: 'linear' } }, plugins: { tooltip: { callbacks: { title() { return ''; } } } } }; function getRatioAndOffset(rotation, circumference, cutout) { let ratioX = 1; let ratioY = 1; let offsetX = 0; let offsetY = 0; if (circumference < TAU) { const startAngle = rotation; const endAngle = startAngle + circumference; const startX = Math.cos(startAngle); const startY = Math.sin(startAngle); const endX = Math.cos(endAngle); const endY = Math.sin(endAngle); const calcMax = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? 1 : Math.max(a, a * cutout, b, b * cutout); const calcMin = (angle, a, b) => _angleBetween(angle, startAngle, endAngle, true) ? -1 : Math.min(a, a * cutout, b, b * cutout); const maxX = calcMax(0, startX, endX); const maxY = calcMax(HALF_PI, startY, endY); const minX = calcMin(PI, startX, endX); const minY = calcMin(PI + HALF_PI, startY, endY); ratioX = (maxX - minX) / 2; ratioY = (maxY - minY) / 2; offsetX = -(maxX + minX) / 2; offsetY = -(maxY + minY) / 2; } return {ratioX, ratioY, offsetX, offsetY}; } class DoughnutController extends DatasetController { constructor(chart, datasetIndex) { super(chart, datasetIndex); this.enableOptionSharing = true; this.innerRadius = undefined; this.outerRadius = undefined; this.offsetX = undefined; this.offsetY = undefined; } linkScales() {} parse(start, count) { const data = this.getDataset().data; const meta = this._cachedMeta; if (this._parsing === false) { meta._parsed = data; } else { let getter = (i) => +data[i]; if (isObject(data[start])) { const {key = 'value'} = this._parsing; getter = (i) => +resolveObjectKey(data[i], key); } let i, ilen; for (i = start, ilen = start + count; i < ilen; ++i) { meta._parsed[i] = getter(i); } } } _getRotation() { return toRadians(this.options.rotation - 90); } _getCircumference() { return toRadians(this.options.circumference); } _getRotationExtents() { let min = TAU; let max = -TAU; for (let i = 0; i < this.chart.data.datasets.length; ++i) { if (this.chart.isDatasetVisible(i)) { const controller = this.chart.getDatasetMeta(i).controller; const rotation = controller._getRotation(); const circumference = controller._getCircumference(); min = Math.min(min, rotation); max = Math.max(max, rotation + circumference); } } return { rotation: min, circumference: max - min, }; } update(mode) { const chart = this.chart; const {chartArea} = chart; const meta = this._cachedMeta; const arcs = meta.data; const spacing = this.getMaxBorderWidth() + this.getMaxOffset(arcs) + this.options.spacing; const maxSize = Math.max((Math.min(chartArea.width, chartArea.height) - spacing) / 2, 0); const cutout = Math.min(toPercentage(this.options.cutout, maxSize), 1); const chartWeight = this._getRingWeight(this.index); const {circumference, rotation} = this._getRotationExtents(); const {ratioX, ratioY, offsetX, offsetY} = getRatioAndOffset(rotation, circumference, cutout); const maxWidth = (chartArea.width - spacing) / ratioX; const maxHeight = (chartArea.height - spacing) / ratioY; const maxRadius = Math.max(Math.min(maxWidth, maxHeight) / 2, 0); const outerRadius = toDimension(this.options.radius, maxRadius); const innerRadius = Math.max(outerRadius * cutout, 0); const radiusLength = (outerRadius - innerRadius) / this._getVisibleDatasetWeightTotal(); this.offsetX = offsetX * outerRadius; this.offsetY = offsetY * outerRadius; meta.total = this.calculateTotal(); this.outerRadius = outerRadius - radiusLength * this._getRingWeightOffset(this.index); this.innerRadius = Math.max(this.outerRadius - radiusLength * chartWeight, 0); this.updateElements(arcs, 0, arcs.length, mode); } _circumference(i, reset) { const opts = this.options; const meta = this._cachedMeta; const circumference = this._getCircumference(); if ((reset && opts.animation.animateRotate) || !this.chart.getDataVisibility(i) || meta._parsed[i] === null || meta.data[i].hidden) { return 0; } return this.calculateCircumference(meta._parsed[i] * circumference / TAU); } updateElements(arcs, start, count, mode) { const reset = mode === 'reset'; const chart = this.chart; const chartArea = chart.chartArea; const opts = chart.options; const animationOpts = opts.animation; const centerX = (chartArea.left + chartArea.right) / 2; const centerY = (chartArea.top + chartArea.bottom) / 2; const animateScale = reset && animationOpts.animateScale; const innerRadius = animateScale ? 0 : this.innerRadius; const outerRadius = animateScale ? 0 : this.outerRadius; const firstOpts = this.resolveDataElementOptions(start, mode); const sharedOptions = this.getSharedOptions(firstOpts); const includeOptions = this.includeOptions(mode, sharedOptions); let startAngle = this._getRotation(); let i; for (i = 0; i < start; ++i) { startAngle += this._circumference(i, reset); } for (i = start; i < start + count; ++i) { const circumference = this._circumference(i, reset); const arc = arcs[i]; const properties = { x: centerX + this.offsetX, y: centerY + this.offsetY, startAngle, endAngle: startAngle + circumference, circumference, outerRadius, innerRadius }; if (includeOptions) { properties.options = sharedOptions || this.resolveDataElementOptions(i, arc.active ? 'active' : mode); } startAngle += circumference; this.updateElement(arc, i, properties, mode); } this.updateSharedOptions(sharedOptions, mode, firstOpts); } calculateTotal() { const meta = this._cachedMeta; const metaData = meta.data; let total = 0; let i; for (i = 0; i < metaData.length; i++) { const value = meta._parsed[i]; if (value !== null && !isNaN(value) && this.chart.getDataVisibility(i) && !metaData[i].hidden) { total += Math.abs(value); } } return total; } calculateCircumference(value) { const total = this._cachedMeta.total; if (total > 0 && !isNaN(value)) { return TAU * (Math.abs(value) / total); } return 0; } getLabelAndValue(index) { const meta = this._cachedMeta; const chart = this.chart; const labels = chart.data.labels || []; const value = formatNumber(meta._parsed[index], chart.options.locale); return { label: labels[index] || '', value, }; } getMaxBorderWidth(arcs) { let max = 0; const chart = this.chart; let i, ilen, meta, controller, options; if (!arcs) { for (i = 0, ilen = chart.data.datasets.length; i < ilen; ++i) { if (chart.isDatasetVisible(i)) { meta = chart.getDatasetMeta(i); arcs = meta.data; controller = meta.controller; break; } } } if (!arcs) { return 0; } for (i = 0, ilen = arcs.length; i < ilen; ++i) { options = controller.resolveDataElementOptions(i); if (options.borderAlign !== 'inner') { max = Math.max(max, options.borderWidth || 0, options.hoverBorderWidth || 0); } } return max; } getMaxOffset(arcs) { let max = 0; for (let i = 0, ilen = arcs.length; i < ilen; ++i) { const options = this.resolveDataElementOptions(i); max = Math.max(max, options.offset || 0, options.hoverOffset || 0); } return max; } _getRingWeightOffset(datasetIndex) { let ringWeightOffset = 0; for (let i = 0; i < datasetIndex; ++i) { if (this.chart.isDatasetVisible(i)) { ringWeightOffset += this._getRingWeight(i); } } return ringWeightOffset; } _getRingWeight(datasetIndex) { return Math.max(valueOrDefault(this.chart.data.datasets[datasetIndex].weight, 1), 0); } _getVisibleDatasetWeightTotal() { return this._getRingWeightOffset(this.chart.data.datasets.length) || 1; } } DoughnutController.id = 'doughnut'; DoughnutController.defaults = { datasetElementType: false, dataElementType: 'arc', animation: { animateRotate: true, animateScale: false }, animations: { numbers: { type: 'number', properties: ['circumference', 'endAngle', 'innerRadius', 'outerRadius', 'startAngle', 'x', 'y', 'offset', 'borderWidth', 'spacing'] }, }, cutout: '50%', rotation: 0, circumference: 360, radius: '100%', spacing: 0, indexAxis: 'r', }; DoughnutController.descriptors = { _scriptable: (name) => name !== 'spacing', _indexable: (name) => name !== 'spacing', }; DoughnutController.overrides = { aspectRatio: 1, plugins: { legend: { labels: { generateLabels(chart) { const data = chart.data; if (data.labels.length && data.datasets.length) { const {labels: {pointStyle}} = chart.legend.options; return data.labels.map((label, i) => { const meta = chart.getDatasetMeta(0); const style = meta.controller.getStyle(i); return { text: label, fillStyle: style.backgroundColor, strokeStyle: style.borderColor, lineWidth: style.borderWidth, pointStyle: pointStyle, hidden: !chart.getDataVisibility(i), index: i }; }); } return []; } }, onClick(e, legendItem, legend) { legend.chart.toggleDataVisibility(legendItem.index); legend.chart.update(); } }, tooltip: { callbacks: { title() { return ''; }, label(tooltipItem) { let dataLabel = tooltipItem.label; const value = ': ' + tooltipItem.formattedValue; if (isArray(dataLabel)) { dataLabel = dataLabel.slice(); dataLabel[0] += value; } else { dataLabel += value; } return dataLabel; } } } } }; class LineController extends DatasetController { initialize() { this.enableOptionSharing = true; super.initialize(); } update(mode) { const meta = this._cachedMeta; const {dataset: line, data: points = [], _dataset} = meta; const animationsDisabled = this.chart._animationsDisabled; let {start, count} = getStartAndCountOfVisiblePoints(meta, points, animationsDisabled); this._drawStart = start; this._drawCount = count; if (scaleRangesChanged(meta)) { start = 0; count = points.length; } line._chart = this.chart; line._datasetIndex = this.index; line._decimated = !!_dataset._decimated; line.points = points; const options = this.resolveDatasetElementOptions(mode); if (!this.options.showLine) { options.borderWidth = 0; } options.segment = this.options.segment; this.updateElement(line, undefined, { animated: !animationsDisabled, options }, mode); this.updateElements(points, start, count, mode); } updateElements(points, start, count, mode) { const reset = mode === 'reset'; const {iScale, vScale, _stacked, _dataset} = this._cachedMeta; const firstOpts = this.resolveDataElementOptions(start, mode); const sharedOptions = this.getSharedOptions(firstOpts); const includeOptions = this.includeOptions(mode, sharedOptions); const iAxis = iScale.axis; const vAxis = vScale.axis; const {spanGaps, segment} = this.options; const maxGapLength = isNumber(spanGaps) ? spanGaps : Number.POSITIVE_INFINITY; const directUpdate = this.chart._animationsDisabled || reset || mode === 'none'; let prevParsed = start > 0 && this.getParsed(start - 1); for (let i = start; i < start + count; ++i) { const point = points[i]; const parsed = this.getParsed(i); const properties = directUpdate ? point : {}; const nullData = isNullOrUndef(parsed[vAxis]); const iPixel = properties[iAxis] = iScale.getPixelForValue(parsed[iAxis], i); const vPixel = properties[vAxis] = reset || nullData ? vScale.getBasePixel() : vScale.getPixelForValue(_stacked ? this.applyStack(vScale, parsed, _stacked) : parsed[vAxis], i); properties.skip = isNaN(iPixel) || isNaN(vPixel) || nullData; properties.stop = i > 0 && (parsed[iAxis] - prevParsed[iAxis]) > maxGapLength; if (segment) { properties.parsed = parsed; properties.raw = _dataset.data[i]; } if (includeOptions) { properties.options = sharedOptions || this.resolveDataElementOptions(i, point.active ? 'active' : mode); } if (!directUpdate) { this.updateElement(point, i, properties, mode); } prevParsed = parsed; } this.updateSharedOptions(sharedOptions, mode, firstOpts); } getMaxOverflow() { const meta = this._cachedMeta; const dataset = meta.dataset; const border = dataset.options && dataset.options.borderWidth || 0; const data = meta.data || []; if (!data.length) { return border; } const firstPoint = data[0].size(this.resolveDataElementOptions(0)); const lastPoint = data[data.length - 1].size(this.resolveDataElementOptions(data.length - 1)); return Math.max(border, firstPoint, lastPoint) / 2; } draw() { const meta = this._cachedMeta; meta.dataset.updateControlPoints(this.chart.chartArea, meta.iScale.axis); super.draw(); } } LineController.id = 'line'; LineController.defaults = { datasetElementType: 'line', dataElementType: 'point', showLine: true, spanGaps: false, }; LineController.overrides = { scales: { _index_: { type: 'category', }, _value_: { type: 'linear', }, } }; function getStartAndCountOfVisiblePoints(meta, points, animationsDisabled) { const pointCount = points.length; let start = 0; let count = pointCount; if (meta._sorted) { const {iScale, _parsed} = meta; const axis = iScale.axis; const {min, max, minDefined, maxDefined} = iScale.getUserBounds(); if (minDefined) { start = _limitValue(Math.min( _lookupByKey(_parsed, iScale.axis, min).lo, animationsDisabled ? pointCount : _lookupByKey(points, axis, iScale.getPixelForValue(min)).lo), 0, pointCount - 1); } if (maxDefined) { count = _limitValue(Math.max( _lookupByKey(_parsed, iScale.axis, max).hi + 1, animationsDisabled ? 0 : _lookupByKey(points, axis, iScale.getPixelForValue(max)).hi + 1), start, pointCount) - start; } else { count = pointCount - start; } } return {start, count}; } function scaleRangesChanged(meta) { const {xScale, yScale, _scaleRanges} = meta; const newRanges = { xmin: xScale.min, xmax: xScale.max, ymin: yScale.min, ymax: yScale.max }; if (!_scaleRanges) { meta._scaleRanges = newRanges; return true; } const changed = _scaleRanges.xmin !== xScale.min || _scaleRanges.xmax !== xScale.max || _scaleRanges.ymin !== yScale.min || _scaleRanges.ymax !== yScale.max; Object.assign(_scaleRanges, newRanges); return changed; } class PolarAreaController extends DatasetController { constructor(chart, datasetIndex) { super(chart, datasetIndex); this.innerRadius = undefined; this.outerRadius = undefined; } getLabelAndValue(index) { const meta = this._cachedMeta; const chart = this.chart; const labels = chart.data.labels || []; const value = formatNumber(meta._parsed[index].r, chart.options.locale); return { label: labels[index] || '', value, }; } update(mode) { const arcs = this._cachedMeta.data; this._updateRadius(); this.updateElements(arcs, 0, arcs.length, mode); } _updateRadius() { const chart = this.chart; const chartArea = chart.chartArea; const opts = chart.options; const minSize = Math.min(chartArea.right - chartArea.left, chartArea.bottom - chartArea.top); const outerRadius = Math.max(minSize / 2, 0); const innerRadius = Math.max(opts.cutoutPercentage ? (outerRadius / 100) * (opts.cutoutPercentage) : 1, 0); const radiusLength = (outerRadius - innerRadius) / chart.getVisibleDatasetCount(); this.outerRadius = outerRadius - (radiusLength * this.index); this.innerRadius = this.outerRadius - radiusLength; } updateElements(arcs, start, count, mode) { const reset = mode === 'reset'; const chart = this.chart; const dataset = this.getDataset(); const opts = chart.options; const animationOpts = opts.animation; const scale = this._cachedMeta.rScale; const centerX = scale.xCenter; const centerY = scale.yCenter; const datasetStartAngle = scale.getIndexAngle(0) - 0.5 * PI; let angle = datasetStartAngle; let i; const defaultAngle = 360 / this.countVisibleElements(); for (i = 0; i < start; ++i) { angle += this._computeAngle(i, mode, defaultAngle); } for (i = start; i < start + count; i++) { const arc = arcs[i]; let startAngle = angle; let endAngle = angle + this._computeAngle(i, mode, defaultAngle); let outerRadius = chart.getDataVisibility(i) ? scale.getDistanceFromCenterForValue(dataset.data[i]) : 0; angle = endAngle; if (reset) { if (animationOpts.animateScale) { outerRadius = 0; } if (animationOpts.animateRotate) { startAngle = endAngle = datasetStartAngle; } } const properties = { x: centerX, y: centerY, innerRadius: 0, outerRadius, startAngle, endAngle, options: this.resolveDataElementOptions(i, arc.active ? 'active' : mode) }; this.updateElement(arc, i, properties, mode); } } countVisibleElements() { const dataset = this.getDataset(); const meta = this._cachedMeta; let count = 0; meta.data.forEach((element, index) => { if (!isNaN(dataset.data[index]) && this.chart.getDataVisibility(index)) { count++; } }); return count; } _computeAngle(index, mode, defaultAngle) { return this.chart.getDataVisibility(index) ? toRadians(this.resolveDataElementOptions(index, mode).angle || defaultAngle) : 0; } } PolarAreaController.id = 'polarArea'; PolarAreaController.defaults = { dataElementType: 'arc', animation: { animateRotate: true, animateScale: true }, animations: { numbers: { type: 'number', properties: ['x', 'y', 'startAngle', 'endAngle', 'innerRadius', 'outerRadius'] }, }, indexAxis: 'r', startAngle: 0, }; PolarAreaController.overrides = { aspectRatio: 1, plugins: { legend: { labels: { generateLabels(chart) { const data = chart.data; if (data.labels.length && data.datasets.length) { const {labels: {pointStyle}} = chart.legend.options; return data.labels.map((label, i) => { const meta = chart.getDatasetMeta(0); const style = meta.controller.getStyle(i); return { text: label, fillStyle: style.backgroundColor, strokeStyle: style.borderColor, lineWidth: style.borderWidth, pointStyle: pointStyle, hidden: !chart.getDataVisibility(i), index: i }; }); } return []; } }, onClick(e, legendItem, legend) { legend.chart.toggleDataVisibility(legendItem.index); legend.chart.update(); } }, tooltip: { callbacks: { title() { return ''; }, label(context) { return context.chart.data.labels[context.dataIndex] + ': ' + context.formattedValue; } } } }, scales: { r: { type: 'radialLinear', angleLines: { display: false }, beginAtZero: true, grid: { circular: true }, pointLabels: { display: false }, startAngle: 0 } } }; class PieController extends DoughnutController { } PieController.id = 'pie'; PieController.defaults = { cutout: 0, rotation: 0, circumference: 360, radius: '100%' }; class RadarController extends DatasetController { getLabelAndValue(index) { const vScale = this._cachedMeta.vScale; const parsed = this.getParsed(index); return { label: vScale.getLabels()[index], value: '' + vScale.getLabelForValue(parsed[vScale.axis]) }; } update(mode) { const meta = this._cachedMeta; const line = meta.dataset; const points = meta.data || []; const labels = meta.iScale.getLabels(); line.points = points; if (mode !== 'resize') { const options = this.resolveDatasetElementOptions(mode); if (!this.options.showLine) { options.borderWidth = 0; } const properties = { _loop: true, _fullLoop: labels.length === points.length, options }; this.updateElement(line, undefined, properties, mode); } this.updateElements(points, 0, points.length, mode); } updateElements(points, start, count, mode) { const dataset = this.getDataset(); const scale = this._cachedMeta.rScale; const reset = mode === 'reset'; for (let i = start; i < start + count; i++) { const point = points[i]; const options = this.resolveDataElementOptions(i, point.active ? 'active' : mode); const pointPosition = scale.getPointPositionForValue(i, dataset.data[i]); const x = reset ? scale.xCenter : pointPosition.x; const y = reset ? scale.yCenter : pointPosition.y; const properties = { x, y, angle: pointPosition.angle, skip: isNaN(x) || isNaN(y), options }; this.updateElement(point, i, properties, mode); } } } RadarController.id = 'radar'; RadarController.defaults = { datasetElementType: 'line', dataElementType: 'point', indexAxis: 'r', showLine: true, elements: { line: { fill: 'start' } }, }; RadarController.overrides = { aspectRatio: 1, scales: { r: { type: 'radialLinear', } } }; class ScatterController extends LineController { } ScatterController.id = 'scatter'; ScatterController.defaults = { showLine: false, fill: false }; ScatterController.overrides = { interaction: { mode: 'point' }, plugins: { tooltip: { callbacks: { title() { return ''; }, label(item) { return '(' + item.label + ', ' + item.formattedValue + ')'; } } } }, scales: { x: { type: 'linear' }, y: { type: 'linear' } } }; var controllers = /*#__PURE__*/Object.freeze({ __proto__: null, BarController: BarController, BubbleController: BubbleController, DoughnutController: DoughnutController, LineController: LineController, PolarAreaController: PolarAreaController, PieController: PieController, RadarController: RadarController, ScatterController: ScatterController }); function clipArc(ctx, element, endAngle) { const {startAngle, pixelMargin, x, y, outerRadius, innerRadius} = element; let angleMargin = pixelMargin / outerRadius; ctx.beginPath(); ctx.arc(x, y, outerRadius, startAngle - angleMargin, endAngle + angleMargin); if (innerRadius > pixelMargin) { angleMargin = pixelMargin / innerRadius; ctx.arc(x, y, innerRadius, endAngle + angleMargin, startAngle - angleMargin, true); } else { ctx.arc(x, y, pixelMargin, endAngle + HALF_PI, startAngle - HALF_PI); } ctx.closePath(); ctx.clip(); } function toRadiusCorners(value) { return _readValueToProps(value, ['outerStart', 'outerEnd', 'innerStart', 'innerEnd']); } function parseBorderRadius$1(arc, innerRadius, outerRadius, angleDelta) { const o = toRadiusCorners(arc.options.borderRadius); const halfThickness = (outerRadius - innerRadius) / 2; const innerLimit = Math.min(halfThickness, angleDelta * innerRadius / 2); const computeOuterLimit = (val) => { const outerArcLimit = (outerRadius - Math.min(halfThickness, val)) * angleDelta / 2; return _limitValue(val, 0, Math.min(halfThickness, outerArcLimit)); }; return { outerStart: computeOuterLimit(o.outerStart), outerEnd: computeOuterLimit(o.outerEnd), innerStart: _limitValue(o.innerStart, 0, innerLimit), innerEnd: _limitValue(o.innerEnd, 0, innerLimit), }; } function rThetaToXY(r, theta, x, y) { return { x: x + r * Math.cos(theta), y: y + r * Math.sin(theta), }; } function pathArc(ctx, element, offset, spacing, end) { const {x, y, startAngle: start, pixelMargin, innerRadius: innerR} = element; const outerRadius = Math.max(element.outerRadius + spacing + offset - pixelMargin, 0); const innerRadius = innerR > 0 ? innerR + spacing + offset + pixelMargin : 0; let spacingOffset = 0; const alpha = end - start; if (spacing) { const noSpacingInnerRadius = innerR > 0 ? innerR - spacing : 0; const noSpacingOuterRadius = outerRadius > 0 ? outerRadius - spacing : 0; const avNogSpacingRadius = (noSpacingInnerRadius + noSpacingOuterRadius) / 2; const adjustedAngle = avNogSpacingRadius !== 0 ? (alpha * avNogSpacingRadius) / (avNogSpacingRadius + spacing) : alpha; spacingOffset = (alpha - adjustedAngle) / 2; } const beta = Math.max(0.001, alpha * outerRadius - offset / PI) / outerRadius; const angleOffset = (alpha - beta) / 2; const startAngle = start + angleOffset + spacingOffset; const endAngle = end - angleOffset - spacingOffset; const {outerStart, outerEnd, innerStart, innerEnd} = parseBorderRadius$1(element, innerRadius, outerRadius, endAngle - startAngle); const outerStartAdjustedRadius = outerRadius - outerStart; const outerEndAdjustedRadius = outerRadius - outerEnd; const outerStartAdjustedAngle = startAngle + outerStart / outerStartAdjustedRadius; const outerEndAdjustedAngle = endAngle - outerEnd / outerEndAdjustedRadius; const innerStartAdjustedRadius = innerRadius + innerStart; const innerEndAdjustedRadius = innerRadius + innerEnd; const innerStartAdjustedAngle = startAngle + innerStart / innerStartAdjustedRadius; const innerEndAdjustedAngle = endAngle - innerEnd / innerEndAdjustedRadius; ctx.beginPath(); ctx.arc(x, y, outerRadius, outerStartAdjustedAngle, outerEndAdjustedAngle); if (outerEnd > 0) { const pCenter = rThetaToXY(outerEndAdjustedRadius, outerEndAdjustedAngle, x, y); ctx.arc(pCenter.x, pCenter.y, outerEnd, outerEndAdjustedAngle, endAngle + HALF_PI); } const p4 = rThetaToXY(innerEndAdjustedRadius, endAngle, x, y); ctx.lineTo(p4.x, p4.y); if (innerEnd > 0) { const pCenter = rThetaToXY(innerEndAdjustedRadius, innerEndAdjustedAngle, x, y); ctx.arc(pCenter.x, pCenter.y, innerEnd, endAngle + HALF_PI, innerEndAdjustedAngle + Math.PI); } ctx.arc(x, y, innerRadius, endAngle - (innerEnd / innerRadius), startAngle + (innerStart / innerRadius), true); if (innerStart > 0) { const pCenter = rThetaToXY(innerStartAdjustedRadius, innerStartAdjustedAngle, x, y); ctx.arc(pCenter.x, pCenter.y, innerStart, innerStartAdjustedAngle + Math.PI, startAngle - HALF_PI); } const p8 = rThetaToXY(outerStartAdjustedRadius, startAngle, x, y); ctx.lineTo(p8.x, p8.y); if (outerStart > 0) { const pCenter = rThetaToXY(outerStartAdjustedRadius, outerStartAdjustedAngle, x, y); ctx.arc(pCenter.x, pCenter.y, outerStart, startAngle - HALF_PI, outerStartAdjustedAngle); } ctx.closePath(); } function drawArc(ctx, element, offset, spacing) { const {fullCircles, startAngle, circumference} = element; let endAngle = element.endAngle; if (fullCircles) { pathArc(ctx, element, offset, spacing, startAngle + TAU); for (let i = 0; i < fullCircles; ++i) { ctx.fill(); } if (!isNaN(circumference)) { endAngle = startAngle + circumference % TAU; if (circumference % TAU === 0) { endAngle += TAU; } } } pathArc(ctx, element, offset, spacing, endAngle); ctx.fill(); return endAngle; } function drawFullCircleBorders(ctx, element, inner) { const {x, y, startAngle, pixelMargin, fullCircles} = element; const outerRadius = Math.max(element.outerRadius - pixelMargin, 0); const innerRadius = element.innerRadius + pixelMargin; let i; if (inner) { clipArc(ctx, element, startAngle + TAU); } ctx.beginPath(); ctx.arc(x, y, innerRadius, startAngle + TAU, startAngle, true); for (i = 0; i < fullCircles; ++i) { ctx.stroke(); } ctx.beginPath(); ctx.arc(x, y, outerRadius, startAngle, startAngle + TAU); for (i = 0; i < fullCircles; ++i) { ctx.stroke(); } } function drawBorder(ctx, element, offset, spacing, endAngle) { const {options} = element; const inner = options.borderAlign === 'inner'; if (!options.borderWidth) { return; } if (inner) { ctx.lineWidth = options.borderWidth * 2; ctx.lineJoin = 'round'; } else { ctx.lineWidth = options.borderWidth; ctx.lineJoin = 'bevel'; } if (element.fullCircles) { drawFullCircleBorders(ctx, element, inner); } if (inner) { clipArc(ctx, element, endAngle); } pathArc(ctx, element, offset, spacing, endAngle); ctx.stroke(); } class ArcElement extends Element { constructor(cfg) { super(); this.options = undefined; this.circumference = undefined; this.startAngle = undefined; this.endAngle = undefined; this.innerRadius = undefined; this.outerRadius = undefined; this.pixelMargin = 0; this.fullCircles = 0; if (cfg) { Object.assign(this, cfg); } } inRange(chartX, chartY, useFinalPosition) { const point = this.getProps(['x', 'y'], useFinalPosition); const {angle, distance} = getAngleFromPoint(point, {x: chartX, y: chartY}); const {startAngle, endAngle, innerRadius, outerRadius, circumference} = this.getProps([ 'startAngle', 'endAngle', 'innerRadius', 'outerRadius', 'circumference' ], useFinalPosition); const rAdjust = this.options.spacing / 2; const _circumference = valueOrDefault(circumference, endAngle - startAngle); const betweenAngles = _circumference >= TAU || _angleBetween(angle, startAngle, endAngle); const withinRadius = _isBetween(distance, innerRadius + rAdjust, outerRadius + rAdjust); return (betweenAngles && withinRadius); } getCenterPoint(useFinalPosition) { const {x, y, startAngle, endAngle, innerRadius, outerRadius} = this.getProps([ 'x', 'y', 'startAngle', 'endAngle', 'innerRadius', 'outerRadius', 'circumference', ], useFinalPosition); const {offset, spacing} = this.options; const halfAngle = (startAngle + endAngle) / 2; const halfRadius = (innerRadius + outerRadius + spacing + offset) / 2; return { x: x + Math.cos(halfAngle) * halfRadius, y: y + Math.sin(halfAngle) * halfRadius }; } tooltipPosition(useFinalPosition) { return this.getCenterPoint(useFinalPosition); } draw(ctx) { const {options, circumference} = this; const offset = (options.offset || 0) / 2; const spacing = (options.spacing || 0) / 2; this.pixelMargin = (options.borderAlign === 'inner') ? 0.33 : 0; this.fullCircles = circumference > TAU ? Math.floor(circumference / TAU) : 0; if (circumference === 0 || this.innerRadius < 0 || this.outerRadius < 0) { return; } ctx.save(); let radiusOffset = 0; if (offset) { radiusOffset = offset / 2; const halfAngle = (this.startAngle + this.endAngle) / 2; ctx.translate(Math.cos(halfAngle) * radiusOffset, Math.sin(halfAngle) * radiusOffset); if (this.circumference >= PI) { radiusOffset = offset; } } ctx.fillStyle = options.backgroundColor; ctx.strokeStyle = options.borderColor; const endAngle = drawArc(ctx, this, radiusOffset, spacing); drawBorder(ctx, this, radiusOffset, spacing, endAngle); ctx.restore(); } } ArcElement.id = 'arc'; ArcElement.defaults = { borderAlign: 'center', borderColor: '#fff', borderRadius: 0, borderWidth: 2, offset: 0, spacing: 0, angle: undefined, }; ArcElement.defaultRoutes = { backgroundColor: 'backgroundColor' }; function setStyle(ctx, options, style = options) { ctx.lineCap = valueOrDefault(style.borderCapStyle, options.borderCapStyle); ctx.setLineDash(valueOrDefault(style.borderDash, options.borderDash)); ctx.lineDashOffset = valueOrDefault(style.borderDashOffset, options.borderDashOffset); ctx.lineJoin = valueOrDefault(style.borderJoinStyle, options.borderJoinStyle); ctx.lineWidth = valueOrDefault(style.borderWidth, options.borderWidth); ctx.strokeStyle = valueOrDefault(style.borderColor, options.borderColor); } function lineTo(ctx, previous, target) { ctx.lineTo(target.x, target.y); } function getLineMethod(options) { if (options.stepped) { return _steppedLineTo; } if (options.tension || options.cubicInterpolationMode === 'monotone') { return _bezierCurveTo; } return lineTo; } function pathVars(points, segment, params = {}) { const count = points.length; const {start: paramsStart = 0, end: paramsEnd = count - 1} = params; const {start: segmentStart, end: segmentEnd} = segment; const start = Math.max(paramsStart, segmentStart); const end = Math.min(paramsEnd, segmentEnd); const outside = paramsStart < segmentStart && paramsEnd < segmentStart || paramsStart > segmentEnd && paramsEnd > segmentEnd; return { count, start, loop: segment.loop, ilen: end < start && !outside ? count + end - start : end - start }; } function pathSegment(ctx, line, segment, params) { const {points, options} = line; const {count, start, loop, ilen} = pathVars(points, segment, params); const lineMethod = getLineMethod(options); let {move = true, reverse} = params || {}; let i, point, prev; for (i = 0; i <= ilen; ++i) { point = points[(start + (reverse ? ilen - i : i)) % count]; if (point.skip) { continue; } else if (move) { ctx.moveTo(point.x, point.y); move = false; } else { lineMethod(ctx, prev, point, reverse, options.stepped); } prev = point; } if (loop) { point = points[(start + (reverse ? ilen : 0)) % count]; lineMethod(ctx, prev, point, reverse, options.stepped); } return !!loop; } function fastPathSegment(ctx, line, segment, params) { const points = line.points; const {count, start, ilen} = pathVars(points, segment, params); const {move = true, reverse} = params || {}; let avgX = 0; let countX = 0; let i, point, prevX, minY, maxY, lastY; const pointIndex = (index) => (start + (reverse ? ilen - index : index)) % count; const drawX = () => { if (minY !== maxY) { ctx.lineTo(avgX, maxY); ctx.lineTo(avgX, minY); ctx.lineTo(avgX, lastY); } }; if (move) { point = points[pointIndex(0)]; ctx.moveTo(point.x, point.y); } for (i = 0; i <= ilen; ++i) { point = points[pointIndex(i)]; if (point.skip) { continue; } const x = point.x; const y = point.y; const truncX = x | 0; if (truncX === prevX) { if (y < minY) { minY = y; } else if (y > maxY) { maxY = y; } avgX = (countX * avgX + x) / ++countX; } else { drawX(); ctx.lineTo(x, y); prevX = truncX; countX = 0; minY = maxY = y; } lastY = y; } drawX(); } function _getSegmentMethod(line) { const opts = line.options; const borderDash = opts.borderDash && opts.borderDash.length; const useFastPath = !line._decimated && !line._loop && !opts.tension && opts.cubicInterpolationMode !== 'monotone' && !opts.stepped && !borderDash; return useFastPath ? fastPathSegment : pathSegment; } function _getInterpolationMethod(options) { if (options.stepped) { return _steppedInterpolation; } if (options.tension || options.cubicInterpolationMode === 'monotone') { return _bezierInterpolation; } return _pointInLine; } function strokePathWithCache(ctx, line, start, count) { let path = line._path; if (!path) { path = line._path = new Path2D(); if (line.path(path, start, count)) { path.closePath(); } } setStyle(ctx, line.options); ctx.stroke(path); } function strokePathDirect(ctx, line, start, count) { const {segments, options} = line; const segmentMethod = _getSegmentMethod(line); for (const segment of segments) { setStyle(ctx, options, segment.style); ctx.beginPath(); if (segmentMethod(ctx, line, segment, {start, end: start + count - 1})) { ctx.closePath(); } ctx.stroke(); } } const usePath2D = typeof Path2D === 'function'; function draw(ctx, line, start, count) { if (usePath2D && !line.options.segment) { strokePathWithCache(ctx, line, start, count); } else { strokePathDirect(ctx, line, start, count); } } class LineElement extends Element { constructor(cfg) { super(); this.animated = true; this.options = undefined; this._chart = undefined; this._loop = undefined; this._fullLoop = undefined; this._path = undefined; this._points = undefined; this._segments = undefined; this._decimated = false; this._pointsUpdated = false; this._datasetIndex = undefined; if (cfg) { Object.assign(this, cfg); } } updateControlPoints(chartArea, indexAxis) { const options = this.options; if ((options.tension || options.cubicInterpolationMode === 'monotone') && !options.stepped && !this._pointsUpdated) { const loop = options.spanGaps ? this._loop : this._fullLoop; _updateBezierControlPoints(this._points, options, chartArea, loop, indexAxis); this._pointsUpdated = true; } } set points(points) { this._points = points; delete this._segments; delete this._path; this._pointsUpdated = false; } get points() { return this._points; } get segments() { return this._segments || (this._segments = _computeSegments(this, this.options.segment)); } first() { const segments = this.segments; const points = this.points; return segments.length && points[segments[0].start]; } last() { const segments = this.segments; const points = this.points; const count = segments.length; return count && points[segments[count - 1].end]; } interpolate(point, property) { const options = this.options; const value = point[property]; const points = this.points; const segments = _boundSegments(this, {property, start: value, end: value}); if (!segments.length) { return; } const result = []; const _interpolate = _getInterpolationMethod(options); let i, ilen; for (i = 0, ilen = segments.length; i < ilen; ++i) { const {start, end} = segments[i]; const p1 = points[start]; const p2 = points[end]; if (p1 === p2) { result.push(p1); continue; } const t = Math.abs((value - p1[property]) / (p2[property] - p1[property])); const interpolated = _interpolate(p1, p2, t, options.stepped); interpolated[property] = point[property]; result.push(interpolated); } return result.length === 1 ? result[0] : result; } pathSegment(ctx, segment, params) { const segmentMethod = _getSegmentMethod(this); return segmentMethod(ctx, this, segment, params); } path(ctx, start, count) { const segments = this.segments; const segmentMethod = _getSegmentMethod(this); let loop = this._loop; start = start || 0; count = count || (this.points.length - start); for (const segment of segments) { loop &= segmentMethod(ctx, this, segment, {start, end: start + count - 1}); } return !!loop; } draw(ctx, chartArea, start, count) { const options = this.options || {}; const points = this.points || []; if (points.length && options.borderWidth) { ctx.save(); draw(ctx, this, start, count); ctx.restore(); } if (this.animated) { this._pointsUpdated = false; this._path = undefined; } } } LineElement.id = 'line'; LineElement.defaults = { borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0, borderJoinStyle: 'miter', borderWidth: 3, capBezierPoints: true, cubicInterpolationMode: 'default', fill: false, spanGaps: false, stepped: false, tension: 0, }; LineElement.defaultRoutes = { backgroundColor: 'backgroundColor', borderColor: 'borderColor' }; LineElement.descriptors = { _scriptable: true, _indexable: (name) => name !== 'borderDash' && name !== 'fill', }; function inRange$1(el, pos, axis, useFinalPosition) { const options = el.options; const {[axis]: value} = el.getProps([axis], useFinalPosition); return (Math.abs(pos - value) < options.radius + options.hitRadius); } class PointElement extends Element { constructor(cfg) { super(); this.options = undefined; this.parsed = undefined; this.skip = undefined; this.stop = undefined; if (cfg) { Object.assign(this, cfg); } } inRange(mouseX, mouseY, useFinalPosition) { const options = this.options; const {x, y} = this.getProps(['x', 'y'], useFinalPosition); return ((Math.pow(mouseX - x, 2) + Math.pow(mouseY - y, 2)) < Math.pow(options.hitRadius + options.radius, 2)); } inXRange(mouseX, useFinalPosition) { return inRange$1(this, mouseX, 'x', useFinalPosition); } inYRange(mouseY, useFinalPosition) { return inRange$1(this, mouseY, 'y', useFinalPosition); } getCenterPoint(useFinalPosition) { const {x, y} = this.getProps(['x', 'y'], useFinalPosition); return {x, y}; } size(options) { options = options || this.options || {}; let radius = options.radius || 0; radius = Math.max(radius, radius && options.hoverRadius || 0); const borderWidth = radius && options.borderWidth || 0; return (radius + borderWidth) * 2; } draw(ctx, area) { const options = this.options; if (this.skip || options.radius < 0.1 || !_isPointInArea(this, area, this.size(options) / 2)) { return; } ctx.strokeStyle = options.borderColor; ctx.lineWidth = options.borderWidth; ctx.fillStyle = options.backgroundColor; drawPoint(ctx, options, this.x, this.y); } getRange() { const options = this.options || {}; return options.radius + options.hitRadius; } } PointElement.id = 'point'; PointElement.defaults = { borderWidth: 1, hitRadius: 1, hoverBorderWidth: 1, hoverRadius: 4, pointStyle: 'circle', radius: 3, rotation: 0 }; PointElement.defaultRoutes = { backgroundColor: 'backgroundColor', borderColor: 'borderColor' }; function getBarBounds(bar, useFinalPosition) { const {x, y, base, width, height} = bar.getProps(['x', 'y', 'base', 'width', 'height'], useFinalPosition); let left, right, top, bottom, half; if (bar.horizontal) { half = height / 2; left = Math.min(x, base); right = Math.max(x, base); top = y - half; bottom = y + half; } else { half = width / 2; left = x - half; right = x + half; top = Math.min(y, base); bottom = Math.max(y, base); } return {left, top, right, bottom}; } function skipOrLimit(skip, value, min, max) { return skip ? 0 : _limitValue(value, min, max); } function parseBorderWidth(bar, maxW, maxH) { const value = bar.options.borderWidth; const skip = bar.borderSkipped; const o = toTRBL(value); return { t: skipOrLimit(skip.top, o.top, 0, maxH), r: skipOrLimit(skip.right, o.right, 0, maxW), b: skipOrLimit(skip.bottom, o.bottom, 0, maxH), l: skipOrLimit(skip.left, o.left, 0, maxW) }; } function parseBorderRadius(bar, maxW, maxH) { const {enableBorderRadius} = bar.getProps(['enableBorderRadius']); const value = bar.options.borderRadius; const o = toTRBLCorners(value); const maxR = Math.min(maxW, maxH); const skip = bar.borderSkipped; const enableBorder = enableBorderRadius || isObject(value); return { topLeft: skipOrLimit(!enableBorder || skip.top || skip.left, o.topLeft, 0, maxR), topRight: skipOrLimit(!enableBorder || skip.top || skip.right, o.topRight, 0, maxR), bottomLeft: skipOrLimit(!enableBorder || skip.bottom || skip.left, o.bottomLeft, 0, maxR), bottomRight: skipOrLimit(!enableBorder || skip.bottom || skip.right, o.bottomRight, 0, maxR) }; } function boundingRects(bar) { const bounds = getBarBounds(bar); const width = bounds.right - bounds.left; const height = bounds.bottom - bounds.top; const border = parseBorderWidth(bar, width / 2, height / 2); const radius = parseBorderRadius(bar, width / 2, height / 2); return { outer: { x: bounds.left, y: bounds.top, w: width, h: height, radius }, inner: { x: bounds.left + border.l, y: bounds.top + border.t, w: width - border.l - border.r, h: height - border.t - border.b, radius: { topLeft: Math.max(0, radius.topLeft - Math.max(border.t, border.l)), topRight: Math.max(0, radius.topRight - Math.max(border.t, border.r)), bottomLeft: Math.max(0, radius.bottomLeft - Math.max(border.b, border.l)), bottomRight: Math.max(0, radius.bottomRight - Math.max(border.b, border.r)), } } }; } function inRange(bar, x, y, useFinalPosition) { const skipX = x === null; const skipY = y === null; const skipBoth = skipX && skipY; const bounds = bar && !skipBoth && getBarBounds(bar, useFinalPosition); return bounds && (skipX || _isBetween(x, bounds.left, bounds.right)) && (skipY || _isBetween(y, bounds.top, bounds.bottom)); } function hasRadius(radius) { return radius.topLeft || radius.topRight || radius.bottomLeft || radius.bottomRight; } function addNormalRectPath(ctx, rect) { ctx.rect(rect.x, rect.y, rect.w, rect.h); } function inflateRect(rect, amount, refRect = {}) { const x = rect.x !== refRect.x ? -amount : 0; const y = rect.y !== refRect.y ? -amount : 0; const w = (rect.x + rect.w !== refRect.x + refRect.w ? amount : 0) - x; const h = (rect.y + rect.h !== refRect.y + refRect.h ? amount : 0) - y; return { x: rect.x + x, y: rect.y + y, w: rect.w + w, h: rect.h + h, radius: rect.radius }; } class BarElement extends Element { constructor(cfg) { super(); this.options = undefined; this.horizontal = undefined; this.base = undefined; this.width = undefined; this.height = undefined; this.inflateAmount = undefined; if (cfg) { Object.assign(this, cfg); } } draw(ctx) { const {inflateAmount, options: {borderColor, backgroundColor}} = this; const {inner, outer} = boundingRects(this); const addRectPath = hasRadius(outer.radius) ? addRoundedRectPath : addNormalRectPath; ctx.save(); if (outer.w !== inner.w || outer.h !== inner.h) { ctx.beginPath(); addRectPath(ctx, inflateRect(outer, inflateAmount, inner)); ctx.clip(); addRectPath(ctx, inflateRect(inner, -inflateAmount, outer)); ctx.fillStyle = borderColor; ctx.fill('evenodd'); } ctx.beginPath(); addRectPath(ctx, inflateRect(inner, inflateAmount)); ctx.fillStyle = backgroundColor; ctx.fill(); ctx.restore(); } inRange(mouseX, mouseY, useFinalPosition) { return inRange(this, mouseX, mouseY, useFinalPosition); } inXRange(mouseX, useFinalPosition) { return inRange(this, mouseX, null, useFinalPosition); } inYRange(mouseY, useFinalPosition) { return inRange(this, null, mouseY, useFinalPosition); } getCenterPoint(useFinalPosition) { const {x, y, base, horizontal} = this.getProps(['x', 'y', 'base', 'horizontal'], useFinalPosition); return { x: horizontal ? (x + base) / 2 : x, y: horizontal ? y : (y + base) / 2 }; } getRange(axis) { return axis === 'x' ? this.width / 2 : this.height / 2; } } BarElement.id = 'bar'; BarElement.defaults = { borderSkipped: 'start', borderWidth: 0, borderRadius: 0, inflateAmount: 'auto', pointStyle: undefined }; BarElement.defaultRoutes = { backgroundColor: 'backgroundColor', borderColor: 'borderColor' }; var elements = /*#__PURE__*/Object.freeze({ __proto__: null, ArcElement: ArcElement, LineElement: LineElement, PointElement: PointElement, BarElement: BarElement }); function lttbDecimation(data, start, count, availableWidth, options) { const samples = options.samples || availableWidth; if (samples >= count) { return data.slice(start, start + count); } const decimated = []; const bucketWidth = (count - 2) / (samples - 2); let sampledIndex = 0; const endIndex = start + count - 1; let a = start; let i, maxAreaPoint, maxArea, area, nextA; decimated[sampledIndex++] = data[a]; for (i = 0; i < samples - 2; i++) { let avgX = 0; let avgY = 0; let j; const avgRangeStart = Math.floor((i + 1) * bucketWidth) + 1 + start; const avgRangeEnd = Math.min(Math.floor((i + 2) * bucketWidth) + 1, count) + start; const avgRangeLength = avgRangeEnd - avgRangeStart; for (j = avgRangeStart; j < avgRangeEnd; j++) { avgX += data[j].x; avgY += data[j].y; } avgX /= avgRangeLength; avgY /= avgRangeLength; const rangeOffs = Math.floor(i * bucketWidth) + 1 + start; const rangeTo = Math.min(Math.floor((i + 1) * bucketWidth) + 1, count) + start; const {x: pointAx, y: pointAy} = data[a]; maxArea = area = -1; for (j = rangeOffs; j < rangeTo; j++) { area = 0.5 * Math.abs( (pointAx - avgX) * (data[j].y - pointAy) - (pointAx - data[j].x) * (avgY - pointAy) ); if (area > maxArea) { maxArea = area; maxAreaPoint = data[j]; nextA = j; } } decimated[sampledIndex++] = maxAreaPoint; a = nextA; } decimated[sampledIndex++] = data[endIndex]; return decimated; } function minMaxDecimation(data, start, count, availableWidth) { let avgX = 0; let countX = 0; let i, point, x, y, prevX, minIndex, maxIndex, startIndex, minY, maxY; const decimated = []; const endIndex = start + count - 1; const xMin = data[start].x; const xMax = data[endIndex].x; const dx = xMax - xMin; for (i = start; i < start + count; ++i) { point = data[i]; x = (point.x - xMin) / dx * availableWidth; y = point.y; const truncX = x | 0; if (truncX === prevX) { if (y < minY) { minY = y; minIndex = i; } else if (y > maxY) { maxY = y; maxIndex = i; } avgX = (countX * avgX + point.x) / ++countX; } else { const lastIndex = i - 1; if (!isNullOrUndef(minIndex) && !isNullOrUndef(maxIndex)) { const intermediateIndex1 = Math.min(minIndex, maxIndex); const intermediateIndex2 = Math.max(minIndex, maxIndex); if (intermediateIndex1 !== startIndex && intermediateIndex1 !== lastIndex) { decimated.push({ ...data[intermediateIndex1], x: avgX, }); } if (intermediateIndex2 !== startIndex && intermediateIndex2 !== lastIndex) { decimated.push({ ...data[intermediateIndex2], x: avgX }); } } if (i > 0 && lastIndex !== startIndex) { decimated.push(data[lastIndex]); } decimated.push(point); prevX = truncX; countX = 0; minY = maxY = y; minIndex = maxIndex = startIndex = i; } } return decimated; } function cleanDecimatedDataset(dataset) { if (dataset._decimated) { const data = dataset._data; delete dataset._decimated; delete dataset._data; Object.defineProperty(dataset, 'data', {value: data}); } } function cleanDecimatedData(chart) { chart.data.datasets.forEach((dataset) => { cleanDecimatedDataset(dataset); }); } function getStartAndCountOfVisiblePointsSimplified(meta, points) { const pointCount = points.length; let start = 0; let count; const {iScale} = meta; const {min, max, minDefined, maxDefined} = iScale.getUserBounds(); if (minDefined) { start = _limitValue(_lookupByKey(points, iScale.axis, min).lo, 0, pointCount - 1); } if (maxDefined) { count = _limitValue(_lookupByKey(points, iScale.axis, max).hi + 1, start, pointCount) - start; } else { count = pointCount - start; } return {start, count}; } var plugin_decimation = { id: 'decimation', defaults: { algorithm: 'min-max', enabled: false, }, beforeElementsUpdate: (chart, args, options) => { if (!options.enabled) { cleanDecimatedData(chart); return; } const availableWidth = chart.width; chart.data.datasets.forEach((dataset, datasetIndex) => { const {_data, indexAxis} = dataset; const meta = chart.getDatasetMeta(datasetIndex); const data = _data || dataset.data; if (resolve([indexAxis, chart.options.indexAxis]) === 'y') { return; } if (meta.type !== 'line') { return; } const xAxis = chart.scales[meta.xAxisID]; if (xAxis.type !== 'linear' && xAxis.type !== 'time') { return; } if (chart.options.parsing) { return; } let {start, count} = getStartAndCountOfVisiblePointsSimplified(meta, data); const threshold = options.threshold || 4 * availableWidth; if (count <= threshold) { cleanDecimatedDataset(dataset); return; } if (isNullOrUndef(_data)) { dataset._data = data; delete dataset.data; Object.defineProperty(dataset, 'data', { configurable: true, enumerable: true, get: function() { return this._decimated; }, set: function(d) { this._data = d; } }); } let decimated; switch (options.algorithm) { case 'lttb': decimated = lttbDecimation(data, start, count, availableWidth, options); break; case 'min-max': decimated = minMaxDecimation(data, start, count, availableWidth); break; default: throw new Error(`Unsupported decimation algorithm '${options.algorithm}'`); } dataset._decimated = decimated; }); }, destroy(chart) { cleanDecimatedData(chart); } }; function getLineByIndex(chart, index) { const meta = chart.getDatasetMeta(index); const visible = meta && chart.isDatasetVisible(index); return visible ? meta.dataset : null; } function parseFillOption(line) { const options = line.options; const fillOption = options.fill; let fill = valueOrDefault(fillOption && fillOption.target, fillOption); if (fill === undefined) { fill = !!options.backgroundColor; } if (fill === false || fill === null) { return false; } if (fill === true) { return 'origin'; } return fill; } function decodeFill(line, index, count) { const fill = parseFillOption(line); if (isObject(fill)) { return isNaN(fill.value) ? false : fill; } let target = parseFloat(fill); if (isNumberFinite(target) && Math.floor(target) === target) { if (fill[0] === '-' || fill[0] === '+') { target = index + target; } if (target === index || target < 0 || target >= count) { return false; } return target; } return ['origin', 'start', 'end', 'stack', 'shape'].indexOf(fill) >= 0 && fill; } function computeLinearBoundary(source) { const {scale = {}, fill} = source; let target = null; let horizontal; if (fill === 'start') { target = scale.bottom; } else if (fill === 'end') { target = scale.top; } else if (isObject(fill)) { target = scale.getPixelForValue(fill.value); } else if (scale.getBasePixel) { target = scale.getBasePixel(); } if (isNumberFinite(target)) { horizontal = scale.isHorizontal(); return { x: horizontal ? target : null, y: horizontal ? null : target }; } return null; } class simpleArc { constructor(opts) { this.x = opts.x; this.y = opts.y; this.radius = opts.radius; } pathSegment(ctx, bounds, opts) { const {x, y, radius} = this; bounds = bounds || {start: 0, end: TAU}; ctx.arc(x, y, radius, bounds.end, bounds.start, true); return !opts.bounds; } interpolate(point) { const {x, y, radius} = this; const angle = point.angle; return { x: x + Math.cos(angle) * radius, y: y + Math.sin(angle) * radius, angle }; } } function computeCircularBoundary(source) { const {scale, fill} = source; const options = scale.options; const length = scale.getLabels().length; const target = []; const start = options.reverse ? scale.max : scale.min; const end = options.reverse ? scale.min : scale.max; let i, center, value; if (fill === 'start') { value = start; } else if (fill === 'end') { value = end; } else if (isObject(fill)) { value = fill.value; } else { value = scale.getBaseValue(); } if (options.grid.circular) { center = scale.getPointPositionForValue(0, start); return new simpleArc({ x: center.x, y: center.y, radius: scale.getDistanceFromCenterForValue(value) }); } for (i = 0; i < length; ++i) { target.push(scale.getPointPositionForValue(i, value)); } return target; } function computeBoundary(source) { const scale = source.scale || {}; if (scale.getPointPositionForValue) { return computeCircularBoundary(source); } return computeLinearBoundary(source); } function findSegmentEnd(start, end, points) { for (;end > start; end--) { const point = points[end]; if (!isNaN(point.x) && !isNaN(point.y)) { break; } } return end; } function pointsFromSegments(boundary, line) { const {x = null, y = null} = boundary || {}; const linePoints = line.points; const points = []; line.segments.forEach(({start, end}) => { end = findSegmentEnd(start, end, linePoints); const first = linePoints[start]; const last = linePoints[end]; if (y !== null) { points.push({x: first.x, y}); points.push({x: last.x, y}); } else if (x !== null) { points.push({x, y: first.y}); points.push({x, y: last.y}); } }); return points; } function buildStackLine(source) { const {scale, index, line} = source; const points = []; const segments = line.segments; const sourcePoints = line.points; const linesBelow = getLinesBelow(scale, index); linesBelow.push(createBoundaryLine({x: null, y: scale.bottom}, line)); for (let i = 0; i < segments.length; i++) { const segment = segments[i]; for (let j = segment.start; j <= segment.end; j++) { addPointsBelow(points, sourcePoints[j], linesBelow); } } return new LineElement({points, options: {}}); } function getLinesBelow(scale, index) { const below = []; const metas = scale.getMatchingVisibleMetas('line'); for (let i = 0; i < metas.length; i++) { const meta = metas[i]; if (meta.index === index) { break; } if (!meta.hidden) { below.unshift(meta.dataset); } } return below; } function addPointsBelow(points, sourcePoint, linesBelow) { const postponed = []; for (let j = 0; j < linesBelow.length; j++) { const line = linesBelow[j]; const {first, last, point} = findPoint(line, sourcePoint, 'x'); if (!point || (first && last)) { continue; } if (first) { postponed.unshift(point); } else { points.push(point); if (!last) { break; } } } points.push(...postponed); } function findPoint(line, sourcePoint, property) { const point = line.interpolate(sourcePoint, property); if (!point) { return {}; } const pointValue = point[property]; const segments = line.segments; const linePoints = line.points; let first = false; let last = false; for (let i = 0; i < segments.length; i++) { const segment = segments[i]; const firstValue = linePoints[segment.start][property]; const lastValue = linePoints[segment.end][property]; if (_isBetween(pointValue, firstValue, lastValue)) { first = pointValue === firstValue; last = pointValue === lastValue; break; } } return {first, last, point}; } function getTarget(source) { const {chart, fill, line} = source; if (isNumberFinite(fill)) { return getLineByIndex(chart, fill); } if (fill === 'stack') { return buildStackLine(source); } if (fill === 'shape') { return true; } const boundary = computeBoundary(source); if (boundary instanceof simpleArc) { return boundary; } return createBoundaryLine(boundary, line); } function createBoundaryLine(boundary, line) { let points = []; let _loop = false; if (isArray(boundary)) { _loop = true; points = boundary; } else { points = pointsFromSegments(boundary, line); } return points.length ? new LineElement({ points, options: {tension: 0}, _loop, _fullLoop: _loop }) : null; } function resolveTarget(sources, index, propagate) { const source = sources[index]; let fill = source.fill; const visited = [index]; let target; if (!propagate) { return fill; } while (fill !== false && visited.indexOf(fill) === -1) { if (!isNumberFinite(fill)) { return fill; } target = sources[fill]; if (!target) { return false; } if (target.visible) { return fill; } visited.push(fill); fill = target.fill; } return false; } function _clip(ctx, target, clipY) { ctx.beginPath(); target.path(ctx); ctx.lineTo(target.last().x, clipY); ctx.lineTo(target.first().x, clipY); ctx.closePath(); ctx.clip(); } function getBounds(property, first, last, loop) { if (loop) { return; } let start = first[property]; let end = last[property]; if (property === 'angle') { start = _normalizeAngle(start); end = _normalizeAngle(end); } return {property, start, end}; } function _getEdge(a, b, prop, fn) { if (a && b) { return fn(a[prop], b[prop]); } return a ? a[prop] : b ? b[prop] : 0; } function _segments(line, target, property) { const segments = line.segments; const points = line.points; const tpoints = target.points; const parts = []; for (const segment of segments) { let {start, end} = segment; end = findSegmentEnd(start, end, points); const bounds = getBounds(property, points[start], points[end], segment.loop); if (!target.segments) { parts.push({ source: segment, target: bounds, start: points[start], end: points[end] }); continue; } const targetSegments = _boundSegments(target, bounds); for (const tgt of targetSegments) { const subBounds = getBounds(property, tpoints[tgt.start], tpoints[tgt.end], tgt.loop); const fillSources = _boundSegment(segment, points, subBounds); for (const fillSource of fillSources) { parts.push({ source: fillSource, target: tgt, start: { [property]: _getEdge(bounds, subBounds, 'start', Math.max) }, end: { [property]: _getEdge(bounds, subBounds, 'end', Math.min) } }); } } } return parts; } function clipBounds(ctx, scale, bounds) { const {top, bottom} = scale.chart.chartArea; const {property, start, end} = bounds || {}; if (property === 'x') { ctx.beginPath(); ctx.rect(start, top, end - start, bottom - top); ctx.clip(); } } function interpolatedLineTo(ctx, target, point, property) { const interpolatedPoint = target.interpolate(point, property); if (interpolatedPoint) { ctx.lineTo(interpolatedPoint.x, interpolatedPoint.y); } } function _fill(ctx, cfg) { const {line, target, property, color, scale} = cfg; const segments = _segments(line, target, property); for (const {source: src, target: tgt, start, end} of segments) { const {style: {backgroundColor = color} = {}} = src; const notShape = target !== true; ctx.save(); ctx.fillStyle = backgroundColor; clipBounds(ctx, scale, notShape && getBounds(property, start, end)); ctx.beginPath(); const lineLoop = !!line.pathSegment(ctx, src); let loop; if (notShape) { if (lineLoop) { ctx.closePath(); } else { interpolatedLineTo(ctx, target, end, property); } const targetLoop = !!target.pathSegment(ctx, tgt, {move: lineLoop, reverse: true}); loop = lineLoop && targetLoop; if (!loop) { interpolatedLineTo(ctx, target, start, property); } } ctx.closePath(); ctx.fill(loop ? 'evenodd' : 'nonzero'); ctx.restore(); } } function doFill(ctx, cfg) { const {line, target, above, below, area, scale} = cfg; const property = line._loop ? 'angle' : cfg.axis; ctx.save(); if (property === 'x' && below !== above) { _clip(ctx, target, area.top); _fill(ctx, {line, target, color: above, scale, property}); ctx.restore(); ctx.save(); _clip(ctx, target, area.bottom); } _fill(ctx, {line, target, color: below, scale, property}); ctx.restore(); } function drawfill(ctx, source, area) { const target = getTarget(source); const {line, scale, axis} = source; const lineOpts = line.options; const fillOption = lineOpts.fill; const color = lineOpts.backgroundColor; const {above = color, below = color} = fillOption || {}; if (target && line.points.length) { clipArea(ctx, area); doFill(ctx, {line, target, above, below, area, scale, axis}); unclipArea(ctx); } } var plugin_filler = { id: 'filler', afterDatasetsUpdate(chart, _args, options) { const count = (chart.data.datasets || []).length; const sources = []; let meta, i, line, source; for (i = 0; i < count; ++i) { meta = chart.getDatasetMeta(i); line = meta.dataset; source = null; if (line && line.options && line instanceof LineElement) { source = { visible: chart.isDatasetVisible(i), index: i, fill: decodeFill(line, i, count), chart, axis: meta.controller.options.indexAxis, scale: meta.vScale, line, }; } meta.$filler = source; sources.push(source); } for (i = 0; i < count; ++i) { source = sources[i]; if (!source || source.fill === false) { continue; } source.fill = resolveTarget(sources, i, options.propagate); } }, beforeDraw(chart, _args, options) { const draw = options.drawTime === 'beforeDraw'; const metasets = chart.getSortedVisibleDatasetMetas(); const area = chart.chartArea; for (let i = metasets.length - 1; i >= 0; --i) { const source = metasets[i].$filler; if (!source) { continue; } source.line.updateControlPoints(area, source.axis); if (draw) { drawfill(chart.ctx, source, area); } } }, beforeDatasetsDraw(chart, _args, options) { if (options.drawTime !== 'beforeDatasetsDraw') { return; } const metasets = chart.getSortedVisibleDatasetMetas(); for (let i = metasets.length - 1; i >= 0; --i) { const source = metasets[i].$filler; if (source) { drawfill(chart.ctx, source, chart.chartArea); } } }, beforeDatasetDraw(chart, args, options) { const source = args.meta.$filler; if (!source || source.fill === false || options.drawTime !== 'beforeDatasetDraw') { return; } drawfill(chart.ctx, source, chart.chartArea); }, defaults: { propagate: true, drawTime: 'beforeDatasetDraw' } }; const getBoxSize = (labelOpts, fontSize) => { let {boxHeight = fontSize, boxWidth = fontSize} = labelOpts; if (labelOpts.usePointStyle) { boxHeight = Math.min(boxHeight, fontSize); boxWidth = Math.min(boxWidth, fontSize); } return { boxWidth, boxHeight, itemHeight: Math.max(fontSize, boxHeight) }; }; const itemsEqual = (a, b) => a !== null && b !== null && a.datasetIndex === b.datasetIndex && a.index === b.index; class Legend extends Element { constructor(config) { super(); this._added = false; this.legendHitBoxes = []; this._hoveredItem = null; this.doughnutMode = false; this.chart = config.chart; this.options = config.options; this.ctx = config.ctx; this.legendItems = undefined; this.columnSizes = undefined; this.lineWidths = undefined; this.maxHeight = undefined; this.maxWidth = undefined; this.top = undefined; this.bottom = undefined; this.left = undefined; this.right = undefined; this.height = undefined; this.width = undefined; this._margins = undefined; this.position = undefined; this.weight = undefined; this.fullSize = undefined; } update(maxWidth, maxHeight, margins) { this.maxWidth = maxWidth; this.maxHeight = maxHeight; this._margins = margins; this.setDimensions(); this.buildLabels(); this.fit(); } setDimensions() { if (this.isHorizontal()) { this.width = this.maxWidth; this.left = this._margins.left; this.right = this.width; } else { this.height = this.maxHeight; this.top = this._margins.top; this.bottom = this.height; } } buildLabels() { const labelOpts = this.options.labels || {}; let legendItems = callback(labelOpts.generateLabels, [this.chart], this) || []; if (labelOpts.filter) { legendItems = legendItems.filter((item) => labelOpts.filter(item, this.chart.data)); } if (labelOpts.sort) { legendItems = legendItems.sort((a, b) => labelOpts.sort(a, b, this.chart.data)); } if (this.options.reverse) { legendItems.reverse(); } this.legendItems = legendItems; } fit() { const {options, ctx} = this; if (!options.display) { this.width = this.height = 0; return; } const labelOpts = options.labels; const labelFont = toFont(labelOpts.font); const fontSize = labelFont.size; const titleHeight = this._computeTitleHeight(); const {boxWidth, itemHeight} = getBoxSize(labelOpts, fontSize); let width, height; ctx.font = labelFont.string; if (this.isHorizontal()) { width = this.maxWidth; height = this._fitRows(titleHeight, fontSize, boxWidth, itemHeight) + 10; } else { height = this.maxHeight; width = this._fitCols(titleHeight, fontSize, boxWidth, itemHeight) + 10; } this.width = Math.min(width, options.maxWidth || this.maxWidth); this.height = Math.min(height, options.maxHeight || this.maxHeight); } _fitRows(titleHeight, fontSize, boxWidth, itemHeight) { const {ctx, maxWidth, options: {labels: {padding}}} = this; const hitboxes = this.legendHitBoxes = []; const lineWidths = this.lineWidths = [0]; const lineHeight = itemHeight + padding; let totalHeight = titleHeight; ctx.textAlign = 'left'; ctx.textBaseline = 'middle'; let row = -1; let top = -lineHeight; this.legendItems.forEach((legendItem, i) => { const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width; if (i === 0 || lineWidths[lineWidths.length - 1] + itemWidth + 2 * padding > maxWidth) { totalHeight += lineHeight; lineWidths[lineWidths.length - (i > 0 ? 0 : 1)] = 0; top += lineHeight; row++; } hitboxes[i] = {left: 0, top, row, width: itemWidth, height: itemHeight}; lineWidths[lineWidths.length - 1] += itemWidth + padding; }); return totalHeight; } _fitCols(titleHeight, fontSize, boxWidth, itemHeight) { const {ctx, maxHeight, options: {labels: {padding}}} = this; const hitboxes = this.legendHitBoxes = []; const columnSizes = this.columnSizes = []; const heightLimit = maxHeight - titleHeight; let totalWidth = padding; let currentColWidth = 0; let currentColHeight = 0; let left = 0; let col = 0; this.legendItems.forEach((legendItem, i) => { const itemWidth = boxWidth + (fontSize / 2) + ctx.measureText(legendItem.text).width; if (i > 0 && currentColHeight + itemHeight + 2 * padding > heightLimit) { totalWidth += currentColWidth + padding; columnSizes.push({width: currentColWidth, height: currentColHeight}); left += currentColWidth + padding; col++; currentColWidth = currentColHeight = 0; } hitboxes[i] = {left, top: currentColHeight, col, width: itemWidth, height: itemHeight}; currentColWidth = Math.max(currentColWidth, itemWidth); currentColHeight += itemHeight + padding; }); totalWidth += currentColWidth; columnSizes.push({width: currentColWidth, height: currentColHeight}); return totalWidth; } adjustHitBoxes() { if (!this.options.display) { return; } const titleHeight = this._computeTitleHeight(); const {legendHitBoxes: hitboxes, options: {align, labels: {padding}, rtl}} = this; const rtlHelper = getRtlAdapter(rtl, this.left, this.width); if (this.isHorizontal()) { let row = 0; let left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]); for (const hitbox of hitboxes) { if (row !== hitbox.row) { row = hitbox.row; left = _alignStartEnd(align, this.left + padding, this.right - this.lineWidths[row]); } hitbox.top += this.top + titleHeight + padding; hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(left), hitbox.width); left += hitbox.width + padding; } } else { let col = 0; let top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height); for (const hitbox of hitboxes) { if (hitbox.col !== col) { col = hitbox.col; top = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - this.columnSizes[col].height); } hitbox.top = top; hitbox.left += this.left + padding; hitbox.left = rtlHelper.leftForLtr(rtlHelper.x(hitbox.left), hitbox.width); top += hitbox.height + padding; } } } isHorizontal() { return this.options.position === 'top' || this.options.position === 'bottom'; } draw() { if (this.options.display) { const ctx = this.ctx; clipArea(ctx, this); this._draw(); unclipArea(ctx); } } _draw() { const {options: opts, columnSizes, lineWidths, ctx} = this; const {align, labels: labelOpts} = opts; const defaultColor = defaults.color; const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width); const labelFont = toFont(labelOpts.font); const {color: fontColor, padding} = labelOpts; const fontSize = labelFont.size; const halfFontSize = fontSize / 2; let cursor; this.drawTitle(); ctx.textAlign = rtlHelper.textAlign('left'); ctx.textBaseline = 'middle'; ctx.lineWidth = 0.5; ctx.font = labelFont.string; const {boxWidth, boxHeight, itemHeight} = getBoxSize(labelOpts, fontSize); const drawLegendBox = function(x, y, legendItem) { if (isNaN(boxWidth) || boxWidth <= 0 || isNaN(boxHeight) || boxHeight < 0) { return; } ctx.save(); const lineWidth = valueOrDefault(legendItem.lineWidth, 1); ctx.fillStyle = valueOrDefault(legendItem.fillStyle, defaultColor); ctx.lineCap = valueOrDefault(legendItem.lineCap, 'butt'); ctx.lineDashOffset = valueOrDefault(legendItem.lineDashOffset, 0); ctx.lineJoin = valueOrDefault(legendItem.lineJoin, 'miter'); ctx.lineWidth = lineWidth; ctx.strokeStyle = valueOrDefault(legendItem.strokeStyle, defaultColor); ctx.setLineDash(valueOrDefault(legendItem.lineDash, [])); if (labelOpts.usePointStyle) { const drawOptions = { radius: boxWidth * Math.SQRT2 / 2, pointStyle: legendItem.pointStyle, rotation: legendItem.rotation, borderWidth: lineWidth }; const centerX = rtlHelper.xPlus(x, boxWidth / 2); const centerY = y + halfFontSize; drawPoint(ctx, drawOptions, centerX, centerY); } else { const yBoxTop = y + Math.max((fontSize - boxHeight) / 2, 0); const xBoxLeft = rtlHelper.leftForLtr(x, boxWidth); const borderRadius = toTRBLCorners(legendItem.borderRadius); ctx.beginPath(); if (Object.values(borderRadius).some(v => v !== 0)) { addRoundedRectPath(ctx, { x: xBoxLeft, y: yBoxTop, w: boxWidth, h: boxHeight, radius: borderRadius, }); } else { ctx.rect(xBoxLeft, yBoxTop, boxWidth, boxHeight); } ctx.fill(); if (lineWidth !== 0) { ctx.stroke(); } } ctx.restore(); }; const fillText = function(x, y, legendItem) { renderText(ctx, legendItem.text, x, y + (itemHeight / 2), labelFont, { strikethrough: legendItem.hidden, textAlign: rtlHelper.textAlign(legendItem.textAlign) }); }; const isHorizontal = this.isHorizontal(); const titleHeight = this._computeTitleHeight(); if (isHorizontal) { cursor = { x: _alignStartEnd(align, this.left + padding, this.right - lineWidths[0]), y: this.top + padding + titleHeight, line: 0 }; } else { cursor = { x: this.left + padding, y: _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[0].height), line: 0 }; } overrideTextDirection(this.ctx, opts.textDirection); const lineHeight = itemHeight + padding; this.legendItems.forEach((legendItem, i) => { ctx.strokeStyle = legendItem.fontColor || fontColor; ctx.fillStyle = legendItem.fontColor || fontColor; const textWidth = ctx.measureText(legendItem.text).width; const textAlign = rtlHelper.textAlign(legendItem.textAlign || (legendItem.textAlign = labelOpts.textAlign)); const width = boxWidth + halfFontSize + textWidth; let x = cursor.x; let y = cursor.y; rtlHelper.setWidth(this.width); if (isHorizontal) { if (i > 0 && x + width + padding > this.right) { y = cursor.y += lineHeight; cursor.line++; x = cursor.x = _alignStartEnd(align, this.left + padding, this.right - lineWidths[cursor.line]); } } else if (i > 0 && y + lineHeight > this.bottom) { x = cursor.x = x + columnSizes[cursor.line].width + padding; cursor.line++; y = cursor.y = _alignStartEnd(align, this.top + titleHeight + padding, this.bottom - columnSizes[cursor.line].height); } const realX = rtlHelper.x(x); drawLegendBox(realX, y, legendItem); x = _textX(textAlign, x + boxWidth + halfFontSize, isHorizontal ? x + width : this.right, opts.rtl); fillText(rtlHelper.x(x), y, legendItem); if (isHorizontal) { cursor.x += width + padding; } else { cursor.y += lineHeight; } }); restoreTextDirection(this.ctx, opts.textDirection); } drawTitle() { const opts = this.options; const titleOpts = opts.title; const titleFont = toFont(titleOpts.font); const titlePadding = toPadding(titleOpts.padding); if (!titleOpts.display) { return; } const rtlHelper = getRtlAdapter(opts.rtl, this.left, this.width); const ctx = this.ctx; const position = titleOpts.position; const halfFontSize = titleFont.size / 2; const topPaddingPlusHalfFontSize = titlePadding.top + halfFontSize; let y; let left = this.left; let maxWidth = this.width; if (this.isHorizontal()) { maxWidth = Math.max(...this.lineWidths); y = this.top + topPaddingPlusHalfFontSize; left = _alignStartEnd(opts.align, left, this.right - maxWidth); } else { const maxHeight = this.columnSizes.reduce((acc, size) => Math.max(acc, size.height), 0); y = topPaddingPlusHalfFontSize + _alignStartEnd(opts.align, this.top, this.bottom - maxHeight - opts.labels.padding - this._computeTitleHeight()); } const x = _alignStartEnd(position, left, left + maxWidth); ctx.textAlign = rtlHelper.textAlign(_toLeftRightCenter(position)); ctx.textBaseline = 'middle'; ctx.strokeStyle = titleOpts.color; ctx.fillStyle = titleOpts.color; ctx.font = titleFont.string; renderText(ctx, titleOpts.text, x, y, titleFont); } _computeTitleHeight() { const titleOpts = this.options.title; const titleFont = toFont(titleOpts.font); const titlePadding = toPadding(titleOpts.padding); return titleOpts.display ? titleFont.lineHeight + titlePadding.height : 0; } _getLegendItemAt(x, y) { let i, hitBox, lh; if (_isBetween(x, this.left, this.right) && _isBetween(y, this.top, this.bottom)) { lh = this.legendHitBoxes; for (i = 0; i < lh.length; ++i) { hitBox = lh[i]; if (_isBetween(x, hitBox.left, hitBox.left + hitBox.width) && _isBetween(y, hitBox.top, hitBox.top + hitBox.height)) { return this.legendItems[i]; } } } return null; } handleEvent(e) { const opts = this.options; if (!isListened(e.type, opts)) { return; } const hoveredItem = this._getLegendItemAt(e.x, e.y); if (e.type === 'mousemove') { const previous = this._hoveredItem; const sameItem = itemsEqual(previous, hoveredItem); if (previous && !sameItem) { callback(opts.onLeave, [e, previous, this], this); } this._hoveredItem = hoveredItem; if (hoveredItem && !sameItem) { callback(opts.onHover, [e, hoveredItem, this], this); } } else if (hoveredItem) { callback(opts.onClick, [e, hoveredItem, this], this); } } } function isListened(type, opts) { if (type === 'mousemove' && (opts.onHover || opts.onLeave)) { return true; } if (opts.onClick && (type === 'click' || type === 'mouseup')) { return true; } return false; } var plugin_legend = { id: 'legend', _element: Legend, start(chart, _args, options) { const legend = chart.legend = new Legend({ctx: chart.ctx, options, chart}); layouts.configure(chart, legend, options); layouts.addBox(chart, legend); }, stop(chart) { layouts.removeBox(chart, chart.legend); delete chart.legend; }, beforeUpdate(chart, _args, options) { const legend = chart.legend; layouts.configure(chart, legend, options); legend.options = options; }, afterUpdate(chart) { const legend = chart.legend; legend.buildLabels(); legend.adjustHitBoxes(); }, afterEvent(chart, args) { if (!args.replay) { chart.legend.handleEvent(args.event); } }, defaults: { display: true, position: 'top', align: 'center', fullSize: true, reverse: false, weight: 1000, onClick(e, legendItem, legend) { const index = legendItem.datasetIndex; const ci = legend.chart; if (ci.isDatasetVisible(index)) { ci.hide(index); legendItem.hidden = true; } else { ci.show(index); legendItem.hidden = false; } }, onHover: null, onLeave: null, labels: { color: (ctx) => ctx.chart.options.color, boxWidth: 40, padding: 10, generateLabels(chart) { const datasets = chart.data.datasets; const {labels: {usePointStyle, pointStyle, textAlign, color}} = chart.legend.options; return chart._getSortedDatasetMetas().map((meta) => { const style = meta.controller.getStyle(usePointStyle ? 0 : undefined); const borderWidth = toPadding(style.borderWidth); return { text: datasets[meta.index].label, fillStyle: style.backgroundColor, fontColor: color, hidden: !meta.visible, lineCap: style.borderCapStyle, lineDash: style.borderDash, lineDashOffset: style.borderDashOffset, lineJoin: style.borderJoinStyle, lineWidth: (borderWidth.width + borderWidth.height) / 4, strokeStyle: style.borderColor, pointStyle: pointStyle || style.pointStyle, rotation: style.rotation, textAlign: textAlign || style.textAlign, borderRadius: 0, datasetIndex: meta.index }; }, this); } }, title: { color: (ctx) => ctx.chart.options.color, display: false, position: 'center', text: '', } }, descriptors: { _scriptable: (name) => !name.startsWith('on'), labels: { _scriptable: (name) => !['generateLabels', 'filter', 'sort'].includes(name), } }, }; class Title extends Element { constructor(config) { super(); this.chart = config.chart; this.options = config.options; this.ctx = config.ctx; this._padding = undefined; this.top = undefined; this.bottom = undefined; this.left = undefined; this.right = undefined; this.width = undefined; this.height = undefined; this.position = undefined; this.weight = undefined; this.fullSize = undefined; } update(maxWidth, maxHeight) { const opts = this.options; this.left = 0; this.top = 0; if (!opts.display) { this.width = this.height = this.right = this.bottom = 0; return; } this.width = this.right = maxWidth; this.height = this.bottom = maxHeight; const lineCount = isArray(opts.text) ? opts.text.length : 1; this._padding = toPadding(opts.padding); const textSize = lineCount * toFont(opts.font).lineHeight + this._padding.height; if (this.isHorizontal()) { this.height = textSize; } else { this.width = textSize; } } isHorizontal() { const pos = this.options.position; return pos === 'top' || pos === 'bottom'; } _drawArgs(offset) { const {top, left, bottom, right, options} = this; const align = options.align; let rotation = 0; let maxWidth, titleX, titleY; if (this.isHorizontal()) { titleX = _alignStartEnd(align, left, right); titleY = top + offset; maxWidth = right - left; } else { if (options.position === 'left') { titleX = left + offset; titleY = _alignStartEnd(align, bottom, top); rotation = PI * -0.5; } else { titleX = right - offset; titleY = _alignStartEnd(align, top, bottom); rotation = PI * 0.5; } maxWidth = bottom - top; } return {titleX, titleY, maxWidth, rotation}; } draw() { const ctx = this.ctx; const opts = this.options; if (!opts.display) { return; } const fontOpts = toFont(opts.font); const lineHeight = fontOpts.lineHeight; const offset = lineHeight / 2 + this._padding.top; const {titleX, titleY, maxWidth, rotation} = this._drawArgs(offset); renderText(ctx, opts.text, 0, 0, fontOpts, { color: opts.color, maxWidth, rotation, textAlign: _toLeftRightCenter(opts.align), textBaseline: 'middle', translation: [titleX, titleY], }); } } function createTitle(chart, titleOpts) { const title = new Title({ ctx: chart.ctx, options: titleOpts, chart }); layouts.configure(chart, title, titleOpts); layouts.addBox(chart, title); chart.titleBlock = title; } var plugin_title = { id: 'title', _element: Title, start(chart, _args, options) { createTitle(chart, options); }, stop(chart) { const titleBlock = chart.titleBlock; layouts.removeBox(chart, titleBlock); delete chart.titleBlock; }, beforeUpdate(chart, _args, options) { const title = chart.titleBlock; layouts.configure(chart, title, options); title.options = options; }, defaults: { align: 'center', display: false, font: { weight: 'bold', }, fullSize: true, padding: 10, position: 'top', text: '', weight: 2000 }, defaultRoutes: { color: 'color' }, descriptors: { _scriptable: true, _indexable: false, }, }; const map = new WeakMap(); var plugin_subtitle = { id: 'subtitle', start(chart, _args, options) { const title = new Title({ ctx: chart.ctx, options, chart }); layouts.configure(chart, title, options); layouts.addBox(chart, title); map.set(chart, title); }, stop(chart) { layouts.removeBox(chart, map.get(chart)); map.delete(chart); }, beforeUpdate(chart, _args, options) { const title = map.get(chart); layouts.configure(chart, title, options); title.options = options; }, defaults: { align: 'center', display: false, font: { weight: 'normal', }, fullSize: true, padding: 0, position: 'top', text: '', weight: 1500 }, defaultRoutes: { color: 'color' }, descriptors: { _scriptable: true, _indexable: false, }, }; const positioners = { average(items) { if (!items.length) { return false; } let i, len; let x = 0; let y = 0; let count = 0; for (i = 0, len = items.length; i < len; ++i) { const el = items[i].element; if (el && el.hasValue()) { const pos = el.tooltipPosition(); x += pos.x; y += pos.y; ++count; } } return { x: x / count, y: y / count }; }, nearest(items, eventPosition) { if (!items.length) { return false; } let x = eventPosition.x; let y = eventPosition.y; let minDistance = Number.POSITIVE_INFINITY; let i, len, nearestElement; for (i = 0, len = items.length; i < len; ++i) { const el = items[i].element; if (el && el.hasValue()) { const center = el.getCenterPoint(); const d = distanceBetweenPoints(eventPosition, center); if (d < minDistance) { minDistance = d; nearestElement = el; } } } if (nearestElement) { const tp = nearestElement.tooltipPosition(); x = tp.x; y = tp.y; } return { x, y }; } }; function pushOrConcat(base, toPush) { if (toPush) { if (isArray(toPush)) { Array.prototype.push.apply(base, toPush); } else { base.push(toPush); } } return base; } function splitNewlines(str) { if ((typeof str === 'string' || str instanceof String) && str.indexOf('\n') > -1) { return str.split('\n'); } return str; } function createTooltipItem(chart, item) { const {element, datasetIndex, index} = item; const controller = chart.getDatasetMeta(datasetIndex).controller; const {label, value} = controller.getLabelAndValue(index); return { chart, label, parsed: controller.getParsed(index), raw: chart.data.datasets[datasetIndex].data[index], formattedValue: value, dataset: controller.getDataset(), dataIndex: index, datasetIndex, element }; } function getTooltipSize(tooltip, options) { const ctx = tooltip._chart.ctx; const {body, footer, title} = tooltip; const {boxWidth, boxHeight} = options; const bodyFont = toFont(options.bodyFont); const titleFont = toFont(options.titleFont); const footerFont = toFont(options.footerFont); const titleLineCount = title.length; const footerLineCount = footer.length; const bodyLineItemCount = body.length; const padding = toPadding(options.padding); let height = padding.height; let width = 0; let combinedBodyLength = body.reduce((count, bodyItem) => count + bodyItem.before.length + bodyItem.lines.length + bodyItem.after.length, 0); combinedBodyLength += tooltip.beforeBody.length + tooltip.afterBody.length; if (titleLineCount) { height += titleLineCount * titleFont.lineHeight + (titleLineCount - 1) * options.titleSpacing + options.titleMarginBottom; } if (combinedBodyLength) { const bodyLineHeight = options.displayColors ? Math.max(boxHeight, bodyFont.lineHeight) : bodyFont.lineHeight; height += bodyLineItemCount * bodyLineHeight + (combinedBodyLength - bodyLineItemCount) * bodyFont.lineHeight + (combinedBodyLength - 1) * options.bodySpacing; } if (footerLineCount) { height += options.footerMarginTop + footerLineCount * footerFont.lineHeight + (footerLineCount - 1) * options.footerSpacing; } let widthPadding = 0; const maxLineWidth = function(line) { width = Math.max(width, ctx.measureText(line).width + widthPadding); }; ctx.save(); ctx.font = titleFont.string; each(tooltip.title, maxLineWidth); ctx.font = bodyFont.string; each(tooltip.beforeBody.concat(tooltip.afterBody), maxLineWidth); widthPadding = options.displayColors ? (boxWidth + 2 + options.boxPadding) : 0; each(body, (bodyItem) => { each(bodyItem.before, maxLineWidth); each(bodyItem.lines, maxLineWidth); each(bodyItem.after, maxLineWidth); }); widthPadding = 0; ctx.font = footerFont.string; each(tooltip.footer, maxLineWidth); ctx.restore(); width += padding.width; return {width, height}; } function determineYAlign(chart, size) { const {y, height} = size; if (y < height / 2) { return 'top'; } else if (y > (chart.height - height / 2)) { return 'bottom'; } return 'center'; } function doesNotFitWithAlign(xAlign, chart, options, size) { const {x, width} = size; const caret = options.caretSize + options.caretPadding; if (xAlign === 'left' && x + width + caret > chart.width) { return true; } if (xAlign === 'right' && x - width - caret < 0) { return true; } } function determineXAlign(chart, options, size, yAlign) { const {x, width} = size; const {width: chartWidth, chartArea: {left, right}} = chart; let xAlign = 'center'; if (yAlign === 'center') { xAlign = x <= (left + right) / 2 ? 'left' : 'right'; } else if (x <= width / 2) { xAlign = 'left'; } else if (x >= chartWidth - width / 2) { xAlign = 'right'; } if (doesNotFitWithAlign(xAlign, chart, options, size)) { xAlign = 'center'; } return xAlign; } function determineAlignment(chart, options, size) { const yAlign = options.yAlign || determineYAlign(chart, size); return { xAlign: options.xAlign || determineXAlign(chart, options, size, yAlign), yAlign }; } function alignX(size, xAlign) { let {x, width} = size; if (xAlign === 'right') { x -= width; } else if (xAlign === 'center') { x -= (width / 2); } return x; } function alignY(size, yAlign, paddingAndSize) { let {y, height} = size; if (yAlign === 'top') { y += paddingAndSize; } else if (yAlign === 'bottom') { y -= height + paddingAndSize; } else { y -= (height / 2); } return y; } function getBackgroundPoint(options, size, alignment, chart) { const {caretSize, caretPadding, cornerRadius} = options; const {xAlign, yAlign} = alignment; const paddingAndSize = caretSize + caretPadding; const {topLeft, topRight, bottomLeft, bottomRight} = toTRBLCorners(cornerRadius); let x = alignX(size, xAlign); const y = alignY(size, yAlign, paddingAndSize); if (yAlign === 'center') { if (xAlign === 'left') { x += paddingAndSize; } else if (xAlign === 'right') { x -= paddingAndSize; } } else if (xAlign === 'left') { x -= Math.max(topLeft, bottomLeft) + caretSize; } else if (xAlign === 'right') { x += Math.max(topRight, bottomRight) + caretSize; } return { x: _limitValue(x, 0, chart.width - size.width), y: _limitValue(y, 0, chart.height - size.height) }; } function getAlignedX(tooltip, align, options) { const padding = toPadding(options.padding); return align === 'center' ? tooltip.x + tooltip.width / 2 : align === 'right' ? tooltip.x + tooltip.width - padding.right : tooltip.x + padding.left; } function getBeforeAfterBodyLines(callback) { return pushOrConcat([], splitNewlines(callback)); } function createTooltipContext(parent, tooltip, tooltipItems) { return createContext(parent, { tooltip, tooltipItems, type: 'tooltip' }); } function overrideCallbacks(callbacks, context) { const override = context && context.dataset && context.dataset.tooltip && context.dataset.tooltip.callbacks; return override ? callbacks.override(override) : callbacks; } class Tooltip extends Element { constructor(config) { super(); this.opacity = 0; this._active = []; this._chart = config._chart; this._eventPosition = undefined; this._size = undefined; this._cachedAnimations = undefined; this._tooltipItems = []; this.$animations = undefined; this.$context = undefined; this.options = config.options; this.dataPoints = undefined; this.title = undefined; this.beforeBody = undefined; this.body = undefined; this.afterBody = undefined; this.footer = undefined; this.xAlign = undefined; this.yAlign = undefined; this.x = undefined; this.y = undefined; this.height = undefined; this.width = undefined; this.caretX = undefined; this.caretY = undefined; this.labelColors = undefined; this.labelPointStyles = undefined; this.labelTextColors = undefined; } initialize(options) { this.options = options; this._cachedAnimations = undefined; this.$context = undefined; } _resolveAnimations() { const cached = this._cachedAnimations; if (cached) { return cached; } const chart = this._chart; const options = this.options.setContext(this.getContext()); const opts = options.enabled && chart.options.animation && options.animations; const animations = new Animations(this._chart, opts); if (opts._cacheable) { this._cachedAnimations = Object.freeze(animations); } return animations; } getContext() { return this.$context || (this.$context = createTooltipContext(this._chart.getContext(), this, this._tooltipItems)); } getTitle(context, options) { const {callbacks} = options; const beforeTitle = callbacks.beforeTitle.apply(this, [context]); const title = callbacks.title.apply(this, [context]); const afterTitle = callbacks.afterTitle.apply(this, [context]); let lines = []; lines = pushOrConcat(lines, splitNewlines(beforeTitle)); lines = pushOrConcat(lines, splitNewlines(title)); lines = pushOrConcat(lines, splitNewlines(afterTitle)); return lines; } getBeforeBody(tooltipItems, options) { return getBeforeAfterBodyLines(options.callbacks.beforeBody.apply(this, [tooltipItems])); } getBody(tooltipItems, options) { const {callbacks} = options; const bodyItems = []; each(tooltipItems, (context) => { const bodyItem = { before: [], lines: [], after: [] }; const scoped = overrideCallbacks(callbacks, context); pushOrConcat(bodyItem.before, splitNewlines(scoped.beforeLabel.call(this, context))); pushOrConcat(bodyItem.lines, scoped.label.call(this, context)); pushOrConcat(bodyItem.after, splitNewlines(scoped.afterLabel.call(this, context))); bodyItems.push(bodyItem); }); return bodyItems; } getAfterBody(tooltipItems, options) { return getBeforeAfterBodyLines(options.callbacks.afterBody.apply(this, [tooltipItems])); } getFooter(tooltipItems, options) { const {callbacks} = options; const beforeFooter = callbacks.beforeFooter.apply(this, [tooltipItems]); const footer = callbacks.footer.apply(this, [tooltipItems]); const afterFooter = callbacks.afterFooter.apply(this, [tooltipItems]); let lines = []; lines = pushOrConcat(lines, splitNewlines(beforeFooter)); lines = pushOrConcat(lines, splitNewlines(footer)); lines = pushOrConcat(lines, splitNewlines(afterFooter)); return lines; } _createItems(options) { const active = this._active; const data = this._chart.data; const labelColors = []; const labelPointStyles = []; const labelTextColors = []; let tooltipItems = []; let i, len; for (i = 0, len = active.length; i < len; ++i) { tooltipItems.push(createTooltipItem(this._chart, active[i])); } if (options.filter) { tooltipItems = tooltipItems.filter((element, index, array) => options.filter(element, index, array, data)); } if (options.itemSort) { tooltipItems = tooltipItems.sort((a, b) => options.itemSort(a, b, data)); } each(tooltipItems, (context) => { const scoped = overrideCallbacks(options.callbacks, context); labelColors.push(scoped.labelColor.call(this, context)); labelPointStyles.push(scoped.labelPointStyle.call(this, context)); labelTextColors.push(scoped.labelTextColor.call(this, context)); }); this.labelColors = labelColors; this.labelPointStyles = labelPointStyles; this.labelTextColors = labelTextColors; this.dataPoints = tooltipItems; return tooltipItems; } update(changed, replay) { const options = this.options.setContext(this.getContext()); const active = this._active; let properties; let tooltipItems = []; if (!active.length) { if (this.opacity !== 0) { properties = { opacity: 0 }; } } else { const position = positioners[options.position].call(this, active, this._eventPosition); tooltipItems = this._createItems(options); this.title = this.getTitle(tooltipItems, options); this.beforeBody = this.getBeforeBody(tooltipItems, options); this.body = this.getBody(tooltipItems, options); this.afterBody = this.getAfterBody(tooltipItems, options); this.footer = this.getFooter(tooltipItems, options); const size = this._size = getTooltipSize(this, options); const positionAndSize = Object.assign({}, position, size); const alignment = determineAlignment(this._chart, options, positionAndSize); const backgroundPoint = getBackgroundPoint(options, positionAndSize, alignment, this._chart); this.xAlign = alignment.xAlign; this.yAlign = alignment.yAlign; properties = { opacity: 1, x: backgroundPoint.x, y: backgroundPoint.y, width: size.width, height: size.height, caretX: position.x, caretY: position.y }; } this._tooltipItems = tooltipItems; this.$context = undefined; if (properties) { this._resolveAnimations().update(this, properties); } if (changed && options.external) { options.external.call(this, {chart: this._chart, tooltip: this, replay}); } } drawCaret(tooltipPoint, ctx, size, options) { const caretPosition = this.getCaretPosition(tooltipPoint, size, options); ctx.lineTo(caretPosition.x1, caretPosition.y1); ctx.lineTo(caretPosition.x2, caretPosition.y2); ctx.lineTo(caretPosition.x3, caretPosition.y3); } getCaretPosition(tooltipPoint, size, options) { const {xAlign, yAlign} = this; const {caretSize, cornerRadius} = options; const {topLeft, topRight, bottomLeft, bottomRight} = toTRBLCorners(cornerRadius); const {x: ptX, y: ptY} = tooltipPoint; const {width, height} = size; let x1, x2, x3, y1, y2, y3; if (yAlign === 'center') { y2 = ptY + (height / 2); if (xAlign === 'left') { x1 = ptX; x2 = x1 - caretSize; y1 = y2 + caretSize; y3 = y2 - caretSize; } else { x1 = ptX + width; x2 = x1 + caretSize; y1 = y2 - caretSize; y3 = y2 + caretSize; } x3 = x1; } else { if (xAlign === 'left') { x2 = ptX + Math.max(topLeft, bottomLeft) + (caretSize); } else if (xAlign === 'right') { x2 = ptX + width - Math.max(topRight, bottomRight) - caretSize; } else { x2 = this.caretX; } if (yAlign === 'top') { y1 = ptY; y2 = y1 - caretSize; x1 = x2 - caretSize; x3 = x2 + caretSize; } else { y1 = ptY + height; y2 = y1 + caretSize; x1 = x2 + caretSize; x3 = x2 - caretSize; } y3 = y1; } return {x1, x2, x3, y1, y2, y3}; } drawTitle(pt, ctx, options) { const title = this.title; const length = title.length; let titleFont, titleSpacing, i; if (length) { const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width); pt.x = getAlignedX(this, options.titleAlign, options); ctx.textAlign = rtlHelper.textAlign(options.titleAlign); ctx.textBaseline = 'middle'; titleFont = toFont(options.titleFont); titleSpacing = options.titleSpacing; ctx.fillStyle = options.titleColor; ctx.font = titleFont.string; for (i = 0; i < length; ++i) { ctx.fillText(title[i], rtlHelper.x(pt.x), pt.y + titleFont.lineHeight / 2); pt.y += titleFont.lineHeight + titleSpacing; if (i + 1 === length) { pt.y += options.titleMarginBottom - titleSpacing; } } } } _drawColorBox(ctx, pt, i, rtlHelper, options) { const labelColors = this.labelColors[i]; const labelPointStyle = this.labelPointStyles[i]; const {boxHeight, boxWidth, boxPadding} = options; const bodyFont = toFont(options.bodyFont); const colorX = getAlignedX(this, 'left', options); const rtlColorX = rtlHelper.x(colorX); const yOffSet = boxHeight < bodyFont.lineHeight ? (bodyFont.lineHeight - boxHeight) / 2 : 0; const colorY = pt.y + yOffSet; if (options.usePointStyle) { const drawOptions = { radius: Math.min(boxWidth, boxHeight) / 2, pointStyle: labelPointStyle.pointStyle, rotation: labelPointStyle.rotation, borderWidth: 1 }; const centerX = rtlHelper.leftForLtr(rtlColorX, boxWidth) + boxWidth / 2; const centerY = colorY + boxHeight / 2; ctx.strokeStyle = options.multiKeyBackground; ctx.fillStyle = options.multiKeyBackground; drawPoint(ctx, drawOptions, centerX, centerY); ctx.strokeStyle = labelColors.borderColor; ctx.fillStyle = labelColors.backgroundColor; drawPoint(ctx, drawOptions, centerX, centerY); } else { ctx.lineWidth = labelColors.borderWidth || 1; ctx.strokeStyle = labelColors.borderColor; ctx.setLineDash(labelColors.borderDash || []); ctx.lineDashOffset = labelColors.borderDashOffset || 0; const outerX = rtlHelper.leftForLtr(rtlColorX, boxWidth - boxPadding); const innerX = rtlHelper.leftForLtr(rtlHelper.xPlus(rtlColorX, 1), boxWidth - boxPadding - 2); const borderRadius = toTRBLCorners(labelColors.borderRadius); if (Object.values(borderRadius).some(v => v !== 0)) { ctx.beginPath(); ctx.fillStyle = options.multiKeyBackground; addRoundedRectPath(ctx, { x: outerX, y: colorY, w: boxWidth, h: boxHeight, radius: borderRadius, }); ctx.fill(); ctx.stroke(); ctx.fillStyle = labelColors.backgroundColor; ctx.beginPath(); addRoundedRectPath(ctx, { x: innerX, y: colorY + 1, w: boxWidth - 2, h: boxHeight - 2, radius: borderRadius, }); ctx.fill(); } else { ctx.fillStyle = options.multiKeyBackground; ctx.fillRect(outerX, colorY, boxWidth, boxHeight); ctx.strokeRect(outerX, colorY, boxWidth, boxHeight); ctx.fillStyle = labelColors.backgroundColor; ctx.fillRect(innerX, colorY + 1, boxWidth - 2, boxHeight - 2); } } ctx.fillStyle = this.labelTextColors[i]; } drawBody(pt, ctx, options) { const {body} = this; const {bodySpacing, bodyAlign, displayColors, boxHeight, boxWidth, boxPadding} = options; const bodyFont = toFont(options.bodyFont); let bodyLineHeight = bodyFont.lineHeight; let xLinePadding = 0; const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width); const fillLineOfText = function(line) { ctx.fillText(line, rtlHelper.x(pt.x + xLinePadding), pt.y + bodyLineHeight / 2); pt.y += bodyLineHeight + bodySpacing; }; const bodyAlignForCalculation = rtlHelper.textAlign(bodyAlign); let bodyItem, textColor, lines, i, j, ilen, jlen; ctx.textAlign = bodyAlign; ctx.textBaseline = 'middle'; ctx.font = bodyFont.string; pt.x = getAlignedX(this, bodyAlignForCalculation, options); ctx.fillStyle = options.bodyColor; each(this.beforeBody, fillLineOfText); xLinePadding = displayColors && bodyAlignForCalculation !== 'right' ? bodyAlign === 'center' ? (boxWidth / 2 + boxPadding) : (boxWidth + 2 + boxPadding) : 0; for (i = 0, ilen = body.length; i < ilen; ++i) { bodyItem = body[i]; textColor = this.labelTextColors[i]; ctx.fillStyle = textColor; each(bodyItem.before, fillLineOfText); lines = bodyItem.lines; if (displayColors && lines.length) { this._drawColorBox(ctx, pt, i, rtlHelper, options); bodyLineHeight = Math.max(bodyFont.lineHeight, boxHeight); } for (j = 0, jlen = lines.length; j < jlen; ++j) { fillLineOfText(lines[j]); bodyLineHeight = bodyFont.lineHeight; } each(bodyItem.after, fillLineOfText); } xLinePadding = 0; bodyLineHeight = bodyFont.lineHeight; each(this.afterBody, fillLineOfText); pt.y -= bodySpacing; } drawFooter(pt, ctx, options) { const footer = this.footer; const length = footer.length; let footerFont, i; if (length) { const rtlHelper = getRtlAdapter(options.rtl, this.x, this.width); pt.x = getAlignedX(this, options.footerAlign, options); pt.y += options.footerMarginTop; ctx.textAlign = rtlHelper.textAlign(options.footerAlign); ctx.textBaseline = 'middle'; footerFont = toFont(options.footerFont); ctx.fillStyle = options.footerColor; ctx.font = footerFont.string; for (i = 0; i < length; ++i) { ctx.fillText(footer[i], rtlHelper.x(pt.x), pt.y + footerFont.lineHeight / 2); pt.y += footerFont.lineHeight + options.footerSpacing; } } } drawBackground(pt, ctx, tooltipSize, options) { const {xAlign, yAlign} = this; const {x, y} = pt; const {width, height} = tooltipSize; const {topLeft, topRight, bottomLeft, bottomRight} = toTRBLCorners(options.cornerRadius); ctx.fillStyle = options.backgroundColor; ctx.strokeStyle = options.borderColor; ctx.lineWidth = options.borderWidth; ctx.beginPath(); ctx.moveTo(x + topLeft, y); if (yAlign === 'top') { this.drawCaret(pt, ctx, tooltipSize, options); } ctx.lineTo(x + width - topRight, y); ctx.quadraticCurveTo(x + width, y, x + width, y + topRight); if (yAlign === 'center' && xAlign === 'right') { this.drawCaret(pt, ctx, tooltipSize, options); } ctx.lineTo(x + width, y + height - bottomRight); ctx.quadraticCurveTo(x + width, y + height, x + width - bottomRight, y + height); if (yAlign === 'bottom') { this.drawCaret(pt, ctx, tooltipSize, options); } ctx.lineTo(x + bottomLeft, y + height); ctx.quadraticCurveTo(x, y + height, x, y + height - bottomLeft); if (yAlign === 'center' && xAlign === 'left') { this.drawCaret(pt, ctx, tooltipSize, options); } ctx.lineTo(x, y + topLeft); ctx.quadraticCurveTo(x, y, x + topLeft, y); ctx.closePath(); ctx.fill(); if (options.borderWidth > 0) { ctx.stroke(); } } _updateAnimationTarget(options) { const chart = this._chart; const anims = this.$animations; const animX = anims && anims.x; const animY = anims && anims.y; if (animX || animY) { const position = positioners[options.position].call(this, this._active, this._eventPosition); if (!position) { return; } const size = this._size = getTooltipSize(this, options); const positionAndSize = Object.assign({}, position, this._size); const alignment = determineAlignment(chart, options, positionAndSize); const point = getBackgroundPoint(options, positionAndSize, alignment, chart); if (animX._to !== point.x || animY._to !== point.y) { this.xAlign = alignment.xAlign; this.yAlign = alignment.yAlign; this.width = size.width; this.height = size.height; this.caretX = position.x; this.caretY = position.y; this._resolveAnimations().update(this, point); } } } draw(ctx) { const options = this.options.setContext(this.getContext()); let opacity = this.opacity; if (!opacity) { return; } this._updateAnimationTarget(options); const tooltipSize = { width: this.width, height: this.height }; const pt = { x: this.x, y: this.y }; opacity = Math.abs(opacity) < 1e-3 ? 0 : opacity; const padding = toPadding(options.padding); const hasTooltipContent = this.title.length || this.beforeBody.length || this.body.length || this.afterBody.length || this.footer.length; if (options.enabled && hasTooltipContent) { ctx.save(); ctx.globalAlpha = opacity; this.drawBackground(pt, ctx, tooltipSize, options); overrideTextDirection(ctx, options.textDirection); pt.y += padding.top; this.drawTitle(pt, ctx, options); this.drawBody(pt, ctx, options); this.drawFooter(pt, ctx, options); restoreTextDirection(ctx, options.textDirection); ctx.restore(); } } getActiveElements() { return this._active || []; } setActiveElements(activeElements, eventPosition) { const lastActive = this._active; const active = activeElements.map(({datasetIndex, index}) => { const meta = this._chart.getDatasetMeta(datasetIndex); if (!meta) { throw new Error('Cannot find a dataset at index ' + datasetIndex); } return { datasetIndex, element: meta.data[index], index, }; }); const changed = !_elementsEqual(lastActive, active); const positionChanged = this._positionChanged(active, eventPosition); if (changed || positionChanged) { this._active = active; this._eventPosition = eventPosition; this.update(true); } } handleEvent(e, replay) { const options = this.options; const lastActive = this._active || []; let changed = false; let active = []; if (e.type !== 'mouseout') { active = this._chart.getElementsAtEventForMode(e, options.mode, options, replay); if (options.reverse) { active.reverse(); } } const positionChanged = this._positionChanged(active, e); changed = replay || !_elementsEqual(active, lastActive) || positionChanged; if (changed) { this._active = active; if (options.enabled || options.external) { this._eventPosition = { x: e.x, y: e.y }; this.update(true, replay); } } return changed; } _positionChanged(active, e) { const {caretX, caretY, options} = this; const position = positioners[options.position].call(this, active, e); return position !== false && (caretX !== position.x || caretY !== position.y); } } Tooltip.positioners = positioners; var plugin_tooltip = { id: 'tooltip', _element: Tooltip, positioners, afterInit(chart, _args, options) { if (options) { chart.tooltip = new Tooltip({_chart: chart, options}); } }, beforeUpdate(chart, _args, options) { if (chart.tooltip) { chart.tooltip.initialize(options); } }, reset(chart, _args, options) { if (chart.tooltip) { chart.tooltip.initialize(options); } }, afterDraw(chart) { const tooltip = chart.tooltip; const args = { tooltip }; if (chart.notifyPlugins('beforeTooltipDraw', args) === false) { return; } if (tooltip) { tooltip.draw(chart.ctx); } chart.notifyPlugins('afterTooltipDraw', args); }, afterEvent(chart, args) { if (chart.tooltip) { const useFinalPosition = args.replay; if (chart.tooltip.handleEvent(args.event, useFinalPosition)) { args.changed = true; } } }, defaults: { enabled: true, external: null, position: 'average', backgroundColor: 'rgba(0,0,0,0.8)', titleColor: '#fff', titleFont: { weight: 'bold', }, titleSpacing: 2, titleMarginBottom: 6, titleAlign: 'left', bodyColor: '#fff', bodySpacing: 2, bodyFont: { }, bodyAlign: 'left', footerColor: '#fff', footerSpacing: 2, footerMarginTop: 6, footerFont: { weight: 'bold', }, footerAlign: 'left', padding: 6, caretPadding: 2, caretSize: 5, cornerRadius: 6, boxHeight: (ctx, opts) => opts.bodyFont.size, boxWidth: (ctx, opts) => opts.bodyFont.size, multiKeyBackground: '#fff', displayColors: true, boxPadding: 0, borderColor: 'rgba(0,0,0,0)', borderWidth: 0, animation: { duration: 400, easing: 'easeOutQuart', }, animations: { numbers: { type: 'number', properties: ['x', 'y', 'width', 'height', 'caretX', 'caretY'], }, opacity: { easing: 'linear', duration: 200 } }, callbacks: { beforeTitle: noop, title(tooltipItems) { if (tooltipItems.length > 0) { const item = tooltipItems[0]; const labels = item.chart.data.labels; const labelCount = labels ? labels.length : 0; if (this && this.options && this.options.mode === 'dataset') { return item.dataset.label || ''; } else if (item.label) { return item.label; } else if (labelCount > 0 && item.dataIndex < labelCount) { return labels[item.dataIndex]; } } return ''; }, afterTitle: noop, beforeBody: noop, beforeLabel: noop, label(tooltipItem) { if (this && this.options && this.options.mode === 'dataset') { return tooltipItem.label + ': ' + tooltipItem.formattedValue || tooltipItem.formattedValue; } let label = tooltipItem.dataset.label || ''; if (label) { label += ': '; } const value = tooltipItem.formattedValue; if (!isNullOrUndef(value)) { label += value; } return label; }, labelColor(tooltipItem) { const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex); const options = meta.controller.getStyle(tooltipItem.dataIndex); return { borderColor: options.borderColor, backgroundColor: options.backgroundColor, borderWidth: options.borderWidth, borderDash: options.borderDash, borderDashOffset: options.borderDashOffset, borderRadius: 0, }; }, labelTextColor() { return this.options.bodyColor; }, labelPointStyle(tooltipItem) { const meta = tooltipItem.chart.getDatasetMeta(tooltipItem.datasetIndex); const options = meta.controller.getStyle(tooltipItem.dataIndex); return { pointStyle: options.pointStyle, rotation: options.rotation, }; }, afterLabel: noop, afterBody: noop, beforeFooter: noop, footer: noop, afterFooter: noop } }, defaultRoutes: { bodyFont: 'font', footerFont: 'font', titleFont: 'font' }, descriptors: { _scriptable: (name) => name !== 'filter' && name !== 'itemSort' && name !== 'external', _indexable: false, callbacks: { _scriptable: false, _indexable: false, }, animation: { _fallback: false }, animations: { _fallback: 'animation' } }, additionalOptionScopes: ['interaction'] }; var plugins = /*#__PURE__*/Object.freeze({ __proto__: null, Decimation: plugin_decimation, Filler: plugin_filler, Legend: plugin_legend, SubTitle: plugin_subtitle, Title: plugin_title, Tooltip: plugin_tooltip }); const addIfString = (labels, raw, index, addedLabels) => { if (typeof raw === 'string') { index = labels.push(raw) - 1; addedLabels.unshift({index, label: raw}); } else if (isNaN(raw)) { index = null; } return index; }; function findOrAddLabel(labels, raw, index, addedLabels) { const first = labels.indexOf(raw); if (first === -1) { return addIfString(labels, raw, index, addedLabels); } const last = labels.lastIndexOf(raw); return first !== last ? index : first; } const validIndex = (index, max) => index === null ? null : _limitValue(Math.round(index), 0, max); class CategoryScale extends Scale { constructor(cfg) { super(cfg); this._startValue = undefined; this._valueRange = 0; this._addedLabels = []; } init(scaleOptions) { const added = this._addedLabels; if (added.length) { const labels = this.getLabels(); for (const {index, label} of added) { if (labels[index] === label) { labels.splice(index, 1); } } this._addedLabels = []; } super.init(scaleOptions); } parse(raw, index) { if (isNullOrUndef(raw)) { return null; } const labels = this.getLabels(); index = isFinite(index) && labels[index] === raw ? index : findOrAddLabel(labels, raw, valueOrDefault(index, raw), this._addedLabels); return validIndex(index, labels.length - 1); } determineDataLimits() { const {minDefined, maxDefined} = this.getUserBounds(); let {min, max} = this.getMinMax(true); if (this.options.bounds === 'ticks') { if (!minDefined) { min = 0; } if (!maxDefined) { max = this.getLabels().length - 1; } } this.min = min; this.max = max; } buildTicks() { const min = this.min; const max = this.max; const offset = this.options.offset; const ticks = []; let labels = this.getLabels(); labels = (min === 0 && max === labels.length - 1) ? labels : labels.slice(min, max + 1); this._valueRange = Math.max(labels.length - (offset ? 0 : 1), 1); this._startValue = this.min - (offset ? 0.5 : 0); for (let value = min; value <= max; value++) { ticks.push({value}); } return ticks; } getLabelForValue(value) { const labels = this.getLabels(); if (value >= 0 && value < labels.length) { return labels[value]; } return value; } configure() { super.configure(); if (!this.isHorizontal()) { this._reversePixels = !this._reversePixels; } } getPixelForValue(value) { if (typeof value !== 'number') { value = this.parse(value); } return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange); } getPixelForTick(index) { const ticks = this.ticks; if (index < 0 || index > ticks.length - 1) { return null; } return this.getPixelForValue(ticks[index].value); } getValueForPixel(pixel) { return Math.round(this._startValue + this.getDecimalForPixel(pixel) * this._valueRange); } getBasePixel() { return this.bottom; } } CategoryScale.id = 'category'; CategoryScale.defaults = { ticks: { callback: CategoryScale.prototype.getLabelForValue } }; function generateTicks$1(generationOptions, dataRange) { const ticks = []; const MIN_SPACING = 1e-14; const {bounds, step, min, max, precision, count, maxTicks, maxDigits, includeBounds} = generationOptions; const unit = step || 1; const maxSpaces = maxTicks - 1; const {min: rmin, max: rmax} = dataRange; const minDefined = !isNullOrUndef(min); const maxDefined = !isNullOrUndef(max); const countDefined = !isNullOrUndef(count); const minSpacing = (rmax - rmin) / (maxDigits + 1); let spacing = niceNum((rmax - rmin) / maxSpaces / unit) * unit; let factor, niceMin, niceMax, numSpaces; if (spacing < MIN_SPACING && !minDefined && !maxDefined) { return [{value: rmin}, {value: rmax}]; } numSpaces = Math.ceil(rmax / spacing) - Math.floor(rmin / spacing); if (numSpaces > maxSpaces) { spacing = niceNum(numSpaces * spacing / maxSpaces / unit) * unit; } if (!isNullOrUndef(precision)) { factor = Math.pow(10, precision); spacing = Math.ceil(spacing * factor) / factor; } if (bounds === 'ticks') { niceMin = Math.floor(rmin / spacing) * spacing; niceMax = Math.ceil(rmax / spacing) * spacing; } else { niceMin = rmin; niceMax = rmax; } if (minDefined && maxDefined && step && almostWhole((max - min) / step, spacing / 1000)) { numSpaces = Math.round(Math.min((max - min) / spacing, maxTicks)); spacing = (max - min) / numSpaces; niceMin = min; niceMax = max; } else if (countDefined) { niceMin = minDefined ? min : niceMin; niceMax = maxDefined ? max : niceMax; numSpaces = count - 1; spacing = (niceMax - niceMin) / numSpaces; } else { numSpaces = (niceMax - niceMin) / spacing; if (almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) { numSpaces = Math.round(numSpaces); } else { numSpaces = Math.ceil(numSpaces); } } const decimalPlaces = Math.max( _decimalPlaces(spacing), _decimalPlaces(niceMin) ); factor = Math.pow(10, isNullOrUndef(precision) ? decimalPlaces : precision); niceMin = Math.round(niceMin * factor) / factor; niceMax = Math.round(niceMax * factor) / factor; let j = 0; if (minDefined) { if (includeBounds && niceMin !== min) { ticks.push({value: min}); if (niceMin < min) { j++; } if (almostEquals(Math.round((niceMin + j * spacing) * factor) / factor, min, relativeLabelSize(min, minSpacing, generationOptions))) { j++; } } else if (niceMin < min) { j++; } } for (; j < numSpaces; ++j) { ticks.push({value: Math.round((niceMin + j * spacing) * factor) / factor}); } if (maxDefined && includeBounds && niceMax !== max) { if (ticks.length && almostEquals(ticks[ticks.length - 1].value, max, relativeLabelSize(max, minSpacing, generationOptions))) { ticks[ticks.length - 1].value = max; } else { ticks.push({value: max}); } } else if (!maxDefined || niceMax === max) { ticks.push({value: niceMax}); } return ticks; } function relativeLabelSize(value, minSpacing, {horizontal, minRotation}) { const rad = toRadians(minRotation); const ratio = (horizontal ? Math.sin(rad) : Math.cos(rad)) || 0.001; const length = 0.75 * minSpacing * ('' + value).length; return Math.min(minSpacing / ratio, length); } class LinearScaleBase extends Scale { constructor(cfg) { super(cfg); this.start = undefined; this.end = undefined; this._startValue = undefined; this._endValue = undefined; this._valueRange = 0; } parse(raw, index) { if (isNullOrUndef(raw)) { return null; } if ((typeof raw === 'number' || raw instanceof Number) && !isFinite(+raw)) { return null; } return +raw; } handleTickRangeOptions() { const {beginAtZero} = this.options; const {minDefined, maxDefined} = this.getUserBounds(); let {min, max} = this; const setMin = v => (min = minDefined ? min : v); const setMax = v => (max = maxDefined ? max : v); if (beginAtZero) { const minSign = sign(min); const maxSign = sign(max); if (minSign < 0 && maxSign < 0) { setMax(0); } else if (minSign > 0 && maxSign > 0) { setMin(0); } } if (min === max) { let offset = 1; if (max >= Number.MAX_SAFE_INTEGER || min <= Number.MIN_SAFE_INTEGER) { offset = Math.abs(max * 0.05); } setMax(max + offset); if (!beginAtZero) { setMin(min - offset); } } this.min = min; this.max = max; } getTickLimit() { const tickOpts = this.options.ticks; let {maxTicksLimit, stepSize} = tickOpts; let maxTicks; if (stepSize) { maxTicks = Math.ceil(this.max / stepSize) - Math.floor(this.min / stepSize) + 1; if (maxTicks > 1000) { console.warn(`scales.${this.id}.ticks.stepSize: ${stepSize} would result generating up to ${maxTicks} ticks. Limiting to 1000.`); maxTicks = 1000; } } else { maxTicks = this.computeTickLimit(); maxTicksLimit = maxTicksLimit || 11; } if (maxTicksLimit) { maxTicks = Math.min(maxTicksLimit, maxTicks); } return maxTicks; } computeTickLimit() { return Number.POSITIVE_INFINITY; } buildTicks() { const opts = this.options; const tickOpts = opts.ticks; let maxTicks = this.getTickLimit(); maxTicks = Math.max(2, maxTicks); const numericGeneratorOptions = { maxTicks, bounds: opts.bounds, min: opts.min, max: opts.max, precision: tickOpts.precision, step: tickOpts.stepSize, count: tickOpts.count, maxDigits: this._maxDigits(), horizontal: this.isHorizontal(), minRotation: tickOpts.minRotation || 0, includeBounds: tickOpts.includeBounds !== false }; const dataRange = this._range || this; const ticks = generateTicks$1(numericGeneratorOptions, dataRange); if (opts.bounds === 'ticks') { _setMinAndMaxByKey(ticks, this, 'value'); } if (opts.reverse) { ticks.reverse(); this.start = this.max; this.end = this.min; } else { this.start = this.min; this.end = this.max; } return ticks; } configure() { const ticks = this.ticks; let start = this.min; let end = this.max; super.configure(); if (this.options.offset && ticks.length) { const offset = (end - start) / Math.max(ticks.length - 1, 1) / 2; start -= offset; end += offset; } this._startValue = start; this._endValue = end; this._valueRange = end - start; } getLabelForValue(value) { return formatNumber(value, this.chart.options.locale, this.options.ticks.format); } } class LinearScale extends LinearScaleBase { determineDataLimits() { const {min, max} = this.getMinMax(true); this.min = isNumberFinite(min) ? min : 0; this.max = isNumberFinite(max) ? max : 1; this.handleTickRangeOptions(); } computeTickLimit() { const horizontal = this.isHorizontal(); const length = horizontal ? this.width : this.height; const minRotation = toRadians(this.options.ticks.minRotation); const ratio = (horizontal ? Math.sin(minRotation) : Math.cos(minRotation)) || 0.001; const tickFont = this._resolveTickFontOptions(0); return Math.ceil(length / Math.min(40, tickFont.lineHeight / ratio)); } getPixelForValue(value) { return value === null ? NaN : this.getPixelForDecimal((value - this._startValue) / this._valueRange); } getValueForPixel(pixel) { return this._startValue + this.getDecimalForPixel(pixel) * this._valueRange; } } LinearScale.id = 'linear'; LinearScale.defaults = { ticks: { callback: Ticks.formatters.numeric } }; function isMajor(tickVal) { const remain = tickVal / (Math.pow(10, Math.floor(log10(tickVal)))); return remain === 1; } function generateTicks(generationOptions, dataRange) { const endExp = Math.floor(log10(dataRange.max)); const endSignificand = Math.ceil(dataRange.max / Math.pow(10, endExp)); const ticks = []; let tickVal = finiteOrDefault(generationOptions.min, Math.pow(10, Math.floor(log10(dataRange.min)))); let exp = Math.floor(log10(tickVal)); let significand = Math.floor(tickVal / Math.pow(10, exp)); let precision = exp < 0 ? Math.pow(10, Math.abs(exp)) : 1; do { ticks.push({value: tickVal, major: isMajor(tickVal)}); ++significand; if (significand === 10) { significand = 1; ++exp; precision = exp >= 0 ? 1 : precision; } tickVal = Math.round(significand * Math.pow(10, exp) * precision) / precision; } while (exp < endExp || (exp === endExp && significand < endSignificand)); const lastTick = finiteOrDefault(generationOptions.max, tickVal); ticks.push({value: lastTick, major: isMajor(tickVal)}); return ticks; } class LogarithmicScale extends Scale { constructor(cfg) { super(cfg); this.start = undefined; this.end = undefined; this._startValue = undefined; this._valueRange = 0; } parse(raw, index) { const value = LinearScaleBase.prototype.parse.apply(this, [raw, index]); if (value === 0) { this._zero = true; return undefined; } return isNumberFinite(value) && value > 0 ? value : null; } determineDataLimits() { const {min, max} = this.getMinMax(true); this.min = isNumberFinite(min) ? Math.max(0, min) : null; this.max = isNumberFinite(max) ? Math.max(0, max) : null; if (this.options.beginAtZero) { this._zero = true; } this.handleTickRangeOptions(); } handleTickRangeOptions() { const {minDefined, maxDefined} = this.getUserBounds(); let min = this.min; let max = this.max; const setMin = v => (min = minDefined ? min : v); const setMax = v => (max = maxDefined ? max : v); const exp = (v, m) => Math.pow(10, Math.floor(log10(v)) + m); if (min === max) { if (min <= 0) { setMin(1); setMax(10); } else { setMin(exp(min, -1)); setMax(exp(max, +1)); } } if (min <= 0) { setMin(exp(max, -1)); } if (max <= 0) { setMax(exp(min, +1)); } if (this._zero && this.min !== this._suggestedMin && min === exp(this.min, 0)) { setMin(exp(min, -1)); } this.min = min; this.max = max; } buildTicks() { const opts = this.options; const generationOptions = { min: this._userMin, max: this._userMax }; const ticks = generateTicks(generationOptions, this); if (opts.bounds === 'ticks') { _setMinAndMaxByKey(ticks, this, 'value'); } if (opts.reverse) { ticks.reverse(); this.start = this.max; this.end = this.min; } else { this.start = this.min; this.end = this.max; } return ticks; } getLabelForValue(value) { return value === undefined ? '0' : formatNumber(value, this.chart.options.locale, this.options.ticks.format); } configure() { const start = this.min; super.configure(); this._startValue = log10(start); this._valueRange = log10(this.max) - log10(start); } getPixelForValue(value) { if (value === undefined || value === 0) { value = this.min; } if (value === null || isNaN(value)) { return NaN; } return this.getPixelForDecimal(value === this.min ? 0 : (log10(value) - this._startValue) / this._valueRange); } getValueForPixel(pixel) { const decimal = this.getDecimalForPixel(pixel); return Math.pow(10, this._startValue + decimal * this._valueRange); } } LogarithmicScale.id = 'logarithmic'; LogarithmicScale.defaults = { ticks: { callback: Ticks.formatters.logarithmic, major: { enabled: true } } }; function getTickBackdropHeight(opts) { const tickOpts = opts.ticks; if (tickOpts.display && opts.display) { const padding = toPadding(tickOpts.backdropPadding); return valueOrDefault(tickOpts.font && tickOpts.font.size, defaults.font.size) + padding.height; } return 0; } function measureLabelSize(ctx, font, label) { label = isArray(label) ? label : [label]; return { w: _longestText(ctx, font.string, label), h: label.length * font.lineHeight }; } function determineLimits(angle, pos, size, min, max) { if (angle === min || angle === max) { return { start: pos - (size / 2), end: pos + (size / 2) }; } else if (angle < min || angle > max) { return { start: pos - size, end: pos }; } return { start: pos, end: pos + size }; } function fitWithPointLabels(scale) { const furthestLimits = { l: 0, r: scale.width, t: 0, b: scale.height - scale.paddingTop }; const furthestAngles = {}; const labelSizes = []; const padding = []; const valueCount = scale.getLabels().length; for (let i = 0; i < valueCount; i++) { const opts = scale.options.pointLabels.setContext(scale.getPointLabelContext(i)); padding[i] = opts.padding; const pointPosition = scale.getPointPosition(i, scale.drawingArea + padding[i]); const plFont = toFont(opts.font); const textSize = measureLabelSize(scale.ctx, plFont, scale._pointLabels[i]); labelSizes[i] = textSize; const angleRadians = scale.getIndexAngle(i); const angle = toDegrees(angleRadians); const hLimits = determineLimits(angle, pointPosition.x, textSize.w, 0, 180); const vLimits = determineLimits(angle, pointPosition.y, textSize.h, 90, 270); if (hLimits.start < furthestLimits.l) { furthestLimits.l = hLimits.start; furthestAngles.l = angleRadians; } if (hLimits.end > furthestLimits.r) { furthestLimits.r = hLimits.end; furthestAngles.r = angleRadians; } if (vLimits.start < furthestLimits.t) { furthestLimits.t = vLimits.start; furthestAngles.t = angleRadians; } if (vLimits.end > furthestLimits.b) { furthestLimits.b = vLimits.end; furthestAngles.b = angleRadians; } } scale._setReductions(scale.drawingArea, furthestLimits, furthestAngles); scale._pointLabelItems = buildPointLabelItems(scale, labelSizes, padding); } function buildPointLabelItems(scale, labelSizes, padding) { const items = []; const valueCount = scale.getLabels().length; const opts = scale.options; const tickBackdropHeight = getTickBackdropHeight(opts); const outerDistance = scale.getDistanceFromCenterForValue(opts.ticks.reverse ? scale.min : scale.max); for (let i = 0; i < valueCount; i++) { const extra = (i === 0 ? tickBackdropHeight / 2 : 0); const pointLabelPosition = scale.getPointPosition(i, outerDistance + extra + padding[i]); const angle = toDegrees(scale.getIndexAngle(i)); const size = labelSizes[i]; const y = yForAngle(pointLabelPosition.y, size.h, angle); const textAlign = getTextAlignForAngle(angle); const left = leftForTextAlign(pointLabelPosition.x, size.w, textAlign); items.push({ x: pointLabelPosition.x, y, textAlign, left, top: y, right: left + size.w, bottom: y + size.h }); } return items; } function getTextAlignForAngle(angle) { if (angle === 0 || angle === 180) { return 'center'; } else if (angle < 180) { return 'left'; } return 'right'; } function leftForTextAlign(x, w, align) { if (align === 'right') { x -= w; } else if (align === 'center') { x -= (w / 2); } return x; } function yForAngle(y, h, angle) { if (angle === 90 || angle === 270) { y -= (h / 2); } else if (angle > 270 || angle < 90) { y -= h; } return y; } function drawPointLabels(scale, labelCount) { const {ctx, options: {pointLabels}} = scale; for (let i = labelCount - 1; i >= 0; i--) { const optsAtIndex = pointLabels.setContext(scale.getPointLabelContext(i)); const plFont = toFont(optsAtIndex.font); const {x, y, textAlign, left, top, right, bottom} = scale._pointLabelItems[i]; const {backdropColor} = optsAtIndex; if (!isNullOrUndef(backdropColor)) { const padding = toPadding(optsAtIndex.backdropPadding); ctx.fillStyle = backdropColor; ctx.fillRect(left - padding.left, top - padding.top, right - left + padding.width, bottom - top + padding.height); } renderText( ctx, scale._pointLabels[i], x, y + (plFont.lineHeight / 2), plFont, { color: optsAtIndex.color, textAlign: textAlign, textBaseline: 'middle' } ); } } function pathRadiusLine(scale, radius, circular, labelCount) { const {ctx} = scale; if (circular) { ctx.arc(scale.xCenter, scale.yCenter, radius, 0, TAU); } else { let pointPosition = scale.getPointPosition(0, radius); ctx.moveTo(pointPosition.x, pointPosition.y); for (let i = 1; i < labelCount; i++) { pointPosition = scale.getPointPosition(i, radius); ctx.lineTo(pointPosition.x, pointPosition.y); } } } function drawRadiusLine(scale, gridLineOpts, radius, labelCount) { const ctx = scale.ctx; const circular = gridLineOpts.circular; const {color, lineWidth} = gridLineOpts; if ((!circular && !labelCount) || !color || !lineWidth || radius < 0) { return; } ctx.save(); ctx.strokeStyle = color; ctx.lineWidth = lineWidth; ctx.setLineDash(gridLineOpts.borderDash); ctx.lineDashOffset = gridLineOpts.borderDashOffset; ctx.beginPath(); pathRadiusLine(scale, radius, circular, labelCount); ctx.closePath(); ctx.stroke(); ctx.restore(); } function numberOrZero(param) { return isNumber(param) ? param : 0; } function createPointLabelContext(parent, index, label) { return createContext(parent, { label, index, type: 'pointLabel' }); } class RadialLinearScale extends LinearScaleBase { constructor(cfg) { super(cfg); this.xCenter = undefined; this.yCenter = undefined; this.drawingArea = undefined; this._pointLabels = []; this._pointLabelItems = []; } setDimensions() { this.width = this.maxWidth; this.height = this.maxHeight; this.paddingTop = getTickBackdropHeight(this.options) / 2; this.xCenter = Math.floor(this.width / 2); this.yCenter = Math.floor((this.height - this.paddingTop) / 2); this.drawingArea = Math.min(this.height - this.paddingTop, this.width) / 2; } determineDataLimits() { const {min, max} = this.getMinMax(false); this.min = isNumberFinite(min) && !isNaN(min) ? min : 0; this.max = isNumberFinite(max) && !isNaN(max) ? max : 0; this.handleTickRangeOptions(); } computeTickLimit() { return Math.ceil(this.drawingArea / getTickBackdropHeight(this.options)); } generateTickLabels(ticks) { LinearScaleBase.prototype.generateTickLabels.call(this, ticks); this._pointLabels = this.getLabels().map((value, index) => { const label = callback(this.options.pointLabels.callback, [value, index], this); return label || label === 0 ? label : ''; }); } fit() { const opts = this.options; if (opts.display && opts.pointLabels.display) { fitWithPointLabels(this); } else { this.setCenterPoint(0, 0, 0, 0); } } _setReductions(largestPossibleRadius, furthestLimits, furthestAngles) { let radiusReductionLeft = furthestLimits.l / Math.sin(furthestAngles.l); let radiusReductionRight = Math.max(furthestLimits.r - this.width, 0) / Math.sin(furthestAngles.r); let radiusReductionTop = -furthestLimits.t / Math.cos(furthestAngles.t); let radiusReductionBottom = -Math.max(furthestLimits.b - (this.height - this.paddingTop), 0) / Math.cos(furthestAngles.b); radiusReductionLeft = numberOrZero(radiusReductionLeft); radiusReductionRight = numberOrZero(radiusReductionRight); radiusReductionTop = numberOrZero(radiusReductionTop); radiusReductionBottom = numberOrZero(radiusReductionBottom); this.drawingArea = Math.max(largestPossibleRadius / 2, Math.min( Math.floor(largestPossibleRadius - (radiusReductionLeft + radiusReductionRight) / 2), Math.floor(largestPossibleRadius - (radiusReductionTop + radiusReductionBottom) / 2))); this.setCenterPoint(radiusReductionLeft, radiusReductionRight, radiusReductionTop, radiusReductionBottom); } setCenterPoint(leftMovement, rightMovement, topMovement, bottomMovement) { const maxRight = this.width - rightMovement - this.drawingArea; const maxLeft = leftMovement + this.drawingArea; const maxTop = topMovement + this.drawingArea; const maxBottom = (this.height - this.paddingTop) - bottomMovement - this.drawingArea; this.xCenter = Math.floor(((maxLeft + maxRight) / 2) + this.left); this.yCenter = Math.floor(((maxTop + maxBottom) / 2) + this.top + this.paddingTop); } getIndexAngle(index) { const angleMultiplier = TAU / this.getLabels().length; const startAngle = this.options.startAngle || 0; return _normalizeAngle(index * angleMultiplier + toRadians(startAngle)); } getDistanceFromCenterForValue(value) { if (isNullOrUndef(value)) { return NaN; } const scalingFactor = this.drawingArea / (this.max - this.min); if (this.options.reverse) { return (this.max - value) * scalingFactor; } return (value - this.min) * scalingFactor; } getValueForDistanceFromCenter(distance) { if (isNullOrUndef(distance)) { return NaN; } const scaledDistance = distance / (this.drawingArea / (this.max - this.min)); return this.options.reverse ? this.max - scaledDistance : this.min + scaledDistance; } getPointLabelContext(index) { const pointLabels = this._pointLabels || []; if (index >= 0 && index < pointLabels.length) { const pointLabel = pointLabels[index]; return createPointLabelContext(this.getContext(), index, pointLabel); } } getPointPosition(index, distanceFromCenter) { const angle = this.getIndexAngle(index) - HALF_PI; return { x: Math.cos(angle) * distanceFromCenter + this.xCenter, y: Math.sin(angle) * distanceFromCenter + this.yCenter, angle }; } getPointPositionForValue(index, value) { return this.getPointPosition(index, this.getDistanceFromCenterForValue(value)); } getBasePosition(index) { return this.getPointPositionForValue(index || 0, this.getBaseValue()); } getPointLabelPosition(index) { const {left, top, right, bottom} = this._pointLabelItems[index]; return { left, top, right, bottom, }; } drawBackground() { const {backgroundColor, grid: {circular}} = this.options; if (backgroundColor) { const ctx = this.ctx; ctx.save(); ctx.beginPath(); pathRadiusLine(this, this.getDistanceFromCenterForValue(this._endValue), circular, this.getLabels().length); ctx.closePath(); ctx.fillStyle = backgroundColor; ctx.fill(); ctx.restore(); } } drawGrid() { const ctx = this.ctx; const opts = this.options; const {angleLines, grid} = opts; const labelCount = this.getLabels().length; let i, offset, position; if (opts.pointLabels.display) { drawPointLabels(this, labelCount); } if (grid.display) { this.ticks.forEach((tick, index) => { if (index !== 0) { offset = this.getDistanceFromCenterForValue(tick.value); const optsAtIndex = grid.setContext(this.getContext(index - 1)); drawRadiusLine(this, optsAtIndex, offset, labelCount); } }); } if (angleLines.display) { ctx.save(); for (i = this.getLabels().length - 1; i >= 0; i--) { const optsAtIndex = angleLines.setContext(this.getPointLabelContext(i)); const {color, lineWidth} = optsAtIndex; if (!lineWidth || !color) { continue; } ctx.lineWidth = lineWidth; ctx.strokeStyle = color; ctx.setLineDash(optsAtIndex.borderDash); ctx.lineDashOffset = optsAtIndex.borderDashOffset; offset = this.getDistanceFromCenterForValue(opts.ticks.reverse ? this.min : this.max); position = this.getPointPosition(i, offset); ctx.beginPath(); ctx.moveTo(this.xCenter, this.yCenter); ctx.lineTo(position.x, position.y); ctx.stroke(); } ctx.restore(); } } drawBorder() {} drawLabels() { const ctx = this.ctx; const opts = this.options; const tickOpts = opts.ticks; if (!tickOpts.display) { return; } const startAngle = this.getIndexAngle(0); let offset, width; ctx.save(); ctx.translate(this.xCenter, this.yCenter); ctx.rotate(startAngle); ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; this.ticks.forEach((tick, index) => { if (index === 0 && !opts.reverse) { return; } const optsAtIndex = tickOpts.setContext(this.getContext(index)); const tickFont = toFont(optsAtIndex.font); offset = this.getDistanceFromCenterForValue(this.ticks[index].value); if (optsAtIndex.showLabelBackdrop) { ctx.font = tickFont.string; width = ctx.measureText(tick.label).width; ctx.fillStyle = optsAtIndex.backdropColor; const padding = toPadding(optsAtIndex.backdropPadding); ctx.fillRect( -width / 2 - padding.left, -offset - tickFont.size / 2 - padding.top, width + padding.width, tickFont.size + padding.height ); } renderText(ctx, tick.label, 0, -offset, tickFont, { color: optsAtIndex.color, }); }); ctx.restore(); } drawTitle() {} } RadialLinearScale.id = 'radialLinear'; RadialLinearScale.defaults = { display: true, animate: true, position: 'chartArea', angleLines: { display: true, lineWidth: 1, borderDash: [], borderDashOffset: 0.0 }, grid: { circular: false }, startAngle: 0, ticks: { showLabelBackdrop: true, callback: Ticks.formatters.numeric }, pointLabels: { backdropColor: undefined, backdropPadding: 2, display: true, font: { size: 10 }, callback(label) { return label; }, padding: 5 } }; RadialLinearScale.defaultRoutes = { 'angleLines.color': 'borderColor', 'pointLabels.color': 'color', 'ticks.color': 'color' }; RadialLinearScale.descriptors = { angleLines: { _fallback: 'grid' } }; const INTERVALS = { millisecond: {common: true, size: 1, steps: 1000}, second: {common: true, size: 1000, steps: 60}, minute: {common: true, size: 60000, steps: 60}, hour: {common: true, size: 3600000, steps: 24}, day: {common: true, size: 86400000, steps: 30}, week: {common: false, size: 604800000, steps: 4}, month: {common: true, size: 2.628e9, steps: 12}, quarter: {common: false, size: 7.884e9, steps: 4}, year: {common: true, size: 3.154e10} }; const UNITS = (Object.keys(INTERVALS)); function sorter(a, b) { return a - b; } function parse(scale, input) { if (isNullOrUndef(input)) { return null; } const adapter = scale._adapter; const {parser, round, isoWeekday} = scale._parseOpts; let value = input; if (typeof parser === 'function') { value = parser(value); } if (!isNumberFinite(value)) { value = typeof parser === 'string' ? adapter.parse(value, parser) : adapter.parse(value); } if (value === null) { return null; } if (round) { value = round === 'week' && (isNumber(isoWeekday) || isoWeekday === true) ? adapter.startOf(value, 'isoWeek', isoWeekday) : adapter.startOf(value, round); } return +value; } function determineUnitForAutoTicks(minUnit, min, max, capacity) { const ilen = UNITS.length; for (let i = UNITS.indexOf(minUnit); i < ilen - 1; ++i) { const interval = INTERVALS[UNITS[i]]; const factor = interval.steps ? interval.steps : Number.MAX_SAFE_INTEGER; if (interval.common && Math.ceil((max - min) / (factor * interval.size)) <= capacity) { return UNITS[i]; } } return UNITS[ilen - 1]; } function determineUnitForFormatting(scale, numTicks, minUnit, min, max) { for (let i = UNITS.length - 1; i >= UNITS.indexOf(minUnit); i--) { const unit = UNITS[i]; if (INTERVALS[unit].common && scale._adapter.diff(max, min, unit) >= numTicks - 1) { return unit; } } return UNITS[minUnit ? UNITS.indexOf(minUnit) : 0]; } function determineMajorUnit(unit) { for (let i = UNITS.indexOf(unit) + 1, ilen = UNITS.length; i < ilen; ++i) { if (INTERVALS[UNITS[i]].common) { return UNITS[i]; } } } function addTick(ticks, time, timestamps) { if (!timestamps) { ticks[time] = true; } else if (timestamps.length) { const {lo, hi} = _lookup(timestamps, time); const timestamp = timestamps[lo] >= time ? timestamps[lo] : timestamps[hi]; ticks[timestamp] = true; } } function setMajorTicks(scale, ticks, map, majorUnit) { const adapter = scale._adapter; const first = +adapter.startOf(ticks[0].value, majorUnit); const last = ticks[ticks.length - 1].value; let major, index; for (major = first; major <= last; major = +adapter.add(major, 1, majorUnit)) { index = map[major]; if (index >= 0) { ticks[index].major = true; } } return ticks; } function ticksFromTimestamps(scale, values, majorUnit) { const ticks = []; const map = {}; const ilen = values.length; let i, value; for (i = 0; i < ilen; ++i) { value = values[i]; map[value] = i; ticks.push({ value, major: false }); } return (ilen === 0 || !majorUnit) ? ticks : setMajorTicks(scale, ticks, map, majorUnit); } class TimeScale extends Scale { constructor(props) { super(props); this._cache = { data: [], labels: [], all: [] }; this._unit = 'day'; this._majorUnit = undefined; this._offsets = {}; this._normalized = false; this._parseOpts = undefined; } init(scaleOpts, opts) { const time = scaleOpts.time || (scaleOpts.time = {}); const adapter = this._adapter = new _adapters._date(scaleOpts.adapters.date); mergeIf(time.displayFormats, adapter.formats()); this._parseOpts = { parser: time.parser, round: time.round, isoWeekday: time.isoWeekday }; super.init(scaleOpts); this._normalized = opts.normalized; } parse(raw, index) { if (raw === undefined) { return null; } return parse(this, raw); } beforeLayout() { super.beforeLayout(); this._cache = { data: [], labels: [], all: [] }; } determineDataLimits() { const options = this.options; const adapter = this._adapter; const unit = options.time.unit || 'day'; let {min, max, minDefined, maxDefined} = this.getUserBounds(); function _applyBounds(bounds) { if (!minDefined && !isNaN(bounds.min)) { min = Math.min(min, bounds.min); } if (!maxDefined && !isNaN(bounds.max)) { max = Math.max(max, bounds.max); } } if (!minDefined || !maxDefined) { _applyBounds(this._getLabelBounds()); if (options.bounds !== 'ticks' || options.ticks.source !== 'labels') { _applyBounds(this.getMinMax(false)); } } min = isNumberFinite(min) && !isNaN(min) ? min : +adapter.startOf(Date.now(), unit); max = isNumberFinite(max) && !isNaN(max) ? max : +adapter.endOf(Date.now(), unit) + 1; this.min = Math.min(min, max - 1); this.max = Math.max(min + 1, max); } _getLabelBounds() { const arr = this.getLabelTimestamps(); let min = Number.POSITIVE_INFINITY; let max = Number.NEGATIVE_INFINITY; if (arr.length) { min = arr[0]; max = arr[arr.length - 1]; } return {min, max}; } buildTicks() { const options = this.options; const timeOpts = options.time; const tickOpts = options.ticks; const timestamps = tickOpts.source === 'labels' ? this.getLabelTimestamps() : this._generate(); if (options.bounds === 'ticks' && timestamps.length) { this.min = this._userMin || timestamps[0]; this.max = this._userMax || timestamps[timestamps.length - 1]; } const min = this.min; const max = this.max; const ticks = _filterBetween(timestamps, min, max); this._unit = timeOpts.unit || (tickOpts.autoSkip ? determineUnitForAutoTicks(timeOpts.minUnit, this.min, this.max, this._getLabelCapacity(min)) : determineUnitForFormatting(this, ticks.length, timeOpts.minUnit, this.min, this.max)); this._majorUnit = !tickOpts.major.enabled || this._unit === 'year' ? undefined : determineMajorUnit(this._unit); this.initOffsets(timestamps); if (options.reverse) { ticks.reverse(); } return ticksFromTimestamps(this, ticks, this._majorUnit); } initOffsets(timestamps) { let start = 0; let end = 0; let first, last; if (this.options.offset && timestamps.length) { first = this.getDecimalForValue(timestamps[0]); if (timestamps.length === 1) { start = 1 - first; } else { start = (this.getDecimalForValue(timestamps[1]) - first) / 2; } last = this.getDecimalForValue(timestamps[timestamps.length - 1]); if (timestamps.length === 1) { end = last; } else { end = (last - this.getDecimalForValue(timestamps[timestamps.length - 2])) / 2; } } const limit = timestamps.length < 3 ? 0.5 : 0.25; start = _limitValue(start, 0, limit); end = _limitValue(end, 0, limit); this._offsets = {start, end, factor: 1 / (start + 1 + end)}; } _generate() { const adapter = this._adapter; const min = this.min; const max = this.max; const options = this.options; const timeOpts = options.time; const minor = timeOpts.unit || determineUnitForAutoTicks(timeOpts.minUnit, min, max, this._getLabelCapacity(min)); const stepSize = valueOrDefault(timeOpts.stepSize, 1); const weekday = minor === 'week' ? timeOpts.isoWeekday : false; const hasWeekday = isNumber(weekday) || weekday === true; const ticks = {}; let first = min; let time, count; if (hasWeekday) { first = +adapter.startOf(first, 'isoWeek', weekday); } first = +adapter.startOf(first, hasWeekday ? 'day' : minor); if (adapter.diff(max, min, minor) > 100000 * stepSize) { throw new Error(min + ' and ' + max + ' are too far apart with stepSize of ' + stepSize + ' ' + minor); } const timestamps = options.ticks.source === 'data' && this.getDataTimestamps(); for (time = first, count = 0; time < max; time = +adapter.add(time, stepSize, minor), count++) { addTick(ticks, time, timestamps); } if (time === max || options.bounds === 'ticks' || count === 1) { addTick(ticks, time, timestamps); } return Object.keys(ticks).sort((a, b) => a - b).map(x => +x); } getLabelForValue(value) { const adapter = this._adapter; const timeOpts = this.options.time; if (timeOpts.tooltipFormat) { return adapter.format(value, timeOpts.tooltipFormat); } return adapter.format(value, timeOpts.displayFormats.datetime); } _tickFormatFunction(time, index, ticks, format) { const options = this.options; const formats = options.time.displayFormats; const unit = this._unit; const majorUnit = this._majorUnit; const minorFormat = unit && formats[unit]; const majorFormat = majorUnit && formats[majorUnit]; const tick = ticks[index]; const major = majorUnit && majorFormat && tick && tick.major; const label = this._adapter.format(time, format || (major ? majorFormat : minorFormat)); const formatter = options.ticks.callback; return formatter ? callback(formatter, [label, index, ticks], this) : label; } generateTickLabels(ticks) { let i, ilen, tick; for (i = 0, ilen = ticks.length; i < ilen; ++i) { tick = ticks[i]; tick.label = this._tickFormatFunction(tick.value, i, ticks); } } getDecimalForValue(value) { return value === null ? NaN : (value - this.min) / (this.max - this.min); } getPixelForValue(value) { const offsets = this._offsets; const pos = this.getDecimalForValue(value); return this.getPixelForDecimal((offsets.start + pos) * offsets.factor); } getValueForPixel(pixel) { const offsets = this._offsets; const pos = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end; return this.min + pos * (this.max - this.min); } _getLabelSize(label) { const ticksOpts = this.options.ticks; const tickLabelWidth = this.ctx.measureText(label).width; const angle = toRadians(this.isHorizontal() ? ticksOpts.maxRotation : ticksOpts.minRotation); const cosRotation = Math.cos(angle); const sinRotation = Math.sin(angle); const tickFontSize = this._resolveTickFontOptions(0).size; return { w: (tickLabelWidth * cosRotation) + (tickFontSize * sinRotation), h: (tickLabelWidth * sinRotation) + (tickFontSize * cosRotation) }; } _getLabelCapacity(exampleTime) { const timeOpts = this.options.time; const displayFormats = timeOpts.displayFormats; const format = displayFormats[timeOpts.unit] || displayFormats.millisecond; const exampleLabel = this._tickFormatFunction(exampleTime, 0, ticksFromTimestamps(this, [exampleTime], this._majorUnit), format); const size = this._getLabelSize(exampleLabel); const capacity = Math.floor(this.isHorizontal() ? this.width / size.w : this.height / size.h) - 1; return capacity > 0 ? capacity : 1; } getDataTimestamps() { let timestamps = this._cache.data || []; let i, ilen; if (timestamps.length) { return timestamps; } const metas = this.getMatchingVisibleMetas(); if (this._normalized && metas.length) { return (this._cache.data = metas[0].controller.getAllParsedValues(this)); } for (i = 0, ilen = metas.length; i < ilen; ++i) { timestamps = timestamps.concat(metas[i].controller.getAllParsedValues(this)); } return (this._cache.data = this.normalize(timestamps)); } getLabelTimestamps() { const timestamps = this._cache.labels || []; let i, ilen; if (timestamps.length) { return timestamps; } const labels = this.getLabels(); for (i = 0, ilen = labels.length; i < ilen; ++i) { timestamps.push(parse(this, labels[i])); } return (this._cache.labels = this._normalized ? timestamps : this.normalize(timestamps)); } normalize(values) { return _arrayUnique(values.sort(sorter)); } } TimeScale.id = 'time'; TimeScale.defaults = { bounds: 'data', adapters: {}, time: { parser: false, unit: false, round: false, isoWeekday: false, minUnit: 'millisecond', displayFormats: {} }, ticks: { source: 'auto', major: { enabled: false } } }; function interpolate(table, val, reverse) { let lo = 0; let hi = table.length - 1; let prevSource, nextSource, prevTarget, nextTarget; if (reverse) { if (val >= table[lo].pos && val <= table[hi].pos) { ({lo, hi} = _lookupByKey(table, 'pos', val)); } ({pos: prevSource, time: prevTarget} = table[lo]); ({pos: nextSource, time: nextTarget} = table[hi]); } else { if (val >= table[lo].time && val <= table[hi].time) { ({lo, hi} = _lookupByKey(table, 'time', val)); } ({time: prevSource, pos: prevTarget} = table[lo]); ({time: nextSource, pos: nextTarget} = table[hi]); } const span = nextSource - prevSource; return span ? prevTarget + (nextTarget - prevTarget) * (val - prevSource) / span : prevTarget; } class TimeSeriesScale extends TimeScale { constructor(props) { super(props); this._table = []; this._minPos = undefined; this._tableRange = undefined; } initOffsets() { const timestamps = this._getTimestampsForTable(); const table = this._table = this.buildLookupTable(timestamps); this._minPos = interpolate(table, this.min); this._tableRange = interpolate(table, this.max) - this._minPos; super.initOffsets(timestamps); } buildLookupTable(timestamps) { const {min, max} = this; const items = []; const table = []; let i, ilen, prev, curr, next; for (i = 0, ilen = timestamps.length; i < ilen; ++i) { curr = timestamps[i]; if (curr >= min && curr <= max) { items.push(curr); } } if (items.length < 2) { return [ {time: min, pos: 0}, {time: max, pos: 1} ]; } for (i = 0, ilen = items.length; i < ilen; ++i) { next = items[i + 1]; prev = items[i - 1]; curr = items[i]; if (Math.round((next + prev) / 2) !== curr) { table.push({time: curr, pos: i / (ilen - 1)}); } } return table; } _getTimestampsForTable() { let timestamps = this._cache.all || []; if (timestamps.length) { return timestamps; } const data = this.getDataTimestamps(); const label = this.getLabelTimestamps(); if (data.length && label.length) { timestamps = this.normalize(data.concat(label)); } else { timestamps = data.length ? data : label; } timestamps = this._cache.all = timestamps; return timestamps; } getDecimalForValue(value) { return (interpolate(this._table, value) - this._minPos) / this._tableRange; } getValueForPixel(pixel) { const offsets = this._offsets; const decimal = this.getDecimalForPixel(pixel) / offsets.factor - offsets.end; return interpolate(this._table, decimal * this._tableRange + this._minPos, true); } } TimeSeriesScale.id = 'timeseries'; TimeSeriesScale.defaults = TimeScale.defaults; var scales = /*#__PURE__*/Object.freeze({ __proto__: null, CategoryScale: CategoryScale, LinearScale: LinearScale, LogarithmicScale: LogarithmicScale, RadialLinearScale: RadialLinearScale, TimeScale: TimeScale, TimeSeriesScale: TimeSeriesScale }); Chart.register(controllers, scales, elements, plugins); Chart.helpers = {...helpers}; Chart._adapters = _adapters; Chart.Animation = Animation; Chart.Animations = Animations; Chart.animator = animator; Chart.controllers = registry.controllers.items; Chart.DatasetController = DatasetController; Chart.Element = Element; Chart.elements = elements; Chart.Interaction = Interaction; Chart.layouts = layouts; Chart.platforms = platforms; Chart.Scale = Scale; Chart.Ticks = Ticks; Object.assign(Chart, controllers, scales, elements, plugins, platforms); Chart.Chart = Chart; if (typeof window !== 'undefined') { window.Chart = Chart; } return Chart; })));
// Dependencies var CliUpdate = require("cli-update"); /** * CliFrames * Creates a new instance of CliFrames. * * @name CliFrames * @function * @param {Object} opt_options An optional object containing: * * - `frames` (Array): The frames to be loaded. * - `autostart` (Object): If provided, the animation will be autostarted. * The object will be provided to `start` function. * * @return {CliFrames} The CliFrames instance. */ var CliFrames = module.exports = function (opt_options) { var self = this; opt_options = Object(opt_options); /** * load * Loads the animation frames. * * @name load * @function * @param {Object} options An array of strings representing the animation frames. * @return {CliFrames} The CliFrames instance. */ self.load = function (options) { if (!Array.isArray(options)) { throw new Error("First argument must be an array of strings."); } self.frames = options; return self; }; /** * start * Starts the CLI animation. * * @name start * @function * @param {Object} options An object containing the following fields: * * - `delay` (Number): The frame delay in milliseconds (default: `100`). * - `repeat` (Boolean): If `true`, the animation will be repeated infinitely. * * @return {CliFrames} The CliFrames instance. */ self.start = function (options) { options = Object(options); options.delay = Number(options.delay || 100); options.end = options.end || function (err) { if (err) { console.log(err); } }; process.stdout.write("\u001b[2J\u001b[0;0H"); var cFrame = -1 , frameCount = self.frames.length ; CliUpdate.render(self.frames[++cFrame % frameCount]); var repeat = Boolean(options.repeat) , animation = setInterval(function() { if (++cFrame >= frameCount && !repeat) { clearInterval(animation); options.end(null, self.frames); return; } CliUpdate.render(self.frames[cFrame % frameCount]); }, options.delay) ; return CliFrames; }; // Handle opt_options if (opt_options.frames) { self.load(opt_options.frames); } if (opt_options.autostart) { self.start(opt_options.autostart); } };
var _ = require('lodash'), cheerio = require('cheerio'), crypto = require('crypto'), downsize = require('downsize'), RSS = require('rss'), url = require('url'), config = require('../../../config'), errors = require('../../../errors'), filters = require('../../../filters'), // Really ugly temporary hack for location of things fetchData = require('../../../controllers/frontend/fetch-data'), generate, generateFeed, getFeedXml, feedCache = {}; function isTag(req) { return req.originalUrl.indexOf('/' + config.routeKeywords.tag + '/') !== -1; } function isAuthor(req) { return req.originalUrl.indexOf('/' + config.routeKeywords.author + '/') !== -1; } function handleError(next) { return function handleError(err) { return next(err); }; } function getData(channelOpts, slugParam) { channelOpts.data = channelOpts.data || {}; channelOpts.data.permalinks = { type: 'read', resource: 'settings', options: 'permalinks' }; return fetchData(channelOpts, slugParam).then(function (result) { var response = {}, titleStart = ''; if (result.data.tag) { titleStart = result.data.tag[0].name + ' - ' || ''; } if (result.data.author) { titleStart = result.data.author[0].name + ' - ' || ''; } response.title = titleStart + config.theme.title; response.description = config.theme.description; response.permalinks = result.data.permalinks[0]; response.results = { posts: result.posts, meta: result.meta }; return response; }); } function getBaseUrl(req, slugParam) { var baseUrl = config.paths.subdir; if (isTag(req)) { baseUrl += '/' + config.routeKeywords.tag + '/' + slugParam + '/rss/'; } else if (isAuthor(req)) { baseUrl += '/' + config.routeKeywords.author + '/' + slugParam + '/rss/'; } else { baseUrl += '/rss/'; } return baseUrl; } function processUrls(html, siteUrl, itemUrl) { var htmlContent = cheerio.load(html, {decodeEntities: false}); // convert relative resource urls to absolute ['href', 'src'].forEach(function forEach(attributeName) { htmlContent('[' + attributeName + ']').each(function each(ix, el) { var baseUrl, attributeValue, parsed; el = htmlContent(el); attributeValue = el.attr(attributeName); // if URL is absolute move on to the next element try { parsed = url.parse(attributeValue); if (parsed.protocol) { return; } // Do not convert protocol relative URLs if (attributeValue.lastIndexOf('//', 0) === 0) { return; } } catch (e) { return; } // compose an absolute URL // if the relative URL begins with a '/' use the blog URL (including sub-directory) // as the base URL, otherwise use the post's URL. baseUrl = attributeValue[0] === '/' ? siteUrl : itemUrl; attributeValue = config.urlJoin(baseUrl, attributeValue); el.attr(attributeName, attributeValue); }); }); return htmlContent; } getFeedXml = function getFeedXml(path, data) { var dataHash = crypto.createHash('md5').update(JSON.stringify(data)).digest('hex'); if (!feedCache[path] || feedCache[path].hash !== dataHash) { // We need to regenerate feedCache[path] = { hash: dataHash, xml: generateFeed(data) }; } return feedCache[path].xml; }; generateFeed = function generateFeed(data) { var feed = new RSS({ title: data.title, description: data.description, generator: 'Ghost ' + data.version, feed_url: data.feedUrl, site_url: data.siteUrl, ttl: '60', custom_namespaces: { content: 'http://purl.org/rss/1.0/modules/content/', media: 'http://search.yahoo.com/mrss/' } }); data.results.posts.forEach(function forEach(post) { var itemUrl = config.urlFor('post', {post: post, permalinks: data.permalinks, secure: data.secure}, true), htmlContent = processUrls(post.html, data.siteUrl, itemUrl), item = { title: post.title, description: post.meta_description || downsize(htmlContent.html(), {words: 50}), guid: post.uuid, url: itemUrl, date: post.published_at, categories: _.pluck(post.tags, 'name'), author: post.author ? post.author.name : null, custom_elements: [] }, imageUrl; if (post.image) { imageUrl = config.urlFor('image', {image: post.image, secure: data.secure}, true); // Add a media content tag item.custom_elements.push({ 'media:content': { _attr: { url: imageUrl, medium: 'image' } } }); // Also add the image to the content, because not all readers support media:content htmlContent('p').first().before('<img src="' + imageUrl + '" />'); htmlContent('img').attr('alt', post.title); } item.custom_elements.push({ 'content:encoded': { _cdata: htmlContent.html() } }); filters.doFilter('rss.item', item, post).then(function then(item) { feed.item(item); }); }); return filters.doFilter('rss.feed', feed).then(function then(feed) { return feed.xml(); }); }; generate = function generate(req, res, next) { // Initialize RSS var pageParam = req.params.page !== undefined ? req.params.page : 1, slugParam = req.params.slug, baseUrl = getBaseUrl(req, slugParam); // Ensure we at least have an empty object for postOptions req.channelConfig.postOptions = req.channelConfig.postOptions || {}; // Set page on postOptions for the query made later req.channelConfig.postOptions.page = pageParam; req.channelConfig.slugParam = slugParam; return getData(req.channelConfig).then(function then(data) { var maxPage = data.results.meta.pagination.pages; // If page is greater than number of pages we have, redirect to last page if (pageParam > maxPage) { return next(new errors.NotFoundError()); } data.version = res.locals.safeVersion; data.siteUrl = config.urlFor('home', {secure: req.secure}, true); data.feedUrl = config.urlFor({relativeUrl: baseUrl, secure: req.secure}, true); data.secure = req.secure; return getFeedXml(req.originalUrl, data).then(function then(feedXml) { res.set('Content-Type', 'text/xml; charset=UTF-8'); res.send(feedXml); }); }).catch(handleError(next)); }; module.exports = generate;
`use strict` const users_games = require('../users_games') exports.seed = function(knex, Promise) { // Deletes ALL existing entries return knex('users_games').del() .then(function () { // Inserts seed entries return knex('users_games').insert(users_games); }); };
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), watch: { css: { files: [ ['css/**', 'sass/**'], ], tasks: ['sass', 'cssmin'] }, // js: { // files: [ // 'js/**', // ], // tasks: ['uglify'] // }, }, cssmin: { target: { files: { 'css/main.css': ['css/normalize.css', 'css/main.css'] } } }, sass: { dist: { options: { noCache: true, style: 'compact', sourcemap: 'none', }, files: { 'css/main.css': 'sass/style.scss' } } }, // uglify: { // my_target: { // files: { // 'js/plugins.min.js' : ['js/plugins.js'] // } // } // }, }); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-cssmin'); // grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.registerTask('default', [ 'sass', 'cssmin', // 'uglify', 'watch', ]); };
/* * A gradient background * * The background is a quad that sits at the back of the view frustum. * * The color for the quad is specified as a color for each of the quad's vertices. The color is given as * a flat array of 16 double precision numbers, in the range [0.0..1.0], in this format: * * [r, g, b, a, r, b, b, a, r, g, b, a, r, g, b, a] * * which is for top-left, top-right, bottom-right and bottom-left corners, respectively. * * The 'a' components are for the alpha channel, and should be given the value 1.0. That's just * there in case we want to do something fancy with alpha channel at some point, like blending. * * var bg = myNode.addNode({ * depth: -30, // default * colors:[ * 0.05, 0.06, 0.07, 1.0, // top left (R,G,B,A) * 0.05, 0.06, 0.07, 1.0, // top right * 0.85, 0.9, 0.98, 1.0, // bottom right * 0.85, 0.9, 0.98, 1.0 // bottom left * ] * }); * * // Change the colors: * * bg.setColors([ * 0.01, 0.03, 0.07, 1.0, * 0.01, 0.03, 0.07, 1.0, * 0.21, 0.2, 0.98, 1.0, * 0.21, 0.2, 0.98, 1.0 * ]); * * // Change the depth: * * bg.setDepth(-50); * */ (function () { var defaultColors = [ 0.05, 0.06, 0.07, 1.0, // top left (R,G,B,A) 0.05, 0.06, 0.07, 1.0, // top right 0.85, 0.9, 0.98, 1.0, // bottom right 0.85, 0.9, 0.98, 1.0 // bottom left ]; var defaultDepth = -30; SceneJS.Types.addType("backgrounds/gradient", { construct:function (params) { var colors = params.colors; if (colors && colors.length != 16) { this.log("error", "Invalid 'colors' param for backgrounds/gradients: should be 16-element array"); colors = defaultColors; } this._lookat = this.addNode({ type:"lookAt", eye:{ x:0, y:0, z:params.depth || defaultDepth }, look:{ x:0, y:0, z:0 }, up:{ x:0, y:1, z:.0 } }); var lights = this._lookat.addNode({ type:"lights", lights:[ { mode:"dir", color:{ r:1.0, g:1.0, b:1.0 }, dir:{ x:0.0, y:0.0, z:-1.0 }, diffuse:true, specular:true, space:"view" } ] }); var material = lights.addNode({ type:"material", baseColor:{ r:.95, g:.95, b:.95 }, specularColor:{ r:0.0, g:0.0, b:0.0 }, emit:0.2, specular:0.9, shine:3.0 }); // TODO: width and height, perhaps from frustum this._geometry = material.addNode({ type:"geometry", primitive:"triangles", positions:[ 950, 200, 300, -950, 200, 300, -950, -200, 300, 950, -200, 300 ], normals:[ 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1 ], uv:[ 10, 10, 0, 10, 0, 0, 10, 0 ], colors:params.colors || defaultColors, indices:[ 0, 1, 2, 0, 2, 3 ] }); }, /** * Sets the gradient colors * * @param {Array} [colors] 16-element flat array of colors for vertices - reverts to default when not given */ setColors:function (colors) { this._geometry.setColors(colors || defaultColors); }, /** Sets the depth * * @param {Number} [depth] Depth on Z-axis - default is -30, reverets to that when no parameter given */ setDepth: function(depth) { this._lookat.setEye({ x:0, y:0, z:params.depth || defaultDepth }); }, destruct:function () { // Not used } }); })();
app.directive('state', function () { return function (scope, element, attrs) { scope.$watch('state.currentState', function(actual_value) { if(!actual_value) { return; } if (actual_value.indexOf(attrs.state) != -1) { element.css("display", ""); } else { element.css("display", "none"); } }); } });
var chai = require('chai'); chai.use(require('chai-as-promised')); describe('Hexo', () => { require('./scripts/box'); require('./scripts/console'); require('./scripts/extend'); require('./scripts/filters'); require('./scripts/generators'); require('./scripts/helpers'); require('./scripts/hexo'); require('./scripts/models'); require('./scripts/processors'); require('./scripts/renderers'); require('./scripts/tags'); require('./scripts/theme'); require('./scripts/theme_processors'); });
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See http://js.arcgis.com/3.17/esri/copyright.txt for details. //>>built define("esri/layers/HeatmapManager","dojo/_base/declare dojo/_base/lang dojo/aspect dojo/_base/array require ../kernel ../sniff ../geometry/Point ../geometry/webMercatorUtils ./MapImage ../renderers/HeatmapRenderer ../tasks/query dojo/_base/fx".split(" "),function(e,l,t,q,u,v,w,x,y,z,r,A,s){function B(){}function C(b){var a=b.layer;return{geometry:b.geometry,attributes:b.attributes,getLayer:function(){return a}}}e=e(null,{declaredClass:"esri.layers.HeatmapManager",heatmapRenderer:null,sourceLayer:null, imageLayer:null,useTiles:!0,useWorker:!1,map:null,constructor:function(b){this.sourceLayer=b;this._hndls=[]},initialize:function(b){this.map=b;var a=this.sourceLayer,d=a.renderer;a.setDrawMode(!1);this.imageLayer=b._getMapImageLyr();var c=this;this.heatmapRenderer=d instanceof r?d:(d.getRendererInfoByZoom(b.getZoom())||d.getRendererInfoByScale(b.getScale())).renderer;this._setupDraw=this._setupDraw.bind(this);this.recalculateHeatmap=this.recalculateHeatmap.bind(this);this._removeRenderer=this._removeRenderer.bind(this); this._handleRendererChange=this._handleRendererChange.bind(this);this._rendererChangeHandle=this.sourceLayer.on("renderer-change",this._handleRendererChange);this._handleOpacityChange=this._handleOpacityChange.bind(this);this._reprojectFeature=this._reprojectFeature.bind(this);u(["../workers/heatmapCalculator"],function(a){c._calculator=new a(l.mixin({width:c.map.width,height:c.map.height},c._getOptions()));c._setupRenderer();c.heatmapRenderer.getStats=a.calculateStats;c.heatmapRenderer.getHistogramData= a.getHistogramData})},destroy:function(){this._removeHandlers();this._rendererChangeHandle&&this._rendererChangeHandle.remove();this._rendererChangeHandle=this.sourceLayer=this.imageLayer=this.map=this.heatmapRenderer=this._hndls=null},_handleRendererChange:function(b){var a=b.renderer,d=a instanceof r;this.heatmapRenderer?d?this.heatmapRenderer=a:this._removeRenderer(b):d&&(this.heatmapRenderer=a,this.sourceLayer&&this.map&&this._setupRenderer())},_handleOpacityChange:function(b){b=b.opacity;var a= this._getImageBySourceId(this.sourceLayer.id);a&&a.setOpacity(b)},_setupRenderer:function(){var b=this._hndls,a=this.sourceLayer,d=this.map,c=this;a._originalDraw=a._draw;a._draw=B;a._div.clear();clearTimeout(this._resetTimer);this._resetTimer=setTimeout(this._resetGraphics.bind(this),250);b.push(a.on("update-end",this._setupDraw));b.push(a.on("suspend",function(a){(a=c._getImageBySourceId(c.sourceLayer.id))&&a.hide()}));b.push(a.on("resume",function(a){(a=c._getImageBySourceId(c.sourceLayer.id))&& a.show()}));b.push(t.after(a,"redraw",this._setupDraw));b.push(d.on("layer-remove",function(b){b.layer==a&&((b=c._getImageBySourceId(c.sourceLayer.id))&&c.imageLayer.removeImage(b),c._removeRenderer({target:a}))}));a._collection&&b.push(a.on("graphic-add",function(a){c._reprojectFeature(a.graphic);c._setupDraw()}));1!==a.mode&&(b.push(d.on("resize, pan-end",this._setupDraw)),b.push(d.on("zoom-end",this._setupDraw)));b.push(a.on("opacity-change",this._handleOpacityChange));this.imageLayer.suspended&& this.imageLayer.resume();a.graphics&&a.graphics.length&&(a.graphics[0].geometry&&!d.spatialReference.equals(a.graphics[0].geometry.spatialReference)&&q.forEach(a.graphics,function(a){this._reprojectFeature(a)}.bind(this)),this._setupDraw())},_setupDraw:function(){if(!this._drawTimer){var b=this;this._drawTimer=setTimeout(function(){clearTimeout(b._drawTimer);b._drawTimer=null;b.sourceLayer._getRenderer().isInstanceOf(r)&&b.recalculateHeatmap()},16)}},_removeRenderer:function(b){var a=b.target;a._draw= a._originalDraw;delete a._originalDraw;a.setDrawMode(!0);this._removeHandlers();this._hndls=[];var d=this._getImageBySourceId(this.sourceLayer.id);d&&this.imageLayer.removeImage(d);clearTimeout(this._drawTimer);clearTimeout(this._resetTimer);this._drawTimer=this._resetTimer=null;a.renderer!=b.renderer&&a.renderer.getRendererInfo?this.heatmapRenderer=null:(a.redraw(),this.destroy())},recalculateHeatmap:function(){this._calculator?this._doMainCalculation():this._calculatorClient&&this._doWorkerCalculation()}, _reprojectFeature:function(b){if(b&&b.geometry){var a=b.geometry,d=this.map.spatialReference;d.equals(a.spatialReference)||(a=y.project(a,d),null==a?console.log("Unable to reproject features to map's spatial reference. Please convert feature geometry before adding to layer"):b.geometry=a)}},_doWorkerCalculation:function(){},_doMainCalculation:function(){var b=this.sourceLayer,a=this.map,d=this.heatmapRenderer,c=this.map.extent,p=this.map.width,e=this.map.height,g=this._calculator,h=this,m=function(f){f= h._getScreenPoints(f.features,a,b);f=g.calculateImageData(l.mixin({screenPoints:f,mapinfo:{extent:[c.xmin,c.ymin,c.xmax,c.ymax],resolution:a.getResolution()},width:p,height:e},h._getOptions()));f=d.getSymbol(C({geometry:a.extent,attributes:{size:[p,e],imageData:f},layer:b}));f=new z({extent:a.extent,href:f.url,opacity:0,sourceId:b.id});h._swapMapImages(f,h._getImageBySourceId(b.id));b.suspended&&f.hide()},k={geometry:a.extent,timeExtent:b.useMapTime?a.timeExtent:void 0,spatialRelationship:A.SPATIAL_REL_INTERSECTS}; null!=b._canDoClientSideQuery(k)?b.queryFeatures(k,m):m({features:b.graphics})},_getScreenPoints:function(b,a,d){var c=[],p=b.length,e=0,g=0,h,m=new x(a.extent.xmin,a.extent.ymax,a.spatialReference),k=a.toScreen(m),f=k.x,k=k.y,l=a.getResolution(),n;for((g=a.extent.getCacheValue("_parts"))&&(n=q.map(g,function(b){return d._intersects(a,b.extent)[0]}));p--;)g=b[p],g.geometry&&(h={x:Math.ceil((g.geometry.x-m.x)/l+f),y:Math.floor((m.y-g.geometry.y)/l-k),attributes:g.attributes},n&&(g=1<n.length&&h.x< -n[0]?n[1]:n[0],h.x+=g),c[e++]=h);return c},_getImageBySourceId:function(b){var a=this.imageLayer.getImages(),a=q.filter(a,function(a){return a.sourceId==b});if(a.length)return a[a.length-1]},_swapMapImages:function(b,a){function d(){c.removeImage(a)}var c=this.imageLayer,e=this.sourceLayer.opacity||1;c.addImage(b);s.anim(b._node,{opacity:e},null,null,function(){b.opacity=e});null!=a&&s.anim(a._node,{opacity:0},null,null,d)},_removeHandlers:function(){if(null!=this._hndls)for(var b=this._hndls.length;b--;)this._hndls[b].remove()}, _getOptions:function(){var b=this.heatmapRenderer;return{blurRadius:b.blurRadius,gradient:b.gradient,maxPixelIntensity:b.maxPixelIntensity,minPixelIntensity:b.minPixelIntensity,field:b.field,fieldOffset:b.fieldOffset}},_resetGraphics:function(){clearTimeout(this._resetTimer);this._resetTimer=null;for(var b=this.sourceLayer.graphics,a=b.length,d;a--;)d=b[a],d._shape=d._offsets=void 0}});w("extend-esri")&&l.setObject("layers.HeatmapManager",e,v);return e});
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { refType } from '@material-ui/utils'; import { useFormControl } from '../FormControl'; import withStyles from '../styles/withStyles'; import Typography from '../Typography'; import capitalize from '../utils/capitalize'; export var styles = function styles(theme) { return { /* Styles applied to the root element. */ root: { display: 'inline-flex', alignItems: 'center', cursor: 'pointer', // For correct alignment with the text. verticalAlign: 'middle', WebkitTapHighlightColor: 'transparent', marginLeft: -11, marginRight: 16, // used for row presentation of radio/checkbox '&$disabled': { cursor: 'default' } }, /* Styles applied to the root element if `labelPlacement="start"`. */ labelPlacementStart: { flexDirection: 'row-reverse', marginLeft: 16, // used for row presentation of radio/checkbox marginRight: -11 }, /* Styles applied to the root element if `labelPlacement="top"`. */ labelPlacementTop: { flexDirection: 'column-reverse', marginLeft: 16 }, /* Styles applied to the root element if `labelPlacement="bottom"`. */ labelPlacementBottom: { flexDirection: 'column', marginLeft: 16 }, /* Pseudo-class applied to the root element if `disabled={true}`. */ disabled: {}, /* Styles applied to the label's Typography component. */ label: { '&$disabled': { color: theme.palette.text.disabled } } }; }; /** * Drop in replacement of the `Radio`, `Switch` and `Checkbox` component. * Use this component if you want to display an extra label. */ var FormControlLabel = React.forwardRef(function FormControlLabel(props, ref) { var checked = props.checked, classes = props.classes, className = props.className, control = props.control, disabledProp = props.disabled, inputRef = props.inputRef, label = props.label, _props$labelPlacement = props.labelPlacement, labelPlacement = _props$labelPlacement === void 0 ? 'end' : _props$labelPlacement, name = props.name, onChange = props.onChange, value = props.value, other = _objectWithoutProperties(props, ["checked", "classes", "className", "control", "disabled", "inputRef", "label", "labelPlacement", "name", "onChange", "value"]); var muiFormControl = useFormControl(); var disabled = disabledProp; if (typeof disabled === 'undefined' && typeof control.props.disabled !== 'undefined') { disabled = control.props.disabled; } if (typeof disabled === 'undefined' && muiFormControl) { disabled = muiFormControl.disabled; } var controlProps = { disabled: disabled }; ['checked', 'name', 'onChange', 'value', 'inputRef'].forEach(function (key) { if (typeof control.props[key] === 'undefined' && typeof props[key] !== 'undefined') { controlProps[key] = props[key]; } }); return /*#__PURE__*/React.createElement("label", _extends({ className: clsx(classes.root, className, labelPlacement !== 'end' && classes["labelPlacement".concat(capitalize(labelPlacement))], disabled && classes.disabled), ref: ref }, other), React.cloneElement(control, controlProps), /*#__PURE__*/React.createElement(Typography, { component: "span", className: clsx(classes.label, disabled && classes.disabled) }, label)); }); process.env.NODE_ENV !== "production" ? FormControlLabel.propTypes = { /** * If `true`, the component appears selected. */ checked: PropTypes.bool, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * A control element. For instance, it can be be a `Radio`, a `Switch` or a `Checkbox`. */ control: PropTypes.element, /** * If `true`, the control will be disabled. */ disabled: PropTypes.bool, /** * Pass a ref to the `input` element. */ inputRef: refType, /** * The text to be used in an enclosing label element. */ label: PropTypes.node, /** * The position of the label. */ labelPlacement: PropTypes.oneOf(['end', 'start', 'top', 'bottom']), /* * @ignore */ name: PropTypes.string, /** * Callback fired when the state is changed. * * @param {object} event The event source of the callback. * You can pull out the new checked state by accessing `event.target.checked` (boolean). */ onChange: PropTypes.func, /** * The value of the component. */ value: PropTypes.any } : void 0; export default withStyles(styles, { name: 'MuiFormControlLabel' })(FormControlLabel);
import {Component, PropTypes} from 'react'; import ReactDOM from 'react-dom'; import events from '../utils/events'; const isDescendant = (el, target) => { if (target !== null) { return el === target || isDescendant(el, target.parentNode); } return false; }; const clickAwayEvents = ['mouseup', 'touchend']; const bind = (callback) => clickAwayEvents.forEach((event) => events.on(document, event, callback)); const unbind = (callback) => clickAwayEvents.forEach((event) => events.off(document, event, callback)); export default class ClickAwayListener extends Component { static propTypes = { children: PropTypes.node, onClickAway: PropTypes.any, }; componentDidMount() { this.isCurrentlyMounted = true; if (this.props.onClickAway) { bind(this.handleClickAway); } } componentDidUpdate(prevProps) { if (prevProps.onClickAway !== this.props.onClickAway) { unbind(this.handleClickAway); if (this.props.onClickAway) { bind(this.handleClickAway); } } } componentWillUnmount() { this.isCurrentlyMounted = false; unbind(this.handleClickAway); } handleClickAway = (event) => { if (event.defaultPrevented) { return; } // IE11 support, which trigger the handleClickAway even after the unbind if (this.isCurrentlyMounted) { const el = ReactDOM.findDOMNode(this); if (document.documentElement.contains(event.target) && !isDescendant(el, event.target)) { this.props.onClickAway(event); } } }; render() { return this.props.children; } }
/** * Component definition for frost-textarea component */ import FrostEventsProxyMixin from '../mixins/frost-events-proxy' import layout from '../templates/components/frost-textarea' import Component from './frost-component' import Ember from 'ember' import {task, timeout} from 'ember-concurrency' import {PropTypes} from 'ember-prop-types' const {isPresent, on} = Ember export default Component.extend(FrostEventsProxyMixin, { // == Dependencies ========================================================== // == Keyword Properties ==================================================== classNameBindings: [ 'isClearVisible', 'isClearEnabled' ], layout, // == PropTypes ============================================================= propTypes: { // options autofocus: PropTypes.bool, cols: PropTypes.number, disabled: PropTypes.bool, form: PropTypes.string, isClearEnabled: PropTypes.bool, isClearVisible: PropTypes.bool, onClear: PropTypes.func, placeholder: PropTypes.string, readonly: PropTypes.bool, rows: PropTypes.number, tabindex: PropTypes.number, value: PropTypes.string, wrap: PropTypes.string // state }, getDefaultProps () { return { // options autofocus: false, isClearEnabled: false, isClearVisible: false, disabled: false, readonly: false, tabindex: 0, // Setting these as part of establishing an initial value cols: null, form: null, rows: null, placeholder: null, value: null, wrap: 'soft' // state } }, // == Computed Properties =================================================== // == Functions ============================================================= // == Tasks ================================================================== _clear: task(function * () { this.$('textarea') .focus() .val('') .trigger('input') if (this.onClear) { this.onClear() } }).restartable(), _showClear: task(function * (isFocused) { const showClear = isFocused && isPresent(this.get('value')) && !this.get('readonly') if (this.get('isClearVisible') === showClear) { return } this.set('isClearVisible', showClear) // If the clear button is clicked the focusOut event occurs before // the click event, so delay disabling the clear so that the click // can process first if (!showClear) { yield timeout(200) // Duration of the visibility animation } this.set('isClearEnabled', showClear) }).restartable(), // == DOM Events ============================================================ _showClearEvent: on('focusIn', 'focusOut', 'input', function (event) { const isFocused = event.type !== 'focusout' this.get('_showClear').perform(isFocused) }), // == Lifecycle Hooks ======================================================= // == Actions =============================================================== actions: { clear () { this.get('_clear').perform() }, // Setting 'keyUp' directly on the {{input}} helper overwrites // Ember's TextSupport keyUp property, which means that other // TextSupport events (i.e. 'enter' and 'escape') don't fire. // To avoid this, we use the TextSupport 'key-up' event and // proxy the event to the keyUp handler. keyUp (value, event) { if (isPresent(this.get('_eventProxy.keyUp'))) { this._eventProxy.keyUp(event) } }, _onInput (event) { if (isPresent(this.get('_eventProxy.input'))) { // Add id and value for legacy support event.id = this.get('elementId') event.value = event.target.value this._eventProxy.input(event) } } } })
process.on('uncaughtException', (err) => { console.error(err); process.exit(1); }); const { autoUpdater } = require('electron'); autoUpdater.on('error', (err) => { console.error(err); process.exit(1); }); const feedUrl = process.argv[1]; autoUpdater.setFeedURL({ url: feedUrl, headers: { 'X-test': 'this-is-a-test' } }); autoUpdater.checkForUpdates(); autoUpdater.on('update-not-available', () => { process.exit(0); });
/* * Copyright (c) 2014 - present Adobe Systems Incorporated. All rights reserved. * * 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. * */ /** * Pane objects host views of files, editors, etc... Clients cannot access * Pane objects directly. Instead the implementation is protected by the * MainViewManager -- however View Factories are given a Pane object which * they can use to add views. References to Pane objects should not be kept * as they may be destroyed and removed from the DOM. * * To get a custom view, there are two components: * * 1) A View Factory * 2) A View Object * * View objects are anonymous object that have a particular interface. * * Views can be added to a pane but do not have to exist in the Pane object's view list. * Such views are "temporary views". Temporary views are not serialized with the Pane state * or reconstituted when the pane is serialized from disk. They are destroyed at the earliest * opportunity. * * Temporary views are added by calling `Pane.showView()` and passing it the view object. The view * will be destroyed when the next view is shown, the pane is mereged with another pane or the "Close All" * command is exectuted on the Pane. Temporary Editor Views do not contain any modifications and are * added to the workingset (and are no longer tempoary views) once the document has been modified. They * will remain in the working set until closed from that point on. * * Views that have a longer life span are added by calling addView to associate the view with a * filename in the _views object. These views are not destroyed until they are removed from the pane * by calling one of the following: removeView, removeViews, or _reset * * Pane Object Events: * * - viewListChange - Whenever there is a file change to a file in the working set. These 2 events: `DocumentManager.pathRemove` * and `DocumentManager.fileNameChange` will cause a `viewListChange` event so the WorkingSetView can update. * * - currentViewChange - Whenever the current view changes. * (e, newView:View, oldView:View) * * - viewDestroy - Whenever a view has been destroyed * (e, view:View) * * View Interface: * * The view is an anonymous object which has the following method signatures. see ImageViewer for an example or the sample * provided with Brackets `src/extensions/samples/BracketsConfigCentral` * * { * $el:jQuery * getFile: function ():!File * updateLayout: function(forceRefresh:boolean) * destroy: function() * getScrollPos: function():*= * adjustScrollPos: function(state:Object=, heightDelta:number)= * notifyContainerChange: function()= * notifyVisibilityChange: function(boolean)= * focus:function()= * } * * When views are created they can be added to the pane by calling `pane.addView()`. * Views can be created and parented by attaching directly to `pane.$el` * * this._codeMirror = new CodeMirror(pane.$el, ...) * * Factories can create a view that's initially hidden by calling `pane.addView(view)` and passing `false` for the show parameter. * Hidden views can be later shown by calling `pane.showView(view)` * * `$el:jQuery!` * * property that stores the jQuery wrapped DOM element of the view. All views must have one so pane objects can manipulate the DOM * element when necessary (e.g. `showView`, `_reparent`, etc...) * * `getFile():File!` * * Called throughout the life of a View when the current file is queried by the system. * * `updateLayout(forceRefresh:boolean)` * * Called to notify the view that it should be resized to fit its parent container. This may be called several times * or only once. Views can ignore the `forceRefresh` flag. It is used for editor views to force a relayout of the editor * which probably isn't necessary for most views. Views should implement their html to be dynamic and not rely on this * function to be called whenever possible. * * `destroy()` * * Views must implement a destroy method to remove their DOM element at the very least. There is no default * implementation and views are hidden before this method is called. The Pane object doesn't make assumptions * about when it is safe to remove a node. In some instances other cleanup must take place before a the DOM * node is destroyed so the implementation details are left to the view. * * Views can implement a simple destroy by calling * * this.$el.remove() * * These members are optional and need not be implemented by Views * * getScrollPos() * adjustScrollPos() * * The system at various times will want to save and restore a view's scroll position. The data returned by `getScrollPos()` * is specific to the view and will be passed back to `adjustScrollPos()` when the scroll position needs to be restored. * * When Modal Bars are invoked, the system calls `getScrollPos()` so that the current scroll psotion of all visible Views can be cached. * That cached scroll position is later passed to `adjustScrollPos()` along with a height delta. The height delta is used to * scroll the view so that it doesn't appear to have "jumped" when invoking the Modal Bar. * * Height delta will be a positive when the Modal Bar is being shown and negative number when the Modal Bar is being hidden. * * `getViewState()` is another optional member that is used to cache a view's state when hiding or destroying a view or closing the project. * The data returned by this member is stored in `ViewStateManager` and is saved with the project. * * Views or View Factories are responsible for restoring the view state when the view of that file is created by recalling the cached state * * var view = createIconView(file, pane); * view.restoreViewState(ViewStateManager.getViewState(file.fullPath)); * * Notifications * The following optional methods receive notifications from the Pane object when certain events take place which affect the view: * * `notifyContainerChange()` * * Optional Notification callback called when the container changes. The view can perform any synchronization or state update * it needs to do when its parent container changes. * * `notifyVisiblityChange()` * * Optional Notification callback called when the view's vsibility changes. The view can perform any synchronization or * state update it needs to do when its visiblity state changes. */ define(function (require, exports, module) { "use strict"; var _ = require("thirdparty/lodash"), Mustache = require("thirdparty/mustache/mustache"), EventDispatcher = require("utils/EventDispatcher"), FileSystem = require("filesystem/FileSystem"), InMemoryFile = require("document/InMemoryFile"), ViewStateManager = require("view/ViewStateManager"), MainViewManager = require("view/MainViewManager"), PreferencesManager = require("preferences/PreferencesManager"), DocumentManager = require("document/DocumentManager"), CommandManager = require("command/CommandManager"), Commands = require("command/Commands"), Strings = require("strings"), StringUtils = require("utils/StringUtils"), ViewUtils = require("utils/ViewUtils"), ProjectManager = require("project/ProjectManager"), paneTemplate = require("text!htmlContent/pane.html"); /** * Internal pane id * @const * @private */ var FIRST_PANE = "first-pane"; /** * Internal pane id * @const * @private */ var SECOND_PANE = "second-pane"; // Define showPaneHeaderButtons, which controls when to show close and flip-view buttons // on the header. PreferencesManager.definePreference("pane.showPaneHeaderButtons", "string", "hover", { description: Strings.DESCRIPTION_SHOW_PANE_HEADER_BUTTONS, values: ["hover", "always", "never"] }); // Define mergePanesWhenLastFileClosed, which controls if a split view pane should be // closed when the last file is closed, skipping the "Open a file while this pane has focus" // step completely. PreferencesManager.definePreference("pane.mergePanesWhenLastFileClosed", "boolean", false, { description: Strings.DESCRIPTION_MERGE_PANES_WHEN_LAST_FILE_CLOSED }); /** * Make an index request object * @param {boolean} requestIndex - true to request an index, false if not * @param {number} index - the index to request * @return {indexRequested:boolean, index:number} an object that can be passed to * {@link Pane#addToViewList} to insert the item at a specific index * @see Pane#addToViewList */ function _makeIndexRequestObject(requestIndex, index) { return {indexRequested: requestIndex, index: index}; } /** * Ensures that the given pane is focused after other focus related events occur * @params {string} paneId - paneId of the pane to focus * @private */ function _ensurePaneIsFocused(paneId) { var pane = MainViewManager._getPane(paneId); // Defer the focusing until other focus events have occurred. setTimeout(function () { // Focus has most likely changed: give it back to the given pane. pane.focus(); this._lastFocusedElement = pane.$el[0]; MainViewManager.setActivePaneId(paneId); }, 1); } /** * @typedef {!$el: jQuery, getFile:function():!File, updateLayout:function(forceRefresh:boolean), destroy:function(), getScrollPos:function():?, adjustScrollPos:function(state:Object=, heightDelta:number)=, getViewState:function():?*=, restoreViewState:function(viewState:!*)=, notifyContainerChange:function()=, notifyVisibilityChange:function(boolean)=} View */ /** * Pane Objects are constructed by the MainViewManager object when a Pane view is needed * @see {@link MainViewManager} for more information * * @constructor * @param {!string} id - The id to use to identify this pane * @param {!JQuery} $container - The parent $container to place the pane view */ function Pane(id, $container) { this._initialize(); // Setup the container and the element we're inserting var self = this, showPaneHeaderButtonsPref = PreferencesManager.get("pane.showPaneHeaderButtons"), $el = $container.append(Mustache.render(paneTemplate, {id: id})).find("#" + id), $header = $el.find(".pane-header"), $headerText = $header.find(".pane-header-text"), $headerFlipViewBtn = $header.find(".pane-header-flipview-btn"), $headerCloseBtn = $header.find(".pane-header-close-btn"), $content = $el.find(".pane-content"); $el.on("focusin.pane", function (e) { self._lastFocusedElement = e.target; }); // Flips the current file to the other pane when clicked $headerFlipViewBtn.on("click.pane", function (e) { var currentFile = self.getCurrentlyViewedFile(); var otherPaneId = self.id === FIRST_PANE ? SECOND_PANE : FIRST_PANE; var otherPane = MainViewManager._getPane(otherPaneId); var sameDocInOtherView = otherPane.getViewForPath(currentFile.fullPath); // If the same doc view is present in the destination, show the file instead of flipping it if (sameDocInOtherView) { CommandManager.execute(Commands.FILE_OPEN, {fullPath: currentFile.fullPath, paneId: otherPaneId}).always(function () { _ensurePaneIsFocused(otherPaneId); }); return; } // Currently active pane is not necessarily self.id as just clicking the button does not // give focus to the pane. This way it is possible to flip multiple panes to the active one // without losing focus. var activePaneIdBeforeFlip = MainViewManager.getActivePaneId(); MainViewManager._moveView(self.id, otherPaneId, currentFile).always(function () { CommandManager.execute(Commands.FILE_OPEN, {fullPath: currentFile.fullPath, paneId: otherPaneId}).always(function () { // Trigger view list changes for both panes self.trigger("viewListChange"); otherPane.trigger("viewListChange"); _ensurePaneIsFocused(activePaneIdBeforeFlip); }); }); }); // Closes the current view on the pane when clicked. If pane has no files, merge // panes. $headerCloseBtn.on("click.pane", function () { //set clicked pane as active to ensure that this._currentView is updated before closing MainViewManager.setActivePaneId(self.id); var file = self.getCurrentlyViewedFile(); if (file) { CommandManager.execute(Commands.FILE_CLOSE, {File: file, paneId: self.id}); if (!self.getCurrentlyViewedFile() && PreferencesManager.get("pane.mergePanesWhenLastFileClosed")) { MainViewManager.setLayoutScheme(1, 1); } } else { MainViewManager.setLayoutScheme(1, 1); } }); this._lastFocusedElement = $el[0]; // Make these properties read only Object.defineProperty(this, "id", { get: function () { return id; }, set: function () { console.error("cannot change the id of a working pane"); } }); Object.defineProperty(this, "$el", { get: function () { return $el; }, set: function () { console.error("cannot change the DOM node of a working pane"); } }); Object.defineProperty(this, "$header", { get: function () { return $header; }, set: function () { console.error("cannot change the DOM node of a working pane"); } }); Object.defineProperty(this, "$headerText", { get: function () { return $headerText; }, set: function () { console.error("cannot change the DOM node of a working pane"); } }); Object.defineProperty(this, "$headerFlipViewBtn", { get: function () { return $headerFlipViewBtn; }, set: function () { console.error("cannot change the DOM node of a working pane"); } }); Object.defineProperty(this, "$headerCloseBtn", { get: function () { return $headerCloseBtn; }, set: function () { console.error("cannot change the DOM node of a working pane"); } }); Object.defineProperty(this, "$content", { get: function () { return $content; }, set: function () { console.error("cannot change the DOM node of a working pane"); } }); Object.defineProperty(this, "$container", { get: function () { return $container; }, set: function () { console.error("cannot change the DOM node of a working pane"); } }); this.updateHeaderText(); switch (showPaneHeaderButtonsPref) { case "always": this.$header.addClass("always-show-header-buttons"); break; case "never": this.$headerFlipViewBtn.css("display", "none"); this.$headerCloseBtn.css("display", "none"); break; } // Listen to document events so we can update ourself DocumentManager.on(this._makeEventName("fileNameChange"), _.bind(this._handleFileNameChange, this)); DocumentManager.on(this._makeEventName("pathDeleted"), _.bind(this._handleFileDeleted, this)); MainViewManager.on(this._makeEventName("activePaneChange"), _.bind(this._handleActivePaneChange, this)); MainViewManager.on(this._makeEventName("workingSetAdd"), _.bind(this.updateHeaderText, this)); MainViewManager.on(this._makeEventName("workingSetRemove"), _.bind(this.updateHeaderText, this)); MainViewManager.on(this._makeEventName("workingSetAddList"), _.bind(this.updateHeaderText, this)); MainViewManager.on(this._makeEventName("workingSetRemoveList"), _.bind(this.updateHeaderText, this)); MainViewManager.on(this._makeEventName("paneLayoutChange"), _.bind(this.updateFlipViewIcon, this)); } EventDispatcher.makeEventDispatcher(Pane.prototype); /** * id of the pane * @readonly * @type {!string} */ Pane.prototype.id = null; /** * container where the pane lives * @readonly * @type {JQuery} */ Pane.prototype.$container = null; /** * the wrapped DOM node of this pane * @readonly * @type {JQuery} */ Pane.prototype.$el = null; /** * the wrapped DOM node container that contains name of current view and the switch view button, or informational string if there is no view * @readonly * @type {JQuery} */ Pane.prototype.$header = null; /** * the wrapped DOM node that contains name of current view, or informational string if there is no view * @readonly * @type {JQuery} */ Pane.prototype.$headerText = null; /** * the wrapped DOM node that is used to flip the view to another pane * @readonly * @type {JQuery} */ Pane.prototype.$headerFlipViewBtn = null; /** * close button of the pane * @readonly * @type {JQuery} */ Pane.prototype.$headerCloseBtn = null; /** * the wrapped DOM node that contains views * @readonly * @type {JQuery} */ Pane.prototype.$content = null; /** * The list of files views * @type {Array.<File>} */ Pane.prototype._viewList = []; /** * The list of files views in MRU order * @type {Array.<File>} */ Pane.prototype._viewListMRUOrder = []; /** * The list of files views in Added order * @type {Array.<File>} */ Pane.prototype._viewListAddedOrder = []; /** * Dictionary mapping fullpath to view * @type {Object.<!string, !View>} * @private */ Pane.prototype._views = {}; /** * The current view * @type {?View} * @private */ Pane.prototype._currentView = null; /** * The last thing that received a focus event * @type {?DomElement} * @private */ Pane.prototype._lastFocusedElement = null; /** * Initializes the Pane to its default state * @private */ Pane.prototype._initialize = function () { this._viewList = []; this._viewListMRUOrder = []; this._viewListAddedOrder = []; this._views = {}; this._currentView = null; this.showInterstitial(true); }; /** * Creates a pane event namespaced to this pane * (pass an empty string to generate just the namespace key to pass to jQuery to turn off all events handled by this pane) * @private * @param {!string} name - the name of the event to namespace * @return {string} an event namespaced to this pane */ Pane.prototype._makeEventName = function (name) { return name + ".pane-" + this.id; }; /** * Reparents a view to this pane * @private * @param {!View} view - the view to reparent */ Pane.prototype._reparent = function (view) { view.$el.appendTo(this.$content); this._views[view.getFile().fullPath] = view; if (view.notifyContainerChange) { view.notifyContainerChange(); } }; /** * Hides the current view if there is one, shows the * interstitial screen and notifies that the view changed */ Pane.prototype._hideCurrentView = function () { if (this._currentView) { var currentView = this._currentView; this._setViewVisibility(this._currentView, false); this.showInterstitial(true); this._currentView = null; this._notifyCurrentViewChange(null, currentView); } }; /** * moves a view from one pane to another * @param {!File} file - the File to move * @param {Pane} destinationPane - the destination pane * @param {Number} destinationIndex - the working set index of the file in the destination pane * @return {jQuery.Promise} a promise object which resolves after the view has been moved and its * replacement document has been opened * @private */ Pane.prototype.moveView = function (file, destinationPane, destinationIndex) { var self = this, openNextPromise = new $.Deferred(), result = new $.Deferred(); // if we're moving the currently viewed file we // need to open another file so wait for that operation // to finish before we move the view if ((this.getCurrentlyViewedPath() === file.fullPath)) { var nextFile = this.traverseViewListByMRU(1, file.fullPath); if (nextFile) { this._execOpenFile(nextFile.fullPath) .fail(function () { // the FILE_OPEN failed self._hideCurrentView(); }) .always(function () { openNextPromise.resolve(); }); } else { this._hideCurrentView(); openNextPromise.resolve(); } } else { openNextPromise.resolve(); } // Once the next file has opened, we can // move the item in the working set and // open it in the destination pane openNextPromise.done(function () { var viewListIndex = self.findInViewList(file.fullPath); var shouldAddView = viewListIndex !== -1; var view = self._views[file.fullPath]; // If the file isn't in working set, destroy the view and delete it from // source pane's view map and return as solved if (!shouldAddView) { if (view) { self._doDestroyView(view); } return result.resolve(); } // Remove file from all 3 view lists self._viewList.splice(viewListIndex, 1); self._viewListMRUOrder.splice(self.findInViewListMRUOrder(file.fullPath), 1); self._viewListAddedOrder.splice(self.findInViewListAddedOrder(file.fullPath), 1); // insert the view into the working set destinationPane._addToViewList(file, _makeIndexRequestObject(true, destinationIndex)); // if we had a view, it had previously been opened // otherwise, the file was in the working set unopened if (view) { // delete it from the source pane's view map and add it to the destination pane's view map delete self._views[file.fullPath]; destinationPane.addView(view, !destinationPane.getCurrentlyViewedFile()); // we're done result.resolve(); } else if (!destinationPane.getCurrentlyViewedFile()) { // The view has not have been created and the pane was // not showing anything so open the file moved in to the pane destinationPane._execOpenFile(file.fullPath).always(function () { // wait until the file has been opened before // we resolve the promise so the working set // view can sync appropriately result.resolve(); }); } else { // nothing to do, we're done result.resolve(); } }); return result.promise(); }; /** * Merges the another Pane object's contents into this Pane * @param {!Pane} Other - Pane from which to copy */ Pane.prototype.mergeFrom = function (other) { // save this because we're setting it to null and we // may need to destroy it if it's a temporary view var otherCurrentView = other._currentView; // Hide the current view while we // merge the 2 panes together other._hideCurrentView(); // Copy the File lists this._viewList = _.union(this._viewList, other._viewList); this._viewListMRUOrder = _.union(this._viewListMRUOrder, other._viewListMRUOrder); this._viewListAddedOrder = _.union(this._viewListAddedOrder, other._viewListAddedOrder); var self = this, viewsToDestroy = []; // Copy the views _.forEach(other._views, function (view) { var file = view.getFile(), fullPath = file && file.fullPath; if (fullPath && other.findInViewList(fullPath) !== -1) { // switch the container to this Pane self._reparent(view); } else { // We don't copy temporary views so destroy them viewsToDestroy.push(view); } }); // 1-off views if (otherCurrentView && !other._isViewNeeded(otherCurrentView) && viewsToDestroy.indexOf(otherCurrentView) === -1) { viewsToDestroy.push(otherCurrentView); } // Destroy temporary views _.forEach(viewsToDestroy, function (view) { self.trigger("viewDestroy", view); view.destroy(); }); // this _reset all internal data structures // and will set the current view to null other._initialize(); }; /** * Removes the DOM node for the Pane, removes all * event handlers and _resets all internal data structures */ Pane.prototype.destroy = function () { if (this._currentView || Object.keys(this._views).length > 0 || this._viewList.length > 0) { console.warn("destroying a pane that isn't empty"); } this._reset(); DocumentManager.off(this._makeEventName("")); MainViewManager.off(this._makeEventName("")); this.$el.off(".pane"); this.$el.remove(); }; /** * Returns a copy of the view file list * @return {!Array.<File>} */ Pane.prototype.getViewList = function () { return _.clone(this._viewList); }; /** * Returns the number of entries in the view file list * @return {number} */ Pane.prototype.getViewListSize = function () { return this._viewList.length; }; /** * Returns the index of the item in the view file list * @param {!string} fullPath the full path of the item to look for * @return {number} index of the item or -1 if not found */ Pane.prototype.findInViewList = function (fullPath) { return _.findIndex(this._viewList, function (file) { return file.fullPath === fullPath; }); }; /** * Returns the order in which the item was added * @param {!string} fullPath the full path of the item to look for * @return {number} order of the item or -1 if not found */ Pane.prototype.findInViewListAddedOrder = function (fullPath) { return _.findIndex(this._viewListAddedOrder, function (file) { return file.fullPath === fullPath; }); }; /** * Returns the order in which the item was last used * @param {!string} fullPath the full path of the item to look for * @return {number} order of the item or -1 if not found. * 0 indicates most recently used, followed by 1 and so on... */ Pane.prototype.findInViewListMRUOrder = function (fullPath) { return _.findIndex(this._viewListMRUOrder, function (file) { return file.fullPath === fullPath; }); }; /** * Return value from reorderItem when the Item was not found * @see {@link Pane#reorderItem} * @const */ Pane.prototype.ITEM_NOT_FOUND = -1; /** * Return value from reorderItem when the Item was found at its natural index * and the workingset does not need to be resorted * @see {@link Pane#reorderItem} * @const */ Pane.prototype.ITEM_FOUND_NO_SORT = 0; /** * Return value from reorderItem when the Item was found and reindexed * and the workingset needs to be resorted * @see {@link Pane#reorderItem} * @const */ Pane.prototype.ITEM_FOUND_NEEDS_SORT = 1; /** * reorders the specified file in the view list to the desired position * * @param {File} file - the file object of the item to reorder * @param {number=} index - the new position of the item * @param {boolean=} force - true to force the item into that position, false otherwise. (Requires an index be requested) * @return {number} this function returns one of the following manifest constants: * ITEM_NOT_FOUND : The request file object was not found * ITEM_FOUND_NO_SORT : The request file object was found but it was already at the requested index * ITEM_FOUND_NEEDS_SORT : The request file object was found and moved to a new index and the list should be resorted */ Pane.prototype.reorderItem = function (file, index, force) { var indexRequested = (index !== undefined && index !== null && index >= 0), curIndex = this.findInViewList(file.fullPath); if (curIndex !== -1) { // File is in view list, but not at the specifically requested index - only need to reorder if (force || (indexRequested && curIndex !== index)) { var entry = this._viewList.splice(curIndex, 1)[0]; this._viewList.splice(index, 0, entry); return this.ITEM_FOUND_NEEDS_SORT; } return this.ITEM_FOUND_NO_SORT; } return this.ITEM_NOT_FOUND; }; /** * Determines if a file can be added to our file list * @private * @param {!File} file - file object to test * @return {boolean} true if it can be added, false if not */ Pane.prototype._canAddFile = function (file) { return ((this._views.hasOwnProperty(file.fullPath) && this.findInViewList(file.fullPath) === -1) || (MainViewManager._getPaneIdForPath(file.fullPath) !== this.id)); }; /** * Adds the given file to the end of the workingset, if it is not already in the list * @private * @param {!File} file * @param {Object=} inPlace record with inPlace add data (index, indexRequested). Used internally */ Pane.prototype._addToViewList = function (file, inPlace) { if (inPlace && inPlace.indexRequested) { // If specified, insert into the workingset at this 0-based index this._viewList.splice(inPlace.index, 0, file); } else { // If no index is specified, just add the file to the end of the workingset. this._viewList.push(file); } // Add to MRU order: either first or last, depending on whether it's already the current doc or not var currentPath = this.getCurrentlyViewedPath(); if (currentPath && currentPath === file.fullPath) { this._viewListMRUOrder.unshift(file); } else { this._viewListMRUOrder.push(file); } // Add first to Added order this._viewListAddedOrder.unshift(file); }; /** * Adds the given file to the end of the workingset, if it is not already in the list * Does not change which document is currently open in the editor. Completes synchronously. * @param {!File} file - file to add * @param {number=} index - position where to add the item * @return {number} index of where the item was added */ Pane.prototype.addToViewList = function (file, index) { var indexRequested = (index !== undefined && index !== null && index >= 0 && index < this._viewList.length); this._addToViewList(file, _makeIndexRequestObject(indexRequested, index)); if (!indexRequested) { index = this._viewList.length - 1; } return index; }; /** * Adds the given file list to the end of the workingset. * @param {!Array.<File>} fileList * @return {!Array.<File>} list of files added to the list */ Pane.prototype.addListToViewList = function (fileList) { var self = this, uniqueFileList = []; // Process only files not already in view list fileList.forEach(function (file) { if (self._canAddFile(file)) { self._addToViewList(file); uniqueFileList.push(file); } }); return uniqueFileList; }; /** * Dispatches a currentViewChange event * @param {?View} newView - the view become the current view * @param {?View} oldView - the view being replaced */ Pane.prototype._notifyCurrentViewChange = function (newView, oldView) { this.updateHeaderText(); this.trigger("currentViewChange", newView, oldView); }; /** * Destroys a view and removes it from the view map. If it is the current view then the view * is first hidden and the interstitial page is displayed * @private * @param {!View} view - view to destroy */ Pane.prototype._doDestroyView = function (view) { if (this._currentView === view) { // if we're removing the current // view then we need to hide the view this._hideCurrentView(); } delete this._views[view.getFile().fullPath]; this.trigger("viewDestroy", view); view.destroy(); }; /** * Removes the specifed file from all internal lists, destroys the view of the file (if there is one) * and shows the interstitial page if the current view is destroyed * @private * @param {!File} file - file to remove * @param {boolean} preventViewChange - false to hide the current view if removing the current view, true * to prevent the current view from changing. * * When passing true for preventViewChange, it is assumed that the caller will perform an OPEN_FILE op * to show the next file in line to view. Since the file was removed from the workingset in _doRemove * its view is now considered to be a temporary view and the call to showView for the OPEN_FILE op * will destroy the view. the caller needs to handle the reject case in the event of failure * * @return {boolean} true if removed, false if the file was not found either in a list or view */ Pane.prototype._doRemove = function (file, preventViewChange) { // If it's in the view list then we need to remove it var index = this.findInViewList(file.fullPath); if (index > -1) { // Remove it from all 3 view lists this._viewList.splice(index, 1); this._viewListMRUOrder.splice(this.findInViewListMRUOrder(file.fullPath), 1); this._viewListAddedOrder.splice(this.findInViewListAddedOrder(file.fullPath), 1); } // Destroy the view var view = this._views[file.fullPath]; if (view) { if (!preventViewChange) { this._doDestroyView(view); } } return ((index > -1) || Boolean(view)); }; /** * Moves the specified file to the front of the MRU list * @param {!File} file */ Pane.prototype.makeViewMostRecent = function (file) { var index = this.findInViewListMRUOrder(file.fullPath); if (index !== -1) { this._viewListMRUOrder.splice(index, 1); this._viewListMRUOrder.unshift(file); } }; /** * Sorts items in the pane's view list * @param {function(paneId:!string, left:!string, right:!string):number} compareFn - the function used to compare items in the viewList */ /** * invokes Array.sort method on the internal view list. * @param {sortFunctionCallback} compareFn - the function to call to determine if the */ Pane.prototype.sortViewList = function (compareFn) { this._viewList.sort(_.partial(compareFn, this.id)); }; /** * moves a working set item from one index to another shifting the items * after in the working set up and reinserting it at the desired location * @param {!number} fromIndex - the index of the item to move * @param {!number} toIndex - the index to move to * @private */ Pane.prototype.moveWorkingSetItem = function (fromIndex, toIndex) { this._viewList.splice(toIndex, 0, this._viewList.splice(fromIndex, 1)[0]); }; /** * Swaps two items in the file view list (used while dragging items in the working set view) * @param {number} index1 - the index of the first item to swap * @param {number} index2 - the index of the second item to swap * @return {boolean}} true */ Pane.prototype.swapViewListIndexes = function (index1, index2) { var temp = this._viewList[index1]; this._viewList[index1] = this._viewList[index2]; this._viewList[index2] = temp; return true; }; /** * Traverses the list and returns the File object of the next item in the MRU order * @param {!number} direction - Must be 1 or -1 to traverse forward or backward * @param {string=} current - the fullPath of the item where traversal is to start. * If this parameter is omitted then the path of the current view is used. * If the current view is a temporary view then the first item in the MRU list is returned * @return {?File} The File object of the next item in the travesal order or null if there isn't one. */ Pane.prototype.traverseViewListByMRU = function (direction, current) { if (!current && this._currentView) { var file = this._currentView.getFile(); current = file && file.fullPath; } var index = current ? this.findInViewListMRUOrder(current) : -1; return ViewUtils.traverseViewArray(this._viewListMRUOrder, index, direction); }; /** * Updates flipview icon in pane header * @private */ Pane.prototype.updateFlipViewIcon = function () { var paneID = this.id, directionIndex = 0, ICON_CLASSES = ["flipview-icon-none", "flipview-icon-top", "flipview-icon-right", "flipview-icon-bottom", "flipview-icon-left"], DIRECTION_STRINGS = ["", Strings.TOP, Strings.RIGHT, Strings.BOTTOM, Strings.LEFT], layoutScheme = MainViewManager.getLayoutScheme(), hasFile = this.getCurrentlyViewedFile(); if (layoutScheme.columns > 1 && hasFile) { directionIndex = paneID === FIRST_PANE ? 2 : 4; } else if (layoutScheme.rows > 1 && hasFile) { directionIndex = paneID === FIRST_PANE ? 3 : 1; } this.$headerFlipViewBtn.removeClass(ICON_CLASSES.join(" ")) .addClass(ICON_CLASSES[directionIndex]); this.$headerFlipViewBtn.attr("title", StringUtils.format(Strings.FLIPVIEW_BTN_TOOLTIP, DIRECTION_STRINGS[directionIndex].toLowerCase())); }; /** * Updates text in pane header * @private */ Pane.prototype.updateHeaderText = function () { var file = this.getCurrentlyViewedFile(), files, displayName; if (file) { files = MainViewManager.getAllOpenFiles().filter(function (item) { return (item.name === file.name); }); if (files.length < 2) { this.$headerText.text(file.name); } else { displayName = ProjectManager.makeProjectRelativeIfPossible(file.fullPath); this.$headerText.text(displayName); } } else { this.$headerText.html(Strings.EMPTY_VIEW_HEADER); } this.updateFlipViewIcon(); }; /** * Event handler when a file changes name * @private * @param {!JQuery.Event} e - jQuery event object * @param {!string} oldname - path of the file that was renamed * @param {!string} newname - the new path to the file */ Pane.prototype._handleFileNameChange = function (e, oldname, newname) { // Check to see if we need to dispatch a viewListChange event // The list contains references to file objects and, for a rename event, // the File object's name has changed by the time we've gotten the event. // So, we need to look for the file by its new name to determine if // if we need to dispatch the event which may look funny var dispatchEvent = (this.findInViewList(newname) >= 0); // rename the view if (this._views.hasOwnProperty(oldname)) { var view = this._views[oldname]; this._views[newname] = view; delete this._views[oldname]; } this.updateHeaderText(); // dispatch the change event if (dispatchEvent) { this.trigger("viewListChange"); } }; /** * Event handler when a file is deleted * @private * @param {!JQuery.Event} e - jQuery event object * @param {!string} fullPath - path of the file that was deleted */ Pane.prototype._handleFileDeleted = function (e, fullPath) { if (this.removeView({fullPath: fullPath})) { this.trigger("viewListChange"); } }; /** * Shows the pane's interstitial page * @param {boolean} show - show or hide the interstitial page */ Pane.prototype.showInterstitial = function (show) { if (this.$content) { this.$content.find(".not-editor").css("display", (show) ? "" : "none"); } }; /** * retrieves the view object for the given path * @param {!string} path - the fullPath of the view to retrieve * @return {boolean} show - show or hide the interstitial page */ Pane.prototype.getViewForPath = function (path) { return this._views[path]; }; /** * Adds a view to the pane * @param {!View} view - the View object to add * @param {boolean} show - true to show the view right away, false otherwise */ Pane.prototype.addView = function (view, show) { var file = view.getFile(), path = file && file.fullPath; if (!path) { console.error("cannot add a view that does not have a fullPath"); return; } if (view.$el.parent() !== this.$content) { this._reparent(view); } else { this._views[path] = view; } // Ensure that we don't endup marking the custom views if (view.markPaneId) { view.markPaneId(this.id); } if (show) { this.showView(view); } }; /** * Shows or hides a view * @param {!View} view - the to show or hide * @param {boolean} visible - true to show the view, false to hide it * @private */ Pane.prototype._setViewVisibility = function (view, visible) { view.$el.css("display", (visible ? "" : "none")); if (view.notifyVisibilityChange) { view.notifyVisibilityChange(visible); } }; /** * Swaps the current view with the requested view. * If the interstitial page is shown, it is hidden. * If the currentView is a temporary view, it is destroyed. * @param {!View} view - the to show */ Pane.prototype.showView = function (view) { if (this._currentView && this._currentView === view) { this._setViewVisibility(this._currentView, true); this.updateLayout(true); return; } var file = view.getFile(), newPath = file && file.fullPath, oldView = this._currentView; if (this._currentView) { if (this._currentView.getFile()) { ViewStateManager.updateViewState(this._currentView); } this._setViewVisibility(this._currentView, false); } else { this.showInterstitial(false); } this._currentView = view; this._setViewVisibility(this._currentView, true); this.updateLayout(); this._notifyCurrentViewChange(view, oldView); if (oldView) { this.destroyViewIfNotNeeded(oldView); } if (!this._views.hasOwnProperty(newPath)) { console.error(newPath + " found in pane working set but pane.addView() has not been called for the view created for it"); } }; /** * Update header and content height */ Pane.prototype._updateHeaderHeight = function () { var paneContentHeight = this.$el.height(); // Adjust pane content height for header if (MainViewManager.getPaneCount() > 1) { this.$header.show(); paneContentHeight -= this.$header.outerHeight(); } else { this.$header.hide(); } this.$content.height(paneContentHeight); }; /** * Sets pane content height. Updates the layout causing the current view to redraw itself * @param {boolean} forceRefresh - true to force a resize and refresh of the current view, * false if just to resize forceRefresh is only used by Editor views to force a relayout * of all editor DOM elements. Custom View implementations should just ignore this flag. */ Pane.prototype.updateLayout = function (forceRefresh) { this._updateHeaderHeight(); if (this._currentView) { this._currentView.updateLayout(forceRefresh); } }; /** * Determines if the view can be disposed of * @private * @param {!View} view - the View object to test * @return {boolean}} true if the view can be disposed, false if not */ Pane.prototype._isViewNeeded = function (view) { var path = view.getFile().fullPath, currentPath = this.getCurrentlyViewedPath(); return ((this._currentView && currentPath === path) || (this.findInViewList(path) !== -1)); }; /** * Retrieves the File object of the current view * @return {?File} the File object of the current view or null if there isn't one */ Pane.prototype.getCurrentlyViewedFile = function () { return this._currentView ? this._currentView.getFile() : null; }; /** * Retrieves the path of the current view * @return {?string} the path of the current view or null if there isn't one */ Pane.prototype.getCurrentlyViewedPath = function () { var file = this.getCurrentlyViewedFile(); return file ? file.fullPath : null; }; /** * destroys the view if it isn't needed * @param {View} view - the view to destroy */ Pane.prototype.destroyViewIfNotNeeded = function (view) { if (!this._isViewNeeded(view)) { var file = view.getFile(), path = file && file.fullPath; delete this._views[path]; this.trigger("viewDestroy", view); view.destroy(); } }; /** * _resets the pane to an empty state * @private */ Pane.prototype._reset = function () { var self = this, views = [], view = this._currentView; _.forEach(this._views, function (_view) { views.push(_view); }); // If the current view is a temporary view, // add it to the destroy list to dispose of if (this._currentView && views.indexOf(this._currentView) === -1) { views.push(this._currentView); } // This will reinitialize the object back to // the default state this._initialize(); if (view) { this._notifyCurrentViewChange(null, view); } // Now destroy the views views.forEach(function (_view) { self.trigger("viewDestroy", _view); _view.destroy(); }); }; /** * Executes a FILE_OPEN command to open a file * @param {!string} fullPath - path of the file to open * @return {jQuery.promise} promise that will resolve when the file is opened */ Pane.prototype._execOpenFile = function (fullPath) { return CommandManager.execute(Commands.CMD_ADD_TO_WORKINGSET_AND_OPEN, { fullPath: fullPath, paneId: this.id, options: {noPaneActivate: true}}); }; /** * Removes the view and opens the next view * @param {File} file - the file to close * @param {boolean} suppressOpenNextFile - suppresses opening the next file in MRU order * @param {boolean} preventViewChange - if suppressOpenNextFile is truthy, this flag can be used to * prevent the current view from being destroyed. * Ignored if suppressOpenNextFile is falsy * @return {boolean} true if the file was removed from the working set * This function will remove a temporary view of a file but will return false in that case */ Pane.prototype.removeView = function (file, suppressOpenNextFile, preventViewChange) { var nextFile = !suppressOpenNextFile && this.traverseViewListByMRU(1, file.fullPath); if (nextFile && nextFile.fullPath !== file.fullPath && this.getCurrentlyViewedPath() === file.fullPath) { var self = this, fullPath = nextFile.fullPath, needOpenNextFile = this.findInViewList(fullPath) !== -1; if (this._doRemove(file, needOpenNextFile)) { if (needOpenNextFile) { // this will destroy the current view this._execOpenFile(fullPath) .fail(function () { // the FILE_OPEN op failed so destroy the current view self._doDestroyView(self._currentView); }); } return true; } else { // Nothing was removed so don't try to remove it again return false; } } else { return this._doRemove(file, preventViewChange); } }; /** * Removes the specifed file from all internal lists, destroys the view of the file (if there is one) * and shows the interstitial page if the current view is destroyed. * @param {!Array.<File>} list - Array of files to remove * @return {!Array.<File>} Array of File objects removed from the working set. * This function will remove temporary views but the file objects for those views will not be found * in the result set. Only the file objects removed from the working set are returned. */ Pane.prototype.removeViews = function (list) { var self = this, needsDestroyCurrentView = false, result; // Check to see if we need to destroy the current view later needsDestroyCurrentView = _.findIndex(list, function (file) { return file.fullPath === self.getCurrentlyViewedPath(); }) !== -1; // destroy the views in the list result = list.filter(function (file) { return (self.removeView(file, true, true)); }); // we may have been passed a list of files that did not include the current view if (needsDestroyCurrentView) { // _doRemove will have whittled the MRU list down to just the remaining views var nextFile = this.traverseViewListByMRU(1, this.getCurrentlyViewedPath()), fullPath = nextFile && nextFile.fullPath, needOpenNextFile = fullPath && (this.findInViewList(fullPath) !== -1); if (needOpenNextFile) { // A successful open will destroy the current view this._execOpenFile(fullPath) .fail(function () { // the FILE_OPEN op failed so destroy the current view self._doDestroyView(self._currentView); }); } else { // Nothing left to show so destroy the current view this._doDestroyView(this._currentView); } } // return the result return result; }; /** * Gives focus to the last thing that had focus, the current view or the pane in that order */ Pane.prototype.focus = function () { var current = window.document.activeElement, self = this; // Helper to focus the current view if it can function tryFocusingCurrentView() { if (self._currentView) { if (self._currentView.focus) { // Views can implement a focus // method for focusing a complex // DOM like codemirror self._currentView.focus(); } else { // Otherwise, no focus method // just try and give the DOM // element focus self._currentView.$el.focus(); } } else { // no view so just focus the pane self.$el.focus(); } } // short-circuit for performance if (this._lastFocusedElement === current) { return; } // If the focus was in a <textarea> (assumed to be CodeMirror) and currentView is // anything other than an Editor, blur the textarea explicitly, in case the new // _currentView's $el isn't focusable. E.g.: // 1. Open a js file in the left pane and an image in the right pane and // 2. Focus the js file using the working-set // 3. Focus the image view using the working-set. // ==> Focus is still in the text area. Any keyboard input will modify the document if (current.tagName.toLowerCase() === "textarea" && (!this._currentView || !this._currentView._codeMirror)) { current.blur(); } var $lfe = $(this._lastFocusedElement); if ($lfe.length && !$lfe.is(".view-pane") && $lfe.is(":visible")) { // if we had a last focused element // and it wasn't a pane element // and it's still visible, focus it $lfe.focus(); } else { // otherwise, just try to give focus // to the currently active view tryFocusingCurrentView(); } }; /** * MainViewManager.activePaneChange handler * @param {jQuery.event} e - event data * @param {!string} activePaneId - the new active pane id */ Pane.prototype._handleActivePaneChange = function (e, activePaneId) { this.$el.toggleClass("active-pane", Boolean(activePaneId === this.id)); }; /** * serializes the pane state from JSON * @param {!Object} state - the state to load * @return {jQuery.Promise} A promise which resolves to * {fullPath:string, paneId:string} * which can be passed as command data to FILE_OPEN */ Pane.prototype.loadState = function (state) { var filesToAdd = [], viewStates = {}, activeFile, data, self = this; var getInitialViewFilePath = function () { return (self._viewList.length > 0) ? self._viewList[0].fullPath : null; }; _.forEach(state, function (entry) { filesToAdd.push(FileSystem.getFileForPath(entry.file)); if (entry.active) { activeFile = entry.file; } if (entry.viewState) { viewStates[entry.file] = entry.viewState; } }); this.addListToViewList(filesToAdd); ViewStateManager.addViewStates(viewStates); activeFile = activeFile || getInitialViewFilePath(); if (activeFile) { data = {paneId: self.id, fullPath: activeFile}; } return new $.Deferred().resolve(data); }; /** * Returns the JSON-ified state of the object so it can be serialize * @return {!Object} state - the state to save */ Pane.prototype.saveState = function () { var result = [], currentlyViewedPath = this.getCurrentlyViewedPath(); // Save the current view state first if (this._currentView && this._currentView.getFile()) { // We save the view state of the current view before // hiding the view and showing to a different file // But the current view's view state may not be // up to date in the view state cache so update it // before we save so we don't JSON-ify stale data. ViewStateManager.updateViewState(this._currentView); } // walk the list of views and save this._viewList.forEach(function (file) { // Do not persist untitled document paths if (!(file instanceof InMemoryFile)) { result.push({ file: file.fullPath, active: (file.fullPath === currentlyViewedPath), viewState: ViewStateManager.getViewState(file) }); } }); return result; }; /** * gets the current view's scroll state data * @return {Object=} scroll state - the current scroll state */ Pane.prototype.getScrollState = function () { if (this._currentView && this._currentView.getScrollPos) { return {scrollPos: this._currentView.getScrollPos()}; } }; /** * tells the current view to restore its scroll state from cached data and apply a height delta * @param {Object=} state - the current scroll state * @param {number=} heightDelta - the amount to add or subtract from the state */ Pane.prototype.restoreAndAdjustScrollState = function (state, heightDelta) { if (this._currentView && state && state.scrollPos && this._currentView.adjustScrollPos) { this._currentView.adjustScrollPos(state.scrollPos, heightDelta); } }; exports.Pane = Pane; });
/* * * * Data module * * (c) 2012-2021 Torstein Honsi * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import Chart from '../Core/Chart/Chart.js'; import G from '../Core/Globals.js'; var doc = G.doc; import HU from '../Core/HttpUtilities.js'; var ajax = HU.ajax; import Point from '../Core/Series/Point.js'; import SeriesRegistry from '../Core/Series/SeriesRegistry.js'; var seriesTypes = SeriesRegistry.seriesTypes; import U from '../Core/Utilities.js'; var addEvent = U.addEvent, defined = U.defined, extend = U.extend, fireEvent = U.fireEvent, isNumber = U.isNumber, merge = U.merge, objectEach = U.objectEach, pick = U.pick, splat = U.splat; /** * Callback function to modify the CSV before parsing it by the data module. * * @callback Highcharts.DataBeforeParseCallbackFunction * * @param {string} csv * The CSV to modify. * * @return {string} * The CSV to parse. */ /** * Callback function that gets called after parsing data. * * @callback Highcharts.DataCompleteCallbackFunction * * @param {Highcharts.Options} chartOptions * The chart options that were used. */ /** * Callback function that returns the correspondig Date object to a match. * * @callback Highcharts.DataDateFormatCallbackFunction * * @param {Array<number>} match * * @return {number} */ /** * Structure for alternative date formats to parse. * * @interface Highcharts.DataDateFormatObject */ /** * @name Highcharts.DataDateFormatObject#alternative * @type {string|undefined} */ /** * @name Highcharts.DataDateFormatObject#parser * @type {Highcharts.DataDateFormatCallbackFunction} */ /** * @name Highcharts.DataDateFormatObject#regex * @type {global.RegExp} */ /** * Possible types for a data item in a column or row. * * @typedef {number|string|null} Highcharts.DataValueType */ /** * Callback function to parse string representations of dates into * JavaScript timestamps (milliseconds since 1.1.1970). * * @callback Highcharts.DataParseDateCallbackFunction * * @param {string} dateValue * * @return {number} * Timestamp (milliseconds since 1.1.1970) as integer for Date class. */ /** * Callback function to access the parsed columns, the two-dimentional * input data array directly, before they are interpreted into series * data and categories. * * @callback Highcharts.DataParsedCallbackFunction * * @param {Array<Array<*>>} columns * The parsed columns by the data module. * * @return {boolean|undefined} * Return `false` to stop completion, or call `this.complete()` to * continue async. */ /** * The Data module provides a simplified interface for adding data to * a chart from sources like CVS, HTML tables or grid views. See also * the [tutorial article on the Data module]( * https://www.highcharts.com/docs/working-with-data/data-module). * * It requires the `modules/data.js` file to be loaded. * * Please note that the default way of adding data in Highcharts, without * the need of a module, is through the [series._type_.data](#series.line.data) * option. * * @sample {highcharts} highcharts/demo/column-parsed/ * HTML table * @sample {highcharts} highcharts/data/csv/ * CSV * * @since 4.0 * @requires modules/data * @apioption data */ /** * A callback function to modify the CSV before parsing it. Return the modified * string. * * @sample {highcharts} highcharts/demo/line-ajax/ * Modify CSV before parse * * @type {Highcharts.DataBeforeParseCallbackFunction} * @since 6.1 * @apioption data.beforeParse */ /** * A two-dimensional array representing the input data on tabular form. * This input can be used when the data is already parsed, for example * from a grid view component. Each cell can be a string or number. * If not switchRowsAndColumns is set, the columns are interpreted as * series. * * @see [data.rows](#data.rows) * * @sample {highcharts} highcharts/data/columns/ * Columns * * @type {Array<Array<Highcharts.DataValueType>>} * @since 4.0 * @apioption data.columns */ /** * The callback that is evaluated when the data is finished loading, * optionally from an external source, and parsed. The first argument * passed is a finished chart options object, containing the series. * These options can be extended with additional options and passed * directly to the chart constructor. * * @see [data.parsed](#data.parsed) * * @sample {highcharts} highcharts/data/complete/ * Modify data on complete * * @type {Highcharts.DataCompleteCallbackFunction} * @since 4.0 * @apioption data.complete */ /** * A comma delimited string to be parsed. Related options are [startRow]( * #data.startRow), [endRow](#data.endRow), [startColumn](#data.startColumn) * and [endColumn](#data.endColumn) to delimit what part of the table * is used. The [lineDelimiter](#data.lineDelimiter) and [itemDelimiter]( * #data.itemDelimiter) options define the CSV delimiter formats. * * The built-in CSV parser doesn't support all flavours of CSV, so in * some cases it may be necessary to use an external CSV parser. See * [this example](https://jsfiddle.net/highcharts/u59176h4/) of parsing * CSV through the MIT licensed [Papa Parse](http://papaparse.com/) * library. * * @sample {highcharts} highcharts/data/csv/ * Data from CSV * * @type {string} * @since 4.0 * @apioption data.csv */ /** * Which of the predefined date formats in Date.prototype.dateFormats * to use to parse date values. Defaults to a best guess based on what * format gives valid and ordered dates. Valid options include: `YYYY/mm/dd`, * `dd/mm/YYYY`, `mm/dd/YYYY`, `dd/mm/YY`, `mm/dd/YY`. * * @see [data.parseDate](#data.parseDate) * * @sample {highcharts} highcharts/data/dateformat-auto/ * Best guess date format * * @type {string} * @since 4.0 * @validvalue ["YYYY/mm/dd", "dd/mm/YYYY", "mm/dd/YYYY", "dd/mm/YYYY", * "dd/mm/YY", "mm/dd/YY"] * @apioption data.dateFormat */ /** * The decimal point used for parsing numbers in the CSV. * * If both this and data.delimiter is set to `undefined`, the parser will * attempt to deduce the decimal point automatically. * * @sample {highcharts} highcharts/data/delimiters/ * Comma as decimal point * * @type {string} * @default . * @since 4.1.0 * @apioption data.decimalPoint */ /** * In tabular input data, the last column (indexed by 0) to use. Defaults * to the last column containing data. * * @sample {highcharts} highcharts/data/start-end/ * Limited data * * @type {number} * @since 4.0 * @apioption data.endColumn */ /** * In tabular input data, the last row (indexed by 0) to use. Defaults * to the last row containing data. * * @sample {highcharts} highcharts/data/start-end/ * Limited data * * @type {number} * @since 4.0.4 * @apioption data.endRow */ /** * Whether to use the first row in the data set as series names. * * @sample {highcharts} highcharts/data/start-end/ * Don't get series names from the CSV * @sample {highstock} highcharts/data/start-end/ * Don't get series names from the CSV * * @type {boolean} * @default true * @since 4.1.0 * @product highcharts highstock gantt * @apioption data.firstRowAsNames */ /** * The Google Spreadsheet API key required for access generated at [API Services * / Credentials](https://console.cloud.google.com/apis/credentials). See a * comprehensive tutorial for setting up the key at the * [Hands-On Data Visualization](https://handsondataviz.org/google-sheets-api-key.html) * book website. * * @sample {highcharts} highcharts/data/google-spreadsheet/ * Load a Google Spreadsheet * * @type {string} * @since 9.2.2 * @apioption data.googleAPIKey */ /** * The key or `spreadsheetId` value for a Google Spreadsheet to load. See * [developers.google.com](https://developers.google.com/sheets/api/guides/concepts) * for how to find the `spreadsheetId`. * * In order for Google Sheets to load, a valid [googleAPIKey](#data.googleAPIKey) * must also be given. * * @sample {highcharts} highcharts/data/google-spreadsheet/ * Load a Google Spreadsheet * * @type {string} * @since 4.0 * @apioption data.googleSpreadsheetKey */ /** * The Google Spreadsheet `range` to use in combination with * [googleSpreadsheetKey](#data.googleSpreadsheetKey). See * [developers.google.com](https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get) * for details. * * If given, it takes precedence over `startColumn`, `endColumn`, `startRow` and * `endRow`. * * @example * googleSpreadsheetRange: 'Fruit Consumption' // Load a named worksheet * googleSpreadsheetRange: 'A:Z' // Load columns A to Z * * @sample {highcharts} highcharts/data/google-spreadsheet/ * Load a Google Spreadsheet * * @type {string|undefined} * @since 9.2.2 * @apioption data.googleSpreadsheetRange */ /** * No longer works since v9.2.2, that uses Google Sheets API v4. Instead, use * the [googleSpreadsheetRange](#data.googleSpreadsheetRange) option to load a * specific sheet. * * @deprecated * @type {string} * @since 4.0 * @apioption data.googleSpreadsheetWorksheet */ /** * Item or cell delimiter for parsing CSV. Defaults to the tab character * `\t` if a tab character is found in the CSV string, if not it defaults * to `,`. * * If this is set to false or undefined, the parser will attempt to deduce * the delimiter automatically. * * @sample {highcharts} highcharts/data/delimiters/ * Delimiters * * @type {string} * @since 4.0 * @apioption data.itemDelimiter */ /** * Line delimiter for parsing CSV. * * @sample {highcharts} highcharts/data/delimiters/ * Delimiters * * @type {string} * @default \n * @since 4.0 * @apioption data.lineDelimiter */ /** * A callback function to access the parsed columns, the two-dimentional * input data array directly, before they are interpreted into series * data and categories. Return `false` to stop completion, or call * `this.complete()` to continue async. * * @see [data.complete](#data.complete) * * @sample {highcharts} highcharts/data/parsed/ * Modify data after parse * * @type {Highcharts.DataParsedCallbackFunction} * @since 4.0 * @apioption data.parsed */ /** * A callback function to parse string representations of dates into * JavaScript timestamps. Should return an integer timestamp on success. * * @see [dateFormat](#data.dateFormat) * * @type {Highcharts.DataParseDateCallbackFunction} * @since 4.0 * @apioption data.parseDate */ /** * The same as the columns input option, but defining rows intead of * columns. * * @see [data.columns](#data.columns) * * @sample {highcharts} highcharts/data/rows/ * Data in rows * * @type {Array<Array<Highcharts.DataValueType>>} * @since 4.0 * @apioption data.rows */ /** * An array containing dictionaries for each series. A dictionary exists of * Point property names as the key and the CSV column index as the value. * * @sample {highcharts} highcharts/data/seriesmapping-label/ * Label from data set * * @type {Array<Highcharts.Dictionary<number>>} * @since 4.0.4 * @apioption data.seriesMapping */ /** * In tabular input data, the first column (indexed by 0) to use. * * @sample {highcharts} highcharts/data/start-end/ * Limited data * * @type {number} * @default 0 * @since 4.0 * @apioption data.startColumn */ /** * In tabular input data, the first row (indexed by 0) to use. * * @sample {highcharts} highcharts/data/start-end/ * Limited data * * @type {number} * @default 0 * @since 4.0 * @apioption data.startRow */ /** * Switch rows and columns of the input data, so that `this.columns` * effectively becomes the rows of the data set, and the rows are interpreted * as series. * * @sample {highcharts} highcharts/data/switchrowsandcolumns/ * Switch rows and columns * * @type {boolean} * @default false * @since 4.0 * @apioption data.switchRowsAndColumns */ /** * An HTML table or the id of such to be parsed as input data. Related * options are `startRow`, `endRow`, `startColumn` and `endColumn` to * delimit what part of the table is used. * * @sample {highcharts} highcharts/demo/column-parsed/ * Parsed table * * @type {string|global.HTMLElement} * @since 4.0 * @apioption data.table */ /** * An URL to a remote CSV dataset. Will be fetched when the chart is created * using Ajax. * * @sample highcharts/data/livedata-columns * Categorized bar chart with CSV and live polling * @sample highcharts/data/livedata-csv * Time based line chart with CSV and live polling * * @type {string} * @apioption data.csvURL */ /** * A URL to a remote JSON dataset, structured as a row array. * Will be fetched when the chart is created using Ajax. * * @sample highcharts/data/livedata-rows * Rows with live polling * * @type {string} * @apioption data.rowsURL */ /** * A URL to a remote JSON dataset, structured as a column array. * Will be fetched when the chart is created using Ajax. * * @sample highcharts/data/livedata-columns * Columns with live polling * * @type {string} * @apioption data.columnsURL */ /** * Sets the refresh rate for data polling when importing remote dataset by * setting [data.csvURL](data.csvURL), [data.rowsURL](data.rowsURL), * [data.columnsURL](data.columnsURL), or * [data.googleSpreadsheetKey](data.googleSpreadsheetKey). * * Note that polling must be enabled by setting * [data.enablePolling](data.enablePolling) to true. * * The value is the number of seconds between pollings. * It cannot be set to less than 1 second. * * @sample highcharts/demo/live-data * Live data with user set refresh rate * * @default 1 * @type {number} * @apioption data.dataRefreshRate */ /** * Enables automatic refetching of remote datasets every _n_ seconds (defined by * setting [data.dataRefreshRate](data.dataRefreshRate)). * * Only works when either [data.csvURL](data.csvURL), * [data.rowsURL](data.rowsURL), [data.columnsURL](data.columnsURL), or * [data.googleSpreadsheetKey](data.googleSpreadsheetKey). * * @sample highcharts/demo/live-data * Live data * @sample highcharts/data/livedata-columns * Categorized bar chart with CSV and live polling * * @type {boolean} * @default false * @apioption data.enablePolling */ /* eslint-disable valid-jsdoc */ /** * The Data class * * @requires module:modules/data * * @class * @name Highcharts.Data * * @param {Highcharts.DataOptions} dataOptions * * @param {Highcharts.Options} [chartOptions] * * @param {Highcharts.Chart} [chart] */ var Data = /** @class */ (function () { /* * * * Constructors * * */ function Data(dataOptions, chartOptions, chart) { this.chart = void 0; this.chartOptions = void 0; this.firstRowAsNames = void 0; this.rawColumns = void 0; this.options = void 0; /** * A collection of available date formats, extendable from the outside to * support custom date formats. * * @name Highcharts.Data#dateFormats * @type {Highcharts.Dictionary<Highcharts.DataDateFormatObject>} */ this.dateFormats = { 'YYYY/mm/dd': { regex: /^([0-9]{4})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{1,2})$/, parser: function (match) { return (match ? Date.UTC(+match[1], match[2] - 1, +match[3]) : NaN); } }, 'dd/mm/YYYY': { regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{4})$/, parser: function (match) { return (match ? Date.UTC(+match[3], match[2] - 1, +match[1]) : NaN); }, alternative: 'mm/dd/YYYY' // different format with the same regex }, 'mm/dd/YYYY': { regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{4})$/, parser: function (match) { return (match ? Date.UTC(+match[3], match[1] - 1, +match[2]) : NaN); } }, 'dd/mm/YY': { regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{2})$/, parser: function (match) { if (!match) { return NaN; } var year = +match[3], d = new Date(); if (year > (d.getFullYear() - 2000)) { year += 1900; } else { year += 2000; } return Date.UTC(year, match[2] - 1, +match[1]); }, alternative: 'mm/dd/YY' // different format with the same regex }, 'mm/dd/YY': { regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{2})$/, parser: function (match) { return (match ? Date.UTC(+match[3] + 2000, match[1] - 1, +match[2]) : NaN); } } }; this.init(dataOptions, chartOptions, chart); } /* * * * Functions * * */ /** * Initialize the Data object with the given options * * @private * @function Highcharts.Data#init */ Data.prototype.init = function (options, chartOptions, chart) { var decimalPoint = options.decimalPoint, hasData; if (chartOptions) { this.chartOptions = chartOptions; } if (chart) { this.chart = chart; } if (decimalPoint !== '.' && decimalPoint !== ',') { decimalPoint = void 0; } this.options = options; this.columns = (options.columns || this.rowsToColumns(options.rows) || []); this.firstRowAsNames = pick(options.firstRowAsNames, this.firstRowAsNames, true); this.decimalRegex = (decimalPoint && new RegExp('^(-?[0-9]+)' + decimalPoint + '([0-9]+)$')); // This is a two-dimensional array holding the raw, trimmed string // values with the same organisation as the columns array. It makes it // possible for example to revert from interpreted timestamps to // string-based categories. this.rawColumns = []; // No need to parse or interpret anything if (this.columns.length) { this.dataFound(); hasData = true; } if (this.hasURLOption(options)) { clearTimeout(this.liveDataTimeout); hasData = false; } if (!hasData) { // Fetch live data hasData = this.fetchLiveData(); } if (!hasData) { // Parse a CSV string if options.csv is given. The parseCSV function // returns a columns array, if it has no length, we have no data hasData = Boolean(this.parseCSV().length); } if (!hasData) { // Parse a HTML table if options.table is given hasData = Boolean(this.parseTable().length); } if (!hasData) { // Parse a Google Spreadsheet hasData = this.parseGoogleSpreadsheet(); } if (!hasData && options.afterComplete) { options.afterComplete(); } }; Data.prototype.hasURLOption = function (options) { return Boolean(options && (options.rowsURL || options.csvURL || options.columnsURL)); }; /** * Get the column distribution. For example, a line series takes a single * column for Y values. A range series takes two columns for low and high * values respectively, and an OHLC series takes four columns. * * @function Highcharts.Data#getColumnDistribution */ Data.prototype.getColumnDistribution = function () { var chartOptions = this.chartOptions, options = this.options, xColumns = [], getValueCount = function (type) { return (seriesTypes[type || 'line'].prototype.pointArrayMap || [0]).length; }, getPointArrayMap = function (type) { return seriesTypes[type || 'line'].prototype.pointArrayMap; }, globalType = (chartOptions && chartOptions.chart && chartOptions.chart.type), individualCounts = [], seriesBuilders = [], seriesIndex = 0, // If no series mapping is defined, check if the series array is // defined with types. seriesMapping = ((options && options.seriesMapping) || (chartOptions && chartOptions.series && chartOptions.series.map(function () { return { x: 0 }; })) || []), i; ((chartOptions && chartOptions.series) || []).forEach(function (series) { individualCounts.push(getValueCount(series.type || globalType)); }); // Collect the x-column indexes from seriesMapping seriesMapping.forEach(function (mapping) { xColumns.push(mapping.x || 0); }); // If there are no defined series with x-columns, use the first column // as x column if (xColumns.length === 0) { xColumns.push(0); } // Loop all seriesMappings and constructs SeriesBuilders from // the mapping options. seriesMapping.forEach(function (mapping) { var builder = new SeriesBuilder(), numberOfValueColumnsNeeded = individualCounts[seriesIndex] || getValueCount(globalType), seriesArr = (chartOptions && chartOptions.series) || [], series = seriesArr[seriesIndex] || {}, defaultPointArrayMap = getPointArrayMap(series.type || globalType), pointArrayMap = defaultPointArrayMap || ['y']; if ( // User-defined x.mapping defined(mapping.x) || // All non cartesian don't need 'x' series.isCartesian || // Except pie series: !defaultPointArrayMap) { // Add an x reader from the x property or from an undefined // column if the property is not set. It will then be auto // populated later. builder.addColumnReader(mapping.x, 'x'); } // Add all column mappings objectEach(mapping, function (val, name) { if (name !== 'x') { builder.addColumnReader(val, name); } }); // Add missing columns for (i = 0; i < numberOfValueColumnsNeeded; i++) { if (!builder.hasReader(pointArrayMap[i])) { // Create and add a column reader for the next free column // index builder.addColumnReader(void 0, pointArrayMap[i]); } } seriesBuilders.push(builder); seriesIndex++; }); var globalPointArrayMap = getPointArrayMap(globalType); if (typeof globalPointArrayMap === 'undefined') { globalPointArrayMap = ['y']; } this.valueCount = { global: getValueCount(globalType), xColumns: xColumns, individual: individualCounts, seriesBuilders: seriesBuilders, globalPointArrayMap: globalPointArrayMap }; }; /** * When the data is parsed into columns, either by CSV, table, GS or direct * input, continue with other operations. * * @private * @function Highcharts.Data#dataFound */ Data.prototype.dataFound = function () { if (this.options.switchRowsAndColumns) { this.columns = this.rowsToColumns(this.columns); } // Interpret the info about series and columns this.getColumnDistribution(); // Interpret the values into right types this.parseTypes(); // Handle columns if a handleColumns callback is given if (this.parsed() !== false) { // Complete if a complete callback is given this.complete(); } }; /** * Parse a CSV input string * * @function Highcharts.Data#parseCSV */ Data.prototype.parseCSV = function (inOptions) { var self = this, options = inOptions || this.options, csv = options.csv, columns, startRow = (typeof options.startRow !== 'undefined' && options.startRow ? options.startRow : 0), endRow = options.endRow || Number.MAX_VALUE, startColumn = (typeof options.startColumn !== 'undefined' && options.startColumn) ? options.startColumn : 0, endColumn = options.endColumn || Number.MAX_VALUE, itemDelimiter, lines, rowIt = 0, // activeRowNo = 0, dataTypes = [], // We count potential delimiters in the prepass, and use the // result as the basis of half-intelligent guesses. potDelimiters = { ',': 0, ';': 0, '\t': 0 }; columns = this.columns = []; /* This implementation is quite verbose. It will be shortened once it's stable and passes all the test. It's also not written with speed in mind, instead everything is very seggregated, and there a several redundant loops. This is to make it easier to stabilize the code initially. We do a pre-pass on the first 4 rows to make some intelligent guesses on the set. Guessed delimiters are in this pass counted. Auto detecting delimiters - If we meet a quoted string, the next symbol afterwards (that's not \s, \t) is the delimiter - If we meet a date, the next symbol afterwards is the delimiter Date formats - If we meet a column with date formats, check all of them to see if one of the potential months crossing 12. If it does, we now know the format It would make things easier to guess the delimiter before doing the actual parsing. General rules: - Quoting is allowed, e.g: "Col 1",123,321 - Quoting is optional, e.g.: Col1,123,321 - Doubble quoting is escaping, e.g. "Col ""Hello world""",123 - Spaces are considered part of the data: Col1 ,123 - New line is always the row delimiter - Potential column delimiters are , ; \t - First row may optionally contain headers - The last row may or may not have a row delimiter - Comments are optionally supported, in which case the comment must start at the first column, and the rest of the line will be ignored */ /** * Parse a single row. * @private */ function parseRow(columnStr, rowNumber, noAdd, callbacks) { var i = 0, c = '', cl = '', cn = '', token = '', actualColumn = 0, column = 0; /** * @private */ function read(j) { c = columnStr[j]; cl = columnStr[j - 1]; cn = columnStr[j + 1]; } /** * @private */ function pushType(type) { if (dataTypes.length < column + 1) { dataTypes.push([type]); } if (dataTypes[column][dataTypes[column].length - 1] !== type) { dataTypes[column].push(type); } } /** * @private */ function push() { if (startColumn > actualColumn || actualColumn > endColumn) { // Skip this column, but increment the column count (#7272) ++actualColumn; token = ''; return; } if (!isNaN(parseFloat(token)) && isFinite(token)) { token = parseFloat(token); pushType('number'); } else if (!isNaN(Date.parse(token))) { token = token.replace(/\//g, '-'); pushType('date'); } else { pushType('string'); } if (columns.length < column + 1) { columns.push([]); } if (!noAdd) { // Don't push - if there's a varrying amount of columns // for each row, pushing will skew everything down n slots columns[column][rowNumber] = token; } token = ''; ++column; ++actualColumn; } if (!columnStr.trim().length) { return; } if (columnStr.trim()[0] === '#') { return; } for (; i < columnStr.length; i++) { read(i); if (c === '"') { read(++i); while (i < columnStr.length) { if (c === '"' && cl !== '"' && cn !== '"') { break; } if (c !== '"' || (c === '"' && cl !== '"')) { token += c; } read(++i); } // Perform "plugin" handling } else if (callbacks && callbacks[c]) { if (callbacks[c](c, token)) { push(); } // Delimiter - push current token } else if (c === itemDelimiter) { push(); // Actual column data } else { token += c; } } push(); } /** * Attempt to guess the delimiter. We do a separate parse pass here * because we need to count potential delimiters softly without making * any assumptions. * @private */ function guessDelimiter(lines) { var points = 0, commas = 0, guessed = false; lines.some(function (columnStr, i) { var inStr = false, c, cn, cl, token = ''; // We should be able to detect dateformats within 13 rows if (i > 13) { return true; } for (var j = 0; j < columnStr.length; j++) { c = columnStr[j]; cn = columnStr[j + 1]; cl = columnStr[j - 1]; if (c === '#') { // Skip the rest of the line - it's a comment return; } if (c === '"') { if (inStr) { if (cl !== '"' && cn !== '"') { while (cn === ' ' && j < columnStr.length) { cn = columnStr[++j]; } // After parsing a string, the next non-blank // should be a delimiter if the CSV is properly // formed. if (typeof potDelimiters[cn] !== 'undefined') { potDelimiters[cn]++; } inStr = false; } } else { inStr = true; } } else if (typeof potDelimiters[c] !== 'undefined') { token = token.trim(); if (!isNaN(Date.parse(token))) { potDelimiters[c]++; } else if (isNaN(token) || !isFinite(token)) { potDelimiters[c]++; } token = ''; } else { token += c; } if (c === ',') { commas++; } if (c === '.') { points++; } } }); // Count the potential delimiters. // This could be improved by checking if the number of delimiters // equals the number of columns - 1 if (potDelimiters[';'] > potDelimiters[',']) { guessed = ';'; } else if (potDelimiters[','] > potDelimiters[';']) { guessed = ','; } else { // No good guess could be made.. guessed = ','; } // Try to deduce the decimal point if it's not explicitly set. // If both commas or points is > 0 there is likely an issue if (!options.decimalPoint) { if (points > commas) { options.decimalPoint = '.'; } else { options.decimalPoint = ','; } // Apply a new decimal regex based on the presumed decimal sep. self.decimalRegex = new RegExp('^(-?[0-9]+)' + options.decimalPoint + '([0-9]+)$'); } return guessed; } /** * Tries to guess the date format * - Check if either month candidate exceeds 12 * - Check if year is missing (use current year) * - Check if a shortened year format is used (e.g. 1/1/99) * - If no guess can be made, the user must be prompted * data is the data to deduce a format based on * @private */ function deduceDateFormat(data, limit) { var format = 'YYYY/mm/dd', thing, guessedFormat = [], calculatedFormat, i = 0, madeDeduction = false, // candidates = {}, stable = [], max = [], j; if (!limit || limit > data.length) { limit = data.length; } for (; i < limit; i++) { if (typeof data[i] !== 'undefined' && data[i] && data[i].length) { thing = data[i] .trim() .replace(/\//g, ' ') .replace(/\-/g, ' ') .replace(/\./g, ' ') .split(' '); guessedFormat = [ '', '', '' ]; for (j = 0; j < thing.length; j++) { if (j < guessedFormat.length) { thing[j] = parseInt(thing[j], 10); if (thing[j]) { max[j] = (!max[j] || max[j] < thing[j]) ? thing[j] : max[j]; if (typeof stable[j] !== 'undefined') { if (stable[j] !== thing[j]) { stable[j] = false; } } else { stable[j] = thing[j]; } if (thing[j] > 31) { if (thing[j] < 100) { guessedFormat[j] = 'YY'; } else { guessedFormat[j] = 'YYYY'; } // madeDeduction = true; } else if (thing[j] > 12 && thing[j] <= 31) { guessedFormat[j] = 'dd'; madeDeduction = true; } else if (!guessedFormat[j].length) { guessedFormat[j] = 'mm'; } } } } } } if (madeDeduction) { // This handles a few edge cases with hard to guess dates for (j = 0; j < stable.length; j++) { if (stable[j] !== false) { if (max[j] > 12 && guessedFormat[j] !== 'YY' && guessedFormat[j] !== 'YYYY') { guessedFormat[j] = 'YY'; } } else if (max[j] > 12 && guessedFormat[j] === 'mm') { guessedFormat[j] = 'dd'; } } // If the middle one is dd, and the last one is dd, // the last should likely be year. if (guessedFormat.length === 3 && guessedFormat[1] === 'dd' && guessedFormat[2] === 'dd') { guessedFormat[2] = 'YY'; } calculatedFormat = guessedFormat.join('/'); // If the caculated format is not valid, we need to present an // error. if (!(options.dateFormats || self.dateFormats)[calculatedFormat]) { // This should emit an event instead fireEvent('deduceDateFailed'); return format; } return calculatedFormat; } return format; } /** * @todo * Figure out the best axis types for the data * - If the first column is a number, we're good * - If the first column is a date, set to date/time * - If the first column is a string, set to categories * @private */ function deduceAxisTypes() { } if (csv && options.beforeParse) { csv = options.beforeParse.call(this, csv); } if (csv) { lines = csv .replace(/\r\n/g, '\n') // Unix .replace(/\r/g, '\n') // Mac .split(options.lineDelimiter || '\n'); if (!startRow || startRow < 0) { startRow = 0; } if (!endRow || endRow >= lines.length) { endRow = lines.length - 1; } if (options.itemDelimiter) { itemDelimiter = options.itemDelimiter; } else { itemDelimiter = null; itemDelimiter = guessDelimiter(lines); } var offset = 0; for (rowIt = startRow; rowIt <= endRow; rowIt++) { if (lines[rowIt][0] === '#') { offset++; } else { parseRow(lines[rowIt], rowIt - startRow - offset); } } // //Make sure that there's header columns for everything // columns.forEach(function (col) { // }); deduceAxisTypes(); if ((!options.columnTypes || options.columnTypes.length === 0) && dataTypes.length && dataTypes[0].length && dataTypes[0][1] === 'date' && !options.dateFormat) { options.dateFormat = deduceDateFormat(columns[0]); } // lines.forEach(function (line, rowNo) { // let trimmed = self.trim(line), // isComment = trimmed.indexOf('#') === 0, // isBlank = trimmed === '', // items; // if ( // rowNo >= startRow && // rowNo <= endRow && // !isComment && !isBlank // ) { // items = line.split(itemDelimiter); // items.forEach(function (item, colNo) { // if (colNo >= startColumn && colNo <= endColumn) { // if (!columns[colNo - startColumn]) { // columns[colNo - startColumn] = []; // } // columns[colNo - startColumn][activeRowNo] = item; // } // }); // activeRowNo += 1; // } // }); // this.dataFound(); } return columns; }; /** * Parse a HTML table * * @function Highcharts.Data#parseTable */ Data.prototype.parseTable = function () { var options = this.options, table = options.table, columns = this.columns || [], startRow = options.startRow || 0, endRow = options.endRow || Number.MAX_VALUE, startColumn = options.startColumn || 0, endColumn = options.endColumn || Number.MAX_VALUE; if (table) { if (typeof table === 'string') { table = doc.getElementById(table); } [].forEach.call(table.getElementsByTagName('tr'), function (tr, rowNo) { if (rowNo >= startRow && rowNo <= endRow) { [].forEach.call(tr.children, function (item, colNo) { var row = columns[colNo - startColumn]; var i = 1; if ((item.tagName === 'TD' || item.tagName === 'TH') && colNo >= startColumn && colNo <= endColumn) { if (!columns[colNo - startColumn]) { columns[colNo - startColumn] = []; } columns[colNo - startColumn][rowNo - startRow] = item.innerHTML; // Loop over all previous indices and make sure // they are nulls, not undefined. while (rowNo - startRow >= i && row[rowNo - startRow - i] === void 0) { row[rowNo - startRow - i] = null; i++; } } }); } }); this.dataFound(); // continue } return columns; }; /** * Fetch or refetch live data * * @function Highcharts.Data#fetchLiveData * * @return {boolean} * The URLs that were tried can be found in the options */ Data.prototype.fetchLiveData = function () { var data = this, chart = this.chart, options = this.options, maxRetries = 3, currentRetries = 0, pollingEnabled = options.enablePolling, updateIntervalMs = (options.dataRefreshRate || 2) * 1000, originalOptions = merge(options); if (!this.hasURLOption(options)) { return false; } // Do not allow polling more than once a second if (updateIntervalMs < 1000) { updateIntervalMs = 1000; } delete options.csvURL; delete options.rowsURL; delete options.columnsURL; /** * @private */ function performFetch(initialFetch) { /** * Helper function for doing the data fetch + polling. * @private */ function request(url, done, tp) { if (!url || !/^(http|\/|\.\/|\.\.\/)/.test(url)) { if (url && options.error) { options.error('Invalid URL'); } return false; } if (initialFetch) { clearTimeout(data.liveDataTimeout); chart.liveDataURL = url; } /** * @private */ function poll() { // Poll if (pollingEnabled && chart.liveDataURL === url) { // We need to stop doing this if the URL has changed data.liveDataTimeout = setTimeout(performFetch, updateIntervalMs); } } ajax({ url: url, dataType: tp || 'json', success: function (res) { if (chart && chart.series) { done(res); } poll(); }, error: function (xhr, text) { if (++currentRetries < maxRetries) { poll(); } return options.error && options.error(text, xhr); } }); return true; } if (!request(originalOptions.csvURL, function (res) { chart.update({ data: { csv: res } }); }, 'text')) { if (!request(originalOptions.rowsURL, function (res) { chart.update({ data: { rows: res } }); })) { request(originalOptions.columnsURL, function (res) { chart.update({ data: { columns: res } }); }); } } } performFetch(true); return this.hasURLOption(options); }; /** * Parse a Google spreadsheet. * * @function Highcharts.Data#parseGoogleSpreadsheet * * @return {boolean} * Always returns false, because it is an intermediate fetch. */ Data.prototype.parseGoogleSpreadsheet = function () { var data = this, options = this.options, googleSpreadsheetKey = options.googleSpreadsheetKey, chart = this.chart, refreshRate = Math.max((options.dataRefreshRate || 2) * 1000, 4000); /** * Form the `values` field after range settings, unless the * googleSpreadsheetRange option is set. */ var getRange = function () { if (options.googleSpreadsheetRange) { return options.googleSpreadsheetRange; } var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var start = (alphabet.charAt(options.startColumn || 0) || 'A') + ((options.startRow || 0) + 1); var end = alphabet.charAt(pick(options.endColumn, -1)) || 'ZZ'; if (defined(options.endRow)) { end += options.endRow + 1; } return start + ":" + end; }; /** * Fetch the actual spreadsheet using XMLHttpRequest. * @private */ function fetchSheet(fn) { var url = [ 'https://sheets.googleapis.com/v4/spreadsheets', googleSpreadsheetKey, 'values', getRange(), '?alt=json&' + 'majorDimension=COLUMNS&' + 'valueRenderOption=UNFORMATTED_VALUE&' + 'dateTimeRenderOption=FORMATTED_STRING&' + 'key=' + options.googleAPIKey ].join('/'); ajax({ url: url, dataType: 'json', success: function (json) { fn(json); if (options.enablePolling) { setTimeout(function () { fetchSheet(fn); }, refreshRate); } }, error: function (xhr, text) { return options.error && options.error(text, xhr); } }); } if (googleSpreadsheetKey) { delete options.googleSpreadsheetKey; fetchSheet(function (json) { // Prepare the data from the spreadsheat var columns = json.values; if (!columns || columns.length === 0) { return false; } // Find the maximum row count in order to extend shorter columns var rowCount = columns.reduce(function (rowCount, column) { return Math.max(rowCount, column.length); }, 0); // Insert null for empty spreadsheet cells (#5298) columns.forEach(function (column) { for (var i = 0; i < rowCount; i++) { if (typeof column[i] === 'undefined') { column[i] = null; } } }); if (chart && chart.series) { chart.update({ data: { columns: columns } }); } else { // #8245 data.columns = columns; data.dataFound(); } }); } // This is an intermediate fetch, so always return false. return false; }; /** * Trim a string from whitespaces. * * @function Highcharts.Data#trim * * @param {string} str * String to trim * * @param {boolean} [inside=false] * Remove all spaces between numbers. * * @return {string} * Trimed string */ Data.prototype.trim = function (str, inside) { if (typeof str === 'string') { str = str.replace(/^\s+|\s+$/g, ''); // Clear white space insdie the string, like thousands separators if (inside && /^[0-9\s]+$/.test(str)) { str = str.replace(/\s/g, ''); } if (this.decimalRegex) { str = str.replace(this.decimalRegex, '$1.$2'); } } return str; }; /** * Parse numeric cells in to number types and date types in to true dates. * * @function Highcharts.Data#parseTypes */ Data.prototype.parseTypes = function () { var columns = this.columns, col = columns.length; while (col--) { this.parseColumn(columns[col], col); } }; /** * Parse a single column. Set properties like .isDatetime and .isNumeric. * * @function Highcharts.Data#parseColumn * * @param {Array<Highcharts.DataValueType>} column * Column to parse * * @param {number} col * Column index */ Data.prototype.parseColumn = function (column, col) { var rawColumns = this.rawColumns, columns = this.columns, row = column.length, val, floatVal, trimVal, trimInsideVal, firstRowAsNames = this.firstRowAsNames, isXColumn = this.valueCount.xColumns.indexOf(col) !== -1, dateVal, backup = [], diff, chartOptions = this.chartOptions, descending, columnTypes = this.options.columnTypes || [], columnType = columnTypes[col], forceCategory = isXColumn && ((chartOptions && chartOptions.xAxis && splat(chartOptions.xAxis)[0].type === 'category') || columnType === 'string'); if (!rawColumns[col]) { rawColumns[col] = []; } while (row--) { val = backup[row] || column[row]; trimVal = this.trim(val); trimInsideVal = this.trim(val, true); floatVal = parseFloat(trimInsideVal); // Set it the first time if (typeof rawColumns[col][row] === 'undefined') { rawColumns[col][row] = trimVal; } // Disable number or date parsing by setting the X axis type to // category if (forceCategory || (row === 0 && firstRowAsNames)) { column[row] = '' + trimVal; } else if (+trimInsideVal === floatVal) { // is numeric column[row] = floatVal; // If the number is greater than milliseconds in a year, assume // datetime if (floatVal > 365 * 24 * 3600 * 1000 && columnType !== 'float') { column.isDatetime = true; } else { column.isNumeric = true; } if (typeof column[row + 1] !== 'undefined') { descending = floatVal > column[row + 1]; } // String, continue to determine if it is a date string or really a // string } else { if (trimVal && trimVal.length) { dateVal = this.parseDate(val); } // Only allow parsing of dates if this column is an x-column if (isXColumn && isNumber(dateVal) && columnType !== 'float') { backup[row] = val; column[row] = dateVal; column.isDatetime = true; // Check if the dates are uniformly descending or ascending. // If they are not, chances are that they are a different // time format, so check for alternative. if (typeof column[row + 1] !== 'undefined') { diff = dateVal > column[row + 1]; if (diff !== descending && typeof descending !== 'undefined') { if (this.alternativeFormat) { this.dateFormat = this.alternativeFormat; row = column.length; this.alternativeFormat = this.dateFormats[this.dateFormat] .alternative; } else { column.unsorted = true; } } descending = diff; } } else { // string column[row] = trimVal === '' ? null : trimVal; if (row !== 0 && (column.isDatetime || column.isNumeric)) { column.mixed = true; } } } } // If strings are intermixed with numbers or dates in a parsed column, // it is an indication that parsing went wrong or the data was not // intended to display as numbers or dates and parsing is too // aggressive. Fall back to categories. Demonstrated in the // highcharts/demo/column-drilldown sample. if (isXColumn && column.mixed) { columns[col] = rawColumns[col]; } // If the 0 column is date or number and descending, reverse all // columns. if (isXColumn && descending && this.options.sort) { for (col = 0; col < columns.length; col++) { columns[col].reverse(); if (firstRowAsNames) { columns[col].unshift(columns[col].pop()); } } } }; /** * Parse a date and return it as a number. Overridable through * `options.parseDate`. * * @function Highcharts.Data#parseDate */ Data.prototype.parseDate = function (val) { var parseDate = this.options.parseDate; var ret, key, format, dateFormat = this.options.dateFormat || this.dateFormat, match; if (parseDate) { ret = parseDate(val); } else if (typeof val === 'string') { // Auto-detect the date format the first time if (!dateFormat) { for (key in this.dateFormats) { // eslint-disable-line guard-for-in format = this.dateFormats[key]; match = val.match(format.regex); if (match) { this.dateFormat = dateFormat = key; this.alternativeFormat = format.alternative; ret = format.parser(match); break; } } // Next time, use the one previously found } else { format = this.dateFormats[dateFormat]; if (!format) { // The selected format is invalid format = this.dateFormats['YYYY/mm/dd']; } match = val.match(format.regex); if (match) { ret = format.parser(match); } } // Fall back to Date.parse if (!match) { if (val.match(/:.+(GMT|UTC|[Z+-])/)) { val = val .replace(/\s*(?:GMT|UTC)?([+-])(\d\d)(\d\d)$/, '$1$2:$3') .replace(/(?:\s+|GMT|UTC)([+-])/, '$1') .replace(/(\d)\s*(?:GMT|UTC|Z)$/, '$1+00:00'); } match = Date.parse(val); // External tools like Date.js and MooTools extend Date object // and return a date. if (typeof match === 'object' && match !== null && match.getTime) { ret = (match.getTime() - match.getTimezoneOffset() * 60000); // Timestamp } else if (isNumber(match)) { ret = match - (new Date(match)).getTimezoneOffset() * 60000; } } } return ret; }; /** * Reorganize rows into columns. * * @function Highcharts.Data#rowsToColumns */ Data.prototype.rowsToColumns = function (rows) { var row, rowsLength, col, colsLength, columns; if (rows) { columns = []; rowsLength = rows.length; for (row = 0; row < rowsLength; row++) { colsLength = rows[row].length; for (col = 0; col < colsLength; col++) { if (!columns[col]) { columns[col] = []; } columns[col][row] = rows[row][col]; } } } return columns; }; /** * Get the parsed data in a form that we can apply directly to the * `series.data` config. Array positions can be mapped using the * `series.keys` option. * * @example * const data = Highcharts.data({ * csv: document.getElementById('data').innerHTML * }).getData(); * * @function Highcharts.Data#getData * * @return {Array<Array<(number|string)>>|undefined} Data rows */ Data.prototype.getData = function () { if (this.columns) { return this.rowsToColumns(this.columns).slice(1); } }; /** * A hook for working directly on the parsed columns * * @function Highcharts.Data#parsed */ Data.prototype.parsed = function () { if (this.options.parsed) { return this.options.parsed.call(this, this.columns); } }; /** * @private * @function Highcharts.Data#getFreeIndexes */ Data.prototype.getFreeIndexes = function (numberOfColumns, seriesBuilders) { var s, i, freeIndexes = [], freeIndexValues = [], referencedIndexes; // Add all columns as free for (i = 0; i < numberOfColumns; i = i + 1) { freeIndexes.push(true); } // Loop all defined builders and remove their referenced columns for (s = 0; s < seriesBuilders.length; s = s + 1) { referencedIndexes = seriesBuilders[s].getReferencedColumnIndexes(); for (i = 0; i < referencedIndexes.length; i = i + 1) { freeIndexes[referencedIndexes[i]] = false; } } // Collect the values for the free indexes for (i = 0; i < freeIndexes.length; i = i + 1) { if (freeIndexes[i]) { freeIndexValues.push(i); } } return freeIndexValues; }; /** * If a complete callback function is provided in the options, interpret the * columns into a Highcharts options object. * * @function Highcharts.Data#complete */ Data.prototype.complete = function () { var columns = this.columns, xColumns = [], type, options = this.options, series, data, i, j, r, seriesIndex, chartOptions, allSeriesBuilders = [], builder, freeIndexes, typeCol, index; xColumns.length = columns.length; if (options.complete || options.afterComplete) { // Get the names and shift the top row if (this.firstRowAsNames) { for (i = 0; i < columns.length; i++) { var curCol = columns[i]; if (!defined(curCol.name)) { curCol.name = pick(curCol.shift(), '').toString(); } } } // Use the next columns for series series = []; freeIndexes = this.getFreeIndexes(columns.length, this.valueCount.seriesBuilders); // Populate defined series for (seriesIndex = 0; seriesIndex < this.valueCount.seriesBuilders.length; seriesIndex++) { builder = this.valueCount.seriesBuilders[seriesIndex]; // If the builder can be populated with remaining columns, then // add it to allBuilders if (builder.populateColumns(freeIndexes)) { allSeriesBuilders.push(builder); } } // Populate dynamic series while (freeIndexes.length > 0) { builder = new SeriesBuilder(); builder.addColumnReader(0, 'x'); // Mark index as used (not free) index = freeIndexes.indexOf(0); if (index !== -1) { freeIndexes.splice(index, 1); } for (i = 0; i < this.valueCount.global; i++) { // Create and add a column reader for the next free column // index builder.addColumnReader(void 0, this.valueCount.globalPointArrayMap[i]); } // If the builder can be populated with remaining columns, then // add it to allBuilders if (builder.populateColumns(freeIndexes)) { allSeriesBuilders.push(builder); } } // Get the data-type from the first series x column if (allSeriesBuilders.length > 0 && allSeriesBuilders[0].readers.length > 0) { typeCol = columns[allSeriesBuilders[0].readers[0].columnIndex]; if (typeof typeCol !== 'undefined') { if (typeCol.isDatetime) { type = 'datetime'; } else if (!typeCol.isNumeric) { type = 'category'; } } } // Axis type is category, then the "x" column should be called // "name" if (type === 'category') { for (seriesIndex = 0; seriesIndex < allSeriesBuilders.length; seriesIndex++) { builder = allSeriesBuilders[seriesIndex]; for (r = 0; r < builder.readers.length; r++) { if (builder.readers[r].configName === 'x') { builder.readers[r].configName = 'name'; } } } } // Read data for all builders for (seriesIndex = 0; seriesIndex < allSeriesBuilders.length; seriesIndex++) { builder = allSeriesBuilders[seriesIndex]; // Iterate down the cells of each column and add data to the // series data = []; for (j = 0; j < columns[0].length; j++) { data[j] = builder.read(columns, j); } // Add the series series[seriesIndex] = { data: data }; if (builder.name) { series[seriesIndex].name = builder.name; } if (type === 'category') { series[seriesIndex].turboThreshold = 0; } } // Do the callback chartOptions = { series: series }; if (type) { chartOptions.xAxis = { type: type }; if (type === 'category') { chartOptions.xAxis.uniqueNames = false; } } if (options.complete) { options.complete(chartOptions); } // The afterComplete hook is used internally to avoid conflict with // the externally available complete option. if (options.afterComplete) { options.afterComplete(chartOptions); } } }; /** * Updates the chart with new data options. * * @function Highcharts.Data#update * * @param {Highcharts.DataOptions} options * * @param {boolean} [redraw=true] */ Data.prototype.update = function (options, redraw) { var chart = this.chart; if (options) { // Set the complete handler options.afterComplete = function (dataOptions) { // Avoid setting axis options unless the type changes. Running // Axis.update will cause the whole structure to be destroyed // and rebuilt, and animation is lost. if (dataOptions) { if (dataOptions.xAxis && chart.xAxis[0] && dataOptions.xAxis.type === chart.xAxis[0].options.type) { delete dataOptions.xAxis; } // @todo looks not right: chart.update(dataOptions, redraw, true); } }; // Apply it merge(true, chart.options.data, options); this.init(chart.options.data); } }; return Data; }()); // Register the Data prototype and data function on Highcharts // Highcharts.Data = Data as any; /** * Creates a data object to parse data for a chart. * * @function Highcharts.data */ G.data = function (dataOptions, chartOptions, chart) { return new G.Data(dataOptions, chartOptions, chart); }; // Extend Chart.init so that the Chart constructor accepts a new configuration // option group, data. addEvent(Chart, 'init', function (e) { var chart = this, // eslint-disable-line no-invalid-this userOptions = (e.args[0] || {}), callback = e.args[1]; if (userOptions && userOptions.data && !chart.hasDataDef) { chart.hasDataDef = true; /** * The data parser for this chart. * * @name Highcharts.Chart#data * @type {Highcharts.Data|undefined} */ chart.data = new G.Data(extend(userOptions.data, { afterComplete: function (dataOptions) { var i, series; // Merge series configs if (Object.hasOwnProperty.call(userOptions, 'series')) { if (typeof userOptions.series === 'object') { i = Math.max(userOptions.series.length, dataOptions && dataOptions.series ? dataOptions.series.length : 0); while (i--) { series = userOptions.series[i] || {}; userOptions.series[i] = merge(series, dataOptions && dataOptions.series ? dataOptions.series[i] : {}); } } else { // Allow merging in dataOptions.series (#2856) delete userOptions.series; } } // Do the merge userOptions = merge(dataOptions, userOptions); // Run chart.init again chart.init(userOptions, callback); } }), userOptions, chart); e.preventDefault(); } }); /** * Creates a new SeriesBuilder. A SeriesBuilder consists of a number * of ColumnReaders that reads columns and give them a name. * Ex: A series builder can be constructed to read column 3 as 'x' and * column 7 and 8 as 'y1' and 'y2'. * The output would then be points/rows of the form {x: 11, y1: 22, y2: 33} * * The name of the builder is taken from the second column. In the above * example it would be the column with index 7. * * @private * @class * @name SeriesBuilder */ var SeriesBuilder = /** @class */ (function () { function SeriesBuilder() { /* eslint-disable no-invalid-this */ this.readers = []; this.pointIsArray = true; /* eslint-enable no-invalid-this */ this.name = void 0; } /** * Populates readers with column indexes. A reader can be added without * a specific index and for those readers the index is taken sequentially * from the free columns (this is handled by the ColumnCursor instance). * * @function SeriesBuilder#populateColumns */ SeriesBuilder.prototype.populateColumns = function (freeIndexes) { var builder = this, enoughColumns = true; // Loop each reader and give it an index if its missing. // The freeIndexes.shift() will return undefined if there // are no more columns. builder.readers.forEach(function (reader) { if (typeof reader.columnIndex === 'undefined') { reader.columnIndex = freeIndexes.shift(); } }); // Now, all readers should have columns mapped. If not // then return false to signal that this series should // not be added. builder.readers.forEach(function (reader) { if (typeof reader.columnIndex === 'undefined') { enoughColumns = false; } }); return enoughColumns; }; /** * Reads a row from the dataset and returns a point or array depending * on the names of the readers. * * @function SeriesBuilder#read<T> */ SeriesBuilder.prototype.read = function (columns, rowIndex) { var builder = this, pointIsArray = builder.pointIsArray, point = pointIsArray ? [] : {}, columnIndexes; // Loop each reader and ask it to read its value. // Then, build an array or point based on the readers names. builder.readers.forEach(function (reader) { var value = columns[reader.columnIndex][rowIndex]; if (pointIsArray) { point.push(value); } else { if (reader.configName.indexOf('.') > 0) { // Handle nested property names Point.prototype.setNestedProperty(point, value, reader.configName); } else { point[reader.configName] = value; } } }); // The name comes from the first column (excluding the x column) if (typeof this.name === 'undefined' && builder.readers.length >= 2) { columnIndexes = builder.getReferencedColumnIndexes(); if (columnIndexes.length >= 2) { // remove the first one (x col) columnIndexes.shift(); // Sort the remaining columnIndexes.sort(function (a, b) { return a - b; }); // Now use the lowest index as name column this.name = columns[columnIndexes.shift()].name; } } return point; }; /** * Creates and adds ColumnReader from the given columnIndex and configName. * ColumnIndex can be undefined and in that case the reader will be given * an index when columns are populated. * * @function SeriesBuilder#addColumnReader */ SeriesBuilder.prototype.addColumnReader = function (columnIndex, configName) { this.readers.push({ columnIndex: columnIndex, configName: configName }); if (!(configName === 'x' || configName === 'y' || typeof configName === 'undefined')) { this.pointIsArray = false; } }; /** * Returns an array of column indexes that the builder will use when * reading data. * * @function SeriesBuilder#getReferencedColumnIndexes */ SeriesBuilder.prototype.getReferencedColumnIndexes = function () { var i, referencedColumnIndexes = [], columnReader; for (i = 0; i < this.readers.length; i = i + 1) { columnReader = this.readers[i]; if (typeof columnReader.columnIndex !== 'undefined') { referencedColumnIndexes.push(columnReader.columnIndex); } } return referencedColumnIndexes; }; /** * Returns true if the builder has a reader for the given configName. * * @function SeriesBuider#hasReader */ SeriesBuilder.prototype.hasReader = function (configName) { var i, columnReader; for (i = 0; i < this.readers.length; i = i + 1) { columnReader = this.readers[i]; if (columnReader.configName === configName) { return true; } } // Else return undefined }; return SeriesBuilder; }()); G.Data = Data; export default G.Data;
/* Name: View - Contact Written by: Okler Themes - (http://www.okler.net) Version: 4.3.1 */ (function($) { 'use strict'; /* Contact Form: Basic */ $('#contactForm:not([data-type=advanced])').validate({ submitHandler: function(form) { var $form = $(form), $messageSuccess = $('#contactSuccess'), $messageError = $('#contactError'), $submitButton = $(this.submitButton); $submitButton.button('loading'); // Ajax Submit $.ajax({ type: 'POST', url: $form.attr('action'), data: { name: $form.find('#name').val(), email: $form.find('#email').val(), subject: $form.find('#subject').val(), message: $form.find('#message').val() }, dataType: 'json', complete: function(data) { if (typeof data.responseJSON === 'object') { if (data.responseJSON.response == 'success') { $messageSuccess.removeClass('hidden'); $messageError.addClass('hidden'); // Reset Form $form.find('.form-control') .val('') .blur() .parent() .removeClass('has-success') .removeClass('has-error') .find('label.error') .remove(); if (($messageSuccess.offset().top - 80) < $(window).scrollTop()) { $('html, body').animate({ scrollTop: $messageSuccess.offset().top - 80 }, 300); } $submitButton.button('reset'); return; } } $messageError.removeClass('hidden'); $messageSuccess.addClass('hidden'); if (($messageError.offset().top - 80) < $(window).scrollTop()) { $('html, body').animate({ scrollTop: $messageError.offset().top - 80 }, 300); } $form.find('.has-success') .removeClass('has-success'); $submitButton.button('reset'); } }); } }); /* Contact Form: Advanced */ $('#contactFormAdvanced, #contactForm[data-type=advanced]').validate({ onkeyup: false, onclick: false, onfocusout: false, rules: { 'captcha': { captcha: true }, 'checkboxes[]': { required: true }, 'radios': { required: true } }, errorPlacement: function(error, element) { if (element.attr('type') == 'radio' || element.attr('type') == 'checkbox') { error.appendTo(element.parent().parent()); } else { error.insertAfter(element); } } }); }).apply(this, [jQuery]);
/*! * Waves v0.6.4 * http://fian.my.id/Waves * * Copyright 2014 Alfiana E. Sibuea and other contributors * Released under the MIT license * https://github.com/fians/Waves/blob/master/LICENSE */ ;(function(window) { 'use strict'; var Waves = Waves || {}; var $$ = document.querySelectorAll.bind(document); // Find exact position of element function isWindow(obj) { return obj !== null && obj === obj.window; } function getWindow(elem) { return isWindow(elem) ? elem : elem.nodeType === 9 && elem.defaultView; } function offset(elem) { var docElem, win, box = {top: 0, left: 0}, doc = elem && elem.ownerDocument; docElem = doc.documentElement; if (typeof elem.getBoundingClientRect !== typeof undefined) { box = elem.getBoundingClientRect(); } win = getWindow(doc); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; } function convertStyle(obj) { var style = ''; for (var a in obj) { if (obj.hasOwnProperty(a)) { style += (a + ':' + obj[a] + ';'); } } return style; } var Effect = { // Effect delay duration: 750, show: function(e, element) { // Disable right click if (e.button === 2) { return false; } var el = element || this; // Create ripple var ripple = document.createElement('div'); ripple.className = 'waves-ripple'; el.appendChild(ripple); // Get click coordinate and element witdh var pos = offset(el); var relativeY = (e.pageY - pos.top); var relativeX = (e.pageX - pos.left); var scale = 'scale('+((el.clientWidth / 100) * 10)+')'; // Support for touch devices if ('touches' in e) { relativeY = (e.touches[0].pageY - pos.top); relativeX = (e.touches[0].pageX - pos.left); } // Attach data to element ripple.setAttribute('data-hold', Date.now()); ripple.setAttribute('data-scale', scale); ripple.setAttribute('data-x', relativeX); ripple.setAttribute('data-y', relativeY); // Set ripple position var rippleStyle = { 'top': relativeY+'px', 'left': relativeX+'px' }; ripple.className = ripple.className + ' waves-notransition'; ripple.setAttribute('style', convertStyle(rippleStyle)); ripple.className = ripple.className.replace('waves-notransition', ''); // Scale the ripple rippleStyle['-webkit-transform'] = scale; rippleStyle['-moz-transform'] = scale; rippleStyle['-ms-transform'] = scale; rippleStyle['-o-transform'] = scale; rippleStyle.transform = scale; rippleStyle.opacity = '1'; rippleStyle['-webkit-transition-duration'] = Effect.duration + 'ms'; rippleStyle['-moz-transition-duration'] = Effect.duration + 'ms'; rippleStyle['-o-transition-duration'] = Effect.duration + 'ms'; rippleStyle['transition-duration'] = Effect.duration + 'ms'; rippleStyle['-webkit-transition-timing-function'] = 'cubic-bezier(0.250, 0.460, 0.450, 0.940)'; rippleStyle['-moz-transition-timing-function'] = 'cubic-bezier(0.250, 0.460, 0.450, 0.940)'; rippleStyle['-o-transition-timing-function'] = 'cubic-bezier(0.250, 0.460, 0.450, 0.940)'; rippleStyle['transition-timing-function'] = 'cubic-bezier(0.250, 0.460, 0.450, 0.940)'; ripple.setAttribute('style', convertStyle(rippleStyle)); }, hide: function(e) { TouchHandler.touchup(e); var el = this; var width = el.clientWidth * 1.4; // Get first ripple var ripple = null; var ripples = el.getElementsByClassName('waves-ripple'); if (ripples.length > 0) { ripple = ripples[ripples.length - 1]; } else { return false; } var relativeX = ripple.getAttribute('data-x'); var relativeY = ripple.getAttribute('data-y'); var scale = ripple.getAttribute('data-scale'); // Get delay beetween mousedown and mouse leave var diff = Date.now() - Number(ripple.getAttribute('data-hold')); var delay = 350 - diff; if (delay < 0) { delay = 0; } // Fade out ripple after delay setTimeout(function() { var style = { 'top': relativeY+'px', 'left': relativeX+'px', 'opacity': '0', // Duration '-webkit-transition-duration': Effect.duration + 'ms', '-moz-transition-duration': Effect.duration + 'ms', '-o-transition-duration': Effect.duration + 'ms', 'transition-duration': Effect.duration + 'ms', '-webkit-transform': scale, '-moz-transform': scale, '-ms-transform': scale, '-o-transform': scale, 'transform': scale, }; ripple.setAttribute('style', convertStyle(style)); setTimeout(function() { try { el.removeChild(ripple); } catch(e) { return false; } }, Effect.duration); }, delay); }, // Little hack to make <input> can perform waves effect wrapInput: function(elements) { for (var a = 0; a < elements.length; a++) { var el = elements[a]; if (el.tagName.toLowerCase() === 'input') { var parent = el.parentNode; // If input already have parent just pass through if (parent.tagName.toLowerCase() === 'i' && parent.className.indexOf('waves-effect') !== -1) { continue; } // Put element class and style to the specified parent var wrapper = document.createElement('i'); wrapper.className = el.className + ' waves-input-wrapper'; var elementStyle = el.getAttribute('style'); if (!elementStyle) { elementStyle = ''; } wrapper.setAttribute('style', elementStyle); el.className = 'waves-button-input'; el.removeAttribute('style'); // Put element as child parent.replaceChild(wrapper, el); wrapper.appendChild(el); } } } }; /** * Disable mousedown event for 500ms during and after touch */ var TouchHandler = { /* uses an integer rather than bool so there's no issues with * needing to clear timeouts if another touch event occurred * within the 500ms. Cannot mouseup between touchstart and * touchend, nor in the 500ms after touchend. */ touches: 0, allowEvent: function(e) { var allow = true; if (e.type === 'touchstart') { TouchHandler.touches += 1; //push } else if (e.type === 'touchend' || e.type === 'touchcancel') { setTimeout(function() { if (TouchHandler.touches > 0) { TouchHandler.touches -= 1; //pop after 500ms } }, 500); } else if (e.type === 'mousedown' && TouchHandler.touches > 0) { allow = false; } return allow; }, touchup: function(e) { TouchHandler.allowEvent(e); } }; /** * Delegated click handler for .waves-effect element. * returns null when .waves-effect element not in "click tree" */ function getWavesEffectElement(e) { if (TouchHandler.allowEvent(e) === false) { return null; } var element = null; var target = e.target || e.srcElement; while (target.parentElement !== null) { if (!(target instanceof SVGElement) && target.className.indexOf('waves-effect') !== -1) { element = target; break; } else if (target.classList.contains('waves-effect')) { element = target; break; } target = target.parentElement; } return element; } /** * Bubble the click and show effect if .waves-effect elem was found */ function showEffect(e) { var element = getWavesEffectElement(e); if (element !== null) { Effect.show(e, element); if ('ontouchstart' in window) { element.addEventListener('touchend', Effect.hide, false); element.addEventListener('touchcancel', Effect.hide, false); } element.addEventListener('mouseup', Effect.hide, false); element.addEventListener('mouseleave', Effect.hide, false); } } Waves.displayEffect = function(options) { options = options || {}; if ('duration' in options) { Effect.duration = options.duration; } //Wrap input inside <i> tag Effect.wrapInput($$('.waves-effect')); if ('ontouchstart' in window) { document.body.addEventListener('touchstart', showEffect, false); } document.body.addEventListener('mousedown', showEffect, false); }; /** * Attach Waves to an input element (or any element which doesn't * bubble mouseup/mousedown events). * Intended to be used with dynamically loaded forms/inputs, or * where the user doesn't want a delegated click handler. */ Waves.attach = function(element) { //FUTURE: automatically add waves classes and allow users // to specify them with an options param? Eg. light/classic/button if (element.tagName.toLowerCase() === 'input') { Effect.wrapInput([element]); element = element.parentElement; } if ('ontouchstart' in window) { element.addEventListener('touchstart', showEffect, false); } element.addEventListener('mousedown', showEffect, false); }; window.Waves = Waves; document.addEventListener('DOMContentLoaded', function() { Waves.displayEffect(); }, false); })(window);
/** * BxSlider v4.1.1 - Fully loaded, responsive content slider * http://bxslider.com * * Copyright 2013, Steven Wanderski - http://stevenwanderski.com - http://bxcreative.com * Written while drinking Belgian ales and listening to jazz * * Released under the MIT license - http://opensource.org/licenses/MIT */ ;(function($){ var plugin = {}; var defaults = { // GENERAL mode: 'horizontal', slideSelector: '', infiniteLoop: true, hideControlOnEnd: false, speed: 500, easing: null, slideMargin: 0, startSlide: 0, randomStart: false, captions: false, ticker: false, tickerHover: false, adaptiveHeight: false, adaptiveHeightSpeed: 500, video: false, useCSS: true, preloadImages: 'visible', responsive: true, // TOUCH touchEnabled: true, swipeThreshold: 50, oneToOneTouch: true, preventDefaultSwipeX: true, preventDefaultSwipeY: false, // PAGER pager: true, pagerType: 'full', pagerShortSeparator: ' / ', pagerSelector: null, buildPager: null, pagerCustom: null, // CONTROLS controls: true, nextText: 'Next', prevText: 'Prev', nextSelector: null, prevSelector: null, autoControls: false, startText: 'Start', stopText: 'Stop', autoControlsCombine: false, autoControlsSelector: null, // AUTO auto: false, pause: 4000, autoStart: true, autoDirection: 'next', autoHover: false, autoDelay: 0, // CAROUSEL minSlides: 1, maxSlides: 1, moveSlides: 0, slideWidth: 0, // CALLBACKS onSliderLoad: function() {}, onSlideBefore: function() {}, onSlideAfter: function() {}, onSlideNext: function() {}, onSlidePrev: function() {} } $.fn.bxSlider = function(options){ if(this.length == 0) return this; // support mutltiple elements if(this.length > 1){ this.each(function(){$(this).bxSlider(options)}); return this; } // create a namespace to be used throughout the plugin var slider = {}; // set a reference to our slider element var el = this; plugin.el = this; /** * Makes slideshow responsive */ // first get the original window dimens (thanks alot IE) var windowWidth = $(window).width(); var windowHeight = $(window).height(); /** * =================================================================================== * = PRIVATE FUNCTIONS * =================================================================================== */ /** * Initializes namespace settings to be used throughout plugin */ var init = function(){ // merge user-supplied options with the defaults slider.settings = $.extend({}, defaults, options); // parse slideWidth setting slider.settings.slideWidth = parseInt(slider.settings.slideWidth); // store the original children slider.children = el.children(slider.settings.slideSelector); // check if actual number of slides is less than minSlides / maxSlides if(slider.children.length < slider.settings.minSlides) slider.settings.minSlides = slider.children.length; if(slider.children.length < slider.settings.maxSlides) slider.settings.maxSlides = slider.children.length; // if random start, set the startSlide setting to random number if(slider.settings.randomStart) slider.settings.startSlide = Math.floor(Math.random() * slider.children.length); // store active slide information slider.active = { index: slider.settings.startSlide } // store if the slider is in carousel mode (displaying / moving multiple slides) slider.carousel = slider.settings.minSlides > 1 || slider.settings.maxSlides > 1; // if carousel, force preloadImages = 'all' if(slider.carousel) slider.settings.preloadImages = 'all'; // calculate the min / max width thresholds based on min / max number of slides // used to setup and update carousel slides dimensions slider.minThreshold = (slider.settings.minSlides * slider.settings.slideWidth) + ((slider.settings.minSlides - 1) * slider.settings.slideMargin); slider.maxThreshold = (slider.settings.maxSlides * slider.settings.slideWidth) + ((slider.settings.maxSlides - 1) * slider.settings.slideMargin); // store the current state of the slider (if currently animating, working is true) slider.working = false; // initialize the controls object slider.controls = {}; // initialize an auto interval slider.interval = null; // determine which property to use for transitions slider.animProp = slider.settings.mode == 'vertical' ? 'top' : 'left'; // determine if hardware acceleration can be used slider.usingCSS = slider.settings.useCSS && slider.settings.mode != 'fade' && (function(){ // create our test div element var div = document.createElement('div'); // css transition properties var props = ['WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective']; // test for each property for(var i in props){ if(div.style[props[i]] !== undefined){ slider.cssPrefix = props[i].replace('Perspective', '').toLowerCase(); slider.animProp = '-' + slider.cssPrefix + '-transform'; return true; } } return false; }()); // if vertical mode always make maxSlides and minSlides equal if(slider.settings.mode == 'vertical') slider.settings.maxSlides = slider.settings.minSlides; // save original style data el.data("origStyle", el.attr("style")); el.children(slider.settings.slideSelector).each(function() { $(this).data("origStyle", $(this).attr("style")); }); // perform all DOM / CSS modifications setup(); } /** * Performs all DOM and CSS modifications */ var setup = function(){ // wrap el in a wrapper el.wrap('<div class="bx-wrapper"><div class="bx-viewport"></div></div>'); // store a namspace reference to .bx-viewport slider.viewport = el.parent(); // add a loading div to display while images are loading slider.loader = $('<div class="bx-loading" />'); slider.viewport.prepend(slider.loader); // set el to a massive width, to hold any needed slides // also strip any margin and padding from el el.css({ width: slider.settings.mode == 'horizontal' ? (slider.children.length * 100 + 215) + '%' : 'auto', position: 'relative' }); // if using CSS, add the easing property if(slider.usingCSS && slider.settings.easing){ el.css('-' + slider.cssPrefix + '-transition-timing-function', slider.settings.easing); // if not using CSS and no easing value was supplied, use the default JS animation easing (swing) }else if(!slider.settings.easing){ slider.settings.easing = 'swing'; } var slidesShowing = getNumberSlidesShowing(); // make modifications to the viewport (.bx-viewport) slider.viewport.css({ width: '100%', overflow: 'hidden', position: 'relative' }); slider.viewport.parent().css({ maxWidth: getViewportMaxWidth() }); // make modification to the wrapper (.bx-wrapper) if(!slider.settings.pager) { slider.viewport.parent().css({ margin: '0 auto 0px' }); } // apply css to all slider children slider.children.css({ 'float': slider.settings.mode == 'horizontal' ? 'left' : 'none', listStyle: 'none', position: 'relative' }); // apply the calculated width after the float is applied to prevent scrollbar interference slider.children.css('width', getSlideWidth()); // if slideMargin is supplied, add the css if(slider.settings.mode == 'horizontal' && slider.settings.slideMargin > 0) slider.children.css('marginRight', slider.settings.slideMargin); if(slider.settings.mode == 'vertical' && slider.settings.slideMargin > 0) slider.children.css('marginBottom', slider.settings.slideMargin); // if "fade" mode, add positioning and z-index CSS if(slider.settings.mode == 'fade'){ slider.children.css({ position: 'absolute', zIndex: 0, display: 'none' }); // prepare the z-index on the showing element slider.children.eq(slider.settings.startSlide).css({zIndex: 50, display: 'block'}); } // create an element to contain all slider controls (pager, start / stop, etc) slider.controls.el = $('<div class="bx-controls" />'); // if captions are requested, add them if(slider.settings.captions) appendCaptions(); // check if startSlide is last slide slider.active.last = slider.settings.startSlide == getPagerQty() - 1; // if video is true, set up the fitVids plugin if(slider.settings.video) el.fitVids(); // set the default preload selector (visible) var preloadSelector = slider.children.eq(slider.settings.startSlide); if (slider.settings.preloadImages == "all") preloadSelector = slider.children; // only check for control addition if not in "ticker" mode if(!slider.settings.ticker){ // if pager is requested, add it if(slider.settings.pager) appendPager(); // if controls are requested, add them if(slider.settings.controls) appendControls(); // if auto is true, and auto controls are requested, add them if(slider.settings.auto && slider.settings.autoControls) appendControlsAuto(); // if any control option is requested, add the controls wrapper if(slider.settings.controls || slider.settings.autoControls || slider.settings.pager) slider.viewport.after(slider.controls.el); // if ticker mode, do not allow a pager }else{ slider.settings.pager = false; } // preload all images, then perform final DOM / CSS modifications that depend on images being loaded loadElements(preloadSelector, start); } var loadElements = function(selector, callback){ var total = selector.find('img, iframe').length; if (total == 0){ callback(); return; } var count = 0; selector.find('img, iframe').each(function(){ $(this).one('load', function() { if(++count == total) callback(); }).each(function() { if(this.complete) $(this).load(); }); }); } /** * Start the slider */ var start = function(){ // if infinite loop, prepare additional slides if(slider.settings.infiniteLoop && slider.settings.mode != 'fade' && !slider.settings.ticker){ var slice = slider.settings.mode == 'vertical' ? slider.settings.minSlides : slider.settings.maxSlides; var sliceAppend = slider.children.slice(0, slice).clone().addClass('bx-clone'); var slicePrepend = slider.children.slice(-slice).clone().addClass('bx-clone'); el.append(sliceAppend).prepend(slicePrepend); } // remove the loading DOM element slider.loader.remove(); // set the left / top position of "el" setSlidePosition(); // if "vertical" mode, always use adaptiveHeight to prevent odd behavior if (slider.settings.mode == 'vertical') slider.settings.adaptiveHeight = true; // set the viewport height slider.viewport.height(getViewportHeight()); // make sure everything is positioned just right (same as a window resize) el.redrawSlider(); // onSliderLoad callback slider.settings.onSliderLoad(slider.active.index); // slider has been fully initialized slider.initialized = true; // bind the resize call to the window if (slider.settings.responsive) $(window).bind('resize', resizeWindow); // if auto is true, start the show if (slider.settings.auto && slider.settings.autoStart) initAuto(); // if ticker is true, start the ticker if (slider.settings.ticker) initTicker(); // if pager is requested, make the appropriate pager link active if (slider.settings.pager) updatePagerActive(slider.settings.startSlide); // check for any updates to the controls (like hideControlOnEnd updates) if (slider.settings.controls) updateDirectionControls(); // if touchEnabled is true, setup the touch events if (slider.settings.touchEnabled && !slider.settings.ticker) initTouch(); } /** * Returns the calculated height of the viewport, used to determine either adaptiveHeight or the maxHeight value */ var getViewportHeight = function(){ var height = 0; // first determine which children (slides) should be used in our height calculation var children = $(); // if mode is not "vertical" and adaptiveHeight is false, include all children if(slider.settings.mode != 'vertical' && !slider.settings.adaptiveHeight){ children = slider.children; }else{ // if not carousel, return the single active child if(!slider.carousel){ children = slider.children.eq(slider.active.index); // if carousel, return a slice of children }else{ // get the individual slide index var currentIndex = slider.settings.moveSlides == 1 ? slider.active.index : slider.active.index * getMoveBy(); // add the current slide to the children children = slider.children.eq(currentIndex); // cycle through the remaining "showing" slides for (i = 1; i <= slider.settings.maxSlides - 1; i++){ // if looped back to the start if(currentIndex + i >= slider.children.length){ children = children.add(slider.children.eq(i - 1)); }else{ children = children.add(slider.children.eq(currentIndex + i)); } } } } // if "vertical" mode, calculate the sum of the heights of the children if(slider.settings.mode == 'vertical'){ children.each(function(index) { height += $(this).outerHeight(); }); // add user-supplied margins if(slider.settings.slideMargin > 0){ height += slider.settings.slideMargin * (slider.settings.minSlides - 1); } // if not "vertical" mode, calculate the max height of the children }else{ height = Math.max.apply(Math, children.map(function(){ return $(this).outerHeight(false); }).get()); } return height; } /** * Returns the calculated width to be used for the outer wrapper / viewport */ var getViewportMaxWidth = function(){ var width = '100%'; if(slider.settings.slideWidth > 0){ if(slider.settings.mode == 'horizontal'){ width = (slider.settings.maxSlides * slider.settings.slideWidth) + ((slider.settings.maxSlides - 1) * slider.settings.slideMargin); }else{ width = slider.settings.slideWidth; } } return width; } /** * Returns the calculated width to be applied to each slide */ var getSlideWidth = function(){ // start with any user-supplied slide width var newElWidth = slider.settings.slideWidth; // get the current viewport width var wrapWidth = slider.viewport.width(); // if slide width was not supplied, or is larger than the viewport use the viewport width if(slider.settings.slideWidth == 0 || (slider.settings.slideWidth > wrapWidth && !slider.carousel) || slider.settings.mode == 'vertical'){ newElWidth = wrapWidth; // if carousel, use the thresholds to determine the width }else if(slider.settings.maxSlides > 1 && slider.settings.mode == 'horizontal'){ if(wrapWidth > slider.maxThreshold){ // newElWidth = (wrapWidth - (slider.settings.slideMargin * (slider.settings.maxSlides - 1))) / slider.settings.maxSlides; }else if(wrapWidth < slider.minThreshold){ newElWidth = (wrapWidth - (slider.settings.slideMargin * (slider.settings.minSlides - 1))) / slider.settings.minSlides; } } return newElWidth; } /** * Returns the number of slides currently visible in the viewport (includes partially visible slides) */ var getNumberSlidesShowing = function(){ var slidesShowing = 1; if(slider.settings.mode == 'horizontal' && slider.settings.slideWidth > 0){ // if viewport is smaller than minThreshold, return minSlides if(slider.viewport.width() < slider.minThreshold){ slidesShowing = slider.settings.minSlides; // if viewport is larger than minThreshold, return maxSlides }else if(slider.viewport.width() > slider.maxThreshold){ slidesShowing = slider.settings.maxSlides; // if viewport is between min / max thresholds, divide viewport width by first child width }else{ var childWidth = slider.children.first().width(); slidesShowing = Math.floor(slider.viewport.width() / childWidth); } // if "vertical" mode, slides showing will always be minSlides }else if(slider.settings.mode == 'vertical'){ slidesShowing = slider.settings.minSlides; } return slidesShowing; } /** * Returns the number of pages (one full viewport of slides is one "page") */ var getPagerQty = function(){ var pagerQty = 0; // if moveSlides is specified by the user if(slider.settings.moveSlides > 0){ if(slider.settings.infiniteLoop){ pagerQty = slider.children.length / getMoveBy(); }else{ // use a while loop to determine pages var breakPoint = 0; var counter = 0 // when breakpoint goes above children length, counter is the number of pages while (breakPoint < slider.children.length){ ++pagerQty; breakPoint = counter + getNumberSlidesShowing(); counter += slider.settings.moveSlides <= getNumberSlidesShowing() ? slider.settings.moveSlides : getNumberSlidesShowing(); } } // if moveSlides is 0 (auto) divide children length by sides showing, then round up }else{ pagerQty = Math.ceil(slider.children.length / getNumberSlidesShowing()); } return pagerQty; } /** * Returns the number of indivual slides by which to shift the slider */ var getMoveBy = function(){ // if moveSlides was set by the user and moveSlides is less than number of slides showing if(slider.settings.moveSlides > 0 && slider.settings.moveSlides <= getNumberSlidesShowing()){ return slider.settings.moveSlides; } // if moveSlides is 0 (auto) return getNumberSlidesShowing(); } /** * Sets the slider's (el) left or top position */ var setSlidePosition = function(){ // if last slide, not infinite loop, and number of children is larger than specified maxSlides if(slider.children.length > slider.settings.maxSlides && slider.active.last && !slider.settings.infiniteLoop){ if (slider.settings.mode == 'horizontal'){ // get the last child's position var lastChild = slider.children.last(); var position = lastChild.position(); // set the left position setPositionProperty(-(position.left - (slider.viewport.width() - lastChild.width())), 'reset', 0); }else if(slider.settings.mode == 'vertical'){ // get the last showing index's position var lastShowingIndex = slider.children.length - slider.settings.minSlides; var position = slider.children.eq(lastShowingIndex).position(); // set the top position setPositionProperty(-position.top, 'reset', 0); } // if not last slide }else{ // get the position of the first showing slide var position = slider.children.eq(slider.active.index * getMoveBy()).position(); // check for last slide if (slider.active.index == getPagerQty() - 1) slider.active.last = true; // set the repective position if (position != undefined){ if (slider.settings.mode == 'horizontal') setPositionProperty(-position.left, 'reset', 0); else if (slider.settings.mode == 'vertical') setPositionProperty(-position.top, 'reset', 0); } } } /** * Sets the el's animating property position (which in turn will sometimes animate el). * If using CSS, sets the transform property. If not using CSS, sets the top / left property. * * @param value (int) * - the animating property's value * * @param type (string) 'slider', 'reset', 'ticker' * - the type of instance for which the function is being * * @param duration (int) * - the amount of time (in ms) the transition should occupy * * @param params (array) optional * - an optional parameter containing any variables that need to be passed in */ var setPositionProperty = function(value, type, duration, params){ // use CSS transform if(slider.usingCSS){ // determine the translate3d value var propValue = slider.settings.mode == 'vertical' ? 'translate3d(0, ' + value + 'px, 0)' : 'translate3d(' + value + 'px, 0, 0)'; // add the CSS transition-duration el.css('-' + slider.cssPrefix + '-transition-duration', duration / 1000 + 's'); if(type == 'slide'){ // set the property value el.css(slider.animProp, propValue); // bind a callback method - executes when CSS transition completes el.bind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function(){ // unbind the callback el.unbind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd'); updateAfterSlideTransition(); }); }else if(type == 'reset'){ el.css(slider.animProp, propValue); }else if(type == 'ticker'){ // make the transition use 'linear' el.css('-' + slider.cssPrefix + '-transition-timing-function', 'linear'); el.css(slider.animProp, propValue); // bind a callback method - executes when CSS transition completes el.bind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function(){ // unbind the callback el.unbind('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd'); // reset the position setPositionProperty(params['resetValue'], 'reset', 0); // start the loop again tickerLoop(); }); } // use JS animate }else{ var animateObj = {}; animateObj[slider.animProp] = value; if(type == 'slide'){ el.animate(animateObj, duration, slider.settings.easing, function(){ updateAfterSlideTransition(); }); }else if(type == 'reset'){ el.css(slider.animProp, value) }else if(type == 'ticker'){ el.animate(animateObj, speed, 'linear', function(){ setPositionProperty(params['resetValue'], 'reset', 0); // run the recursive loop after animation tickerLoop(); }); } } } /** * Populates the pager with proper amount of pages */ var populatePager = function(){ var pagerHtml = ''; var pagerQty = getPagerQty(); // loop through each pager item for(var i=0; i < pagerQty; i++){ var linkContent = ''; // if a buildPager function is supplied, use it to get pager link value, else use index + 1 if(slider.settings.buildPager && $.isFunction(slider.settings.buildPager)){ linkContent = slider.settings.buildPager(i); slider.pagerEl.addClass('bx-custom-pager'); }else{ linkContent = i + 1; slider.pagerEl.addClass('bx-default-pager'); } // var linkContent = slider.settings.buildPager && $.isFunction(slider.settings.buildPager) ? slider.settings.buildPager(i) : i + 1; // add the markup to the string pagerHtml += '<div class="bx-pager-item"><a href="" data-slide-index="' + i + '" class="bx-pager-link">' + linkContent + '</a></div>'; }; // populate the pager element with pager links slider.pagerEl.html(pagerHtml); } /** * Appends the pager to the controls element */ var appendPager = function(){ if(!slider.settings.pagerCustom){ // create the pager DOM element slider.pagerEl = $('<div class="bx-pager" />'); // if a pager selector was supplied, populate it with the pager if(slider.settings.pagerSelector){ $(slider.settings.pagerSelector).html(slider.pagerEl); // if no pager selector was supplied, add it after the wrapper }else{ slider.controls.el.addClass('bx-has-pager').append(slider.pagerEl); } // populate the pager populatePager(); }else{ slider.pagerEl = $(slider.settings.pagerCustom); } // assign the pager click binding slider.pagerEl.delegate('a', 'click', clickPagerBind); } /** * Appends prev / next controls to the controls element */ var appendControls = function(){ slider.controls.next = $('<a class="bx-next" href="">' + slider.settings.nextText + '</a>'); slider.controls.prev = $('<a class="bx-prev" href="">' + slider.settings.prevText + '</a>'); // bind click actions to the controls slider.controls.next.bind('click', clickNextBind); slider.controls.prev.bind('click', clickPrevBind); // if nextSlector was supplied, populate it if(slider.settings.nextSelector){ $(slider.settings.nextSelector).append(slider.controls.next); } // if prevSlector was supplied, populate it if(slider.settings.prevSelector){ $(slider.settings.prevSelector).append(slider.controls.prev); } // if no custom selectors were supplied if(!slider.settings.nextSelector && !slider.settings.prevSelector){ // add the controls to the DOM slider.controls.directionEl = $('<div class="bx-controls-direction" />'); // add the control elements to the directionEl slider.controls.directionEl.append(slider.controls.prev).append(slider.controls.next); // slider.viewport.append(slider.controls.directionEl); slider.controls.el.addClass('bx-has-controls-direction').append(slider.controls.directionEl); } } /** * Appends start / stop auto controls to the controls element */ var appendControlsAuto = function(){ slider.controls.start = $('<div class="bx-controls-auto-item"><a class="bx-start" href="">' + slider.settings.startText + '</a></div>'); slider.controls.stop = $('<div class="bx-controls-auto-item"><a class="bx-stop" href="">' + slider.settings.stopText + '</a></div>'); // add the controls to the DOM slider.controls.autoEl = $('<div class="bx-controls-auto" />'); // bind click actions to the controls slider.controls.autoEl.delegate('.bx-start', 'click', clickStartBind); slider.controls.autoEl.delegate('.bx-stop', 'click', clickStopBind); // if autoControlsCombine, insert only the "start" control if(slider.settings.autoControlsCombine){ slider.controls.autoEl.append(slider.controls.start); // if autoControlsCombine is false, insert both controls }else{ slider.controls.autoEl.append(slider.controls.start).append(slider.controls.stop); } // if auto controls selector was supplied, populate it with the controls if(slider.settings.autoControlsSelector){ $(slider.settings.autoControlsSelector).html(slider.controls.autoEl); // if auto controls selector was not supplied, add it after the wrapper }else{ slider.controls.el.addClass('bx-has-controls-auto').append(slider.controls.autoEl); } // update the auto controls updateAutoControls(slider.settings.autoStart ? 'stop' : 'start'); } /** * Appends image captions to the DOM */ var appendCaptions = function(){ // cycle through each child slider.children.each(function(index){ // get the image title attribute var title = $(this).find('img:first').attr('title'); // append the caption if (title != undefined && ('' + title).length) { $(this).append('<div class="bx-caption"><span>' + title + '</span></div>'); } }); } /** * Click next binding * * @param e (event) * - DOM event object */ var clickNextBind = function(e){ // if auto show is running, stop it if (slider.settings.auto) el.stopAuto(); el.goToNextSlide(); e.preventDefault(); } /** * Click prev binding * * @param e (event) * - DOM event object */ var clickPrevBind = function(e){ // if auto show is running, stop it if (slider.settings.auto) el.stopAuto(); el.goToPrevSlide(); e.preventDefault(); } /** * Click start binding * * @param e (event) * - DOM event object */ var clickStartBind = function(e){ el.startAuto(); e.preventDefault(); } /** * Click stop binding * * @param e (event) * - DOM event object */ var clickStopBind = function(e){ el.stopAuto(); e.preventDefault(); } /** * Click pager binding * * @param e (event) * - DOM event object */ var clickPagerBind = function(e){ // if auto show is running, stop it if (slider.settings.auto) el.stopAuto(); var pagerLink = $(e.currentTarget); var pagerIndex = parseInt(pagerLink.attr('data-slide-index')); // if clicked pager link is not active, continue with the goToSlide call if(pagerIndex != slider.active.index) el.goToSlide(pagerIndex); e.preventDefault(); } /** * Updates the pager links with an active class * * @param slideIndex (int) * - index of slide to make active */ var updatePagerActive = function(slideIndex){ // if "short" pager type var len = slider.children.length; // nb of children if(slider.settings.pagerType == 'short'){ if(slider.settings.maxSlides > 1) { len = Math.ceil(slider.children.length/slider.settings.maxSlides); } slider.pagerEl.html( (slideIndex + 1) + slider.settings.pagerShortSeparator + len); return; } // remove all pager active classes slider.pagerEl.find('a').removeClass('active'); // apply the active class for all pagers slider.pagerEl.each(function(i, el) { $(el).find('a').eq(slideIndex).addClass('active'); }); } /** * Performs needed actions after a slide transition */ var updateAfterSlideTransition = function(){ // if infinte loop is true if(slider.settings.infiniteLoop){ var position = ''; // first slide if(slider.active.index == 0){ // set the new position position = slider.children.eq(0).position(); // carousel, last slide }else if(slider.active.index == getPagerQty() - 1 && slider.carousel){ position = slider.children.eq((getPagerQty() - 1) * getMoveBy()).position(); // last slide }else if(slider.active.index == slider.children.length - 1){ position = slider.children.eq(slider.children.length - 1).position(); } if (slider.settings.mode == 'horizontal') { setPositionProperty(-position.left, 'reset', 0);; } else if (slider.settings.mode == 'vertical') { setPositionProperty(-position.top, 'reset', 0);; } } // declare that the transition is complete slider.working = false; // onSlideAfter callback slider.settings.onSlideAfter(slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index); } /** * Updates the auto controls state (either active, or combined switch) * * @param state (string) "start", "stop" * - the new state of the auto show */ var updateAutoControls = function(state){ // if autoControlsCombine is true, replace the current control with the new state if(slider.settings.autoControlsCombine){ slider.controls.autoEl.html(slider.controls[state]); // if autoControlsCombine is false, apply the "active" class to the appropriate control }else{ slider.controls.autoEl.find('a').removeClass('active'); slider.controls.autoEl.find('a:not(.bx-' + state + ')').addClass('active'); } } /** * Updates the direction controls (checks if either should be hidden) */ var updateDirectionControls = function(){ if(getPagerQty() == 1){ slider.controls.prev.addClass('disabled'); slider.controls.next.addClass('disabled'); }else if(!slider.settings.infiniteLoop && slider.settings.hideControlOnEnd){ // if first slide if (slider.active.index == 0){ slider.controls.prev.addClass('disabled'); slider.controls.next.removeClass('disabled'); // if last slide }else if(slider.active.index == getPagerQty() - 1){ slider.controls.next.addClass('disabled'); slider.controls.prev.removeClass('disabled'); // if any slide in the middle }else{ slider.controls.prev.removeClass('disabled'); slider.controls.next.removeClass('disabled'); } } } /** * Initialzes the auto process */ var initAuto = function(){ // if autoDelay was supplied, launch the auto show using a setTimeout() call if(slider.settings.autoDelay > 0){ var timeout = setTimeout(el.startAuto, slider.settings.autoDelay); // if autoDelay was not supplied, start the auto show normally }else{ el.startAuto(); } // if autoHover is requested if(slider.settings.autoHover){ // on el hover el.hover(function(){ // if the auto show is currently playing (has an active interval) if(slider.interval){ // stop the auto show and pass true agument which will prevent control update el.stopAuto(true); // create a new autoPaused value which will be used by the relative "mouseout" event slider.autoPaused = true; } }, function(){ // if the autoPaused value was created be the prior "mouseover" event if(slider.autoPaused){ // start the auto show and pass true agument which will prevent control update el.startAuto(true); // reset the autoPaused value slider.autoPaused = null; } }); } } /** * Initialzes the ticker process */ var initTicker = function(){ var startPosition = 0; // if autoDirection is "next", append a clone of the entire slider if(slider.settings.autoDirection == 'next'){ el.append(slider.children.clone().addClass('bx-clone')); // if autoDirection is "prev", prepend a clone of the entire slider, and set the left position }else{ el.prepend(slider.children.clone().addClass('bx-clone')); var position = slider.children.first().position(); startPosition = slider.settings.mode == 'horizontal' ? -position.left : -position.top; } setPositionProperty(startPosition, 'reset', 0); // do not allow controls in ticker mode slider.settings.pager = false; slider.settings.controls = false; slider.settings.autoControls = false; // if autoHover is requested if(slider.settings.tickerHover && !slider.usingCSS){ // on el hover slider.viewport.hover(function(){ el.stop(); }, function(){ // calculate the total width of children (used to calculate the speed ratio) var totalDimens = 0; slider.children.each(function(index){ totalDimens += slider.settings.mode == 'horizontal' ? $(this).outerWidth(true) : $(this).outerHeight(true); }); // calculate the speed ratio (used to determine the new speed to finish the paused animation) var ratio = slider.settings.speed / totalDimens; // determine which property to use var property = slider.settings.mode == 'horizontal' ? 'left' : 'top'; // calculate the new speed var newSpeed = ratio * (totalDimens - (Math.abs(parseInt(el.css(property))))); tickerLoop(newSpeed); }); } // start the ticker loop tickerLoop(); } /** * Runs a continuous loop, news ticker-style */ var tickerLoop = function(resumeSpeed){ speed = resumeSpeed ? resumeSpeed : slider.settings.speed; var position = {left: 0, top: 0}; var reset = {left: 0, top: 0}; // if "next" animate left position to last child, then reset left to 0 if(slider.settings.autoDirection == 'next'){ position = el.find('.bx-clone').first().position(); // if "prev" animate left position to 0, then reset left to first non-clone child }else{ reset = slider.children.first().position(); } var animateProperty = slider.settings.mode == 'horizontal' ? -position.left : -position.top; var resetValue = slider.settings.mode == 'horizontal' ? -reset.left : -reset.top; var params = {resetValue: resetValue}; setPositionProperty(animateProperty, 'ticker', speed, params); } /** * Initializes touch events */ var initTouch = function(){ // initialize object to contain all touch values slider.touch = { start: {x: 0, y: 0}, end: {x: 0, y: 0} } slider.viewport.bind('touchstart', onTouchStart); } /** * Event handler for "touchstart" * * @param e (event) * - DOM event object */ var onTouchStart = function(e){ if(slider.working){ e.preventDefault(); }else{ // record the original position when touch starts slider.touch.originalPos = el.position(); var orig = e.originalEvent; // record the starting touch x, y coordinates slider.touch.start.x = orig.changedTouches[0].pageX; slider.touch.start.y = orig.changedTouches[0].pageY; // bind a "touchmove" event to the viewport slider.viewport.bind('touchmove', onTouchMove); // bind a "touchend" event to the viewport slider.viewport.bind('touchend', onTouchEnd); } } /** * Event handler for "touchmove" * * @param e (event) * - DOM event object */ var onTouchMove = function(e){ var orig = e.originalEvent; // if scrolling on y axis, do not prevent default var xMovement = Math.abs(orig.changedTouches[0].pageX - slider.touch.start.x); var yMovement = Math.abs(orig.changedTouches[0].pageY - slider.touch.start.y); // x axis swipe if((xMovement * 3) > yMovement && slider.settings.preventDefaultSwipeX){ e.preventDefault(); // y axis swipe }else if((yMovement * 3) > xMovement && slider.settings.preventDefaultSwipeY){ e.preventDefault(); } if(slider.settings.mode != 'fade' && slider.settings.oneToOneTouch){ var value = 0; // if horizontal, drag along x axis if(slider.settings.mode == 'horizontal'){ var change = orig.changedTouches[0].pageX - slider.touch.start.x; value = slider.touch.originalPos.left + change; // if vertical, drag along y axis }else{ var change = orig.changedTouches[0].pageY - slider.touch.start.y; value = slider.touch.originalPos.top + change; } setPositionProperty(value, 'reset', 0); } } /** * Event handler for "touchend" * * @param e (event) * - DOM event object */ var onTouchEnd = function(e){ slider.viewport.unbind('touchmove', onTouchMove); var orig = e.originalEvent; var value = 0; // record end x, y positions slider.touch.end.x = orig.changedTouches[0].pageX; slider.touch.end.y = orig.changedTouches[0].pageY; // if fade mode, check if absolute x distance clears the threshold if(slider.settings.mode == 'fade'){ var distance = Math.abs(slider.touch.start.x - slider.touch.end.x); if(distance >= slider.settings.swipeThreshold){ slider.touch.start.x > slider.touch.end.x ? el.goToNextSlide() : el.goToPrevSlide(); el.stopAuto(); } // not fade mode }else{ var distance = 0; // calculate distance and el's animate property if(slider.settings.mode == 'horizontal'){ distance = slider.touch.end.x - slider.touch.start.x; value = slider.touch.originalPos.left; }else{ distance = slider.touch.end.y - slider.touch.start.y; value = slider.touch.originalPos.top; } // if not infinite loop and first / last slide, do not attempt a slide transition if(!slider.settings.infiniteLoop && ((slider.active.index == 0 && distance > 0) || (slider.active.last && distance < 0))){ setPositionProperty(value, 'reset', 200); }else{ // check if distance clears threshold if(Math.abs(distance) >= slider.settings.swipeThreshold){ distance < 0 ? el.goToNextSlide() : el.goToPrevSlide(); el.stopAuto(); }else{ // el.animate(property, 200); setPositionProperty(value, 'reset', 200); } } } slider.viewport.unbind('touchend', onTouchEnd); } /** * Window resize event callback */ var resizeWindow = function(e){ // get the new window dimens (again, thank you IE) var windowWidthNew = $(window).width(); var windowHeightNew = $(window).height(); // make sure that it is a true window resize // *we must check this because our dinosaur friend IE fires a window resize event when certain DOM elements // are resized. Can you just die already?* if(windowWidth != windowWidthNew || windowHeight != windowHeightNew){ // set the new window dimens windowWidth = windowWidthNew; windowHeight = windowHeightNew; // update all dynamic elements el.redrawSlider(); } } /** * =================================================================================== * = PUBLIC FUNCTIONS * =================================================================================== */ /** * Performs slide transition to the specified slide * * @param slideIndex (int) * - the destination slide's index (zero-based) * * @param direction (string) * - INTERNAL USE ONLY - the direction of travel ("prev" / "next") */ el.goToSlide = function(slideIndex, direction){ // if plugin is currently in motion, ignore request if(slider.working || slider.active.index == slideIndex) return; // declare that plugin is in motion slider.working = true; // store the old index slider.oldIndex = slider.active.index; // if slideIndex is less than zero, set active index to last child (this happens during infinite loop) if(slideIndex < 0){ slider.active.index = getPagerQty() - 1; // if slideIndex is greater than children length, set active index to 0 (this happens during infinite loop) }else if(slideIndex >= getPagerQty()){ slider.active.index = 0; // set active index to requested slide }else{ slider.active.index = slideIndex; } // onSlideBefore, onSlideNext, onSlidePrev callbacks slider.settings.onSlideBefore(slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index); if(direction == 'next'){ slider.settings.onSlideNext(slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index); }else if(direction == 'prev'){ slider.settings.onSlidePrev(slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index); } // check if last slide slider.active.last = slider.active.index >= getPagerQty() - 1; // update the pager with active class if(slider.settings.pager) updatePagerActive(slider.active.index); // // check for direction control update if(slider.settings.controls) updateDirectionControls(); // if slider is set to mode: "fade" if(slider.settings.mode == 'fade'){ // if adaptiveHeight is true and next height is different from current height, animate to the new height if(slider.settings.adaptiveHeight && slider.viewport.height() != getViewportHeight()){ slider.viewport.animate({height: getViewportHeight()}, slider.settings.adaptiveHeightSpeed); } // fade out the visible child and reset its z-index value slider.children.filter(':visible').fadeOut(slider.settings.speed).css({zIndex: 0}); // fade in the newly requested slide slider.children.eq(slider.active.index).css('zIndex', 51).fadeIn(slider.settings.speed, function(){ $(this).css('zIndex', 50); updateAfterSlideTransition(); }); // slider mode is not "fade" }else{ // if adaptiveHeight is true and next height is different from current height, animate to the new height if(slider.settings.adaptiveHeight && slider.viewport.height() != getViewportHeight()){ slider.viewport.animate({height: getViewportHeight()}, slider.settings.adaptiveHeightSpeed); } var moveBy = 0; var position = {left: 0, top: 0}; // if carousel and not infinite loop if(!slider.settings.infiniteLoop && slider.carousel && slider.active.last){ if(slider.settings.mode == 'horizontal'){ // get the last child position var lastChild = slider.children.eq(slider.children.length - 1); position = lastChild.position(); // calculate the position of the last slide moveBy = slider.viewport.width() - lastChild.outerWidth(); }else{ // get last showing index position var lastShowingIndex = slider.children.length - slider.settings.minSlides; position = slider.children.eq(lastShowingIndex).position(); } // horizontal carousel, going previous while on first slide (infiniteLoop mode) }else if(slider.carousel && slider.active.last && direction == 'prev'){ // get the last child position var eq = slider.settings.moveSlides == 1 ? slider.settings.maxSlides - getMoveBy() : ((getPagerQty() - 1) * getMoveBy()) - (slider.children.length - slider.settings.maxSlides); var lastChild = el.children('.bx-clone').eq(eq); position = lastChild.position(); // if infinite loop and "Next" is clicked on the last slide }else if(direction == 'next' && slider.active.index == 0){ // get the last clone position position = el.find('> .bx-clone').eq(slider.settings.maxSlides).position(); slider.active.last = false; // normal non-zero requests }else if(slideIndex >= 0){ var requestEl = slideIndex * getMoveBy(); position = slider.children.eq(requestEl).position(); } /* If the position doesn't exist * (e.g. if you destroy the slider on a next click), * it doesn't throw an error. */ if ("undefined" !== typeof(position)) { var value = slider.settings.mode == 'horizontal' ? -(position.left - moveBy) : -position.top; // plugin values to be animated setPositionProperty(value, 'slide', slider.settings.speed); } } } /** * Transitions to the next slide in the show */ el.goToNextSlide = function(){ // if infiniteLoop is false and last page is showing, disregard call if (!slider.settings.infiniteLoop && slider.active.last) return; var pagerIndex = parseInt(slider.active.index) + 1; el.goToSlide(pagerIndex, 'next'); } /** * Transitions to the prev slide in the show */ el.goToPrevSlide = function(){ // if infiniteLoop is false and last page is showing, disregard call if (!slider.settings.infiniteLoop && slider.active.index == 0) return; var pagerIndex = parseInt(slider.active.index) - 1; el.goToSlide(pagerIndex, 'prev'); } /** * Starts the auto show * * @param preventControlUpdate (boolean) * - if true, auto controls state will not be updated */ el.startAuto = function(preventControlUpdate){ // if an interval already exists, disregard call if(slider.interval) return; // create an interval slider.interval = setInterval(function(){ slider.settings.autoDirection == 'next' ? el.goToNextSlide() : el.goToPrevSlide(); }, slider.settings.pause); // if auto controls are displayed and preventControlUpdate is not true if (slider.settings.autoControls && preventControlUpdate != true) updateAutoControls('stop'); } /** * Stops the auto show * * @param preventControlUpdate (boolean) * - if true, auto controls state will not be updated */ el.stopAuto = function(preventControlUpdate){ // if no interval exists, disregard call if(!slider.interval) return; // clear the interval clearInterval(slider.interval); slider.interval = null; // if auto controls are displayed and preventControlUpdate is not true if (slider.settings.autoControls && preventControlUpdate != true) updateAutoControls('start'); } /** * Returns current slide index (zero-based) */ el.getCurrentSlide = function(){ return slider.active.index; } /** * Returns number of slides in show */ el.getSlideCount = function(){ return slider.children.length; } /** * Update all dynamic slider elements */ el.redrawSlider = function(){ // resize all children in ratio to new screen size slider.children.add(el.find('.bx-clone')).outerWidth(getSlideWidth()); // adjust the height slider.viewport.css('height', getViewportHeight()); // update the slide position if(!slider.settings.ticker) setSlidePosition(); // if active.last was true before the screen resize, we want // to keep it last no matter what screen size we end on if (slider.active.last) slider.active.index = getPagerQty() - 1; // if the active index (page) no longer exists due to the resize, simply set the index as last if (slider.active.index >= getPagerQty()) slider.active.last = true; // if a pager is being displayed and a custom pager is not being used, update it if(slider.settings.pager && !slider.settings.pagerCustom){ populatePager(); updatePagerActive(slider.active.index); } } /** * Destroy the current instance of the slider (revert everything back to original state) */ el.destroySlider = function(){ // don't do anything if slider has already been destroyed if(!slider.initialized) return; slider.initialized = false; $('.bx-clone', this).remove(); slider.children.each(function() { $(this).data("origStyle") != undefined ? $(this).attr("style", $(this).data("origStyle")) : $(this).removeAttr('style'); }); $(this).data("origStyle") != undefined ? this.attr("style", $(this).data("origStyle")) : $(this).removeAttr('style'); $(this).unwrap().unwrap(); if(slider.controls.el) slider.controls.el.remove(); if(slider.controls.next) slider.controls.next.remove(); if(slider.controls.prev) slider.controls.prev.remove(); if(slider.pagerEl) slider.pagerEl.remove(); $('.bx-caption', this).remove(); if(slider.controls.autoEl) slider.controls.autoEl.remove(); clearInterval(slider.interval); if(slider.settings.responsive) $(window).unbind('resize', resizeWindow); } /** * Reload the slider (revert all DOM changes, and re-initialize) */ el.reloadSlider = function(settings){ if (settings != undefined) options = settings; el.destroySlider(); init(); } init(); // returns the current jQuery object return this; } })(jQuery);
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Alert from '../src/Alert'; describe('Alert', function () { it('Should output a alert with message', function () { let instance = ReactTestUtils.renderIntoDocument( <Alert> <strong>Message</strong> </Alert> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'strong')); }); it('Should have bsType by default', function () { let instance = ReactTestUtils.renderIntoDocument( <Alert> Message </Alert> ); assert.ok(instance.getDOMNode().className.match(/\balert\b/)); }); it('Should have dismissable style with onDismiss', function () { let noOp = function () {}; let instance = ReactTestUtils.renderIntoDocument( <Alert onDismiss={noOp}> Message </Alert> ); assert.ok(instance.getDOMNode().className.match(/\balert-dismissable\b/)); }); it('Should call onDismiss callback on dismiss click', function (done) { let doneOp = function () { done(); }; let instance = ReactTestUtils.renderIntoDocument( <Alert onDismiss={doneOp}> Message </Alert> ); ReactTestUtils.Simulate.click(instance.getDOMNode().children[0]); }); it('Should call onDismiss callback on dismissAfter time', function (done) { let doneOp = function () { done(); }; ReactTestUtils.renderIntoDocument( <Alert onDismiss={doneOp} dismissAfter={1}> Message </Alert> ); }); it('Should have a default bsStyle class', function () { let instance = ReactTestUtils.renderIntoDocument( <Alert> Message </Alert> ); assert.ok(instance.getDOMNode().className.match(/\balert-\w+\b/)); }); it('Should have use bsStyle class', function () { let instance = ReactTestUtils.renderIntoDocument( <Alert bsStyle='danger'> Message </Alert> ); assert.ok(instance.getDOMNode().className.match(/\balert-danger\b/)); }); });
define([ 'extensions/views/view' ], function (View) { return View.extend({ lowerBound: '2013-04-01T00:00:00Z', dateFormat: 'YYYY-MM-DD[T]HH:mm:ss[Z]', interval: 'month', events: { 'change select': 'update' }, initialize: function () { View.prototype.initialize.apply(this, arguments); var options = this.model.get('date-picker') || {}; if (options['start-date']) { this.lowerBound = options['start-date']; } }, update: function () { var from = this.getMoment(this.$('#date-from').val()); var to = this.getMoment(this.$('#date-to').val()); var now = this.getMoment(); var period = this.collection.getPeriod(); if (from.isAfter(to)) { this.showError('Start date must be before end date'); } else { this.setHashParams({ from: this.$('#date-from').val(), to: this.$('#date-to').val() }); from = from.startOf(period); to = to.endOf(this.interval); if (to.isAfter(now)) { to = now.subtract(1, 'day'); } if (period === 'week') { from = from.add(1, 'day'); to = to.endOf('week').add(1, 'day'); } this.hideError(); this.collection.dataSource.setQueryParam({ start_at: from.format(this.dateFormat), end_at: to.format(this.dateFormat), }); } }, render: function () { var hashParams = this.getHashParams(); var firstDate = hashParams.from || this.collection.first().get('_end_at'); var lastDate = hashParams.to || this.collection.last().get('_end_at'); var from = this.makeSelect({ id: 'date-from' }, { selected: this.getMoment(firstDate).startOf(this.interval).format(this.dateFormat), upperBound: this.getMoment().subtract(1, this.interval).startOf(this.interval) }); var to = this.makeSelect({ id: 'date-to' }, { selected: this.getMoment(lastDate).startOf(this.interval).format(this.dateFormat) }); this.$el.append('Show data from: ').append(from).append(' to ').append(to); if ('from' in hashParams || 'to' in hashParams) { this.update(); } }, makeSelect: function (attrs, options) { options = options || {}; _.defaults(options, { lowerBound: this.lowerBound, format: 'MMM YYYY' }); var $select = $('<select/>', attrs); var date = this.getMoment(options.lowerBound).startOf(this.interval); var now = this.getMoment(options.upperBound).startOf(this.interval); while (!date.isAfter(now)) { var option = '<option value="' + date.format(this.dateFormat) + '">' + date.format(options.format) + '</option>'; $select.prepend(option); date = date.add(1, this.interval); } $select.val(options.selected); return $select; }, showError: function (msg) { this.hideError(); var $error = $('<p/>').addClass('error').text(msg); this.$el.prepend($error); }, hideError: function () { this.$('.error').remove(); } }); });
'use strict'; /* * Handles mobile nav */ function toggleMobileNavState() { var body = document.querySelector('body'); body.classList.toggle('nav--active'); } /* * Initializes burger functionality */ function initBurger() { var burger = document.querySelector('.burger'); burger.addEventListener('click', toggleMobileNavState); } initBurger();
import React from "react" class Index extends React.Component { render() { return ( <div> <h1 className="tu">Hi sassy friends</h1> <div className="sass-nav-example"> <h2>Nav example</h2> <ul className="pa0 ma0 list"> <li> <a href="#">Store</a> </li> <li> <a href="#">Help</a> </li> <li> <a href="#">Logout</a> </li> <li> <a href="https://github.com/gatsbyjs/gatsby/tree/1.0/examples/using-sass"> Code for site on Github </a> </li> </ul> </div> </div> ) } } export default Index
/* * Copyright (c) 2015 - present Adobe Systems Incorporated. All rights reserved. * * 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. * */ /** * Utilities functions related to Health Data logging */ /*global Map*/ define(function (require, exports, module) { "use strict"; var PreferencesManager = require("preferences/PreferencesManager"), LanguageManager = require("language/LanguageManager"), FileUtils = require("file/FileUtils"), PerfUtils = require("utils/PerfUtils"), FindUtils = require("search/FindUtils"), StringUtils = require("utils/StringUtils"), EventDispatcher = require("utils/EventDispatcher"), HEALTH_DATA_STATE_KEY = "HealthData.Logs", logHealthData = true, analyticsEventMap = new Map(); var commonStrings = { USAGE: "usage", FILE_OPEN: "fileOpen", FILE_NEW: "newfile", FILE_SAVE: "fileSave", FILE_CLOSE: "fileClose", LANGUAGE_CHANGE: "languageChange", LANGUAGE_SERVER_PROTOCOL: "languageServerProtocol", CODE_HINTS: "codeHints", PARAM_HINTS: "parameterHints", JUMP_TO_DEF: "jumpToDefinition" }; EventDispatcher.makeEventDispatcher(exports); /** * Init: creates the health log preference keys in the state.json file */ function init() { PreferencesManager.stateManager.definePreference(HEALTH_DATA_STATE_KEY, "object", {}); } /** * All the logging functions should be disabled if this returns false * @return {boolean} true if health data can be logged */ function shouldLogHealthData() { return logHealthData; } /** * Return all health data logged till now stored in the state prefs * @return {Object} Health Data aggregated till now */ function getStoredHealthData() { var storedData = PreferencesManager.getViewState(HEALTH_DATA_STATE_KEY) || {}; return storedData; } /** * Return the aggregate of all health data logged till now from all sources * @return {Object} Health Data aggregated till now */ function getAggregatedHealthData() { var healthData = getStoredHealthData(); $.extend(healthData, PerfUtils.getHealthReport()); $.extend(healthData, FindUtils.getHealthReport()); return healthData; } /** * Sets the health data * @param {Object} dataObject The object to be stored as health data */ function setHealthData(dataObject) { if (!shouldLogHealthData()) { return; } PreferencesManager.setViewState(HEALTH_DATA_STATE_KEY, dataObject); } /** * Returns health data logged for the given key * @return {Object} Health Data object for the key or undefined if no health data stored */ function getHealthDataLog(key) { var healthData = getStoredHealthData(); return healthData[key]; } /** * Sets the health data for the given key * @param {Object} dataObject The object to be stored as health data for the key */ function setHealthDataLog(key, dataObject) { var healthData = getStoredHealthData(); healthData[key] = dataObject; setHealthData(healthData); } /** * Clears all the health data recorded till now */ function clearHealthData() { PreferencesManager.setViewState(HEALTH_DATA_STATE_KEY, {}); //clear the performance related health data also PerfUtils.clear(); } /** * Enable or disable health data logs * @param {boolean} enabled true to enable health logs */ function setHealthLogsEnabled(enabled) { logHealthData = enabled; if (!enabled) { clearHealthData(); } } /** * Whenever a file is opened call this function. The function will record the number of times * the standard file types have been opened. We only log the standard filetypes * @param {String} filePath The path of the file to be registered * @param {boolean} addedToWorkingSet set to true if extensions of files added to the * working set needs to be logged */ function fileOpened(filePath, addedToWorkingSet, encoding) { if (!shouldLogHealthData()) { return; } var fileExtension = FileUtils.getFileExtension(filePath), language = LanguageManager.getLanguageForPath(filePath), healthData = getStoredHealthData(), fileExtCountMap = []; healthData.fileStats = healthData.fileStats || { openedFileExt : {}, workingSetFileExt : {}, openedFileEncoding: {} }; if (language.getId() !== "unknown") { fileExtCountMap = addedToWorkingSet ? healthData.fileStats.workingSetFileExt : healthData.fileStats.openedFileExt; if (!fileExtCountMap[fileExtension]) { fileExtCountMap[fileExtension] = 0; } fileExtCountMap[fileExtension]++; setHealthData(healthData); } if (encoding) { var fileEncCountMap = healthData.fileStats.openedFileEncoding; if (!fileEncCountMap) { healthData.fileStats.openedFileEncoding = {}; fileEncCountMap = healthData.fileStats.openedFileEncoding; } if (!fileEncCountMap[encoding]) { fileEncCountMap[encoding] = 0; } fileEncCountMap[encoding]++; setHealthData(healthData); } sendAnalyticsData(commonStrings.USAGE + commonStrings.FILE_OPEN + language._name, commonStrings.USAGE, commonStrings.FILE_OPEN, language._name.toLowerCase() ); } /** * Whenever a file is saved call this function. * The function will send the analytics Data * We only log the standard filetypes and fileSize * @param {String} filePath The path of the file to be registered */ function fileSaved(docToSave) { if (!docToSave) { return; } var fileType = docToSave.language ? docToSave.language._name : ""; sendAnalyticsData(commonStrings.USAGE + commonStrings.FILE_SAVE + fileType, commonStrings.USAGE, commonStrings.FILE_SAVE, fileType.toLowerCase() ); } /** * Whenever a file is closed call this function. * The function will send the analytics Data. * We only log the standard filetypes and fileSize * @param {String} filePath The path of the file to be registered */ function fileClosed(file) { if (!file) { return; } var language = LanguageManager.getLanguageForPath(file._path), size = -1; function _sendData(fileSize) { var subType = ""; if(fileSize/1024 <= 1) { if(fileSize < 0) { subType = ""; } if(fileSize <= 10) { subType = "Size_0_10KB"; } else if (fileSize <= 50) { subType = "Size_10_50KB"; } else if (fileSize <= 100) { subType = "Size_50_100KB"; } else if (fileSize <= 500) { subType = "Size_100_500KB"; } else { subType = "Size_500KB_1MB"; } } else { fileSize = fileSize/1024; if(fileSize <= 2) { subType = "Size_1_2MB"; } else if(fileSize <= 5) { subType = "Size_2_5MB"; } else { subType = "Size_Above_5MB"; } } sendAnalyticsData(commonStrings.USAGE + commonStrings.FILE_CLOSE + language._name + subType, commonStrings.USAGE, commonStrings.FILE_CLOSE, language._name.toLowerCase(), subType ); } file.stat(function(err, fileStat) { if(!err) { size = fileStat.size.valueOf()/1024; } _sendData(size); }); } /** * Sets the project details(a probably unique prjID, number of files in the project and the node cache size) in the health log * The name of the project is never saved into the health data log, only the hash(name) is for privacy requirements. * @param {string} projectName The name of the project * @param {number} numFiles The number of file in the project * @param {number} cacheSize The node file cache memory consumed by the project */ function setProjectDetail(projectName, numFiles, cacheSize) { var projectNameHash = StringUtils.hashCode(projectName), FIFLog = getHealthDataLog("ProjectDetails"); if (!FIFLog) { FIFLog = {}; } FIFLog["prj" + projectNameHash] = { numFiles : numFiles, cacheSize : cacheSize }; setHealthDataLog("ProjectDetails", FIFLog); } /** * Increments health log count for a particular kind of search done * @param {string} searchType The kind of search type that needs to be logged- should be a js var compatible string */ function searchDone(searchType) { var searchDetails = getHealthDataLog("searchDetails"); if (!searchDetails) { searchDetails = {}; } if (!searchDetails[searchType]) { searchDetails[searchType] = 0; } searchDetails[searchType]++; setHealthDataLog("searchDetails", searchDetails); } /** * Notifies the HealthData extension to send Analytics Data to server * @param{Object} eventParams Event Data to be sent to Analytics Server */ function notifyHealthManagerToSendData(eventParams) { exports.trigger("SendAnalyticsData", eventParams); } /** * Send Analytics Data * @param {string} eventCategory The kind of Event Category that * needs to be logged- should be a js var compatible string * @param {string} eventSubCategory The kind of Event Sub Category that * needs to be logged- should be a js var compatible string * @param {string} eventType The kind of Event Type that needs to be logged- should be a js var compatible string * @param {string} eventSubType The kind of Event Sub Type that * needs to be logged- should be a js var compatible string */ function sendAnalyticsData(eventName, eventCategory, eventSubCategory, eventType, eventSubType) { var isEventDataAlreadySent = analyticsEventMap.get(eventName), isHDTracking = PreferencesManager.getExtensionPrefs("healthData").get("healthDataTracking"), eventParams = {}; if (isHDTracking && !isEventDataAlreadySent && eventName && eventCategory) { eventParams = { eventName: eventName, eventCategory: eventCategory, eventSubCategory: eventSubCategory || "", eventType: eventType || "", eventSubType: eventSubType || "" }; notifyHealthManagerToSendData(eventParams); } } // Define public API exports.getHealthDataLog = getHealthDataLog; exports.setHealthDataLog = setHealthDataLog; exports.getAggregatedHealthData = getAggregatedHealthData; exports.clearHealthData = clearHealthData; exports.fileOpened = fileOpened; exports.fileSaved = fileSaved; exports.fileClosed = fileClosed; exports.setProjectDetail = setProjectDetail; exports.searchDone = searchDone; exports.setHealthLogsEnabled = setHealthLogsEnabled; exports.shouldLogHealthData = shouldLogHealthData; exports.init = init; exports.sendAnalyticsData = sendAnalyticsData; // constants // searchType for searchDone() exports.SEARCH_INSTANT = "searchInstant"; exports.SEARCH_ON_RETURN_KEY = "searchOnReturnKey"; exports.SEARCH_REPLACE_ALL = "searchReplaceAll"; exports.SEARCH_NEXT_PAGE = "searchNextPage"; exports.SEARCH_PREV_PAGE = "searchPrevPage"; exports.SEARCH_LAST_PAGE = "searchLastPage"; exports.SEARCH_FIRST_PAGE = "searchFirstPage"; exports.SEARCH_REGEXP = "searchRegExp"; exports.SEARCH_CASE_SENSITIVE = "searchCaseSensitive"; // A new search context on search bar up-Gives an idea of number of times user did a discrete search exports.SEARCH_NEW = "searchNew"; exports.commonStrings = commonStrings; exports.analyticsEventMap = analyticsEventMap; });
/*----------------------------------------------------------------------------- Session handler: -----------------------------------------------------------------------------*/ function Session(parent) { var self = this; var current = ''; var params = {}; self.refresh = function() { if (current == location.hash) return true; current = location.hash; params = {}; jQuery.each(current.slice(1).split('&'), function(index, param) { param = decodeURIComponent(param); if (!/^([a-z]+)\-(.+)$/.test(param)) return true; var bits = /^([a-z]+)\-(.+)$/.exec(param); var value = bits.pop(), name = bits.pop(); params[name] = value; }); jQuery(parent).trigger('sessionupdate'); }; self.get = function(name) { return params[name]; }; self.set = function(name, value) { var bits = []; if (value != null) { params[name] = value; } else { delete params[name]; } jQuery.each(params, function(name, value) { if (value) bits.push(encodeURIComponent(name + '-' + value)); }); location.hash = bits.join('&'); self.refresh(); }; setInterval(self.refresh, 10); return self; }; /*----------------------------------------------------------------------------- Line highlighting: -----------------------------------------------------------------------------*/ function LineHighlighter(source, session) { var self = this; self.action = null; self.jumped = false; self.from = null; self.to = null; self.refresh = function() { var value = session.get('line'); if (value) { var values = value.split(','); self.action = 'selected'; self.clear(); while (values.length) { var value = values.shift(); var bits = /([0-9]+)(-([0-9]+))?/.exec(value); if (bits[3] == undefined) { self.from = parseInt(bits[1]); self.to = parseInt(bits[1]); } else { self.from = parseInt(bits[1]); self.to = parseInt(bits[3]); } self.draw(self.from, self.to); source.addClass('selected'); } } else { self.clear(); } self.jumped = false; }; self.clear = function() { source.removeClass('selected'); source.find('line') .removeClass('selected selecting deselecting'); }; self.draw = function() { var from = Math.min(self.from, self.to); var to = Math.max(self.from, self.to); var selector = 'line'; var index_from = from - 2; var index_to = (to - from) + 1; if (index_from >= 0) { selector = selector + ':gt(' + index_from + ')'; } selector = selector + ':lt(' + index_to + ')'; source.find(selector).addClass(self.action); }; /*------------------------------------------------------------------------- Drag handlers: -------------------------------------------------------------------------*/ self.drag_ignore = function() { return false; }; self.drag_start = function() { var line = jQuery(this).parent(); source .bind('mousedown', self.drag_ignore); source.find('line') .bind('mouseover', self.drag_select) .bind('mouseup', self.drag_stop); self.action = 'selecting'; self.to = self.from = parseInt(line.attr('id')); if (line.hasClass('selected')) { self.action = 'deselecting'; } self.draw(); return false; }; self.drag_select = function() { var line = jQuery(this); source.find('.selecting, .deselecting') .removeClass('selecting deselecting'); self.to = parseInt(line.attr('id')); self.draw(); return false; }; self.drag_stop = function() { var last = null, hash = ''; var selection = [] source.addClass('selected'); source.find('.selecting') .removeClass('selecting') .addClass('selected'); source.find('.deselecting') .removeClass('deselecting selected'); source .unbind('mousedown', self.drag_ignore); source.find('line') .unbind('mouseover', self.drag_select) .unbind('mouseup', self.drag_stop); source.find('line.selected').each(function() { var id = parseInt(jQuery(this).attr('id')); if (selection.indexOf(id) == -1) { selection.push(id); } }); selection.sort(function(a, b) { return (a < b ? -1 : 1); }); jQuery.each(selection, function(index, value) { if (last != value - 1) { if (last != null) hash = hash + ','; hash = hash + value; } else if (selection[index + 1] != value + 1) { hash = hash + '-' + value; } last = value; }); if (hash == '') session.set('line', null); else session.set('line', hash); return false; }; source.bind('sessionupdate', self.refresh); source.find('line marker') .bind('mousedown', self.drag_start); return this; }; /*----------------------------------------------------------------------------- Tag matching: -----------------------------------------------------------------------------*/ function TagMatcher(source, session) { var self = this; self.depth = 0; self.stack = []; self.readyTagMatcher = false; self.initialiseTagMatcher = function() { if (self.readyTagMatcher) return true; self.readyTagMatcher = true; // Create tag mapping attributes: source.find('.tag').each(function(position) { var tag = jQuery(this); // Tag content: if (tag.text().match(/[^>]$/)) return; // Self closing else if (tag.text().match(/\/>$/)) { tag.attr('handle', self.depth + 'x' + position); } // Closing: else if (tag.hasClass('close')) { tag.attr('handle', self.stack.pop()); self.depth = self.depth - 1; } // Opening: else { self.depth = self.depth + 1; tag.attr('handle', self.depth + 'x' + position); self.stack.push(tag.attr('handle')); } }); }; self.refresh = function() { var handles = session.get('tag'); self.initialiseTagMatcher(); source.find('.tag-match') .removeClass('tag-match') .bind('click', self.match) .unbind('click', self.unmatch) .unbind('click', self.jump); if (!handles) return; jQuery(handles.split('-')).each(function() { var handle = this; source.find('.tag[handle = "' + handle + '"]') .addClass('tag-match') .unbind('click', self.match) .bind('click', self.unmatch) .bind('click', self.jump); }); }; self.ignore = function(event) { if (jQuery(this).is('.tag-match')) return false; return event.button != 0 || event.metaKey != true; }; self.jump = function(event) { if (event.button != 0 || event.metaKey == true) return true; var handle = jQuery(this).attr('handle'); var target = source.find('.tag[handle = "' + handle + '"]').not(this); if (!target) return false; jQuery('#content').scrollTo(target, { offset: (0 - event.clientY) + (target.height() / 2) + 40 }); return false; } self.unmatch = function(event) { if (event.button != 0 || event.metaKey != true) return true; var handle = jQuery(this).attr('handle'); var handles = session.get('tag'); if (handles) { handles = jQuery(handles.split('-')); handles = handles.map(function() { if (this == handle) return null; return this; }); session.set('tag', handles.get().join('-')); } else { session.set('tag', ''); } return false; } self.match = function(event) { if (event.button != 0 || event.metaKey != true) return true; self.initialiseTagMatcher(); var handle = jQuery(this).attr('handle'); var handles = session.get('tag'); if (handles) { var append = true; handles = jQuery(handles.split('-')); handles.each(function() { if (this == handle) return append = false; }); if (append) handles.push(handle); session.set('tag', handles.get().join('-')); } else { session.set('tag', handle); } return false; }; source.find('.tag') .bind('click', self.match) .bind('mousedown', self.ignore); source.bind('sessionupdate', self.refresh); return self; }; /*----------------------------------------------------------------------------- XPath highlighting: -----------------------------------------------------------------------------*/ function XPathMatcher(source, session) { var self = this; var index = -1, last_tag_index = -1; var in_text = false, in_document = false; var source_document = new DOMParser() .parseFromString(source.text(), 'text/xml'); var container = jQuery('<div />') .attr('id', 'input') .insertBefore('#content'); var input = jQuery('<input />') .attr('autocomplete', 'off') .val('//*') .appendTo(container); var output = jQuery('<div />') .attr('id', 'output') .insertBefore('#content') .hide(); var nodes = {}; var elements = []; var attributes = []; var texts = []; self.readyXPathMatcher = false; self.initialiseXPathMatcher = function() { if (self.readyXPathMatcher) return true; self.readyXPathMatcher = true; source.find('.tag, .attribute, .text, .cdata').each(function() { var node = jQuery(this); if (node.is('.tag.open')) { if (node.text().match(/^[^<]/)) { nodes[last_tag_index].push(node); in_text = false; in_document = true; return true; } index += 1; last_tag_index = index; in_text = false; in_document = true; } else if (node.is('.tag.close')) { in_text = false; return true; } else if (in_document && node.is('.text, .cdata')) { if (!in_text) index += 1; in_text = true; } else if (in_document && node.is('.attribute')) { if (/^xmlns:?/i.test(node.text())) { in_text = false; return true; } index += 1; in_text = false; } else return true; if (index >= 0) { node.attr('index', index); if (nodes[index]) { nodes[index].push(node); } else { nodes[index] = [node]; } // End tag: if (node.is('.tag.open[handle]')) { nodes[index].push(source.find( '.tag.close[handle = "' + node.attr('handle') + '"]' )); } } }); }; self.refresh = function() { var value = session.get('xpath'); if (value) { self.initialiseXPathMatcher(); input.val(value); self.execute(); } }; self.execute = function() { source.find('.xpath-match').removeClass('xpath-match'); var parent = source_document.documentElement; var resolver = source_document.createNSResolver(parent); var matches = source_document.evaluate( input.val(), parent, resolver, 0, null ); if (matches.resultType < 4) { var value = null, type = null; switch (matches.resultType) { case 1: value = matches.numberValue; break; case 2: value = matches.stringValue; break; case 3: value = matches.booleanValue; break; } if (value == null) return true; output.text(value).fadeIn(150); setTimeout(function() { output.fadeOut(250); }, 3000); return true; } while (match = matches.iterateNext()) { var index = source_document.evaluate( 'count((ancestor::* | preceding::* | ancestor::* /@* | preceding::* /@* | preceding::text())[not(comment())])', match, resolver, 1, null ).numberValue; // Attributes are offset: if (match.nodeType === 2) { index += Array.prototype.indexOf.call(match.ownerElement.attributes, match); index -= match.ownerElement.attributes.length; // Sometimes an attribute thinks it's the first // node, it can't be, so make it 1: if (index <= 0) index = 1; } jQuery.each(nodes[index], function() { jQuery(this).not(':empty').addClass('xpath-match'); }); } return true; }; // Initialize on first focus: input.focus().bind('focus', function() { self.initialiseXPathMatcher(); }); input.bind('keyup', function(event) { if ((event || window.event).keyCode !== 13) { input.change(); return true; } if (session.get('xpath') != input.val()) { session.set('xpath', input.val()); } else self.execute(); return false; }); input.bind('change', function() { if (input.val() != '') return true; session.set('xpath', input.val()); source.find('.xpath-match').removeClass('xpath-match'); }); source.bind('sessionupdate', self.refresh); }; /*---------------------------------------------------------------------------*/ jQuery(document).ready(function() { var source = jQuery('#source pre'); if (source.length) { var session = new Session(source); TagMatcher(source, session); XPathMatcher(source, session); LineHighlighter(source, session); session.refresh(); } }); /*---------------------------------------------------------------------------*/
/* global assert, process, setup, suite, test, THREE */ var entityFactory = require('../helpers').entityFactory; suite('vive-controls', function () { var component; var controlsSystem; var el; setup(function (done) { el = entityFactory(); el.addEventListener('componentinitialized', function (evt) { if (evt.detail.name !== 'vive-controls') { return; } component = el.components['vive-controls']; component.controllersWhenPresent = [ {id: 'OpenVR Gamepad', index: 0, hand: 'right', pose: {}} ]; controlsSystem = el.sceneEl.systems['tracked-controls-webvr']; done(); }); el.setAttribute('vive-controls', 'hand: right; model: false'); // To ensure index = 0. }); suite('checkIfControllerPresent', function () { test('remember not present if no controllers on first call', function () { var addEventListenersSpy = this.sinon.spy(component, 'addEventListeners'); var injectTrackedControlsSpy = this.sinon.spy(component, 'injectTrackedControls'); controlsSystem.controllers = []; // Mock not looked before. component.controllerPresent = false; component.checkIfControllerPresent(); assert.notOk(injectTrackedControlsSpy.called); assert.notOk(addEventListenersSpy.called); assert.strictEqual(component.controllerPresent, false); // Not undefined. }); test('does not remove event listeners if no controllers again', function () { var addEventListenersSpy = this.sinon.spy(component, 'addEventListeners'); var injectTrackedControlsSpy = this.sinon.spy(component, 'injectTrackedControls'); var removeEventListenersSpy = this.sinon.spy(component, 'removeEventListeners'); controlsSystem.controllers = []; // Mock not looked before. component.controllerPresent = false; component.checkIfControllerPresent(); assert.notOk(injectTrackedControlsSpy.called); assert.notOk(addEventListenersSpy.called); assert.notOk(removeEventListenersSpy.called); assert.strictEqual(component.controllerPresent, false); // Not undefined. }); test('attaches events if controller is newly present', function () { var addEventListenersSpy = this.sinon.spy(component, 'addEventListeners'); var injectTrackedControlsSpy = this.sinon.spy(component, 'injectTrackedControls'); var removeEventListenersSpy = this.sinon.spy(component, 'removeEventListeners'); controlsSystem.controllers = component.controllersWhenPresent; // Mock not looked before. component.controllerPresent = false; component.checkIfControllerPresent(); assert.ok(injectTrackedControlsSpy.called); assert.ok(addEventListenersSpy.called); assert.notOk(removeEventListenersSpy.called); assert.ok(component.controllerPresent); }); test('does not inject/attach events again if controller is already present', function () { var addEventListenersSpy = this.sinon.spy(component, 'addEventListeners'); var injectTrackedControlsSpy = this.sinon.spy(component, 'injectTrackedControls'); var removeEventListenersSpy = this.sinon.spy(component, 'removeEventListeners'); controlsSystem.controllers = component.controllersWhenPresent; // Mock looked before. component.controllerEventsActive = true; component.controllerPresent = true; component.checkIfControllerPresent(); assert.notOk(injectTrackedControlsSpy.called); assert.notOk(addEventListenersSpy.called); assert.notOk(removeEventListenersSpy.called); assert.ok(component.controllerPresent); }); test('remove event listeners if controller disappears', function () { var addEventListenersSpy = this.sinon.spy(component, 'addEventListeners'); var injectTrackedControlsSpy = this.sinon.spy(component, 'injectTrackedControls'); var removeEventListenersSpy = this.sinon.spy(component, 'removeEventListeners'); controlsSystem.controllers = []; // Mock looked before. component.controllerEventsActive = true; component.controllerPresent = true; component.checkIfControllerPresent(); assert.notOk(injectTrackedControlsSpy.called); assert.notOk(addEventListenersSpy.called); assert.ok(removeEventListenersSpy.called); assert.notOk(component.controllerPresent); }); }); suite('axismove', function () { test('emits trackpadmoved on axismove', function (done) { controlsSystem.controllers = component.controllersWhenPresent; component.checkIfControllerPresent(); // Install event handler listening for trackpad. el.addEventListener('trackpadmoved', function (evt) { assert.equal(evt.detail.x, 0.1); assert.equal(evt.detail.y, 0.2); assert.ok(evt.detail); done(); }); // Emit axismove. el.emit('axismove', {axis: [0.1, 0.2], changed: [true, false]}); }); test('does not emit trackpadmoved on axismove with no changes', function (done) { controlsSystem.controllers = component.controllersWhenPresent; component.checkIfControllerPresent(); // Install event handler listening for trackpadmoved. el.addEventListener('trackpadmoved', function (evt) { assert.notOk(evt.detail); }); // Emit axismove. el.emit('axismove', {axis: [0.1, 0.2], changed: [false, false]}); setTimeout(function () { done(); }); }); }); suite('buttonchanged', function () { // Generate 3 tests for each button. Verify that it fires up/down/changed for all remapped buttons. [ { button: 'trackpad', id: 0 }, { button: 'trigger', id: 1 }, { button: 'grip', id: 2 }, { button: 'menu', id: 3 }, { button: 'system', id: 4 } ].forEach(function (buttonDescription) { test('emits ' + buttonDescription.button + 'changed on buttonchanged', function (done) { controlsSystem.controllers = component.controllersWhenPresent; component.checkIfControllerPresent(); el.addEventListener(buttonDescription.button + 'changed', function (evt) { assert.ok(evt.detail); done(); }); el.emit('buttonchanged', {id: buttonDescription.id, state: {value: 0.5, pressed: true, touched: true}}); }); test('emits ' + buttonDescription.button + 'down on buttondown', function (done) { controlsSystem.controllers = component.controllersWhenPresent; component.checkIfControllerPresent(); el.addEventListener(buttonDescription.button + 'down', function (evt) { done(); }); el.emit('buttondown', {id: buttonDescription.id}); }); test('emits ' + buttonDescription.button + 'up on buttonup', function (done) { controlsSystem.controllers = component.controllersWhenPresent; component.checkIfControllerPresent(); el.addEventListener(buttonDescription.button + 'up', function (evt) { done(); }); el.emit('buttonup', {id: buttonDescription.id}); }); }); }); suite('model', function () { test.skip('loads', function (done) { component.addEventListeners(); el.addEventListener('model-loaded', function (evt) { assert.ok(component.buttonMeshes); assert.ok(component.buttonMeshes.trigger); assert.ok(el.getObject3D('mesh')); done(); }); component.data.model = true; component.injectTrackedControls(); }); }); suite.skip('button colors', function () { test('has trigger at default color', function (done) { component.addEventListeners(); el.addEventListener('model-loaded', function (evt) { var color = component.buttonMeshes.trigger.material.color; assert.equal(new THREE.Color(color).getHexString(), 'fafafa'); done(); }); component.data.model = true; component.injectTrackedControls(); }); test('has trackpad at default color', function (done) { component.addEventListeners(); el.addEventListener('model-loaded', function (evt) { var color = component.buttonMeshes.trackpad.material.color; assert.equal(new THREE.Color(color).getHexString(), 'fafafa'); done(); }); component.data.model = true; component.injectTrackedControls(); }); test('has grips at default colors', function (done) { component.addEventListeners(); el.addEventListener('model-loaded', function (evt) { var color = component.buttonMeshes.grip.left.material.color; assert.equal(new THREE.Color(color).getHexString(), 'fafafa'); color = component.buttonMeshes.grip.right.material.color; assert.equal(new THREE.Color(color).getHexString(), 'fafafa'); done(); }); component.data.model = true; component.injectTrackedControls(); }); test('sets trigger to highlight color when down', function (done) { component.addEventListeners(); el.addEventListener('model-loaded', function (evt) { el.emit('buttondown', {id: 1, state: {}}); setTimeout(() => { var color = component.buttonMeshes.trigger.material.color; assert.equal(new THREE.Color(color).getHexString(), '22d1ee'); done(); }); }); component.data.model = true; component.injectTrackedControls(); }); test('sets trigger back to default color when up', function (done) { component.addEventListeners(); el.addEventListener('model-loaded', function (evt) { component.buttonMeshes.trigger.material.color.set('#22d1ee'); el.emit('buttonup', {id: 1, state: {}}); setTimeout(() => { var color = component.buttonMeshes.trigger.material.color; assert.equal(new THREE.Color(color).getHexString(), 'fafafa'); done(); }); }); component.data.model = true; component.injectTrackedControls(); }); test('sets trackpad to highlight color when down', function (done) { component.addEventListeners(); el.addEventListener('model-loaded', function (evt) { el.emit('buttondown', {id: 0, state: {}}); setTimeout(() => { var color = component.buttonMeshes.trackpad.material.color; assert.equal(new THREE.Color(color).getHexString(), '22d1ee'); done(); }); }); component.data.model = true; component.injectTrackedControls(); }); test('does not change color for trigger touch', function (done) { component.addEventListeners(); el.addEventListener('model-loaded', function (evt) { el.emit('touchstart', {id: 1, state: {}}); setTimeout(() => { var color = component.buttonMeshes.trigger.material.color; assert.equal(new THREE.Color(color).getHexString(), 'fafafa'); done(); }); }); component.data.model = true; component.injectTrackedControls(); }); test('does not change color for trackpad touch', function (done) { component.addEventListeners(); el.addEventListener('model-loaded', function (evt) { el.emit('touchstart', {id: 0, state: {}}); setTimeout(() => { var color = component.buttonMeshes.trackpad.material.color; assert.equal(new THREE.Color(color).getHexString(), 'fafafa'); done(); }); }); component.data.model = true; component.injectTrackedControls(); }); }); suite('event listener', function () { test('toggles controllerEventsActive', function () { component.controllerEventsActive = false; component.addEventListeners(); assert.ok(component.controllerEventsActive); component.removeEventListeners(); assert.notOk(component.controllerEventsActive); }); }); });
ace.define("ace/mode/red_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(acequire, exports, module) { "use strict"; var oop = acequire("../lib/oop"); var TextHighlightRules = acequire("./text_highlight_rules").TextHighlightRules; var RedHighlightRules = function() { var compoundKeywords = ""; this.$rules = { "start" : [ {token : "keyword.operator", regex: /\s([\-+%/=<>*]|(?:\*\*\|\/\/|==|>>>?|<>|<<|=>|<=|=\?))(\s|(?=:))/}, {token : "string.email", regex : /\w[-\w._]*\@\w[-\w._]*/}, {token : "value.time", regex : /\b\d+:\d+(:\d+)?/}, {token : "string.url", regex : /\w[-\w_]*\:(\/\/)?\w[-\w._]*(:\d+)?/}, {token : "value.date", regex : /(\b\d{1,4}[-/]\d{1,2}[-/]\d{1,2}|\d{1,2}[-/]\d{1,2}[-/]\d{1,4})\b/}, {token : "value.tuple", regex : /\b\d{1,3}\.\d{1,3}\.\d{1,3}(\.\d{1,3}){0,9}/}, {token : "value.pair", regex: /[+-]?\d+x[-+]?\d+/}, {token : "value.binary", regex : /\b2#{([01]{8})+}/}, {token : "value.binary", regex : /\b64#{([\w/=+])+}/}, {token : "value.binary", regex : /(16)?#{([\dabcdefABCDEF][\dabcdefABCDEF])*}/}, {token : "value.issue", regex : /#\w[-\w'*.]*/}, {token : "value.numeric", regex: /[+-]?\d['\d]*(?:\.\d+)?e[-+]?\d{1,3}\%?(?!\w)/}, {token : "invalid.illegal", regex: /[+-]?\d['\d]*(?:\.\d+)?\%?[a-zA-Z]/}, {token : "value.numeric", regex: /[+-]?\d['\d]*(?:\.\d+)?\%?(?![a-zA-Z])/}, {token : "value.character", regex : /#"(\^[-@/_~^"HKLM\[]|.)"/}, {token : "string.file", regex : /%[-\w\.\/]+/}, {token : "string.tag", regex : /</, next : "tag"}, {token : "string", regex : /"/, next : "string"}, {token : "string.other", regex : "{", next : "string.other"}, {token : "comment", regex : "comment [[{]", next : "comment"}, {token : "comment", regex : /;.+$/}, {token : "paren.map-start", regex : "#\\("}, {token : "paren.block-start", regex : "[\\[]"}, {token : "paren.block-end", regex : "[\\]]"}, {token : "paren.parens-start", regex : "[(]"}, {token : "paren.parens-end", regex : "\\)"}, {token : "keyword", regex : "/local|/external"}, {token : "keyword.preprocessor", regex : "#(if|either|" + "switch|case|include|do|macrolocal|reset|process|trace)"}, {token : "constant.datatype!", regex : "(?:datatype|unset|none|logic|block|paren|string|" + "file|url|char|integer|float|word|set-word|lit-word|" + "get-word|refinement|issue|native|action|op|function|" + "path|lit-path|set-path|get-path|routine|bitset|point|" + "object|typeset|error|vector|hash|pair|percent|tuple|" + "map|binary|time|tag|email|handle|date|image|event|" + "series|any-type|number|any-object|scalar|" + "any-string|any-word|any-function|any-block|any-list|" + "any-path|immediate|all-word|internal|external|default)!(?![-!?\\w~])"}, {token : "keyword.function", regex : "\\b(?:collect|quote|on-parse-event|math|last|source|expand|" + "show|context|object|input|quit|dir|make-dir|cause-error|" + "error\\?|none\\?|block\\?|any-list\\?|word\\?|char\\?|" + "any-string\\?|series\\?|binary\\?|attempt|url\\?|" + "string\\?|suffix\\?|file\\?|object\\?|body-of|first|" + "second|third|mod|clean-path|dir\\?|to-red-file|" + "normalize-dir|list-dir|pad|empty\\?|dirize|offset\\?|" + "what-dir|expand-directives|load|split-path|change-dir|" + "to-file|path-thru|save|load-thru|View|float\\?|to-float|" + "charset|\\?|probe|set-word\\?|q|words-of|replace|repend|" + "react|function\\?|spec-of|unset\\?|halt|op\\?|" + "any-function\\?|to-paren|tag\\?|routine|class-of|" + "size-text|draw|handle\\?|link-tabs-to-parent|" + "link-sub-to-parent|on-face-deep-change*|" + "update-font-faces|do-actor|do-safe|do-events|pair\\?|" + "foreach-face|hex-to-rgb|issue\\?|alter|path\\?|" + "typeset\\?|datatype\\?|set-flag|layout|extract|image\\?|" + "get-word\\?|to-logic|to-set-word|to-block|center-face|" + "dump-face|request-font|request-file|request-dir|rejoin|" + "ellipsize-at|any-block\\?|any-object\\?|map\\?|keys-of|" + "a-an|also|parse-func-spec|help-string|what|routine\\?|" + "action\\?|native\\?|refinement\\?|common-substr|" + "red-complete-file|red-complete-path|unview|comment|\\?\\?|" + "fourth|fifth|values-of|bitset\\?|email\\?|get-path\\?|" + "hash\\?|integer\\?|lit-path\\?|lit-word\\?|logic\\?|" + "paren\\?|percent\\?|set-path\\?|time\\?|tuple\\?|date\\?|" + "vector\\?|any-path\\?|any-word\\?|number\\?|immediate\\?|" + "scalar\\?|all-word\\?|to-bitset|to-binary|to-char|to-email|" + "to-get-path|to-get-word|to-hash|to-integer|to-issue|" + "to-lit-path|to-lit-word|to-map|to-none|to-pair|to-path|" + "to-percent|to-refinement|to-set-path|to-string|to-tag|" + "to-time|to-typeset|to-tuple|to-unset|to-url|to-word|" + "to-image|to-date|parse-trace|modulo|eval-set-path|" + "extract-boot-args|flip-exe-flag|split|do-file|" + "exists-thru\\?|read-thru|do-thru|cos|sin|tan|acos|asin|" + "atan|atan2|sqrt|clear-reactions|dump-reactions|react\\?|" + "within\\?|overlap\\?|distance\\?|face\\?|metrics\\?|" + "get-scroller|insert-event-func|remove-event-func|" + "set-focus|help|fetch-help|about|ls|ll|pwd|cd|" + "red-complete-input|matrix)(?![-!?\\w~])"}, {token : "keyword.action", regex : "\\b(?:to|remove|copy|insert|change|clear|move|poke|put|" + "random|reverse|sort|swap|take|trim|add|subtract|" + "divide|multiply|make|reflect|form|mold|modify|" + "absolute|negate|power|remainder|round|even\\?|odd\\?|" + "and~|complement|or~|xor~|append|at|back|find|skip|" + "tail|head|head\\?|index\\?|length\\?|next|pick|" + "select|tail\\?|delete|read|write)(?![-_!?\\w~])" }, {token : "keyword.native", regex : "\\b(?:not|any|set|uppercase|lowercase|checksum|" + "try|catch|browse|throw|all|as|" + "remove-each|func|function|does|has|do|reduce|" + "compose|get|print|prin|equal\\?|not-equal\\?|" + "strict-equal\\?|lesser\\?|greater\\?|lesser-or-equal\\?|" + "greater-or-equal\\?|same\\?|type\\?|stats|bind|in|parse|" + "union|unique|intersect|difference|exclude|" + "complement\\?|dehex|negative\\?|positive\\?|max|min|" + "shift|to-hex|sine|cosine|tangent|arcsine|arccosine|" + "arctangent|arctangent2|NaN\\?|zero\\?|log-2|log-10|log-e|" + "exp|square-root|construct|value\\?|as-pair|" + "extend|debase|enbase|to-local-file|" + "wait|unset|new-line|new-line\\?|context\\?|set-env|" + "get-env|list-env|now|sign\\?|call|size\\?)(?![-!?\\w~])" }, {token : "keyword", regex : "\\b(?:Red(?=\\s+\\[)|object|context|make|self|keep)(?![-!?\\w~])" }, {token: "variable.language", regex : "this"}, {token: "keyword.control", regex : "(?:while|if|return|case|unless|either|until|loop|repeat|" + "forever|foreach|forall|switch|break|continue|exit)(?![-!?\\w~])"}, {token: "constant.language", regex : "\\b(?:true|false|on|off|yes|none|no)(?![-!?\\w~])"}, {token: "constant.numeric", regex : /\bpi(?![^-_])/}, {token: "constant.character", regex : "\\b(space|tab|newline|cr|lf)(?![-!?\\w~])"}, {token: "keyword.operator", regex : "\s(or|and|xor|is)\s"}, {token : "variable.get-path", regex : /:\w[-\w'*.?!]*(\/\w[-\w'*.?!]*)(\/\w[-\w'*.?!]*)*/}, {token : "variable.set-path", regex : /\w[-\w'*.?!]*(\/\w[-\w'*.?!]*)(\/\w[-\w'*.?!]*)*:/}, {token : "variable.lit-path", regex : /'\w[-\w'*.?!]*(\/\w[-\w'*.?!]*)(\/\w[-\w'*.?!]*)*/}, {token : "variable.path", regex : /\w[-\w'*.?!]*(\/\w[-\w'*.?!]*)(\/\w[-\w'*.?!]*)*/}, {token : "variable.refinement", regex : /\/\w[-\w'*.?!]*/}, {token : "keyword.view.style", regex : "\\b(?:window|base|button|text|field|area|check|" + "radio|progress|slider|camera|text-list|" + "drop-list|drop-down|panel|group-box|" + "tab-panel|h1|h2|h3|h4|h5|box|image|init)(?![-!?\\w~])"}, {token : "keyword.view.event", regex : "\\b(?:detect|on-detect|time|on-time|drawing|on-drawing|" + "scroll|on-scroll|down|on-down|up|on-up|mid-down|" + "on-mid-down|mid-up|on-mid-up|alt-down|on-alt-down|" + "alt-up|on-alt-up|aux-down|on-aux-down|aux-up|" + "on-aux-up|wheel|on-wheel|drag-start|on-drag-start|" + "drag|on-drag|drop|on-drop|click|on-click|dbl-click|" + "on-dbl-click|over|on-over|key|on-key|key-down|" + "on-key-down|key-up|on-key-up|ime|on-ime|focus|" + "on-focus|unfocus|on-unfocus|select|on-select|" + "change|on-change|enter|on-enter|menu|on-menu|close|" + "on-close|move|on-move|resize|on-resize|moving|" + "on-moving|resizing|on-resizing|zoom|on-zoom|pan|" + "on-pan|rotate|on-rotate|two-tap|on-two-tap|" + "press-tap|on-press-tap|create|on-create|created|on-created)(?![-!?\\w~])"}, {token : "keyword.view.option", regex : "\\b(?:all-over|center|color|default|disabled|down|" + "flags|focus|font|font-color|font-name|" + "font-size|hidden|hint|left|loose|name|" + "no-border|now|rate|react|select|size|space)(?![-!?\\w~])"}, {token : "constant.other.colour", regex : "\\b(?:Red|white|transparent|" + "black|gray|aqua|beige|blue|brick|brown|coal|coffee|" + "crimson|cyan|forest|gold|green|ivory|khaki|leaf|linen|" + "magenta|maroon|mint|navy|oldrab|olive|orange|papaya|" + "pewter|pink|purple|reblue|rebolor|sienna|silver|sky|" + "snow|tanned|teal|violet|water|wheat|yello|yellow|glass)(?![-!?\\w~])"}, {token : "variable.get-word", regex : /\:\w[-\w'*.?!]*/}, {token : "variable.set-word", regex : /\w[-\w'*.?!]*\:/}, {token : "variable.lit-word", regex : /'\w[-\w'*.?!]*/}, {token : "variable.word", regex : /\b\w+[-\w'*.!?]*/}, {caseInsensitive: true} ], "string" : [ {token : "string", regex : /"/, next : "start"}, {defaultToken : "string"} ], "string.other" : [ {token : "string.other", regex : /}/, next : "start"}, {defaultToken : "string.other"} ], "tag" : [ {token : "string.tag", regex : />/, next : "start"}, {defaultToken : "string.tag"} ], "comment" : [ {token : "comment", regex : /}/, next : "start"}, {defaultToken : "comment"} ] }; }; oop.inherits(RedHighlightRules, TextHighlightRules); exports.RedHighlightRules = RedHighlightRules; }); ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(acequire, exports, module) { "use strict"; var oop = acequire("../../lib/oop"); var Range = acequire("../../range").Range; var BaseFoldMode = acequire("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /([\{\[\(])[^\}\]\)]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{\(]*([\}\]\)])|^[\s\*]*(\*\/)/; this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; this._getFoldWidgetBase = this.getFoldWidget; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.singleLineBlockCommentRe.test(line)) { if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) return ""; } var fw = this._getFoldWidgetBase(session, foldStyle, row); if (!fw && this.startRegionRe.test(line)) return "start"; // lineCommentRegionStart return fw; }; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); if (this.startRegionRe.test(line)) return this.getCommentRegionBlock(session, line, row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; this.getCommentRegionBlock = function(session, line, row) { var startColumn = line.search(/\s*$/); var maxRow = session.getLength(); var startRow = row; var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; var depth = 1; while (++row < maxRow) { line = session.getLine(row); var m = re.exec(line); if (!m) continue; if (m[1]) depth--; else depth++; if (!depth) break; } var endRow = row; if (endRow > startRow) { return new Range(startRow, startColumn, endRow, line.length); } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(acequire, exports, module) { "use strict"; var Range = acequire("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); ace.define("ace/mode/red",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/red_highlight_rules","ace/mode/folding/cstyle","ace/mode/matching_brace_outdent","ace/range"], function(acequire, exports, module) { "use strict"; var oop = acequire("../lib/oop"); var TextMode = acequire("./text").Mode; var RedHighlightRules = acequire("./red_highlight_rules").RedHighlightRules; var RedFoldMode = acequire("./folding/cstyle").FoldMode; var MatchingBraceOutdent = acequire("./matching_brace_outdent").MatchingBraceOutdent; var Range = acequire("../range").Range; var Mode = function() { this.HighlightRules = RedHighlightRules; this.foldingRules = new RedFoldMode(); this.$outdent = new MatchingBraceOutdent(); this.$behaviour = this.$defaultBehaviour; }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = ";"; this.blockCommentStart = "comment {"; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\[\(]\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.$id = "ace/mode/red"; }).call(Mode.prototype); exports.Mode = Mode; });
(function() { var Icommand; Icommand = (function() { function Icommand() {} Icommand.prototype.handle = function(senter, text, args, storage, textRouter, commandManager, fromBinding, originalMessage) { var success; textRouter.output("add method to compelete this!"); success = false; return success; }; Icommand.prototype.help = function(commandPrefix) { console.log("add method to override this!"); return []; }; Icommand.prototype.hasPermission = function(sender, text, args, storage, textRouter, commandManager, fromBinding) { return true; }; Icommand.prototype.handleRaw = function(sender, type, content, textRouter, commandManager, event) { return false; }; Icommand.prototype.isBindSymbol = function() { return false; }; Icommand.__createAsInstance__ = function(obj) { var instance, key, value; instance = new Icommand; for (key in instance) { value = instance[key]; if (obj[key] == null) { obj[key] = instance[key]; } } return obj; }; return Icommand; })(); module.exports = Icommand; }).call(this);
/** * Created by Peter on 2018. 3. 11.. */ "use strict"; const getPixels = require('get-pixels'); //const fs = require('fs'); /** * modelimg_CASE4 * @type {module.exports.image.kaq_korea_image|{coordi, size, pixel_pos, so2_pixel_pos, region, bucketName}} */ const kaqDustImage = require('../config/config').image.kaq_korea_image; /** * modelimg * @type {module.exports.image.kaq_korea_modelimg_image|{coordi, size, pixel_pos}} */ const kaqModelimg = require('../config/config').image.kaq_korea_modelimg_image; class KaqImageParser{ constructor(){ return this; } getImagePos(type) { var pos = kaqDustImage.pixel_pos; if(type === 'modelimg'){ pos = kaqModelimg.pixel_pos; }else if(type === 'CASE4_SO2'){ pos = kaqDustImage.so2_pixel_pos; } return { left: parseInt(pos.left), right: parseInt(pos.right), top: parseInt(pos.top), bottom: parseInt(pos.bottom) } } getDefaultCoordi(type) { var coordi = kaqDustImage.coordi; if(type === 'modelimg'){ coordi = kaqModelimg.coordi; } return { top_left:{ lat: parseFloat(coordi.top_lat), lon: parseFloat(coordi.left_lon) }, top_right:{ lat: parseFloat(coordi.top_lat), lon: parseFloat(coordi.right_lon) }, bottom_left:{ lat: parseFloat(coordi.bottom_lat), lon: parseFloat(coordi.left_lon) }, bottom_right:{ lat: parseFloat(coordi.bottom_lat), lon: parseFloat(coordi.right_lon) } }; } _isValidImage(type, width, height){ var size = { width : parseInt(kaqDustImage.size.width), height: parseInt(kaqDustImage.size.height) }; if(type === 'modelimg'){ size.width = parseInt(kaqModelimg.size.width); size.height = parseInt(kaqModelimg.size.height); } return (size.width === width && size.height === height); } getPixelMap(path, type, format, coordnate, callback){ getPixels(path, format, (err, pixels)=>{ if(err){ log.error('KaqImgParser> Fail to get pixels info : ', err); return callback(err); } if(!this._isValidImage(type, pixels.shape[1], pixels.shape[2])){ log.error('KaqImgParser> Invalid Image size :', pixels.shape[1], pixels.shape[2]); return callback('INVALID_IMAGE'); } var map_area = this.getImagePos(type); var result = { image_count: pixels.shape[0], image_width: pixels.shape[1], image_height: pixels.shape[2], map_width: 0, map_height: 0, map_pixel_distance_width: 0.0, map_pixel_distance_height: 0.0, map_area: map_area, pixels: pixels }; log.debug('KaqImgParser> image count : ', pixels.shape[0]); var default_coordinate = this.getDefaultCoordi(type); // map's width&height (count of pixels) result.map_width = map_area.right - map_area.left; result.map_height = map_area.bottom - map_area.top; if(coordnate === null){ result.map_pixel_distance_width = parseFloat((default_coordinate.top_right.lon - default_coordinate.top_left.lon) / result.map_width); result.map_pixel_distance_height = parseFloat((default_coordinate.top_left.lat - default_coordinate.bottom_left.lat) / result.map_height); }else{ result.map_pixel_distance_width = parseFloat((coordnate.top_right.lon - coordnate.top_left.lon) / result.map_width); result.map_pixel_distance_height = parseFloat((coordnate.top_left.lat - coordnate.bottom_left.lat) / result.map_height); } if(callback){ log.debug('KaqImgParser> Image W: ', result.image_width, 'H: ', result.image_height); log.debug('KaqImgParser> Map W: ', result.map_width, 'H: ', result.map_height); log.debug('KaqImgParser> One pixel size W: ', result.map_pixel_distance_width, 'H: ', result.map_pixel_distance_height); callback(null, result); } }); }; } module.exports = KaqImageParser;
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const models = require('./index'); /** * Defines a global parameter in the graph. * */ class GraphParameter { /** * Create a GraphParameter. * @member {string} [description] Description of this graph parameter. * @member {string} type Graph parameter's type. Possible values include: * 'String', 'Int', 'Float', 'Enumerated', 'Script', 'Mode', 'Credential', * 'Boolean', 'Double', 'ColumnPicker', 'ParameterRange', 'DataGatewayName' * @member {array} links Association links for this parameter to nodes in the * graph. */ constructor() { } /** * Defines the metadata of GraphParameter * * @returns {object} metadata of GraphParameter * */ mapper() { return { required: false, serializedName: 'GraphParameter', type: { name: 'Composite', className: 'GraphParameter', modelProperties: { description: { required: false, serializedName: 'description', type: { name: 'String' } }, type: { required: true, serializedName: 'type', type: { name: 'String' } }, links: { required: true, serializedName: 'links', type: { name: 'Sequence', element: { required: false, serializedName: 'GraphParameterLinkElementType', type: { name: 'Composite', className: 'GraphParameterLink' } } } } } } }; } } module.exports = GraphParameter;
/* ASCIIMathML.js ============== This file contains JavaScript functions to convert ASCII math notation and (some) LaTeX to Presentation MathML. The conversion is done while the HTML page loads, and should work with Firefox and other browsers that can render MathML. Just add the next line to your HTML page with this file in the same folder: <script type="text/javascript" src="ASCIIMathML.js"></script> Version 2.2 Mar 3, 2014. Latest version at https://github.com/mathjax/asciimathml If you use it on a webpage, please send the URL to jipsen@chapman.edu Copyright (c) 2014 Peter Jipsen and other ASCIIMathML.js 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. */ var asciimath = {}; (function(){ var mathcolor = "blue"; // change it to "" (to inherit) or another color var mathfontsize = "1em"; // change to e.g. 1.2em for larger math var mathfontfamily = "serif"; // change to "" to inherit (works in IE) // or another family (e.g. "arial") var automathrecognize = false; // writing "amath" on page makes this true var checkForMathML = true; // check if browser can display MathML var notifyIfNoMathML = true; // display note at top if no MathML capability var alertIfNoMathML = false; // show alert box if no MathML capability var translateOnLoad = true; // set to false to do call translators from js var translateASCIIMath = true; // false to preserve `..` var displaystyle = true; // puts limits above and below large operators var showasciiformulaonhover = true; // helps students learn ASCIIMath var decimalsign = "."; // change to "," if you like, beware of `(1,2)`! var AMdelimiter1 = "`", AMescape1 = "\\\\`"; // can use other characters var AMdocumentId = "wikitext" // PmWiki element containing math (default=body) var fixphi = true; //false to return to legacy phi/varphi mapping /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ var isIE = (navigator.appName.slice(0,9)=="Microsoft"); var noMathML = false, translated = false; if (isIE) { // add MathPlayer info to IE webpages document.write("<object id=\"mathplayer\"\ classid=\"clsid:32F66A20-7614-11D4-BD11-00104BD3F987\"></object>"); document.write("<?import namespace=\"m\" implementation=\"#mathplayer\"?>"); } // Add a stylesheet, replacing any previous custom stylesheet (adapted from TW) function setStylesheet(s) { var id = "AMMLcustomStyleSheet"; var n = document.getElementById(id); if(document.createStyleSheet) { // Test for IE's non-standard createStyleSheet method if(n) n.parentNode.removeChild(n); // This failed without the &nbsp; document.getElementsByTagName("head")[0].insertAdjacentHTML("beforeEnd","&nbsp;<style id='" + id + "'>" + s + "</style>"); } else { if(n) { n.replaceChild(document.createTextNode(s),n.firstChild); } else { n = document.createElement("style"); n.type = "text/css"; n.id = id; n.appendChild(document.createTextNode(s)); document.getElementsByTagName("head")[0].appendChild(n); } } } setStylesheet("#AMMLcloseDiv \{font-size:0.8em; padding-top:1em; color:#014\}\n#AMMLwarningBox \{position:absolute; width:100%; top:0; left:0; z-index:200; text-align:center; font-size:1em; font-weight:bold; padding:0.5em 0 0.5em 0; color:#ffc; background:#c30\}"); function init(){ var msg, warnings = new Array(); if (document.getElementById==null){ alert("This webpage requires a recent browser such as Mozilla Firefox"); return null; } if (checkForMathML && (msg = checkMathML())) warnings.push(msg); if (warnings.length>0) displayWarnings(warnings); if (!noMathML) initSymbols(); return true; } function checkMathML(){ if (navigator.appName.slice(0,8)=="Netscape") if (navigator.appVersion.slice(0,1)>="5") noMathML = null; else noMathML = true; else if (navigator.appName.slice(0,9)=="Microsoft") try { var ActiveX = new ActiveXObject("MathPlayer.Factory.1"); noMathML = null; } catch (e) { noMathML = true; } else if (navigator.appName.slice(0,5)=="Opera") if (navigator.appVersion.slice(0,3)>="9.5") noMathML = null; else noMathML = true; //noMathML = true; //uncomment to check if (noMathML && notifyIfNoMathML) { var msg = "To view the ASCIIMathML notation use Internet Explorer + MathPlayer or Mozilla Firefox 2.0 or later."; if (alertIfNoMathML) alert(msg); else return msg; } } function hideWarning(){ var body = document.getElementsByTagName("body")[0]; body.removeChild(document.getElementById('AMMLwarningBox')); body.onclick = null; } function displayWarnings(warnings) { var i, frag, nd = createElementXHTML("div"); var body = document.getElementsByTagName("body")[0]; body.onclick=hideWarning; nd.id = 'AMMLwarningBox'; for (i=0; i<warnings.length; i++) { frag = createElementXHTML("div"); frag.appendChild(document.createTextNode(warnings[i])); frag.style.paddingBottom = "1.0em"; nd.appendChild(frag); } nd.appendChild(createElementXHTML("p")); nd.appendChild(document.createTextNode("For instructions see the ")); var an = createElementXHTML("a"); an.appendChild(document.createTextNode("ASCIIMathML")); an.setAttribute("href","http://www.chapman.edu/~jipsen/asciimath.html"); nd.appendChild(an); nd.appendChild(document.createTextNode(" homepage")); an = createElementXHTML("div"); an.id = 'AMMLcloseDiv'; an.appendChild(document.createTextNode('(click anywhere to close this warning)')); nd.appendChild(an); var body = document.getElementsByTagName("body")[0]; body.insertBefore(nd,body.childNodes[0]); } function translate(spanclassAM) { if (!translated) { // run this only once translated = true; var body = document.getElementsByTagName("body")[0]; var processN = document.getElementById(AMdocumentId); if (translateASCIIMath) AMprocessNode((processN!=null?processN:body), false, spanclassAM); } } function createElementXHTML(t) { if (isIE) return document.createElement(t); else return document.createElementNS("http://www.w3.org/1999/xhtml",t); } var AMmathml = "http://www.w3.org/1998/Math/MathML"; function AMcreateElementMathML(t) { if (isIE) return document.createElement("m:"+t); else return document.createElementNS(AMmathml,t); } function createMmlNode(t,frag) { var node; if (isIE) node = document.createElement("m:"+t); else node = document.createElementNS(AMmathml,t); if (frag) node.appendChild(frag); return node; } function newcommand(oldstr,newstr) { AMsymbols = AMsymbols.concat([{input:oldstr, tag:"mo", output:newstr, tex:null, ttype:DEFINITION}]); // #### Added from Version 2.0.1 #### // AMsymbols.sort(compareNames); for (i=0; i<AMsymbols.length; i++) AMnames[i] = AMsymbols[i].input; // #### End of Addition #### // } // character lists for Mozilla/Netscape fonts var AMcal = ["\uD835\uDC9C","\u212C","\uD835\uDC9E","\uD835\uDC9F","\u2130","\u2131","\uD835\uDCA2","\u210B","\u2110","\uD835\uDCA5","\uD835\uDCA6","\u2112","\u2133","\uD835\uDCA9","\uD835\uDCAA","\uD835\uDCAB","\uD835\uDCAC","\u211B","\uD835\uDCAE","\uD835\uDCAF","\uD835\uDCB0","\uD835\uDCB1","\uD835\uDCB2","\uD835\uDCB3","\uD835\uDCB4","\uD835\uDCB5","\uD835\uDCB6","\uD835\uDCB7","\uD835\uDCB8","\uD835\uDCB9","\u212F","\uD835\uDCBB","\u210A","\uD835\uDCBD","\uD835\uDCBE","\uD835\uDCBF","\uD835\uDCC0","\uD835\uDCC1","\uD835\uDCC2","\uD835\uDCC3","\u2134","\uD835\uDCC5","\uD835\uDCC6","\uD835\uDCC7","\uD835\uDCC8","\uD835\uDCC9","\uD835\uDCCA","\uD835\uDCCB","\uD835\uDCCC","\uD835\uDCCD","\uD835\uDCCE","\uD835\uDCCF"]; var AMfrk = ["\uD835\uDD04","\uD835\uDD05","\u212D","\uD835\uDD07","\uD835\uDD08","\uD835\uDD09","\uD835\uDD0A","\u210C","\u2111","\uD835\uDD0D","\uD835\uDD0E","\uD835\uDD0F","\uD835\uDD10","\uD835\uDD11","\uD835\uDD12","\uD835\uDD13","\uD835\uDD14","\u211C","\uD835\uDD16","\uD835\uDD17","\uD835\uDD18","\uD835\uDD19","\uD835\uDD1A","\uD835\uDD1B","\uD835\uDD1C","\u2128","\uD835\uDD1E","\uD835\uDD1F","\uD835\uDD20","\uD835\uDD21","\uD835\uDD22","\uD835\uDD23","\uD835\uDD24","\uD835\uDD25","\uD835\uDD26","\uD835\uDD27","\uD835\uDD28","\uD835\uDD29","\uD835\uDD2A","\uD835\uDD2B","\uD835\uDD2C","\uD835\uDD2D","\uD835\uDD2E","\uD835\uDD2F","\uD835\uDD30","\uD835\uDD31","\uD835\uDD32","\uD835\uDD33","\uD835\uDD34","\uD835\uDD35","\uD835\uDD36","\uD835\uDD37"]; var AMbbb = ["\uD835\uDD38","\uD835\uDD39","\u2102","\uD835\uDD3B","\uD835\uDD3C","\uD835\uDD3D","\uD835\uDD3E","\u210D","\uD835\uDD40","\uD835\uDD41","\uD835\uDD42","\uD835\uDD43","\uD835\uDD44","\u2115","\uD835\uDD46","\u2119","\u211A","\u211D","\uD835\uDD4A","\uD835\uDD4B","\uD835\uDD4C","\uD835\uDD4D","\uD835\uDD4E","\uD835\uDD4F","\uD835\uDD50","\u2124","\uD835\uDD52","\uD835\uDD53","\uD835\uDD54","\uD835\uDD55","\uD835\uDD56","\uD835\uDD57","\uD835\uDD58","\uD835\uDD59","\uD835\uDD5A","\uD835\uDD5B","\uD835\uDD5C","\uD835\uDD5D","\uD835\uDD5E","\uD835\uDD5F","\uD835\uDD60","\uD835\uDD61","\uD835\uDD62","\uD835\uDD63","\uD835\uDD64","\uD835\uDD65","\uD835\uDD66","\uD835\uDD67","\uD835\uDD68","\uD835\uDD69","\uD835\uDD6A","\uD835\uDD6B"]; /*var AMcal = [0xEF35,0x212C,0xEF36,0xEF37,0x2130,0x2131,0xEF38,0x210B,0x2110,0xEF39,0xEF3A,0x2112,0x2133,0xEF3B,0xEF3C,0xEF3D,0xEF3E,0x211B,0xEF3F,0xEF40,0xEF41,0xEF42,0xEF43,0xEF44,0xEF45,0xEF46]; var AMfrk = [0xEF5D,0xEF5E,0x212D,0xEF5F,0xEF60,0xEF61,0xEF62,0x210C,0x2111,0xEF63,0xEF64,0xEF65,0xEF66,0xEF67,0xEF68,0xEF69,0xEF6A,0x211C,0xEF6B,0xEF6C,0xEF6D,0xEF6E,0xEF6F,0xEF70,0xEF71,0x2128]; var AMbbb = [0xEF8C,0xEF8D,0x2102,0xEF8E,0xEF8F,0xEF90,0xEF91,0x210D,0xEF92,0xEF93,0xEF94,0xEF95,0xEF96,0x2115,0xEF97,0x2119,0x211A,0x211D,0xEF98,0xEF99,0xEF9A,0xEF9B,0xEF9C,0xEF9D,0xEF9E,0x2124];*/ var CONST = 0, UNARY = 1, BINARY = 2, INFIX = 3, LEFTBRACKET = 4, RIGHTBRACKET = 5, SPACE = 6, UNDEROVER = 7, DEFINITION = 8, LEFTRIGHT = 9, TEXT = 10, BIG = 11, LONG = 12, STRETCHY = 13, MATRIX = 14, UNARYUNDEROVER = 15; // token types var AMquote = {input:"\"", tag:"mtext", output:"mbox", tex:null, ttype:TEXT}; var AMsymbols = [ //some greek symbols {input:"alpha", tag:"mi", output:"\u03B1", tex:null, ttype:CONST}, {input:"beta", tag:"mi", output:"\u03B2", tex:null, ttype:CONST}, {input:"chi", tag:"mi", output:"\u03C7", tex:null, ttype:CONST}, {input:"delta", tag:"mi", output:"\u03B4", tex:null, ttype:CONST}, {input:"Delta", tag:"mo", output:"\u0394", tex:null, ttype:CONST}, {input:"epsi", tag:"mi", output:"\u03B5", tex:"epsilon", ttype:CONST}, {input:"varepsilon", tag:"mi", output:"\u025B", tex:null, ttype:CONST}, {input:"eta", tag:"mi", output:"\u03B7", tex:null, ttype:CONST}, {input:"gamma", tag:"mi", output:"\u03B3", tex:null, ttype:CONST}, {input:"Gamma", tag:"mo", output:"\u0393", tex:null, ttype:CONST}, {input:"iota", tag:"mi", output:"\u03B9", tex:null, ttype:CONST}, {input:"kappa", tag:"mi", output:"\u03BA", tex:null, ttype:CONST}, {input:"lambda", tag:"mi", output:"\u03BB", tex:null, ttype:CONST}, {input:"Lambda", tag:"mo", output:"\u039B", tex:null, ttype:CONST}, {input:"lamda", tag:"mi", output:"\u03BB", tex:null, ttype:CONST}, {input:"Lamda", tag:"mo", output:"\u039B", tex:null, ttype:CONST}, {input:"mu", tag:"mi", output:"\u03BC", tex:null, ttype:CONST}, {input:"nu", tag:"mi", output:"\u03BD", tex:null, ttype:CONST}, {input:"omega", tag:"mi", output:"\u03C9", tex:null, ttype:CONST}, {input:"Omega", tag:"mo", output:"\u03A9", tex:null, ttype:CONST}, {input:"phi", tag:"mi", output:fixphi?"\u03D5":"\u03C6", tex:null, ttype:CONST}, {input:"varphi", tag:"mi", output:fixphi?"\u03C6":"\u03D5", tex:null, ttype:CONST}, {input:"Phi", tag:"mo", output:"\u03A6", tex:null, ttype:CONST}, {input:"pi", tag:"mi", output:"\u03C0", tex:null, ttype:CONST}, {input:"Pi", tag:"mo", output:"\u03A0", tex:null, ttype:CONST}, {input:"psi", tag:"mi", output:"\u03C8", tex:null, ttype:CONST}, {input:"Psi", tag:"mi", output:"\u03A8", tex:null, ttype:CONST}, {input:"rho", tag:"mi", output:"\u03C1", tex:null, ttype:CONST}, {input:"sigma", tag:"mi", output:"\u03C3", tex:null, ttype:CONST}, {input:"Sigma", tag:"mo", output:"\u03A3", tex:null, ttype:CONST}, {input:"tau", tag:"mi", output:"\u03C4", tex:null, ttype:CONST}, {input:"theta", tag:"mi", output:"\u03B8", tex:null, ttype:CONST}, {input:"vartheta", tag:"mi", output:"\u03D1", tex:null, ttype:CONST}, {input:"Theta", tag:"mo", output:"\u0398", tex:null, ttype:CONST}, {input:"upsilon", tag:"mi", output:"\u03C5", tex:null, ttype:CONST}, {input:"xi", tag:"mi", output:"\u03BE", tex:null, ttype:CONST}, {input:"Xi", tag:"mo", output:"\u039E", tex:null, ttype:CONST}, {input:"zeta", tag:"mi", output:"\u03B6", tex:null, ttype:CONST}, //binary operation symbols //{input:"-", tag:"mo", output:"\u0096", tex:null, ttype:CONST}, {input:"*", tag:"mo", output:"\u22C5", tex:"cdot", ttype:CONST}, {input:"**", tag:"mo", output:"\u2217", tex:"ast", ttype:CONST}, {input:"***", tag:"mo", output:"\u22C6", tex:"star", ttype:CONST}, {input:"//", tag:"mo", output:"/", tex:null, ttype:CONST}, {input:"\\\\", tag:"mo", output:"\\", tex:"backslash", ttype:CONST}, {input:"setminus", tag:"mo", output:"\\", tex:null, ttype:CONST}, {input:"xx", tag:"mo", output:"\u00D7", tex:"times", ttype:CONST}, {input:"-:", tag:"mo", output:"\u00F7", tex:"div", ttype:CONST}, {input:"divide", tag:"mo", output:"-:", tex:null, ttype:DEFINITION}, {input:"@", tag:"mo", output:"\u2218", tex:"circ", ttype:CONST}, {input:"o+", tag:"mo", output:"\u2295", tex:"oplus", ttype:CONST}, {input:"ox", tag:"mo", output:"\u2297", tex:"otimes", ttype:CONST}, {input:"o.", tag:"mo", output:"\u2299", tex:"odot", ttype:CONST}, {input:"sum", tag:"mo", output:"\u2211", tex:null, ttype:UNDEROVER}, {input:"prod", tag:"mo", output:"\u220F", tex:null, ttype:UNDEROVER}, {input:"^^", tag:"mo", output:"\u2227", tex:"wedge", ttype:CONST}, {input:"^^^", tag:"mo", output:"\u22C0", tex:"bigwedge", ttype:UNDEROVER}, {input:"vv", tag:"mo", output:"\u2228", tex:"vee", ttype:CONST}, {input:"vvv", tag:"mo", output:"\u22C1", tex:"bigvee", ttype:UNDEROVER}, {input:"nn", tag:"mo", output:"\u2229", tex:"cap", ttype:CONST}, {input:"nnn", tag:"mo", output:"\u22C2", tex:"bigcap", ttype:UNDEROVER}, {input:"uu", tag:"mo", output:"\u222A", tex:"cup", ttype:CONST}, {input:"uuu", tag:"mo", output:"\u22C3", tex:"bigcup", ttype:UNDEROVER}, //binary relation symbols {input:"!=", tag:"mo", output:"\u2260", tex:"ne", ttype:CONST}, {input:":=", tag:"mo", output:":=", tex:null, ttype:CONST}, {input:"lt", tag:"mo", output:"<", tex:null, ttype:CONST}, {input:"<=", tag:"mo", output:"\u2264", tex:"le", ttype:CONST}, {input:"lt=", tag:"mo", output:"\u2264", tex:"leq", ttype:CONST}, {input:"gt", tag:"mo", output:">", tex:null, ttype:CONST}, {input:">=", tag:"mo", output:"\u2265", tex:"ge", ttype:CONST}, {input:"gt=", tag:"mo", output:"\u2265", tex:"geq", ttype:CONST}, {input:"-<", tag:"mo", output:"\u227A", tex:"prec", ttype:CONST}, {input:"-lt", tag:"mo", output:"\u227A", tex:null, ttype:CONST}, {input:">-", tag:"mo", output:"\u227B", tex:"succ", ttype:CONST}, {input:"-<=", tag:"mo", output:"\u2AAF", tex:"preceq", ttype:CONST}, {input:">-=", tag:"mo", output:"\u2AB0", tex:"succeq", ttype:CONST}, {input:"in", tag:"mo", output:"\u2208", tex:null, ttype:CONST}, {input:"!in", tag:"mo", output:"\u2209", tex:"notin", ttype:CONST}, {input:"sub", tag:"mo", output:"\u2282", tex:"subset", ttype:CONST}, {input:"sup", tag:"mo", output:"\u2283", tex:"supset", ttype:CONST}, {input:"sube", tag:"mo", output:"\u2286", tex:"subseteq", ttype:CONST}, {input:"supe", tag:"mo", output:"\u2287", tex:"supseteq", ttype:CONST}, {input:"-=", tag:"mo", output:"\u2261", tex:"equiv", ttype:CONST}, {input:"~=", tag:"mo", output:"\u2245", tex:"cong", ttype:CONST}, {input:"~~", tag:"mo", output:"\u2248", tex:"approx", ttype:CONST}, {input:"prop", tag:"mo", output:"\u221D", tex:"propto", ttype:CONST}, //logical symbols {input:"and", tag:"mtext", output:"and", tex:null, ttype:SPACE}, {input:"or", tag:"mtext", output:"or", tex:null, ttype:SPACE}, {input:"not", tag:"mo", output:"\u00AC", tex:"neg", ttype:CONST}, {input:"=>", tag:"mo", output:"\u21D2", tex:"implies", ttype:CONST}, {input:"if", tag:"mo", output:"if", tex:null, ttype:SPACE}, {input:"<=>", tag:"mo", output:"\u21D4", tex:"iff", ttype:CONST}, {input:"AA", tag:"mo", output:"\u2200", tex:"forall", ttype:CONST}, {input:"EE", tag:"mo", output:"\u2203", tex:"exists", ttype:CONST}, {input:"_|_", tag:"mo", output:"\u22A5", tex:"bot", ttype:CONST}, {input:"TT", tag:"mo", output:"\u22A4", tex:"top", ttype:CONST}, {input:"|--", tag:"mo", output:"\u22A2", tex:"vdash", ttype:CONST}, {input:"|==", tag:"mo", output:"\u22A8", tex:"models", ttype:CONST}, //grouping brackets {input:"(", tag:"mo", output:"(", tex:null, ttype:LEFTBRACKET}, {input:")", tag:"mo", output:")", tex:null, ttype:RIGHTBRACKET}, {input:"[", tag:"mo", output:"[", tex:null, ttype:LEFTBRACKET}, {input:"]", tag:"mo", output:"]", tex:null, ttype:RIGHTBRACKET}, {input:"{", tag:"mo", output:"{", tex:null, ttype:LEFTBRACKET}, {input:"}", tag:"mo", output:"}", tex:null, ttype:RIGHTBRACKET}, {input:"|", tag:"mo", output:"|", tex:null, ttype:LEFTRIGHT}, //{input:"||", tag:"mo", output:"||", tex:null, ttype:LEFTRIGHT}, {input:"(:", tag:"mo", output:"\u2329", tex:"langle", ttype:LEFTBRACKET}, {input:":)", tag:"mo", output:"\u232A", tex:"rangle", ttype:RIGHTBRACKET}, {input:"<<", tag:"mo", output:"\u2329", tex:null, ttype:LEFTBRACKET}, {input:">>", tag:"mo", output:"\u232A", tex:null, ttype:RIGHTBRACKET}, {input:"{:", tag:"mo", output:"{:", tex:null, ttype:LEFTBRACKET, invisible:true}, {input:":}", tag:"mo", output:":}", tex:null, ttype:RIGHTBRACKET, invisible:true}, //miscellaneous symbols {input:"int", tag:"mo", output:"\u222B", tex:null, ttype:CONST}, {input:"dx", tag:"mi", output:"{:d x:}", tex:null, ttype:DEFINITION}, {input:"dy", tag:"mi", output:"{:d y:}", tex:null, ttype:DEFINITION}, {input:"dz", tag:"mi", output:"{:d z:}", tex:null, ttype:DEFINITION}, {input:"dt", tag:"mi", output:"{:d t:}", tex:null, ttype:DEFINITION}, {input:"oint", tag:"mo", output:"\u222E", tex:null, ttype:CONST}, {input:"del", tag:"mo", output:"\u2202", tex:"partial", ttype:CONST}, {input:"grad", tag:"mo", output:"\u2207", tex:"nabla", ttype:CONST}, {input:"+-", tag:"mo", output:"\u00B1", tex:"pm", ttype:CONST}, {input:"O/", tag:"mo", output:"\u2205", tex:"emptyset", ttype:CONST}, {input:"oo", tag:"mo", output:"\u221E", tex:"infty", ttype:CONST}, {input:"aleph", tag:"mo", output:"\u2135", tex:null, ttype:CONST}, {input:"...", tag:"mo", output:"...", tex:"ldots", ttype:CONST}, {input:":.", tag:"mo", output:"\u2234", tex:"therefore", ttype:CONST}, {input:"/_", tag:"mo", output:"\u2220", tex:"angle", ttype:CONST}, {input:"/_\\", tag:"mo", output:"\u25B3", tex:"triangle", ttype:CONST}, {input:"'", tag:"mo", output:"\u2032", tex:"prime", ttype:CONST}, {input:"tilde", tag:"mover", output:"~", tex:null, ttype:UNARY, acc:true}, {input:"\\ ", tag:"mo", output:"\u00A0", tex:null, ttype:CONST}, {input:"quad", tag:"mo", output:"\u00A0\u00A0", tex:null, ttype:CONST}, {input:"qquad", tag:"mo", output:"\u00A0\u00A0\u00A0\u00A0", tex:null, ttype:CONST}, {input:"cdots", tag:"mo", output:"\u22EF", tex:null, ttype:CONST}, {input:"vdots", tag:"mo", output:"\u22EE", tex:null, ttype:CONST}, {input:"ddots", tag:"mo", output:"\u22F1", tex:null, ttype:CONST}, {input:"diamond", tag:"mo", output:"\u22C4", tex:null, ttype:CONST}, {input:"square", tag:"mo", output:"\u25A1", tex:null, ttype:CONST}, {input:"|__", tag:"mo", output:"\u230A", tex:"lfloor", ttype:CONST}, {input:"__|", tag:"mo", output:"\u230B", tex:"rfloor", ttype:CONST}, {input:"|~", tag:"mo", output:"\u2308", tex:"lceiling", ttype:CONST}, {input:"~|", tag:"mo", output:"\u2309", tex:"rceiling", ttype:CONST}, {input:"CC", tag:"mo", output:"\u2102", tex:null, ttype:CONST}, {input:"NN", tag:"mo", output:"\u2115", tex:null, ttype:CONST}, {input:"QQ", tag:"mo", output:"\u211A", tex:null, ttype:CONST}, {input:"RR", tag:"mo", output:"\u211D", tex:null, ttype:CONST}, {input:"ZZ", tag:"mo", output:"\u2124", tex:null, ttype:CONST}, {input:"f", tag:"mi", output:"f", tex:null, ttype:UNARY, func:true}, {input:"g", tag:"mi", output:"g", tex:null, ttype:UNARY, func:true}, //standard functions {input:"lim", tag:"mo", output:"lim", tex:null, ttype:UNDEROVER}, {input:"Lim", tag:"mo", output:"Lim", tex:null, ttype:UNDEROVER}, {input:"sin", tag:"mo", output:"sin", tex:null, ttype:UNARY, func:true}, {input:"cos", tag:"mo", output:"cos", tex:null, ttype:UNARY, func:true}, {input:"tan", tag:"mo", output:"tan", tex:null, ttype:UNARY, func:true}, {input:"sinh", tag:"mo", output:"sinh", tex:null, ttype:UNARY, func:true}, {input:"cosh", tag:"mo", output:"cosh", tex:null, ttype:UNARY, func:true}, {input:"tanh", tag:"mo", output:"tanh", tex:null, ttype:UNARY, func:true}, {input:"cot", tag:"mo", output:"cot", tex:null, ttype:UNARY, func:true}, {input:"sec", tag:"mo", output:"sec", tex:null, ttype:UNARY, func:true}, {input:"csc", tag:"mo", output:"csc", tex:null, ttype:UNARY, func:true}, {input:"arcsin", tag:"mo", output:"arcsin", tex:null, ttype:UNARY, func:true}, {input:"arccos", tag:"mo", output:"arccos", tex:null, ttype:UNARY, func:true}, {input:"arctan", tag:"mo", output:"arctan", tex:null, ttype:UNARY, func:true}, {input:"coth", tag:"mo", output:"coth", tex:null, ttype:UNARY, func:true}, {input:"sech", tag:"mo", output:"sech", tex:null, ttype:UNARY, func:true}, {input:"csch", tag:"mo", output:"csch", tex:null, ttype:UNARY, func:true}, {input:"exp", tag:"mo", output:"exp", tex:null, ttype:UNARY, func:true}, {input:"abs", tag:"mo", output:"abs", tex:null, ttype:UNARY, rewriteleftright:["|","|"]}, {input:"norm", tag:"mo", output:"norm", tex:null, ttype:UNARY, rewriteleftright:["\u2225","\u2225"]}, {input:"floor", tag:"mo", output:"floor", tex:null, ttype:UNARY, rewriteleftright:["\u230A","\u230B"]}, {input:"ceil", tag:"mo", output:"ceil", tex:null, ttype:UNARY, rewriteleftright:["\u2308","\u2309"]}, {input:"log", tag:"mo", output:"log", tex:null, ttype:UNARY, func:true}, {input:"ln", tag:"mo", output:"ln", tex:null, ttype:UNARY, func:true}, {input:"det", tag:"mo", output:"det", tex:null, ttype:UNARY, func:true}, {input:"dim", tag:"mo", output:"dim", tex:null, ttype:CONST}, {input:"mod", tag:"mo", output:"mod", tex:null, ttype:CONST}, {input:"gcd", tag:"mo", output:"gcd", tex:null, ttype:UNARY, func:true}, {input:"lcm", tag:"mo", output:"lcm", tex:null, ttype:UNARY, func:true}, {input:"lub", tag:"mo", output:"lub", tex:null, ttype:CONST}, {input:"glb", tag:"mo", output:"glb", tex:null, ttype:CONST}, {input:"min", tag:"mo", output:"min", tex:null, ttype:UNDEROVER}, {input:"max", tag:"mo", output:"max", tex:null, ttype:UNDEROVER}, //arrows {input:"uarr", tag:"mo", output:"\u2191", tex:"uparrow", ttype:CONST}, {input:"darr", tag:"mo", output:"\u2193", tex:"downarrow", ttype:CONST}, {input:"rarr", tag:"mo", output:"\u2192", tex:"rightarrow", ttype:CONST}, {input:"->", tag:"mo", output:"\u2192", tex:"to", ttype:CONST}, {input:">->", tag:"mo", output:"\u21A3", tex:"rightarrowtail", ttype:CONST}, {input:"->>", tag:"mo", output:"\u21A0", tex:"twoheadrightarrow", ttype:CONST}, {input:">->>", tag:"mo", output:"\u2916", tex:"twoheadrightarrowtail", ttype:CONST}, {input:"|->", tag:"mo", output:"\u21A6", tex:"mapsto", ttype:CONST}, {input:"larr", tag:"mo", output:"\u2190", tex:"leftarrow", ttype:CONST}, {input:"harr", tag:"mo", output:"\u2194", tex:"leftrightarrow", ttype:CONST}, {input:"rArr", tag:"mo", output:"\u21D2", tex:"Rightarrow", ttype:CONST}, {input:"lArr", tag:"mo", output:"\u21D0", tex:"Leftarrow", ttype:CONST}, {input:"hArr", tag:"mo", output:"\u21D4", tex:"Leftrightarrow", ttype:CONST}, //commands with argument {input:"sqrt", tag:"msqrt", output:"sqrt", tex:null, ttype:UNARY}, {input:"root", tag:"mroot", output:"root", tex:null, ttype:BINARY}, {input:"frac", tag:"mfrac", output:"/", tex:null, ttype:BINARY}, {input:"/", tag:"mfrac", output:"/", tex:null, ttype:INFIX}, {input:"stackrel", tag:"mover", output:"stackrel", tex:null, ttype:BINARY}, {input:"overset", tag:"mover", output:"stackrel", tex:null, ttype:BINARY}, {input:"underset", tag:"munder", output:"stackrel", tex:null, ttype:BINARY}, {input:"_", tag:"msub", output:"_", tex:null, ttype:INFIX}, {input:"^", tag:"msup", output:"^", tex:null, ttype:INFIX}, {input:"hat", tag:"mover", output:"\u005E", tex:null, ttype:UNARY, acc:true}, {input:"bar", tag:"mover", output:"\u00AF", tex:"overline", ttype:UNARY, acc:true}, {input:"vec", tag:"mover", output:"\u2192", tex:null, ttype:UNARY, acc:true}, {input:"dot", tag:"mover", output:".", tex:null, ttype:UNARY, acc:true}, {input:"ddot", tag:"mover", output:"..", tex:null, ttype:UNARY, acc:true}, {input:"ul", tag:"munder", output:"\u0332", tex:"underline", ttype:UNARY, acc:true}, {input:"ubrace", tag:"munder", output:"\u23DF", tex:"underbrace", ttype:UNARYUNDEROVER, acc:true}, {input:"obrace", tag:"mover", output:"\u23DE", tex:"overbrace", ttype:UNARYUNDEROVER, acc:true}, {input:"text", tag:"mtext", output:"text", tex:null, ttype:TEXT}, {input:"mbox", tag:"mtext", output:"mbox", tex:null, ttype:TEXT}, {input:"color", tag:"mstyle", ttype:BINARY}, {input:"cancel", tag:"menclose", output:"cancel", tex:null, ttype:UNARY}, AMquote, {input:"bb", tag:"mstyle", atname:"mathvariant", atval:"bold", output:"bb", tex:null, ttype:UNARY}, {input:"mathbf", tag:"mstyle", atname:"mathvariant", atval:"bold", output:"mathbf", tex:null, ttype:UNARY}, {input:"sf", tag:"mstyle", atname:"mathvariant", atval:"sans-serif", output:"sf", tex:null, ttype:UNARY}, {input:"mathsf", tag:"mstyle", atname:"mathvariant", atval:"sans-serif", output:"mathsf", tex:null, ttype:UNARY}, {input:"bbb", tag:"mstyle", atname:"mathvariant", atval:"double-struck", output:"bbb", tex:null, ttype:UNARY, codes:AMbbb}, {input:"mathbb", tag:"mstyle", atname:"mathvariant", atval:"double-struck", output:"mathbb", tex:null, ttype:UNARY, codes:AMbbb}, {input:"cc", tag:"mstyle", atname:"mathvariant", atval:"script", output:"cc", tex:null, ttype:UNARY, codes:AMcal}, {input:"mathcal", tag:"mstyle", atname:"mathvariant", atval:"script", output:"mathcal", tex:null, ttype:UNARY, codes:AMcal}, {input:"tt", tag:"mstyle", atname:"mathvariant", atval:"monospace", output:"tt", tex:null, ttype:UNARY}, {input:"mathtt", tag:"mstyle", atname:"mathvariant", atval:"monospace", output:"mathtt", tex:null, ttype:UNARY}, {input:"fr", tag:"mstyle", atname:"mathvariant", atval:"fraktur", output:"fr", tex:null, ttype:UNARY, codes:AMfrk}, {input:"mathfrak", tag:"mstyle", atname:"mathvariant", atval:"fraktur", output:"mathfrak", tex:null, ttype:UNARY, codes:AMfrk} ]; function compareNames(s1,s2) { if (s1.input > s2.input) return 1 else return -1; } var AMnames = []; //list of input symbols function initSymbols() { var texsymbols = [], i; for (i=0; i<AMsymbols.length; i++) if (AMsymbols[i].tex) { texsymbols[texsymbols.length] = {input:AMsymbols[i].tex, tag:AMsymbols[i].tag, output:AMsymbols[i].output, ttype:AMsymbols[i].ttype, acc:(AMsymbols[i].acc||false)}; } AMsymbols = AMsymbols.concat(texsymbols); refreshSymbols(); } function refreshSymbols(){ var i; AMsymbols.sort(compareNames); for (i=0; i<AMsymbols.length; i++) AMnames[i] = AMsymbols[i].input; } function define(oldstr,newstr) { AMsymbols = AMsymbols.concat([{input:oldstr, tag:"mo", output:newstr, tex:null, ttype:DEFINITION}]); refreshSymbols(); // this may be a problem if many symbols are defined! } function AMremoveCharsAndBlanks(str,n) { //remove n characters and any following blanks var st; if (str.charAt(n)=="\\" && str.charAt(n+1)!="\\" && str.charAt(n+1)!=" ") st = str.slice(n+1); else st = str.slice(n); for (var i=0; i<st.length && st.charCodeAt(i)<=32; i=i+1); return st.slice(i); } function position(arr, str, n) { // return position >=n where str appears or would be inserted // assumes arr is sorted if (n==0) { var h,m; n = -1; h = arr.length; while (n+1<h) { m = (n+h) >> 1; if (arr[m]<str) n = m; else h = m; } return h; } else for (var i=n; i<arr.length && arr[i]<str; i++); return i; // i=arr.length || arr[i]>=str } function AMgetSymbol(str) { //return maximal initial substring of str that appears in names //return null if there is none var k = 0; //new pos var j = 0; //old pos var mk; //match pos var st; var tagst; var match = ""; var more = true; for (var i=1; i<=str.length && more; i++) { st = str.slice(0,i); //initial substring of length i j = k; k = position(AMnames, st, j); if (k<AMnames.length && str.slice(0,AMnames[k].length)==AMnames[k]){ match = AMnames[k]; mk = k; i = match.length; } more = k<AMnames.length && str.slice(0,AMnames[k].length)>=AMnames[k]; } AMpreviousSymbol=AMcurrentSymbol; if (match!=""){ AMcurrentSymbol=AMsymbols[mk].ttype; return AMsymbols[mk]; } // if str[0] is a digit or - return maxsubstring of digits.digits AMcurrentSymbol=CONST; k = 1; st = str.slice(0,1); var integ = true; while ("0"<=st && st<="9" && k<=str.length) { st = str.slice(k,k+1); k++; } if (st == decimalsign) { st = str.slice(k,k+1); if ("0"<=st && st<="9") { integ = false; k++; while ("0"<=st && st<="9" && k<=str.length) { st = str.slice(k,k+1); k++; } } } if ((integ && k>1) || k>2) { st = str.slice(0,k-1); tagst = "mn"; } else { k = 2; st = str.slice(0,1); //take 1 character tagst = (("A">st || st>"Z") && ("a">st || st>"z")?"mo":"mi"); } if (st=="-" && AMpreviousSymbol==INFIX) { AMcurrentSymbol = INFIX; //trick "/" into recognizing "-" on second parse return {input:st, tag:tagst, output:st, ttype:UNARY, func:true}; } return {input:st, tag:tagst, output:st, ttype:CONST}; } function AMremoveBrackets(node) { var st; if (!node.hasChildNodes()) { return; } if (node.firstChild.hasChildNodes() && (node.nodeName=="mrow" || node.nodeName=="M:MROW")) { st = node.firstChild.firstChild.nodeValue; if (st=="(" || st=="[" || st=="{") node.removeChild(node.firstChild); } if (node.lastChild.hasChildNodes() && (node.nodeName=="mrow" || node.nodeName=="M:MROW")) { st = node.lastChild.firstChild.nodeValue; if (st==")" || st=="]" || st=="}") node.removeChild(node.lastChild); } } /*Parsing ASCII math expressions with the following grammar v ::= [A-Za-z] | greek letters | numbers | other constant symbols u ::= sqrt | text | bb | other unary symbols for font commands b ::= frac | root | stackrel binary symbols l ::= ( | [ | { | (: | {: left brackets r ::= ) | ] | } | :) | :} right brackets S ::= v | lEr | uS | bSS Simple expression I ::= S_S | S^S | S_S^S | S Intermediate expression E ::= IE | I/I Expression Each terminal symbol is translated into a corresponding mathml node.*/ var AMnestingDepth,AMpreviousSymbol,AMcurrentSymbol; function AMparseSexpr(str) { //parses str and returns [node,tailstr] var symbol, node, result, i, st,// rightvert = false, newFrag = document.createDocumentFragment(); str = AMremoveCharsAndBlanks(str,0); symbol = AMgetSymbol(str); //either a token or a bracket or empty if (symbol == null || symbol.ttype == RIGHTBRACKET && AMnestingDepth > 0) { return [null,str]; } if (symbol.ttype == DEFINITION) { str = symbol.output+AMremoveCharsAndBlanks(str,symbol.input.length); symbol = AMgetSymbol(str); } switch (symbol.ttype) { case UNDEROVER: case CONST: str = AMremoveCharsAndBlanks(str,symbol.input.length); return [createMmlNode(symbol.tag, //its a constant document.createTextNode(symbol.output)),str]; case LEFTBRACKET: //read (expr+) AMnestingDepth++; str = AMremoveCharsAndBlanks(str,symbol.input.length); result = AMparseExpr(str,true); AMnestingDepth--; if (typeof symbol.invisible == "boolean" && symbol.invisible) node = createMmlNode("mrow",result[0]); else { node = createMmlNode("mo",document.createTextNode(symbol.output)); node = createMmlNode("mrow",node); node.appendChild(result[0]); } return [node,result[1]]; case TEXT: if (symbol!=AMquote) str = AMremoveCharsAndBlanks(str,symbol.input.length); if (str.charAt(0)=="{") i=str.indexOf("}"); else if (str.charAt(0)=="(") i=str.indexOf(")"); else if (str.charAt(0)=="[") i=str.indexOf("]"); else if (symbol==AMquote) i=str.slice(1).indexOf("\"")+1; else i = 0; if (i==-1) i = str.length; st = str.slice(1,i); if (st.charAt(0) == " ") { node = createMmlNode("mspace"); node.setAttribute("width","1ex"); newFrag.appendChild(node); } newFrag.appendChild( createMmlNode(symbol.tag,document.createTextNode(st))); if (st.charAt(st.length-1) == " ") { node = createMmlNode("mspace"); node.setAttribute("width","1ex"); newFrag.appendChild(node); } str = AMremoveCharsAndBlanks(str,i+1); return [createMmlNode("mrow",newFrag),str]; case UNARYUNDEROVER: case UNARY: str = AMremoveCharsAndBlanks(str,symbol.input.length); result = AMparseSexpr(str); if (result[0]==null) return [createMmlNode(symbol.tag, document.createTextNode(symbol.output)),str]; if (typeof symbol.func == "boolean" && symbol.func) { // functions hack st = str.charAt(0); if (st=="^" || st=="_" || st=="/" || st=="|" || st=="," || (symbol.input.length==1 && symbol.input.match(/\w/) && st!="(")) { return [createMmlNode(symbol.tag, document.createTextNode(symbol.output)),str]; } else { node = createMmlNode("mrow", createMmlNode(symbol.tag,document.createTextNode(symbol.output))); node.appendChild(result[0]); return [node,result[1]]; } } AMremoveBrackets(result[0]); if (symbol.input == "sqrt") { // sqrt return [createMmlNode(symbol.tag,result[0]),result[1]]; } else if (typeof symbol.rewriteleftright != "undefined") { // abs, floor, ceil node = createMmlNode("mrow", createMmlNode("mo",document.createTextNode(symbol.rewriteleftright[0]))); node.appendChild(result[0]); node.appendChild(createMmlNode("mo",document.createTextNode(symbol.rewriteleftright[1]))); return [node,result[1]]; } else if (symbol.input == "cancel") { // cancel node = createMmlNode(symbol.tag,result[0]); node.setAttribute("notation","updiagonalstrike"); return [node,result[1]]; } else if (typeof symbol.acc == "boolean" && symbol.acc) { // accent node = createMmlNode(symbol.tag,result[0]); node.appendChild(createMmlNode("mo",document.createTextNode(symbol.output))); return [node,result[1]]; } else { // font change command if (!isIE && typeof symbol.codes != "undefined") { for (i=0; i<result[0].childNodes.length; i++) if (result[0].childNodes[i].nodeName=="mi" || result[0].nodeName=="mi") { st = (result[0].nodeName=="mi"?result[0].firstChild.nodeValue: result[0].childNodes[i].firstChild.nodeValue); var newst = []; for (var j=0; j<st.length; j++) if (st.charCodeAt(j)>64 && st.charCodeAt(j)<91) newst = newst + symbol.codes[st.charCodeAt(j)-65]; else if (st.charCodeAt(j)>96 && st.charCodeAt(j)<123) newst = newst + symbol.codes[st.charCodeAt(j)-71]; else newst = newst + st.charAt(j); if (result[0].nodeName=="mi") result[0]=createMmlNode("mo"). appendChild(document.createTextNode(newst)); else result[0].replaceChild(createMmlNode("mo"). appendChild(document.createTextNode(newst)), result[0].childNodes[i]); } } node = createMmlNode(symbol.tag,result[0]); node.setAttribute(symbol.atname,symbol.atval); return [node,result[1]]; } case BINARY: str = AMremoveCharsAndBlanks(str,symbol.input.length); result = AMparseSexpr(str); if (result[0]==null) return [createMmlNode("mo", document.createTextNode(symbol.input)),str]; AMremoveBrackets(result[0]); var result2 = AMparseSexpr(result[1]); if (result2[0]==null) return [createMmlNode("mo", document.createTextNode(symbol.input)),str]; AMremoveBrackets(result2[0]); if (symbol.input=="color") { if (str.charAt(0)=="{") i=str.indexOf("}"); else if (str.charAt(0)=="(") i=str.indexOf(")"); else if (str.charAt(0)=="[") i=str.indexOf("]"); st = str.slice(1,i); node = createMmlNode(symbol.tag,result2[0]); node.setAttribute("mathcolor",st); return [node,result2[1]]; } if (symbol.input=="root" || symbol.output=="stackrel") newFrag.appendChild(result2[0]); newFrag.appendChild(result[0]); if (symbol.input=="frac") newFrag.appendChild(result2[0]); return [createMmlNode(symbol.tag,newFrag),result2[1]]; case INFIX: str = AMremoveCharsAndBlanks(str,symbol.input.length); return [createMmlNode("mo",document.createTextNode(symbol.output)),str]; case SPACE: str = AMremoveCharsAndBlanks(str,symbol.input.length); node = createMmlNode("mspace"); node.setAttribute("width","1ex"); newFrag.appendChild(node); newFrag.appendChild( createMmlNode(symbol.tag,document.createTextNode(symbol.output))); node = createMmlNode("mspace"); node.setAttribute("width","1ex"); newFrag.appendChild(node); return [createMmlNode("mrow",newFrag),str]; case LEFTRIGHT: // if (rightvert) return [null,str]; else rightvert = true; AMnestingDepth++; str = AMremoveCharsAndBlanks(str,symbol.input.length); result = AMparseExpr(str,false); AMnestingDepth--; st = ""; if (result[0].lastChild!=null) st = result[0].lastChild.firstChild.nodeValue; if (st == "|") { // its an absolute value subterm node = createMmlNode("mo",document.createTextNode(symbol.output)); node = createMmlNode("mrow",node); node.appendChild(result[0]); return [node,result[1]]; } else { // the "|" is a \mid so use unicode 2223 (divides) for spacing node = createMmlNode("mo",document.createTextNode("\u2223")); node = createMmlNode("mrow",node); return [node,str]; } default: //alert("default"); str = AMremoveCharsAndBlanks(str,symbol.input.length); return [createMmlNode(symbol.tag, //its a constant document.createTextNode(symbol.output)),str]; } } function AMparseIexpr(str) { var symbol, sym1, sym2, node, result, underover; str = AMremoveCharsAndBlanks(str,0); sym1 = AMgetSymbol(str); result = AMparseSexpr(str); node = result[0]; str = result[1]; symbol = AMgetSymbol(str); if (symbol.ttype == INFIX && symbol.input != "/") { str = AMremoveCharsAndBlanks(str,symbol.input.length); // if (symbol.input == "/") result = AMparseIexpr(str); else ... result = AMparseSexpr(str); if (result[0] == null) // show box in place of missing argument result[0] = createMmlNode("mo",document.createTextNode("\u25A1")); else AMremoveBrackets(result[0]); str = result[1]; // if (symbol.input == "/") AMremoveBrackets(node); underover = (sym1.ttype == UNDEROVER || sym1.ttype == UNARYUNDEROVER); if (symbol.input == "_") { sym2 = AMgetSymbol(str); if (sym2.input == "^") { str = AMremoveCharsAndBlanks(str,sym2.input.length); var res2 = AMparseSexpr(str); AMremoveBrackets(res2[0]); str = res2[1]; node = createMmlNode((underover?"munderover":"msubsup"),node); node.appendChild(result[0]); node.appendChild(res2[0]); node = createMmlNode("mrow",node); // so sum does not stretch } else { node = createMmlNode((underover?"munder":"msub"),node); node.appendChild(result[0]); } } else if (symbol.input == "^" && underover) { node = createMmlNode("mover",node); node.appendChild(result[0]); } else { node = createMmlNode(symbol.tag,node); node.appendChild(result[0]); } if (typeof sym1.func != 'undefined' && sym1.func) { sym2 = AMgetSymbol(str); if (sym2.ttype != INFIX && sym2.ttype != RIGHTBRACKET) { result = AMparseIexpr(str); node = createMmlNode("mrow",node); node.appendChild(result[0]); str = result[1]; } } } return [node,str]; } function AMparseExpr(str,rightbracket) { var symbol, node, result, i, newFrag = document.createDocumentFragment(); do { str = AMremoveCharsAndBlanks(str,0); result = AMparseIexpr(str); node = result[0]; str = result[1]; symbol = AMgetSymbol(str); if (symbol.ttype == INFIX && symbol.input == "/") { str = AMremoveCharsAndBlanks(str,symbol.input.length); result = AMparseIexpr(str); if (result[0] == null) // show box in place of missing argument result[0] = createMmlNode("mo",document.createTextNode("\u25A1")); else AMremoveBrackets(result[0]); str = result[1]; AMremoveBrackets(node); node = createMmlNode(symbol.tag,node); node.appendChild(result[0]); newFrag.appendChild(node); symbol = AMgetSymbol(str); } else if (node!=undefined) newFrag.appendChild(node); } while ((symbol.ttype != RIGHTBRACKET && (symbol.ttype != LEFTRIGHT || rightbracket) || AMnestingDepth == 0) && symbol!=null && symbol.output!=""); if (symbol.ttype == RIGHTBRACKET || symbol.ttype == LEFTRIGHT) { // if (AMnestingDepth > 0) AMnestingDepth--; var len = newFrag.childNodes.length; if (len>0 && newFrag.childNodes[len-1].nodeName == "mrow" ) { //matrix //removed to allow row vectors: //&& len>1 && //newFrag.childNodes[len-2].nodeName == "mo" && //newFrag.childNodes[len-2].firstChild.nodeValue == "," var right = newFrag.childNodes[len-1].lastChild.firstChild.nodeValue; if (right==")" || right=="]") { var left = newFrag.childNodes[len-1].firstChild.firstChild.nodeValue; if (left=="(" && right==")" && symbol.output != "}" || left=="[" && right=="]") { var pos = []; // positions of commas var matrix = true; var m = newFrag.childNodes.length; for (i=0; matrix && i<m; i=i+2) { pos[i] = []; node = newFrag.childNodes[i]; if (matrix) matrix = node.nodeName=="mrow" && (i==m-1 || node.nextSibling.nodeName=="mo" && node.nextSibling.firstChild.nodeValue==",")&& node.firstChild.firstChild.nodeValue==left && node.lastChild.firstChild.nodeValue==right; if (matrix) for (var j=0; j<node.childNodes.length; j++) if (node.childNodes[j].firstChild.nodeValue==",") pos[i][pos[i].length]=j; if (matrix && i>1) matrix = pos[i].length == pos[i-2].length; } matrix = matrix && (pos.length>1 || pos[0].length>0); if (matrix) { var row, frag, n, k, table = document.createDocumentFragment(); for (i=0; i<m; i=i+2) { row = document.createDocumentFragment(); frag = document.createDocumentFragment(); node = newFrag.firstChild; // <mrow>(-,-,...,-,-)</mrow> n = node.childNodes.length; k = 0; node.removeChild(node.firstChild); //remove ( for (j=1; j<n-1; j++) { if (typeof pos[i][k] != "undefined" && j==pos[i][k]){ node.removeChild(node.firstChild); //remove , row.appendChild(createMmlNode("mtd",frag)); k++; } else frag.appendChild(node.firstChild); } row.appendChild(createMmlNode("mtd",frag)); if (newFrag.childNodes.length>2) { newFrag.removeChild(newFrag.firstChild); //remove <mrow>)</mrow> newFrag.removeChild(newFrag.firstChild); //remove <mo>,</mo> } table.appendChild(createMmlNode("mtr",row)); } node = createMmlNode("mtable",table); if (typeof symbol.invisible == "boolean" && symbol.invisible) node.setAttribute("columnalign","left"); newFrag.replaceChild(node,newFrag.firstChild); } } } } str = AMremoveCharsAndBlanks(str,symbol.input.length); if (typeof symbol.invisible != "boolean" || !symbol.invisible) { node = createMmlNode("mo",document.createTextNode(symbol.output)); newFrag.appendChild(node); } } return [newFrag,str]; } function parseMath(str,latex) { var frag, node; AMnestingDepth = 0; //some basic cleanup for dealing with stuff editors like TinyMCE adds str = str.replace(/&nbsp;/g,""); str = str.replace(/&gt;/g,">"); str = str.replace(/&lt;/g,"<"); str = str.replace(/(Sin|Cos|Tan|Arcsin|Arccos|Arctan|Sinh|Cosh|Tanh|Cot|Sec|Csc|Log|Ln|Abs)/g, function(v) { return v.toLowerCase(); }); frag = AMparseExpr(str.replace(/^\s+/g,""),false)[0]; node = createMmlNode("mstyle",frag); if (mathcolor != "") node.setAttribute("mathcolor",mathcolor); if (mathfontfamily != "") node.setAttribute("fontfamily",mathfontfamily); if (displaystyle) node.setAttribute("displaystyle","true"); node = createMmlNode("math",node); if (showasciiformulaonhover) //fixed by djhsu so newline node.setAttribute("title",str.replace(/\s+/g," "));//does not show in Gecko return node; } function strarr2docFrag(arr, linebreaks, latex) { var newFrag=document.createDocumentFragment(); var expr = false; for (var i=0; i<arr.length; i++) { if (expr) newFrag.appendChild(parseMath(arr[i],latex)); else { var arri = (linebreaks ? arr[i].split("\n\n") : [arr[i]]); newFrag.appendChild(createElementXHTML("span"). appendChild(document.createTextNode(arri[0]))); for (var j=1; j<arri.length; j++) { newFrag.appendChild(createElementXHTML("p")); newFrag.appendChild(createElementXHTML("span"). appendChild(document.createTextNode(arri[j]))); } } expr = !expr; } return newFrag; } function AMautomathrec(str) { //formula is a space (or start of str) followed by a maximal sequence of *two* or more tokens, possibly separated by runs of digits and/or space. //tokens are single letters (except a, A, I) and ASCIIMathML tokens var texcommand = "\\\\[a-zA-Z]+|\\\\\\s|"; var ambigAMtoken = "\\b(?:oo|lim|ln|int|oint|del|grad|aleph|prod|prop|sinh|cosh|tanh|cos|sec|pi|tt|fr|sf|sube|supe|sub|sup|det|mod|gcd|lcm|min|max|vec|ddot|ul|chi|eta|nu|mu)(?![a-z])|"; var englishAMtoken = "\\b(?:sum|ox|log|sin|tan|dim|hat|bar|dot)(?![a-z])|"; var secondenglishAMtoken = "|\\bI\\b|\\bin\\b|\\btext\\b"; // took if and or not out var simpleAMtoken = "NN|ZZ|QQ|RR|CC|TT|AA|EE|sqrt|dx|dy|dz|dt|xx|vv|uu|nn|bb|cc|csc|cot|alpha|beta|delta|Delta|epsilon|gamma|Gamma|kappa|lambda|Lambda|omega|phi|Phi|Pi|psi|Psi|rho|sigma|Sigma|tau|theta|Theta|xi|Xi|zeta"; // uuu nnn? var letter = "[a-zA-HJ-Z](?=(?:[^a-zA-Z]|$|"+ambigAMtoken+englishAMtoken+simpleAMtoken+"))|"; var token = letter+texcommand+"\\d+|[-()[\\]{}+=*&^_%\\\@/<>,\\|!:;'~]|\\.(?!(?:\x20|$))|"+ambigAMtoken+englishAMtoken+simpleAMtoken; var re = new RegExp("(^|\\s)((("+token+")\\s?)(("+token+secondenglishAMtoken+")\\s?)+)([,.?]?(?=\\s|$))","g"); str = str.replace(re," `$2`$7"); var arr = str.split(AMdelimiter1); var re1 = new RegExp("(^|\\s)([b-zB-HJ-Z+*<>]|"+texcommand+ambigAMtoken+simpleAMtoken+")(\\s|\\n|$)","g"); var re2 = new RegExp("(^|\\s)([a-z]|"+texcommand+ambigAMtoken+simpleAMtoken+")([,.])","g"); // removed |\d+ for now for (i=0; i<arr.length; i++) //single nonenglish tokens if (i%2==0) { arr[i] = arr[i].replace(re1," `$2`$3"); arr[i] = arr[i].replace(re2," `$2`$3"); arr[i] = arr[i].replace(/([{}[\]])/,"`$1`"); } str = arr.join(AMdelimiter1); str = str.replace(/((^|\s)\([a-zA-Z]{2,}.*?)\)`/g,"$1`)"); //fix parentheses str = str.replace(/`(\((a\s|in\s))(.*?[a-zA-Z]{2,}\))/g,"$1`$3"); //fix parentheses str = str.replace(/\sin`/g,"` in"); str = str.replace(/`(\(\w\)[,.]?(\s|\n|$))/g,"$1`"); str = str.replace(/`([0-9.]+|e.g|i.e)`(\.?)/gi,"$1$2"); str = str.replace(/`([0-9.]+:)`/g,"$1"); return str; } function processNodeR(n, linebreaks,latex) { var mtch, str, arr, frg, i; if (n.childNodes.length == 0) { if ((n.nodeType!=8 || linebreaks) && n.parentNode.nodeName!="form" && n.parentNode.nodeName!="FORM" && n.parentNode.nodeName!="textarea" && n.parentNode.nodeName!="TEXTAREA" /*&& n.parentNode.nodeName!="pre" && n.parentNode.nodeName!="PRE"*/) { str = n.nodeValue; if (!(str == null)) { str = str.replace(/\r\n\r\n/g,"\n\n"); str = str.replace(/\x20+/g," "); str = str.replace(/\s*\r\n/g," "); if(latex) { // DELIMITERS: mtch = (str.indexOf("\$")==-1 ? false : true); str = str.replace(/([^\\])\$/g,"$1 \$"); str = str.replace(/^\$/," \$"); // in case \$ at start of string arr = str.split(" \$"); for (i=0; i<arr.length; i++) arr[i]=arr[i].replace(/\\\$/g,"\$"); } else { mtch = false; str = str.replace(new RegExp(AMescape1, "g"), function(){mtch = true; return "AMescape1"}); str = str.replace(/\\?end{?a?math}?/i, function(){automathrecognize = false; mtch = true; return ""}); str = str.replace(/amath\b|\\begin{a?math}/i, function(){automathrecognize = true; mtch = true; return ""}); arr = str.split(AMdelimiter1); if (automathrecognize) for (i=0; i<arr.length; i++) if (i%2==0) arr[i] = AMautomathrec(arr[i]); str = arr.join(AMdelimiter1); arr = str.split(AMdelimiter1); for (i=0; i<arr.length; i++) // this is a problem ************ arr[i]=arr[i].replace(/AMescape1/g,AMdelimiter1); } if (arr.length>1 || mtch) { if (!noMathML) { frg = strarr2docFrag(arr,n.nodeType==8,latex); var len = frg.childNodes.length; n.parentNode.replaceChild(frg,n); return len-1; } else return 0; } } } else return 0; } else if (n.nodeName!="math") { for (i=0; i<n.childNodes.length; i++) i += processNodeR(n.childNodes[i], linebreaks,latex); } return 0; } function AMprocessNode(n, linebreaks, spanclassAM) { var frag,st; if (spanclassAM!=null) { frag = document.getElementsByTagName("span") for (var i=0;i<frag.length;i++) if (frag[i].className == "AM") processNodeR(frag[i],linebreaks,false); } else { try { st = n.innerHTML; // look for AMdelimiter on page } catch(err) {} //alert(st) if (st==null || /amath\b|\\begin{a?math}/i.test(st) || st.indexOf(AMdelimiter1+" ")!=-1 || st.slice(-1)==AMdelimiter1 || st.indexOf(AMdelimiter1+"<")!=-1 || st.indexOf(AMdelimiter1+"\n")!=-1) { processNodeR(n,linebreaks,false); } } } function generic(){ if(!init()) return; if (translateOnLoad) { translate(); } }; //setup onload function if(typeof window.addEventListener != 'undefined'){ //.. gecko, safari, konqueror and standard window.addEventListener('load', generic, false); } else if(typeof document.addEventListener != 'undefined'){ //.. opera 7 document.addEventListener('load', generic, false); } else if(typeof window.attachEvent != 'undefined'){ //.. win/ie window.attachEvent('onload', generic); }else{ //.. mac/ie5 and anything else that gets this far //if there's an existing onload function if(typeof window.onload == 'function'){ //store it var existing = onload; //add new onload handler window.onload = function(){ //call existing onload function existing(); //call generic onload function generic(); }; }else{ window.onload = generic; } } //expose some functions to outside asciimath.newcommand = newcommand; asciimath.AMprocesssNode = AMprocessNode; asciimath.parseMath = parseMath; asciimath.translate = translate; })();
var runServices = angular.module('runServices', []); runServices.factory('runTest', ['$routeParams', '$rootScope', 'addAlert', 'BehatServices', function($routeParams, $rootScope, addAlert, BehatServices){ return function(type, message, $scope) { $scope.test_results = 'Running test...'; addAlert('success', 'Running test...', $scope); BehatServices.get({sid: $routeParams.sid, tname: $routeParams.tname}, function(data){ if(data.errors == 0) { var snag_behat_div = jQuery(data.data).get(9); $scope.test_results = jQuery(snag_behat_div).html(); addAlert('info', 'Test Completed...', $scope); } else { addAlert('danger', 'Problem Running Test', $scope); //output error message } }); } }]);
'use strict'; var EventEmitter = require('events').EventEmitter; var fs = require('fs'); var os = require('os'); var sysPath = require('path'); var each = require('async-each'); var readdirp = require('readdirp'); var fsevents; try { fsevents = require('fsevents'); } catch (error) {} var isWin32 = os.platform() === 'win32'; var canUseFsEvents = os.platform() === 'darwin' && !!fsevents; // To disable FSEvents completely. // var canUseFsEvents = false; // Binary file handling code. var _binExts = [ 'adp', 'au', 'mid', 'mp4a', 'mpga', 'oga', 's3m', 'sil', 'eol', 'dra', 'dts', 'dtshd', 'lvp', 'pya', 'ecelp4800', 'ecelp7470', 'ecelp9600', 'rip', 'weba', 'aac', 'aif', 'caf', 'flac', 'mka', 'm3u', 'wax', 'wma', 'wav', 'xm', 'flac', '3gp', '3g2', 'h261', 'h263', 'h264', 'jpgv', 'jpm', 'mj2', 'mp4', 'mpeg', 'ogv', 'qt', 'uvh', 'uvm', 'uvp', 'uvs', 'dvb', 'fvt', 'mxu', 'pyv', 'uvu', 'viv', 'webm', 'f4v', 'fli', 'flv', 'm4v', 'mkv', 'mng', 'asf', 'vob', 'wm', 'wmv', 'wmx', 'wvx', 'movie', 'smv', 'ts', 'bmp', 'cgm', 'g3', 'gif', 'ief', 'jpg', 'jpeg', 'ktx', 'png', 'btif', 'sgi', 'svg', 'tiff', 'psd', 'uvi', 'sub', 'djvu', 'dwg', 'dxf', 'fbs', 'fpx', 'fst', 'mmr', 'rlc', 'mdi', 'wdp', 'npx', 'wbmp', 'xif', 'webp', '3ds', 'ras', 'cmx', 'fh', 'ico', 'pcx', 'pic', 'pnm', 'pbm', 'pgm', 'ppm', 'rgb', 'tga', 'xbm', 'xpm', 'xwd', 'zip', 'rar', 'tar', 'bz2', 'eot', 'ttf', 'woff' ]; var binExts = Object.create(null); _binExts.forEach(function(ext) { binExts[ext] = true; }); function isBinary(extension) { if (extension === '') return false; return !!binExts[extension]; } function isBinaryPath(path) { return isBinary(sysPath.extname(path).slice(1)); } exports.isBinaryPath = isBinaryPath; // Public: Main class. // Watches files & directories for changes. // // * _opts - object, chokidar options hash // // Emitted events: // `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error` // // Examples // // var watcher = new FSWatcher() // .add(directories) // .on('add', function(path) {console.log('File', path, 'was added');}) // .on('change', function(path) {console.log('File', path, 'was changed');}) // .on('unlink', function(path) {console.log('File', path, 'was removed');}) // .on('all', function(event, path) {console.log(path, ' emitted ', event);}) // function FSWatcher(_opts) { var opts = {}; // in case _opts that is passed in is a frozen object if (_opts) for (var opt in _opts) opts[opt] = _opts[opt]; this.watched = Object.create(null); this.watchers = []; this.ignoredPaths = Object.create(null); this.closed = false; this._throttled = Object.create(null); // Set up default options. if (!('persistent' in opts)) opts.persistent = false; if (!('ignoreInitial' in opts)) opts.ignoreInitial = false; if (!('ignorePermissionErrors' in opts)) opts.ignorePermissionErrors = false; if (!('interval' in opts)) opts.interval = 100; if (!('binaryInterval' in opts)) opts.binaryInterval = 300; this.enableBinaryInterval = opts.binaryInterval !== opts.interval; // Enable fsevents on OS X when polling is disabled. // Which is basically super fast watcher. if (!('useFsEvents' in opts)) opts.useFsEvents = !opts.usePolling; // If we can't use fs events, disable it in any case. if (!canUseFsEvents) opts.useFsEvents = false; // Use polling by default on Linux and Mac (if not using fsevents). // Disable polling on Windows. if (!('usePolling' in opts) && !opts.useFsEvents) opts.usePolling = !isWin32; this._isntIgnored = function(entry) { return !this._isIgnored(entry.path, entry.stat); }.bind(this); this.options = opts; // You’re frozen when your heart’s not open. Object.freeze(opts); } FSWatcher.prototype = Object.create(EventEmitter.prototype); // Common helpers // -------------- FSWatcher.prototype._emit = function(event) { var args = [].slice.apply(arguments); this.emit.apply(this, args); if (event !== 'error') this.emit.apply(this, ['all'].concat(args)); return this; }; FSWatcher.prototype._handleError = function(error) { if (error && error.code !== 'ENOENT' && error.code !== 'ENOTDIR' ) this.emit('error', error); return error || this.closed; }; FSWatcher.prototype._throttle = function(action, path, timeout) { if (!(action in this._throttled)) { this._throttled[action] = Object.create(null); } var throttled = this._throttled[action]; if (path in throttled) return false; function clear() { delete throttled[path]; clearTimeout(timeoutObject); } var timeoutObject = setTimeout(clear, timeout); throttled[path] = {timeoutObject: timeoutObject, clear: clear}; return throttled[path]; }; FSWatcher.prototype._isIgnored = function(path, stats) { var userIgnored = (function(ignored) { switch (toString.call(ignored)) { case '[object RegExp]': return function(string) { return ignored.test(string); }; case '[object Function]': return ignored; default: return function() { return false; }; } })(this.options.ignored); var ignoredPaths = Object.keys(this.ignoredPaths); function isParent(ip) { return !path.indexOf(ip + sysPath.sep); } return ignoredPaths.length && ignoredPaths.some(isParent) || userIgnored(path, stats); }; // Directory helpers // ----------------- FSWatcher.prototype._getWatchedDir = function(directory) { var dir = sysPath.resolve(directory); if (!(dir in this.watched)) this.watched[dir] = { _items: Object.create(null), add: function(item) {this._items[item] = true;}, remove: function(item) {delete this._items[item];}, has: function(item) {return item in this._items;}, children: function() {return Object.keys(this._items);} }; return this.watched[dir]; }; // File helpers // ------------ // Private: Check for read permissions // Based on this answer on SO: http://stackoverflow.com/a/11781404/1358405 // // * stats - object, result of fs.stat // // Returns Boolean FSWatcher.prototype._hasReadPermissions = function(stats) { return Boolean(4 & parseInt((stats.mode & 0x1ff).toString(8)[0], 10)); }; // Private: Handles emitting unlink events for // files and directories, and via recursion, for // files and directories within directories that are unlinked // // * directory - string, directory within which the following item is located // * item - string, base path of item/directory // // Returns nothing. FSWatcher.prototype._remove = function(directory, item) { // if what is being deleted is a directory, get that directory's paths // for recursive deleting and cleaning of watched object // if it is not a directory, nestedDirectoryChildren will be empty array var fullPath = sysPath.join(directory, item); var absolutePath = sysPath.resolve(fullPath); var isDirectory = this.watched[fullPath] || this.watched[absolutePath]; // prevent duplicate handling in case of arriving here nearly simultaneously // via multiple paths (such as _handleFile and _handleDir) if (!this._throttle('remove', fullPath, 10)) return; // if the only watched file is removed, watch for its return var watchedDirs = Object.keys(this.watched); if (!isDirectory && !this.options.useFsEvents && watchedDirs.length === 1) { this.add(directory, item); } // This will create a new entry in the watched object in either case // so we got to do the directory check beforehand var nestedDirectoryChildren = this._getWatchedDir(fullPath).children(); // Recursively remove children directories / files. nestedDirectoryChildren.forEach(function(nestedItem) { this._remove(fullPath, nestedItem); }, this); // Remove directory / file from watched list. this._getWatchedDir(directory).remove(item); // The Entry will either be a directory that just got removed // or a bogus entry to a file, in either case we have to remove it delete this.watched[fullPath]; delete this.watched[absolutePath]; var eventName = isDirectory ? 'unlinkDir' : 'unlink'; this._emit(eventName, fullPath); }; // FS Events helper. var FSEventsInstanceCount = 0; function createFSEventsInstance(path, callback) { FSEventsInstanceCount++; return (new fsevents(path)).on('fsevent', callback).start(); } FSWatcher.prototype._watchWithFsEvents = function(watchPath) { if (this._isIgnored(watchPath)) return; var watcher = createFSEventsInstance(watchPath, function(fullPath, flags) { var info = fsevents.getInfo(fullPath, flags); var path = sysPath.join(watchPath, sysPath.relative(watchPath, fullPath)); // ensure directories are tracked var parent = sysPath.dirname(path); var item = sysPath.basename(path); var watchedDir = this._getWatchedDir( info.type === 'directory' ? path : parent ); var checkIgnored = function (stats) { if (this._isIgnored(path, stats)) { this.ignoredPaths[fullPath] = true; return true; } else { delete this.ignoredPaths[fullPath]; } }.bind(this); var handleEvent = function (event) { if (event === 'unlink') { // suppress unlink events on never before seen files (from atomic write) if (info.type === 'directory' || watchedDir.has(item)) { this._remove(parent, item); } else { fs.stat(path, function(error, stats) { if (!stats || checkIgnored(stats)) return; info.type = stats.isDirectory() ? 'directory' : 'file'; handleEvent('add'); }); } return; // Don't emit event twice. } if (checkIgnored()) return; if (event === 'add') { this._getWatchedDir(parent).add(item); if (info.type === 'directory') this._getWatchedDir(path); } var eventName = info.type === 'file' ? event : event + 'Dir'; this._emit(eventName, path); }.bind(this); // correct for wrong events emitted function addOrChange() { handleEvent(watchedDir.has(item) ? 'change' : 'add'); } var wrongEventFlags = [69888, 70400, 71424, 72704, 73472, 131328, 131840]; if (wrongEventFlags.indexOf(flags) !== -1 || info.event === 'unknown') { if (info.event !== 'add' && info.event !== 'change') { fs.stat(path, function(error, stats) { if (checkIgnored(stats)) return; if (stats) { addOrChange(); } else { handleEvent('unlink'); } }); } else { addOrChange(); } return; } switch (info.event) { case 'created': return handleEvent('add'); case 'modified': return handleEvent('change'); case 'deleted': return handleEvent('unlink'); case 'moved': return fs.stat(path, function(error, stats) { stats ? addOrChange() : handleEvent('unlink'); }); } }.bind(this)); return this.watchers.push(watcher); }; // Private: Watch file for changes with fs.watchFile or fs.watch. // * item - string, path to file or directory. // * callback - function that will be executed on fs change. // Returns nothing. FSWatcher.prototype._watch = function(item, callback) { var directory = sysPath.dirname(item); var basename = sysPath.basename(item); var parent = this._getWatchedDir(directory); if (parent.has(basename)) return; parent.add(basename); var absolutePath = sysPath.resolve(item); var options = {persistent: this.options.persistent}; if (!callback) callback = Function.prototype; // empty function if (this.options.usePolling) { options.interval = this.enableBinaryInterval && isBinaryPath(basename) ? this.options.binaryInterval : this.options.interval; var listener = this.listeners[absolutePath] = function(curr, prev) { var currmtime = curr.mtime.getTime(); if (currmtime > prev.mtime.getTime() || currmtime === 0) { callback(item, curr); } }; fs.watchFile(absolutePath, options, listener); } else { var watcher = fs.watch(item, options, function(event, path) { callback(item); }); var _handleError = this._handleError; watcher.on('error', function(error) { // Workaround for https://github.com/joyent/node/issues/4337 if (isWin32 && error.code === 'EPERM') { fs.exists(item, function(exists) { if (exists) _handleError(error); }); } else { _handleError(error); } }); this.watchers.push(watcher); } }; // Private: Emit `change` event once and watch file to emit it in the future // once the file is changed. // * file - string, fs path. // * stats - object, result of fs.stat // * initialAdd - boolean, was the file added at watch instantiation? // Returns nothing. FSWatcher.prototype._handleFile = function(file, stats, initialAdd) { var dirname = sysPath.dirname(file); var basename = sysPath.basename(file); var parent = this._getWatchedDir(dirname); // if the file is already being watched, do nothing if (parent.has(basename)) return; this._watch(file, function(file, newStats) { if (!this._throttle('watch', file, 5)) return; if (!newStats || newStats && newStats.mtime.getTime() === 0) { fs.stat(file, function(error, newStats) { // Fix issues where mtime is null but file is still present if (error) { this._remove(dirname, basename); } else { this._emit('change', file, newStats); } }.bind(this)); // add is about to be emitted if file not already tracked in parent } else if (parent.has(basename)) { this._emit('change', file, newStats); } }.bind(this)); if (!(initialAdd && this.options.ignoreInitial)) { if (!this._throttle('add', file, 0)) return; this._emit('add', file, stats); } }; // Private: Read directory to add / remove files from `@watched` list // and re-read it on change. // * dir - string, fs path. // * stats - object, result of fs.stat // * initialAdd - boolean, was the file added at watch instantiation? // * target - child path actually targeted for watch // Returns nothing. FSWatcher.prototype._handleDir = function(dir, stats, initialAdd, target) { var _this = this; function read(directory, initialAdd, target) { // Normalize the directory name on Windows directory = sysPath.join(directory, ''); var throttler = _this._throttle('readdir', directory, 1000); if (!throttler) return; var previous = _this._getWatchedDir(directory); var current = []; readdirp({ root: directory, entryType: 'both', depth: 0 }).on('data', function(entry) { var item = entry.path; current.push(item); // Files that present in current directory snapshot // but absent in previous are added to watch list and // emit `add` event. if (item === target || !target && !previous.has(item)) { _this._handle(sysPath.join(directory, item), initialAdd, target); } }).on('end', function() { throttler.clear(); // Files that absent in current directory snapshot // but present in previous emit `remove` event // and are removed from @watched[directory]. previous.children().filter(function(item) { return item !== directory && current.indexOf(item) === -1; }).forEach(function(item) { _this._remove(directory, item); }); }).on('error', _this._handleError.bind(_this)); } if (!target) read(dir, initialAdd); this._watch(dir, function(dirPath, stats) { // Current directory is removed, do nothing if (stats && stats.mtime.getTime() === 0) return; read(dirPath, false, target); }); if (!(initialAdd && this.options.ignoreInitial) && !target) { this._emit('addDir', dir, stats); } }; // Private: Handle added file or directory. // Delegates call to _handleFile / _handleDir after checks. // * item - string, path to file or directory. // * initialAdd - boolean, was the file added at watch instantiation? // * target - child path actually targeted for watch // * callback - indicates whether the item was found or not // Returns nothing. FSWatcher.prototype._handle = function(item, initialAdd, target, callback) { if (!callback) callback = Function.prototype; if (this._isIgnored(item) || this.closed) return callback(null, item); fs.realpath(item, function(error, path) { if (this._handleError(error)) return callback(null, item); fs.stat(path, function(error, stats) { if (this._handleError(error)) return callback(null, item); if (( this.options.ignorePermissionErrors && !this._hasReadPermissions(stats) ) || ( this._isIgnored.length === 2 && this._isIgnored(item, stats) )) return callback(null, false); if (stats.isFile() || stats.isCharacterDevice()) { this._handleFile(item, stats, initialAdd); } else if (stats.isDirectory()) { this._handleDir(item, stats, initialAdd, target); } callback(null, false); }.bind(this)); }.bind(this)); }; FSWatcher.prototype._addToFsEvents = function(file) { var emitAdd = function(path, stats) { this._getWatchedDir(sysPath.dirname(path)).add(sysPath.basename(path)); this._emit(stats.isDirectory() ? 'addDir' : 'add', path, stats); }.bind(this); if (!this.options.ignoreInitial) { fs.stat(file, function(error, stats) { if (this._handleError(error)) return; if (stats.isDirectory()) { this._emit('addDir', file, stats); readdirp({ root: file, entryType: 'both', fileFilter: this._isntIgnored, directoryFilter: this._isntIgnored }).on('data', function(entry) { emitAdd(sysPath.join(file, entry.path), entry.stat); }); } else { emitAdd(file, stats); } }.bind(this)); } if (this.options.persistent) this._watchWithFsEvents(file); return this; }; // Public: Adds directories / files for tracking. // * files - array of strings (file or directory paths). // * _origAdd - private argument for handling non-existent paths to be watched // Returns an instance of FSWatcher for chaining. FSWatcher.prototype.add = function(files, _origAdd) { if (!('_initialAdd' in this)) this._initialAdd = true; if (!Array.isArray(files)) files = [files]; if (this.options.useFsEvents && FSEventsInstanceCount < 400) { files.forEach(this._addToFsEvents, this); } else if (!this.closed) { each(files, function(file, next) { this._handle(file, this._initialAdd, _origAdd, next); }.bind(this), function(error, results) { results.forEach(function(item){ if (!item) return; this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item)); }, this); }.bind(this)); } this._initialAdd = false; return this; }; // Public: Remove all listeners from watched files. // Returns an instance of FSWatcher for chaining. FSWatcher.prototype.close = function() { if (this.closed) return this; var listeners = this.listeners; var watched = this.watched; var useFsEvents = this.options.useFsEvents; var method = useFsEvents ? 'stop' : 'close'; this.closed = true; this.watchers.forEach(function(watcher) { if (watcher.stop) { watcher.stop(); FSEventsInstanceCount--; } else { watcher.close(); } }); Object.keys(watched).forEach(function(directory) { watched[directory].children().forEach(function(file) { var absolutePath = sysPath.resolve(directory, file); fs.unwatchFile(absolutePath, listeners[absolutePath]); delete listeners[absolutePath]; }); }); this.watched = Object.create(null); this.removeAllListeners(); return this; }; exports.FSWatcher = FSWatcher; exports.watch = function(files, options) { return new FSWatcher(options).add(files); };
import { assert } from '@ember/debug'; import { DEBUG } from '@glimmer/env'; /** @module @ember-data/store */ /* This is a helper method that validates a JSON API top-level document The format of a document is described here: http://jsonapi.org/format/#document-top-level @method validateDocumentStructure @param {Object} doc JSON API document @return {array} An array of errors found in the document structure */ export function validateDocumentStructure(doc) { let errors = []; if (!doc || typeof doc !== 'object') { errors.push('Top level of a JSON API document must be an object'); } else { if (!('data' in doc) && !('errors' in doc) && !('meta' in doc)) { errors.push('One or more of the following keys must be present: "data", "errors", "meta".'); } else { if ('data' in doc && 'errors' in doc) { errors.push('Top level keys "errors" and "data" cannot both be present in a JSON API document'); } } if ('data' in doc) { if (!(doc.data === null || Array.isArray(doc.data) || typeof doc.data === 'object')) { errors.push('data must be null, an object, or an array'); } } if ('meta' in doc) { if (typeof doc.meta !== 'object') { errors.push('meta must be an object'); } } if ('errors' in doc) { if (!Array.isArray(doc.errors)) { errors.push('errors must be an array'); } } if ('links' in doc) { if (typeof doc.links !== 'object') { errors.push('links must be an object'); } } if ('jsonapi' in doc) { if (typeof doc.jsonapi !== 'object') { errors.push('jsonapi must be an object'); } } if ('included' in doc) { if (typeof doc.included !== 'object') { errors.push('included must be an array'); } } } return errors; } /* This is a helper method that always returns a JSON-API Document. @method normalizeResponseHelper @param {Serializer} serializer @param {Store} store @param {subclass of Model} modelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ export function normalizeResponseHelper(serializer, store, modelClass, payload, id, requestType) { let normalizedResponse = serializer.normalizeResponse(store, modelClass, payload, id, requestType); let validationErrors = []; if (DEBUG) { validationErrors = validateDocumentStructure(normalizedResponse); } assert( `normalizeResponse must return a valid JSON API document:\n\t* ${validationErrors.join('\n\t* ')}`, validationErrors.length === 0 ); return normalizedResponse; }
var expect = chai.expect; describe("Utils", function () { it("should have a method called createUniqueId", function () { expect(GA.Utils).to.have.property('createUniqueId'); expect(GA.Utils.createUniqueId).to.be.a('function'); }); describe("createUniqueId", function () { it('should return a valid uuid v4', function () { var uuid = GA.Utils.createUniqueId(); expect(uuid).to.match(/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/gi); }); }); it("should have a method called postRequest", function () { expect(GA.Utils).to.have.property('postRequest'); expect(GA.Utils.postRequest).to.be.a('function'); }); describe("postRequest", function () { describe('when doing successful request', function () { var xhr, requests = []; beforeEach(function () { this.xhr = sinon.useFakeXMLHttpRequest(); this.requests = []; var self = this; this.xhr.onCreate = function(xhr) { self.requests.push(xhr); }; }); afterEach(function () { this.xhr.restore(); }); it('should call an callback with an object that has success set to true on a good post and a message from the server', function (done) { GA.Utils.postRequest('http://blaat', {}, '', function (data) { expect(data.success).to.equal(true); expect(data.message).to.equal('OK'); done(); }); this.requests[0].respond(200, { 'Content-Type': 'text/plain' }, 'OK'); }); it('should call an callback with an error on incorrect http status', function (done) { GA.Utils.postRequest('http://blaat', {}, '', function (data) { expect(data.success).to.equal(false); expect(data.message).to.match(/^Error/gi); done(); }); this.requests[0].respond(404, { 'Content-Type': 'text/plain' }, ''); }); it('should call an callback when there is no XMLHttpRequest', function () { window.XMLHttpRequest = null; }); }); describe('when in IE9', function () { beforeEach(function () { window._XMLHttpRequest = window.XMLHttpRequest; window.XMLHttpRequest = null; }); afterEach(function () { window.XMLHttpRequest = window._XMLHttpRequest; }); it('should call an callback when there is no XMLHttpRequest', function (done) { GA.Utils.postRequest('http://blaat', {}, '', function (data) { expect(data.success).to.equal(false); expect(data.message).to.match(/^Error/gi); done(); }); }); }); describe('when failing on error', function () { var oldF; beforeEach(function () { var oldF = window.XMLHttpRequest.prototype.send; window.XMLHttpRequest.prototype.send = function () { throw new Error('w00t'); }; }); afterEach(function () { window.XMLHttpRequest.prototype.send = oldF; }); it('should call an callback when there is no XMLHttpRequest', function (done) { GA.Utils.postRequest('http://blaat', {}, '', function (data) { expect(data.success).to.equal(false); expect(data.message).to.match(/^Error/gi); done(); }); }); }); }); describe("Message", function () { it("should have a local event and annotations", function () { var testEvent = new GA.Events.User(); var annotations = GA.Utils.getBaseAnnotations(); var message = new GA.Utils.Message(testEvent, annotations); expect(message.event).to.equal(testEvent); expect(message.annotations).to.equal(annotations); }); it("should have a property data that returns a nice object that can be send over the wire", function () { var testEvent = new GA.Events.SessionEnd(300); var annotations = GA.Utils.getBaseAnnotations(); var message = new GA.Utils.Message(testEvent, annotations); expect(function () { JSON.stringify(message.data) }).to.not.throw(Error); }); }); describe("MessageQueue", function () { it("should behave like an Queue, meaning it can push/pop data and has a length", function () { var queue = new GA.Utils.MessageQueue(); var testEvent = new GA.Events.SessionEnd(300); var annotations = GA.Utils.getBaseAnnotations(); var message = new GA.Utils.Message(testEvent, annotations); expect(queue).to.have.property('pop'); expect(queue).to.have.property('push'); expect(queue).to.have.property('length'); expect(queue.length).to.equal(0); queue.push(message); expect(queue.length).to.equal(1); expect(queue.pop()).to.equal(message); expect(queue.length).to.equal(0); }); }); describe("Response", function () { it("should be default have an empty message and success equal false", function () { var response = new GA.Utils.Response(); expect(response.message).to.equal(''); expect(response.success).to.equal(false); }); }); describe("Annotations", function () { describe("getDefaultAnnotations", function () { describe('on a desktop', function () { it("should return a nice object we can send to gameanalytics including some device data", function () { var user = new GA.User('124123', '1241234', GA.Gender.male, 1970); var obj = GA.Utils.getDefaultAnnotations(user, '12341234', '1'); expect(obj).to.have.property('platform'); expect(obj.platform).to.equal('windows'); expect(obj).to.have.property('os_version'); expect(obj.os_version).to.equal('windows 8'); expect(obj).to.have.property('device'); expect(obj.device).to.equal('unknown'); expect(obj).to.have.property('manufacturer'); expect(obj.manufacturer).to.equal('unknown'); expect(obj).to.have.property('facebook_id'); expect(obj).to.have.property('gender'); expect(obj).to.have.property('birth_year'); expect(obj).to.have.property('user_id'); }); }); }); }); });
// gm - Copyright Aaron Heckmann <aaron.heckmann+github@gmail.com> (MIT Licensed) var assert = require('assert') module.exports = function (_, dir, finish, gm) { var im = _._options.imageMagick; var test = gm(dir + '/photo.JPG'); if (im) test.options({ imageMagick: true }); test.identify(function (err) { if (err) return finish(err); var d = this.data; if (im) { assert.equal(d.Orientation, 'TopLeft'); assert.equal(d['Quality'], 96); assert.equal(d['Geometry'], '430x488+0+0'); assert.equal(d['Print size'], '5.97222x6.77778'); assert.equal(d['Channel depth'].red, '8-bit'); assert.equal(d['Channel depth'].green, '8-bit'); assert.equal(d['Channel statistics'].Red.min, '0 (0)'); assert.equal(d['Channel statistics'].Red['standard deviation'], '71.7079 (0.281208)'); assert.equal(d['Image statistics'].Overall.kurtosis, '-1.09331'); assert.equal(d['Rendering intent'], 'Perceptual'); assert.equal(d.Properties['date:create'], '2012-07-29T15:48:42-07:00'); assert.equal(d.Properties['exif:DateTimeDigitized'], '2011:07:01 11:23:16'); } else { assert.equal(d.Orientation, 'TopLeft'); assert.equal(d['JPEG-Quality'], 96); assert.ok(/(0.2812)/.test(d['Channel Statistics'].Red['Standard Deviation'])); var ex = d['Profile-EXIF']; assert.equal(ex.Make, 'Apple'); assert.equal(ex.Model, 'iPad 2'); assert.equal(ex['GPS Info'], 558); assert.equal(ex['GPS Longitude'], '80/1,4970/100,0/1'); assert.equal(ex['GPS Time Stamp'], '15/1,23/1,945/1'); } finish(); }); }
import _ from 'lodash'; import { getQbankMediaType } from '../../../../constants/genus_types'; export function deserializeSingleMedia(asset, autoPlay = null) { const newMedia = { id: asset.id, type: '', url: '', autoPlay, altText: {}, description: asset.description, license: asset.license, copyright: asset.copyright, original: asset, assetContentId: '', extension: '', }; _.each(asset.assetContents, (content) => { const type = getQbankMediaType(content.genusTypeId); switch (type) { case 'image': case 'video': case 'audio': { // we need the file extension for attempted mime type, so we extract it // out of the genusTypeId const regexp = /%3A(.*)%40/; newMedia.extension = _.get(regexp.exec(content.genusTypeId), '[1]', ''); newMedia.type = type; newMedia.url = content.url; newMedia.assetContentId = content.id; break; } case 'altText': newMedia.altText = content.altText; newMedia.altTexts = content.altTexts; break; case 'description': newMedia.description = content.mediaDescription; break; case 'vtt': newMedia.vtt = { ...content, assetContentId: content.id, id: content.assetId, }; break; case 'transcript': newMedia.transcript = { ...content, assetContentId: content.id, id: content.assetId, }; break; default: console.log(content.genusTypeId); break; } }); return newMedia; } export function deserializeMedia(mediaData) { const newMediaData = { image: {}, audio: {}, video: {}, }; _.each(mediaData, (data) => { const newMedia = deserializeSingleMedia(data); if (newMedia.type) { newMediaData[newMedia.type][newMedia.id] = newMedia; } }); return newMediaData; }
define(['durandal/activator', './step1', './step2', './step3', 'knockout'], function( activator, Step1, Step2, Step3, ko ) { var steps = [new Step1(), new Step2(), new Step3()]; var step = ko.observable(0); var activeStep = activator.create(); var stepsLength = steps.length; var hasPrevious = ko.computed(function() { return step() > 0; }); var hasNext = ko.computed(function() { return (step() < stepsLength - 1); }); // Start with first step activeStep(steps[step()]); return { showCodeUrl: true, steps: steps, step: step, activeStep: activeStep, next: next, previous: previous, hasPrevious: hasPrevious, hasNext: hasNext }; function next () { if ( step() < stepsLength ) { step(step() + 1); activeStep(steps[step()]); } } function previous () { if ( step() > 0 ) { step(step() - 1); activeStep(steps[step()]); } } });
'use strict'; /** * @ngdoc object * @name angular.mock * @description * * Namespace from 'angular-mocks.js' which contains testing related code. * */ angular.mock = {}; /** * ! This is a private undocumented service ! * * @name $browser * * @description * This service is a mock implementation of {@link ng.$browser}. It provides fake * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr, * cookies, etc. * * The api of this service is the same as that of the real {@link ng.$browser $browser}, except * that there are several helper methods available which can be used in tests. */ angular.mock.$BrowserProvider = function() { this.$get = function() { return new angular.mock.$Browser(); }; }; angular.mock.$Browser = function() { var self = this; this.isMock = true; self.$$url = 'http://server/'; self.$$lastUrl = self.$$url; // used by url polling fn self.pollFns = []; // Testability API var outstandingRequestCount = 0; var outstandingRequestCallbacks = []; self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; self.$$completeOutstandingRequest = function(fn) { try { fn(); } finally { outstandingRequestCount--; if (!outstandingRequestCount) { while (outstandingRequestCallbacks.length) { outstandingRequestCallbacks.pop()(); } } } }; self.notifyWhenNoOutstandingRequests = function(callback) { if (outstandingRequestCount) { outstandingRequestCallbacks.push(callback); } else { callback(); } }; // register url polling fn self.onUrlChange = function(listener) { self.pollFns.push( function() { if (self.$$lastUrl !== self.$$url || self.$$state !== self.$$lastState) { self.$$lastUrl = self.$$url; self.$$lastState = self.$$state; listener(self.$$url, self.$$state); } } ); return listener; }; self.$$applicationDestroyed = angular.noop; self.$$checkUrlChange = angular.noop; self.deferredFns = []; self.deferredNextId = 0; self.defer = function(fn, delay) { // Note that we do not use `$$incOutstandingRequestCount` or `$$completeOutstandingRequest` // in this mock implementation. delay = delay || 0; self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId}); self.deferredFns.sort(function(a, b) { return a.time - b.time;}); return self.deferredNextId++; }; /** * @name $browser#defer.now * * @description * Current milliseconds mock time. */ self.defer.now = 0; self.defer.cancel = function(deferId) { var fnIndex; angular.forEach(self.deferredFns, function(fn, index) { if (fn.id === deferId) fnIndex = index; }); if (angular.isDefined(fnIndex)) { self.deferredFns.splice(fnIndex, 1); return true; } return false; }; /** * @name $browser#defer.flush * * @description * Flushes all pending requests and executes the defer callbacks. * * @param {number=} number of milliseconds to flush. See {@link #defer.now} */ self.defer.flush = function(delay) { var nextTime; if (angular.isDefined(delay)) { // A delay was passed so compute the next time nextTime = self.defer.now + delay; } else { if (self.deferredFns.length) { // No delay was passed so set the next time so that it clears the deferred queue nextTime = self.deferredFns[self.deferredFns.length - 1].time; } else { // No delay passed, but there are no deferred tasks so flush - indicates an error! throw new Error('No deferred tasks to be flushed'); } } while (self.deferredFns.length && self.deferredFns[0].time <= nextTime) { // Increment the time and call the next deferred function self.defer.now = self.deferredFns[0].time; self.deferredFns.shift().fn(); } // Ensure that the current time is correct self.defer.now = nextTime; }; self.$$baseHref = '/'; self.baseHref = function() { return this.$$baseHref; }; }; angular.mock.$Browser.prototype = { /** * @name $browser#poll * * @description * run all fns in pollFns */ poll: function poll() { angular.forEach(this.pollFns, function(pollFn) { pollFn(); }); }, url: function(url, replace, state) { if (angular.isUndefined(state)) { state = null; } if (url) { this.$$url = url; // Native pushState serializes & copies the object; simulate it. this.$$state = angular.copy(state); return this; } return this.$$url; }, state: function() { return this.$$state; } }; /** * @ngdoc provider * @name $exceptionHandlerProvider * * @description * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors * passed to the `$exceptionHandler`. */ /** * @ngdoc service * @name $exceptionHandler * * @description * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed * to it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration * information. * * * ```js * describe('$exceptionHandlerProvider', function() { * * it('should capture log messages and exceptions', function() { * * module(function($exceptionHandlerProvider) { * $exceptionHandlerProvider.mode('log'); * }); * * inject(function($log, $exceptionHandler, $timeout) { * $timeout(function() { $log.log(1); }); * $timeout(function() { $log.log(2); throw 'banana peel'; }); * $timeout(function() { $log.log(3); }); * expect($exceptionHandler.errors).toEqual([]); * expect($log.assertEmpty()); * $timeout.flush(); * expect($exceptionHandler.errors).toEqual(['banana peel']); * expect($log.log.logs).toEqual([[1], [2], [3]]); * }); * }); * }); * ``` */ angular.mock.$ExceptionHandlerProvider = function() { var handler; /** * @ngdoc method * @name $exceptionHandlerProvider#mode * * @description * Sets the logging mode. * * @param {string} mode Mode of operation, defaults to `rethrow`. * * - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log` * mode stores an array of errors in `$exceptionHandler.errors`, to allow later assertion of * them. See {@link ngMock.$log#assertEmpty assertEmpty()} and * {@link ngMock.$log#reset reset()}. * - `rethrow`: If any errors are passed to the handler in tests, it typically means that there * is a bug in the application or test, so this mock will make these tests fail. For any * implementations that expect exceptions to be thrown, the `rethrow` mode will also maintain * a log of thrown errors in `$exceptionHandler.errors`. */ this.mode = function(mode) { switch (mode) { case 'log': case 'rethrow': var errors = []; handler = function(e) { if (arguments.length === 1) { errors.push(e); } else { errors.push([].slice.call(arguments, 0)); } if (mode === 'rethrow') { throw e; } }; handler.errors = errors; break; default: throw new Error('Unknown mode \'' + mode + '\', only \'log\'/\'rethrow\' modes are allowed!'); } }; this.$get = function() { return handler; }; this.mode('rethrow'); }; /** * @ngdoc service * @name $log * * @description * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays * (one array per logging level). These arrays are exposed as `logs` property of each of the * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`. * */ angular.mock.$LogProvider = function() { var debug = true; function concat(array1, array2, index) { return array1.concat(Array.prototype.slice.call(array2, index)); } this.debugEnabled = function(flag) { if (angular.isDefined(flag)) { debug = flag; return this; } else { return debug; } }; this.$get = function() { var $log = { log: function() { $log.log.logs.push(concat([], arguments, 0)); }, warn: function() { $log.warn.logs.push(concat([], arguments, 0)); }, info: function() { $log.info.logs.push(concat([], arguments, 0)); }, error: function() { $log.error.logs.push(concat([], arguments, 0)); }, debug: function() { if (debug) { $log.debug.logs.push(concat([], arguments, 0)); } } }; /** * @ngdoc method * @name $log#reset * * @description * Reset all of the logging arrays to empty. */ $log.reset = function() { /** * @ngdoc property * @name $log#log.logs * * @description * Array of messages logged using {@link ng.$log#log `log()`}. * * @example * ```js * $log.log('Some Log'); * var first = $log.log.logs.unshift(); * ``` */ $log.log.logs = []; /** * @ngdoc property * @name $log#info.logs * * @description * Array of messages logged using {@link ng.$log#info `info()`}. * * @example * ```js * $log.info('Some Info'); * var first = $log.info.logs.unshift(); * ``` */ $log.info.logs = []; /** * @ngdoc property * @name $log#warn.logs * * @description * Array of messages logged using {@link ng.$log#warn `warn()`}. * * @example * ```js * $log.warn('Some Warning'); * var first = $log.warn.logs.unshift(); * ``` */ $log.warn.logs = []; /** * @ngdoc property * @name $log#error.logs * * @description * Array of messages logged using {@link ng.$log#error `error()`}. * * @example * ```js * $log.error('Some Error'); * var first = $log.error.logs.unshift(); * ``` */ $log.error.logs = []; /** * @ngdoc property * @name $log#debug.logs * * @description * Array of messages logged using {@link ng.$log#debug `debug()`}. * * @example * ```js * $log.debug('Some Error'); * var first = $log.debug.logs.unshift(); * ``` */ $log.debug.logs = []; }; /** * @ngdoc method * @name $log#assertEmpty * * @description * Assert that all of the logging methods have no logged messages. If any messages are present, * an exception is thrown. */ $log.assertEmpty = function() { var errors = []; angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) { angular.forEach($log[logLevel].logs, function(log) { angular.forEach(log, function(logItem) { errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + (logItem.stack || '')); }); }); }); if (errors.length) { errors.unshift('Expected $log to be empty! Either a message was logged unexpectedly, or ' + 'an expected log message was not checked and removed:'); errors.push(''); throw new Error(errors.join('\n---------\n')); } }; $log.reset(); return $log; }; }; /** * @ngdoc service * @name $interval * * @description * Mock implementation of the $interval service. * * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to * move forward by `millis` milliseconds and trigger any functions scheduled to run in that * time. * * @param {function()} fn A function that should be called repeatedly. * @param {number} delay Number of milliseconds between each function call. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat * indefinitely. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @param {...*=} Pass additional parameters to the executed function. * @returns {promise} A promise which will be notified on each iteration. */ angular.mock.$IntervalProvider = function() { this.$get = ['$browser', '$rootScope', '$q', '$$q', function($browser, $rootScope, $q, $$q) { var repeatFns = [], nextRepeatId = 0, now = 0; var $interval = function(fn, delay, count, invokeApply) { var hasParams = arguments.length > 4, args = hasParams ? Array.prototype.slice.call(arguments, 4) : [], iteration = 0, skipApply = (angular.isDefined(invokeApply) && !invokeApply), deferred = (skipApply ? $$q : $q).defer(), promise = deferred.promise; count = (angular.isDefined(count)) ? count : 0; promise.then(null, function() {}, (!hasParams) ? fn : function() { fn.apply(null, args); }); promise.$$intervalId = nextRepeatId; function tick() { deferred.notify(iteration++); if (count > 0 && iteration >= count) { var fnIndex; deferred.resolve(iteration); angular.forEach(repeatFns, function(fn, index) { if (fn.id === promise.$$intervalId) fnIndex = index; }); if (angular.isDefined(fnIndex)) { repeatFns.splice(fnIndex, 1); } } if (skipApply) { $browser.defer.flush(); } else { $rootScope.$apply(); } } repeatFns.push({ nextTime: (now + (delay || 0)), delay: delay || 1, fn: tick, id: nextRepeatId, deferred: deferred }); repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;}); nextRepeatId++; return promise; }; /** * @ngdoc method * @name $interval#cancel * * @description * Cancels a task associated with the `promise`. * * @param {promise} promise A promise from calling the `$interval` function. * @returns {boolean} Returns `true` if the task was successfully cancelled. */ $interval.cancel = function(promise) { if (!promise) return false; var fnIndex; angular.forEach(repeatFns, function(fn, index) { if (fn.id === promise.$$intervalId) fnIndex = index; }); if (angular.isDefined(fnIndex)) { repeatFns[fnIndex].deferred.promise.then(undefined, function() {}); repeatFns[fnIndex].deferred.reject('canceled'); repeatFns.splice(fnIndex, 1); return true; } return false; }; /** * @ngdoc method * @name $interval#flush * @description * * Runs interval tasks scheduled to be run in the next `millis` milliseconds. * * @param {number=} millis maximum timeout amount to flush up until. * * @return {number} The amount of time moved forward. */ $interval.flush = function(millis) { var before = now; now += millis; while (repeatFns.length && repeatFns[0].nextTime <= now) { var task = repeatFns[0]; task.fn(); if (task.nextTime === before) { // this can only happen the first time // a zero-delay interval gets triggered task.nextTime++; } task.nextTime += task.delay; repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;}); } return millis; }; return $interval; }]; }; function jsonStringToDate(string) { // The R_ISO8061_STR regex is never going to fit into the 100 char limit! // eslit-disable-next-line max-len var R_ISO8061_STR = /^(-?\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/; var match; if ((match = string.match(R_ISO8061_STR))) { var date = new Date(0), tzHour = 0, tzMin = 0; if (match[9]) { tzHour = toInt(match[9] + match[10]); tzMin = toInt(match[9] + match[11]); } date.setUTCFullYear(toInt(match[1]), toInt(match[2]) - 1, toInt(match[3])); date.setUTCHours(toInt(match[4] || 0) - tzHour, toInt(match[5] || 0) - tzMin, toInt(match[6] || 0), toInt(match[7] || 0)); return date; } return string; } function toInt(str) { return parseInt(str, 10); } function padNumberInMock(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while (num.length < digits) num = '0' + num; if (trim) { num = num.substr(num.length - digits); } return neg + num; } /** * @ngdoc type * @name angular.mock.TzDate * @description * * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`. * * Mock of the Date type which has its timezone specified via constructor arg. * * The main purpose is to create Date-like instances with timezone fixed to the specified timezone * offset, so that we can test code that depends on local timezone settings without dependency on * the time zone settings of the machine where the code is running. * * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored) * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC* * * @example * !!!! WARNING !!!!! * This is not a complete Date object so only methods that were implemented can be called safely. * To make matters worse, TzDate instances inherit stuff from Date via a prototype. * * We do our best to intercept calls to "unimplemented" methods, but since the list of methods is * incomplete we might be missing some non-standard methods. This can result in errors like: * "Date.prototype.foo called on incompatible Object". * * ```js * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z'); * newYearInBratislava.getTimezoneOffset() => -60; * newYearInBratislava.getFullYear() => 2010; * newYearInBratislava.getMonth() => 0; * newYearInBratislava.getDate() => 1; * newYearInBratislava.getHours() => 0; * newYearInBratislava.getMinutes() => 0; * newYearInBratislava.getSeconds() => 0; * ``` * */ angular.mock.TzDate = function(offset, timestamp) { var self = new Date(0); if (angular.isString(timestamp)) { var tsStr = timestamp; self.origDate = jsonStringToDate(timestamp); timestamp = self.origDate.getTime(); if (isNaN(timestamp)) { // eslint-disable-next-line no-throw-literal throw { name: 'Illegal Argument', message: 'Arg \'' + tsStr + '\' passed into TzDate constructor is not a valid date string' }; } } else { self.origDate = new Date(timestamp); } var localOffset = new Date(timestamp).getTimezoneOffset(); self.offsetDiff = localOffset * 60 * 1000 - offset * 1000 * 60 * 60; self.date = new Date(timestamp + self.offsetDiff); self.getTime = function() { return self.date.getTime() - self.offsetDiff; }; self.toLocaleDateString = function() { return self.date.toLocaleDateString(); }; self.getFullYear = function() { return self.date.getFullYear(); }; self.getMonth = function() { return self.date.getMonth(); }; self.getDate = function() { return self.date.getDate(); }; self.getHours = function() { return self.date.getHours(); }; self.getMinutes = function() { return self.date.getMinutes(); }; self.getSeconds = function() { return self.date.getSeconds(); }; self.getMilliseconds = function() { return self.date.getMilliseconds(); }; self.getTimezoneOffset = function() { return offset * 60; }; self.getUTCFullYear = function() { return self.origDate.getUTCFullYear(); }; self.getUTCMonth = function() { return self.origDate.getUTCMonth(); }; self.getUTCDate = function() { return self.origDate.getUTCDate(); }; self.getUTCHours = function() { return self.origDate.getUTCHours(); }; self.getUTCMinutes = function() { return self.origDate.getUTCMinutes(); }; self.getUTCSeconds = function() { return self.origDate.getUTCSeconds(); }; self.getUTCMilliseconds = function() { return self.origDate.getUTCMilliseconds(); }; self.getDay = function() { return self.date.getDay(); }; // provide this method only on browsers that already have it if (self.toISOString) { self.toISOString = function() { return padNumberInMock(self.origDate.getUTCFullYear(), 4) + '-' + padNumberInMock(self.origDate.getUTCMonth() + 1, 2) + '-' + padNumberInMock(self.origDate.getUTCDate(), 2) + 'T' + padNumberInMock(self.origDate.getUTCHours(), 2) + ':' + padNumberInMock(self.origDate.getUTCMinutes(), 2) + ':' + padNumberInMock(self.origDate.getUTCSeconds(), 2) + '.' + padNumberInMock(self.origDate.getUTCMilliseconds(), 3) + 'Z'; }; } //hide all methods not implemented in this mock that the Date prototype exposes var unimplementedMethods = ['getUTCDay', 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', 'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString', 'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf']; angular.forEach(unimplementedMethods, function(methodName) { self[methodName] = function() { throw new Error('Method \'' + methodName + '\' is not implemented in the TzDate mock'); }; }); return self; }; //make "tzDateInstance instanceof Date" return true angular.mock.TzDate.prototype = Date.prototype; /** * @ngdoc service * @name $animate * * @description * Mock implementation of the {@link ng.$animate `$animate`} service. Exposes two additional methods * for testing animations. * * You need to require the `ngAnimateMock` module in your test suite for instance `beforeEach(module('ngAnimateMock'))` */ angular.mock.animate = angular.module('ngAnimateMock', ['ng']) .info({ angularVersion: '"NG_VERSION_FULL"' }) .config(['$provide', function($provide) { $provide.factory('$$forceReflow', function() { function reflowFn() { reflowFn.totalReflows++; } reflowFn.totalReflows = 0; return reflowFn; }); $provide.factory('$$animateAsyncRun', function() { var queue = []; var queueFn = function() { return function(fn) { queue.push(fn); }; }; queueFn.flush = function() { if (queue.length === 0) return false; for (var i = 0; i < queue.length; i++) { queue[i](); } queue = []; return true; }; return queueFn; }); $provide.decorator('$$animateJs', ['$delegate', function($delegate) { var runners = []; var animateJsConstructor = function() { var animator = $delegate.apply($delegate, arguments); // If no javascript animation is found, animator is undefined if (animator) { runners.push(animator); } return animator; }; animateJsConstructor.$closeAndFlush = function() { runners.forEach(function(runner) { runner.end(); }); runners = []; }; return animateJsConstructor; }]); $provide.decorator('$animateCss', ['$delegate', function($delegate) { var runners = []; var animateCssConstructor = function(element, options) { var animator = $delegate(element, options); runners.push(animator); return animator; }; animateCssConstructor.$closeAndFlush = function() { runners.forEach(function(runner) { runner.end(); }); runners = []; }; return animateCssConstructor; }]); $provide.decorator('$animate', ['$delegate', '$timeout', '$browser', '$$rAF', '$animateCss', '$$animateJs', '$$forceReflow', '$$animateAsyncRun', '$rootScope', function($delegate, $timeout, $browser, $$rAF, $animateCss, $$animateJs, $$forceReflow, $$animateAsyncRun, $rootScope) { var animate = { queue: [], cancel: $delegate.cancel, on: $delegate.on, off: $delegate.off, pin: $delegate.pin, get reflows() { return $$forceReflow.totalReflows; }, enabled: $delegate.enabled, /** * @ngdoc method * @name $animate#closeAndFlush * @description * * This method will close all pending animations (both {@link ngAnimate#javascript-based-animations Javascript} * and {@link ngAnimate.$animateCss CSS}) and it will also flush any remaining animation frames and/or callbacks. */ closeAndFlush: function() { // we allow the flush command to swallow the errors // because depending on whether CSS or JS animations are // used, there may not be a RAF flush. The primary flush // at the end of this function must throw an exception // because it will track if there were pending animations this.flush(true); $animateCss.$closeAndFlush(); $$animateJs.$closeAndFlush(); this.flush(); }, /** * @ngdoc method * @name $animate#flush * @description * * This method is used to flush the pending callbacks and animation frames to either start * an animation or conclude an animation. Note that this will not actually close an * actively running animation (see {@link ngMock.$animate#closeAndFlush `closeAndFlush()`} for that). */ flush: function(hideErrors) { $rootScope.$digest(); var doNextRun, somethingFlushed = false; do { doNextRun = false; if ($$rAF.queue.length) { $$rAF.flush(); doNextRun = somethingFlushed = true; } if ($$animateAsyncRun.flush()) { doNextRun = somethingFlushed = true; } } while (doNextRun); if (!somethingFlushed && !hideErrors) { throw new Error('No pending animations ready to be closed or flushed'); } $rootScope.$digest(); } }; angular.forEach( ['animate','enter','leave','move','addClass','removeClass','setClass'], function(method) { animate[method] = function() { animate.queue.push({ event: method, element: arguments[0], options: arguments[arguments.length - 1], args: arguments }); return $delegate[method].apply($delegate, arguments); }; }); return animate; }]); }]); /** * @ngdoc function * @name angular.mock.dump * @description * * *NOTE*: This is not an injectable instance, just a globally available function. * * Method for serializing common AngularJS objects (scope, elements, etc..) into strings. * It is useful for logging objects to the console when debugging. * * @param {*} object - any object to turn into string. * @return {string} a serialized string of the argument */ angular.mock.dump = function(object) { return serialize(object); function serialize(object) { var out; if (angular.isElement(object)) { object = angular.element(object); out = angular.element('<div></div>'); angular.forEach(object, function(element) { out.append(angular.element(element).clone()); }); out = out.html(); } else if (angular.isArray(object)) { out = []; angular.forEach(object, function(o) { out.push(serialize(o)); }); out = '[ ' + out.join(', ') + ' ]'; } else if (angular.isObject(object)) { if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) { out = serializeScope(object); } else if (object instanceof Error) { out = object.stack || ('' + object.name + ': ' + object.message); } else { // TODO(i): this prevents methods being logged, // we should have a better way to serialize objects out = angular.toJson(object, true); } } else { out = String(object); } return out; } function serializeScope(scope, offset) { offset = offset || ' '; var log = [offset + 'Scope(' + scope.$id + '): {']; for (var key in scope) { if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\$|this)/)) { log.push(' ' + key + ': ' + angular.toJson(scope[key])); } } var child = scope.$$childHead; while (child) { log.push(serializeScope(child, offset + ' ')); child = child.$$nextSibling; } log.push('}'); return log.join('\n' + offset); } }; /** * @ngdoc service * @name $httpBackend * @description * Fake HTTP backend implementation suitable for unit testing applications that use the * {@link ng.$http $http service}. * * <div class="alert alert-info"> * **Note**: For fake HTTP backend implementation suitable for end-to-end testing or backend-less * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}. * </div> * * During unit testing, we want our unit tests to run quickly and have no external dependencies so * we don’t want to send [XHR](https://developer.mozilla.org/en/xmlhttprequest) or * [JSONP](http://en.wikipedia.org/wiki/JSONP) requests to a real server. All we really need is * to verify whether a certain request has been sent or not, or alternatively just let the * application make requests, respond with pre-trained responses and assert that the end result is * what we expect it to be. * * This mock implementation can be used to respond with static or dynamic responses via the * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc). * * When an AngularJS application needs some data from a server, it calls the $http service, which * sends the request to a real server using $httpBackend service. With dependency injection, it is * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify * the requests and respond with some testing data without sending a request to a real server. * * There are two ways to specify what test data should be returned as http responses by the mock * backend when the code under test makes http requests: * * - `$httpBackend.expect` - specifies a request expectation * - `$httpBackend.when` - specifies a backend definition * * * ## Request Expectations vs Backend Definitions * * Request expectations provide a way to make assertions about requests made by the application and * to define responses for those requests. The test will fail if the expected requests are not made * or they are made in the wrong order. * * Backend definitions allow you to define a fake backend for your application which doesn't assert * if a particular request was made or not, it just returns a trained response if a request is made. * The test will pass whether or not the request gets made during testing. * * * <table class="table"> * <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr> * <tr> * <th>Syntax</th> * <td>.expect(...).respond(...)</td> * <td>.when(...).respond(...)</td> * </tr> * <tr> * <th>Typical usage</th> * <td>strict unit tests</td> * <td>loose (black-box) unit testing</td> * </tr> * <tr> * <th>Fulfills multiple requests</th> * <td>NO</td> * <td>YES</td> * </tr> * <tr> * <th>Order of requests matters</th> * <td>YES</td> * <td>NO</td> * </tr> * <tr> * <th>Request required</th> * <td>YES</td> * <td>NO</td> * </tr> * <tr> * <th>Response required</th> * <td>optional (see below)</td> * <td>YES</td> * </tr> * </table> * * In cases where both backend definitions and request expectations are specified during unit * testing, the request expectations are evaluated first. * * If a request expectation has no response specified, the algorithm will search your backend * definitions for an appropriate response. * * If a request didn't match any expectation or if the expectation doesn't have the response * defined, the backend definitions are evaluated in sequential order to see if any of them match * the request. The response from the first matched definition is returned. * * * ## Flushing HTTP requests * * The $httpBackend used in production always responds to requests asynchronously. If we preserved * this behavior in unit testing, we'd have to create async unit tests, which are hard to write, * to follow and to maintain. But neither can the testing mock respond synchronously; that would * change the execution of the code under test. For this reason, the mock $httpBackend has a * `flush()` method, which allows the test to explicitly flush pending requests. This preserves * the async api of the backend, while allowing the test to execute synchronously. * * * ## Unit testing with mock $httpBackend * The following code shows how to setup and use the mock backend when unit testing a controller. * First we create the controller under test: * ```js // The module code angular .module('MyApp', []) .controller('MyController', MyController); // The controller code function MyController($scope, $http) { var authToken; $http.get('/auth.py').then(function(response) { authToken = response.headers('A-Token'); $scope.user = response.data; }).catch(function() { $scope.status = 'Failed...'; }); $scope.saveMessage = function(message) { var headers = { 'Authorization': authToken }; $scope.status = 'Saving...'; $http.post('/add-msg.py', message, { headers: headers } ).then(function(response) { $scope.status = ''; }).catch(function() { $scope.status = 'Failed...'; }); }; } ``` * * Now we setup the mock backend and create the test specs: * ```js // testing controller describe('MyController', function() { var $httpBackend, $rootScope, createController, authRequestHandler; // Set up the module beforeEach(module('MyApp')); beforeEach(inject(function($injector) { // Set up the mock http service responses $httpBackend = $injector.get('$httpBackend'); // backend definition common for all tests authRequestHandler = $httpBackend.when('GET', '/auth.py') .respond({userId: 'userX'}, {'A-Token': 'xxx'}); // Get hold of a scope (i.e. the root scope) $rootScope = $injector.get('$rootScope'); // The $controller service is used to create instances of controllers var $controller = $injector.get('$controller'); createController = function() { return $controller('MyController', {'$scope' : $rootScope }); }; })); afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); it('should fetch authentication token', function() { $httpBackend.expectGET('/auth.py'); var controller = createController(); $httpBackend.flush(); }); it('should fail authentication', function() { // Notice how you can change the response even after it was set authRequestHandler.respond(401, ''); $httpBackend.expectGET('/auth.py'); var controller = createController(); $httpBackend.flush(); expect($rootScope.status).toBe('Failed...'); }); it('should send msg to server', function() { var controller = createController(); $httpBackend.flush(); // now you don’t care about the authentication, but // the controller will still send the request and // $httpBackend will respond without you having to // specify the expectation and response for this request $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, ''); $rootScope.saveMessage('message content'); expect($rootScope.status).toBe('Saving...'); $httpBackend.flush(); expect($rootScope.status).toBe(''); }); it('should send auth header', function() { var controller = createController(); $httpBackend.flush(); $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) { // check if the header was sent, if it wasn't the expectation won't // match the request and the test will fail return headers['Authorization'] === 'xxx'; }).respond(201, ''); $rootScope.saveMessage('whatever'); $httpBackend.flush(); }); }); ``` * * ## Dynamic responses * * You define a response to a request by chaining a call to `respond()` onto a definition or expectation. * If you provide a **callback** as the first parameter to `respond(callback)` then you can dynamically generate * a response based on the properties of the request. * * The `callback` function should be of the form `function(method, url, data, headers, params)`. * * ### Query parameters * * By default, query parameters on request URLs are parsed into the `params` object. So a request URL * of `/list?q=searchstr&orderby=-name` would set `params` to be `{q: 'searchstr', orderby: '-name'}`. * * ### Regex parameter matching * * If an expectation or definition uses a **regex** to match the URL, you can provide an array of **keys** via a * `params` argument. The index of each **key** in the array will match the index of a **group** in the * **regex**. * * The `params` object in the **callback** will now have properties with these keys, which hold the value of the * corresponding **group** in the **regex**. * * This also applies to the `when` and `expect` shortcut methods. * * * ```js * $httpBackend.expect('GET', /\/user\/(.+)/, undefined, undefined, ['id']) * .respond(function(method, url, data, headers, params) { * // for requested url of '/user/1234' params is {id: '1234'} * }); * * $httpBackend.whenPATCH(/\/user\/(.+)\/article\/(.+)/, undefined, undefined, ['user', 'article']) * .respond(function(method, url, data, headers, params) { * // for url of '/user/1234/article/567' params is {user: '1234', article: '567'} * }); * ``` * * ## Matching route requests * * For extra convenience, `whenRoute` and `expectRoute` shortcuts are available. These methods offer colon * delimited matching of the url path, ignoring the query string. This allows declarations * similar to how application routes are configured with `$routeProvider`. Because these methods convert * the definition url to regex, declaration order is important. Combined with query parameter parsing, * the following is possible: * ```js $httpBackend.whenRoute('GET', '/users/:id') .respond(function(method, url, data, headers, params) { return [200, MockUserList[Number(params.id)]]; }); $httpBackend.whenRoute('GET', '/users') .respond(function(method, url, data, headers, params) { var userList = angular.copy(MockUserList), defaultSort = 'lastName', count, pages, isPrevious, isNext; // paged api response '/v1/users?page=2' params.page = Number(params.page) || 1; // query for last names '/v1/users?q=Archer' if (params.q) { userList = $filter('filter')({lastName: params.q}); } pages = Math.ceil(userList.length / pagingLength); isPrevious = params.page > 1; isNext = params.page < pages; return [200, { count: userList.length, previous: isPrevious, next: isNext, // sort field -> '/v1/users?sortBy=firstName' results: $filter('orderBy')(userList, params.sortBy || defaultSort) .splice((params.page - 1) * pagingLength, pagingLength) }]; }); ``` */ angular.mock.$httpBackendDecorator = ['$rootScope', '$timeout', '$delegate', createHttpBackendMock]; /** * General factory function for $httpBackend mock. * Returns instance for unit testing (when no arguments specified): * - passing through is disabled * - auto flushing is disabled * * Returns instance for e2e testing (when `$delegate` and `$browser` specified): * - passing through (delegating request to real backend) is enabled * - auto flushing is enabled * * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified) * @param {Object=} $browser Auto-flushing enabled if specified * @return {Object} Instance of $httpBackend mock */ function createHttpBackendMock($rootScope, $timeout, $delegate, $browser) { var definitions = [], expectations = [], responses = [], responsesPush = angular.bind(responses, responses.push), copy = angular.copy, // We cache the original backend so that if both ngMock and ngMockE2E override the // service the ngMockE2E version can pass through to the real backend originalHttpBackend = $delegate.$$originalHttpBackend || $delegate; function createResponse(status, data, headers, statusText) { if (angular.isFunction(status)) return status; return function() { return angular.isNumber(status) ? [status, data, headers, statusText, 'complete'] : [200, status, data, headers, 'complete']; }; } // TODO(vojta): change params to: method, url, data, headers, callback function $httpBackend(method, url, data, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) { var xhr = new MockXhr(), expectation = expectations[0], wasExpected = false; xhr.$$events = eventHandlers; xhr.upload.$$events = uploadEventHandlers; function prettyPrint(data) { return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp) ? data : angular.toJson(data); } function wrapResponse(wrapped) { if (!$browser && timeout) { if (timeout.then) { timeout.then(function() { handlePrematureEnd(angular.isDefined(timeout.$$timeoutId) ? 'timeout' : 'abort'); }); } else { $timeout(function() { handlePrematureEnd('timeout'); }, timeout); } } handleResponse.description = method + ' ' + url; return handleResponse; function handleResponse() { var response = wrapped.response(method, url, data, headers, wrapped.params(url)); xhr.$$respHeaders = response[2]; callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(), copy(response[3] || ''), copy(response[4])); } function handlePrematureEnd(reason) { for (var i = 0, ii = responses.length; i < ii; i++) { if (responses[i] === handleResponse) { responses.splice(i, 1); callback(-1, undefined, '', undefined, reason); break; } } } } if (expectation && expectation.match(method, url)) { if (!expectation.matchData(data)) { throw new Error('Expected ' + expectation + ' with different data\n' + 'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data); } if (!expectation.matchHeaders(headers)) { throw new Error('Expected ' + expectation + ' with different headers\n' + 'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' + prettyPrint(headers)); } expectations.shift(); if (expectation.response) { responses.push(wrapResponse(expectation)); return; } wasExpected = true; } var i = -1, definition; while ((definition = definitions[++i])) { if (definition.match(method, url, data, headers || {})) { if (definition.response) { // if $browser specified, we do auto flush all requests ($browser ? $browser.defer : responsesPush)(wrapResponse(definition)); } else if (definition.passThrough) { originalHttpBackend(method, url, data, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers); } else throw new Error('No response defined !'); return; } } var error = wasExpected ? new Error('No response defined !') : new Error('Unexpected request: ' + method + ' ' + url + '\n' + (expectation ? 'Expected ' + expectation : 'No more request expected')); // In addition to be being converted to a rejection, this error also needs to be passed to // the $exceptionHandler and be rethrown (so that the test fails). error.$$passToExceptionHandler = true; throw error; } /** * @ngdoc method * @name $httpBackend#when * @description * Creates a new backend definition. * * @param {string} method HTTP method. * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current definition. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. * * - respond – * ```js * {function([status,] data[, headers, statusText]) * | function(function(method, url, data, headers, params)} * ``` * – The respond method takes a set of static data to be returned or a function that can * return an array containing response status (number), response data (Array|Object|string), * response headers (Object), and the text for the status (string). The respond method returns * the `requestHandler` object for possible overrides. */ $httpBackend.when = function(method, url, data, headers, keys) { assertArgDefined(arguments, 1, 'url'); var definition = new MockHttpExpectation(method, url, data, headers, keys), chain = { respond: function(status, data, headers, statusText) { definition.passThrough = undefined; definition.response = createResponse(status, data, headers, statusText); return chain; } }; if ($browser) { chain.passThrough = function() { definition.response = undefined; definition.passThrough = true; return chain; }; } definitions.push(definition); return chain; }; /** * @ngdoc method * @name $httpBackend#whenGET * @description * Creates a new backend definition for GET requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenHEAD * @description * Creates a new backend definition for HEAD requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenDELETE * @description * Creates a new backend definition for DELETE requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPOST * @description * Creates a new backend definition for POST requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPUT * @description * Creates a new backend definition for PUT requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenJSONP * @description * Creates a new backend definition for JSONP requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ createShortMethods('when'); /** * @ngdoc method * @name $httpBackend#whenRoute * @description * Creates a new backend definition that compares only with the requested route. * * @param {string} method HTTP method. * @param {string} url HTTP url string that supports colon param matching. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. See #when for more info. */ $httpBackend.whenRoute = function(method, url) { var pathObj = parseRoute(url); return $httpBackend.when(method, pathObj.regexp, undefined, undefined, pathObj.keys); }; function parseRoute(url) { var ret = { regexp: url }, keys = ret.keys = []; if (!url || !angular.isString(url)) return ret; url = url .replace(/([().])/g, '\\$1') .replace(/(\/)?:(\w+)([?*])?/g, function(_, slash, key, option) { var optional = option === '?' ? option : null; var star = option === '*' ? option : null; keys.push({ name: key, optional: !!optional }); slash = slash || ''; return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (star && '(.+?)' || '([^/]+)') + (optional || '') + ')' + (optional || ''); }) .replace(/([/$*])/g, '\\$1'); ret.regexp = new RegExp('^' + url, 'i'); return ret; } /** * @ngdoc method * @name $httpBackend#expect * @description * Creates a new request expectation. * * @param {string} method HTTP method. * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current expectation. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. * * - respond – * ``` * { function([status,] data[, headers, statusText]) * | function(function(method, url, data, headers, params)} * ``` * – The respond method takes a set of static data to be returned or a function that can * return an array containing response status (number), response data (Array|Object|string), * response headers (Object), and the text for the status (string). The respond method returns * the `requestHandler` object for possible overrides. */ $httpBackend.expect = function(method, url, data, headers, keys) { assertArgDefined(arguments, 1, 'url'); var expectation = new MockHttpExpectation(method, url, data, headers, keys), chain = { respond: function(status, data, headers, statusText) { expectation.response = createResponse(status, data, headers, statusText); return chain; } }; expectations.push(expectation); return chain; }; /** * @ngdoc method * @name $httpBackend#expectGET * @description * Creates a new request expectation for GET requests. For more info see `expect()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {Object=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. See #expect for more info. */ /** * @ngdoc method * @name $httpBackend#expectHEAD * @description * Creates a new request expectation for HEAD requests. For more info see `expect()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {Object=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectDELETE * @description * Creates a new request expectation for DELETE requests. For more info see `expect()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {Object=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectPOST * @description * Creates a new request expectation for POST requests. For more info see `expect()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {Object=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectPUT * @description * Creates a new request expectation for PUT requests. For more info see `expect()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {Object=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectPATCH * @description * Creates a new request expectation for PATCH requests. For more info see `expect()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that * receives data string and returns true if the data is as expected, or Object if request body * is in JSON format. * @param {Object=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#expectJSONP * @description * Creates a new request expectation for JSONP requests. For more info see `expect()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives an url * and returns true if the url matches the current definition. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described above. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. */ createShortMethods('expect'); /** * @ngdoc method * @name $httpBackend#expectRoute * @description * Creates a new request expectation that compares only with the requested route. * * @param {string} method HTTP method. * @param {string} url HTTP url string that supports colon param matching. * @returns {requestHandler} Returns an object with `respond` method that controls how a matched * request is handled. You can save this object for later use and invoke `respond` again in * order to change how a matched request is handled. See #expect for more info. */ $httpBackend.expectRoute = function(method, url) { var pathObj = parseRoute(url); return $httpBackend.expect(method, pathObj.regexp, undefined, undefined, pathObj.keys); }; /** * @ngdoc method * @name $httpBackend#flush * @description * Flushes pending requests using the trained responses. Requests are flushed in the order they * were made, but it is also possible to skip one or more requests (for example to have them * flushed later). This is useful for simulating scenarios where responses arrive from the server * in any order. * * If there are no pending requests to flush when the method is called, an exception is thrown (as * this is typically a sign of programming error). * * @param {number=} count - Number of responses to flush. If undefined/null, all pending requests * (starting after `skip`) will be flushed. * @param {number=} [skip=0] - Number of pending requests to skip. For example, a value of `5` * would skip the first 5 pending requests and start flushing from the 6th onwards. */ $httpBackend.flush = function(count, skip, digest) { if (digest !== false) $rootScope.$digest(); skip = skip || 0; if (skip >= responses.length) throw new Error('No pending request to flush !'); if (angular.isDefined(count) && count !== null) { while (count--) { var part = responses.splice(skip, 1); if (!part.length) throw new Error('No more pending request to flush !'); part[0](); } } else { while (responses.length > skip) { responses.splice(skip, 1)[0](); } } $httpBackend.verifyNoOutstandingExpectation(digest); }; /** * @ngdoc method * @name $httpBackend#verifyNoOutstandingExpectation * @description * Verifies that all of the requests defined via the `expect` api were made. If any of the * requests were not made, verifyNoOutstandingExpectation throws an exception. * * Typically, you would call this method following each test case that asserts requests using an * "afterEach" clause. * * ```js * afterEach($httpBackend.verifyNoOutstandingExpectation); * ``` */ $httpBackend.verifyNoOutstandingExpectation = function(digest) { if (digest !== false) $rootScope.$digest(); if (expectations.length) { throw new Error('Unsatisfied requests: ' + expectations.join(', ')); } }; /** * @ngdoc method * @name $httpBackend#verifyNoOutstandingRequest * @description * Verifies that there are no outstanding requests that need to be flushed. * * Typically, you would call this method following each test case that asserts requests using an * "afterEach" clause. * * ```js * afterEach($httpBackend.verifyNoOutstandingRequest); * ``` */ $httpBackend.verifyNoOutstandingRequest = function(digest) { if (digest !== false) $rootScope.$digest(); if (responses.length) { var unflushedDescriptions = responses.map(function(res) { return res.description; }); throw new Error('Unflushed requests: ' + responses.length + '\n ' + unflushedDescriptions.join('\n ')); } }; /** * @ngdoc method * @name $httpBackend#resetExpectations * @description * Resets all request expectations, but preserves all backend definitions. Typically, you would * call resetExpectations during a multiple-phase test when you want to reuse the same instance of * $httpBackend mock. */ $httpBackend.resetExpectations = function() { expectations.length = 0; responses.length = 0; }; $httpBackend.$$originalHttpBackend = originalHttpBackend; return $httpBackend; function createShortMethods(prefix) { angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD'], function(method) { $httpBackend[prefix + method] = function(url, headers, keys) { assertArgDefined(arguments, 0, 'url'); // Change url to `null` if `undefined` to stop it throwing an exception further down if (angular.isUndefined(url)) url = null; return $httpBackend[prefix](method, url, undefined, headers, keys); }; }); angular.forEach(['PUT', 'POST', 'PATCH'], function(method) { $httpBackend[prefix + method] = function(url, data, headers, keys) { assertArgDefined(arguments, 0, 'url'); // Change url to `null` if `undefined` to stop it throwing an exception further down if (angular.isUndefined(url)) url = null; return $httpBackend[prefix](method, url, data, headers, keys); }; }); } } function assertArgDefined(args, index, name) { if (args.length > index && angular.isUndefined(args[index])) { throw new Error('Undefined argument `' + name + '`; the argument is provided but not defined'); } } function MockHttpExpectation(method, url, data, headers, keys) { function getUrlParams(u) { var params = u.slice(u.indexOf('?') + 1).split('&'); return params.sort(); } function compareUrl(u) { return (url.slice(0, url.indexOf('?')) === u.slice(0, u.indexOf('?')) && getUrlParams(url).join() === getUrlParams(u).join()); } this.data = data; this.headers = headers; this.match = function(m, u, d, h) { if (method !== m) return false; if (!this.matchUrl(u)) return false; if (angular.isDefined(d) && !this.matchData(d)) return false; if (angular.isDefined(h) && !this.matchHeaders(h)) return false; return true; }; this.matchUrl = function(u) { if (!url) return true; if (angular.isFunction(url.test)) return url.test(u); if (angular.isFunction(url)) return url(u); return (url === u || compareUrl(u)); }; this.matchHeaders = function(h) { if (angular.isUndefined(headers)) return true; if (angular.isFunction(headers)) return headers(h); return angular.equals(headers, h); }; this.matchData = function(d) { if (angular.isUndefined(data)) return true; if (data && angular.isFunction(data.test)) return data.test(d); if (data && angular.isFunction(data)) return data(d); if (data && !angular.isString(data)) { return angular.equals(angular.fromJson(angular.toJson(data)), angular.fromJson(d)); } // eslint-disable-next-line eqeqeq return data == d; }; this.toString = function() { return method + ' ' + url; }; this.params = function(u) { return angular.extend(parseQuery(), pathParams()); function pathParams() { var keyObj = {}; if (!url || !angular.isFunction(url.test) || !keys || keys.length === 0) return keyObj; var m = url.exec(u); if (!m) return keyObj; for (var i = 1, len = m.length; i < len; ++i) { var key = keys[i - 1]; var val = m[i]; if (key && val) { keyObj[key.name || key] = val; } } return keyObj; } function parseQuery() { var obj = {}, key_value, key, queryStr = u.indexOf('?') > -1 ? u.substring(u.indexOf('?') + 1) : ''; angular.forEach(queryStr.split('&'), function(keyValue) { if (keyValue) { key_value = keyValue.replace(/\+/g,'%20').split('='); key = tryDecodeURIComponent(key_value[0]); if (angular.isDefined(key)) { var val = angular.isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true; if (!hasOwnProperty.call(obj, key)) { obj[key] = val; } else if (angular.isArray(obj[key])) { obj[key].push(val); } else { obj[key] = [obj[key],val]; } } } }); return obj; } function tryDecodeURIComponent(value) { try { return decodeURIComponent(value); } catch (e) { // Ignore any invalid uri component } } }; } function createMockXhr() { return new MockXhr(); } function MockXhr() { // hack for testing $http, $httpBackend MockXhr.$$lastInstance = this; this.open = function(method, url, async) { this.$$method = method; this.$$url = url; this.$$async = async; this.$$reqHeaders = {}; this.$$respHeaders = {}; }; this.send = function(data) { this.$$data = data; }; this.setRequestHeader = function(key, value) { this.$$reqHeaders[key] = value; }; this.getResponseHeader = function(name) { // the lookup must be case insensitive, // that's why we try two quick lookups first and full scan last var header = this.$$respHeaders[name]; if (header) return header; name = angular.$$lowercase(name); header = this.$$respHeaders[name]; if (header) return header; header = undefined; angular.forEach(this.$$respHeaders, function(headerVal, headerName) { if (!header && angular.$$lowercase(headerName) === name) header = headerVal; }); return header; }; this.getAllResponseHeaders = function() { var lines = []; angular.forEach(this.$$respHeaders, function(value, key) { lines.push(key + ': ' + value); }); return lines.join('\n'); }; this.abort = function() { if (isFunction(this.onabort)) { this.onabort(); } }; // This section simulates the events on a real XHR object (and the upload object) // When we are testing $httpBackend (inside the AngularJS project) we make partial use of this // but store the events directly ourselves on `$$events`, instead of going through the `addEventListener` this.$$events = {}; this.addEventListener = function(name, listener) { if (angular.isUndefined(this.$$events[name])) this.$$events[name] = []; this.$$events[name].push(listener); }; this.upload = { $$events: {}, addEventListener: this.addEventListener }; } /** * @ngdoc service * @name $timeout * @description * * This service is just a simple decorator for {@link ng.$timeout $timeout} service * that adds a "flush" and "verifyNoPendingTasks" methods. */ angular.mock.$TimeoutDecorator = ['$delegate', '$browser', function($delegate, $browser) { /** * @ngdoc method * @name $timeout#flush * @description * * Flushes the queue of pending tasks. * * @param {number=} delay maximum timeout amount to flush up until */ $delegate.flush = function(delay) { $browser.defer.flush(delay); }; /** * @ngdoc method * @name $timeout#verifyNoPendingTasks * @description * * Verifies that there are no pending tasks that need to be flushed. */ $delegate.verifyNoPendingTasks = function() { if ($browser.deferredFns.length) { throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' + formatPendingTasksAsString($browser.deferredFns)); } }; function formatPendingTasksAsString(tasks) { var result = []; angular.forEach(tasks, function(task) { result.push('{id: ' + task.id + ', time: ' + task.time + '}'); }); return result.join(', '); } return $delegate; }]; angular.mock.$RAFDecorator = ['$delegate', function($delegate) { var rafFn = function(fn) { var index = rafFn.queue.length; rafFn.queue.push(fn); return function() { rafFn.queue.splice(index, 1); }; }; rafFn.queue = []; rafFn.supported = $delegate.supported; rafFn.flush = function() { if (rafFn.queue.length === 0) { throw new Error('No rAF callbacks present'); } var length = rafFn.queue.length; for (var i = 0; i < length; i++) { rafFn.queue[i](); } rafFn.queue = rafFn.queue.slice(i); }; return rafFn; }]; /** * */ var originalRootElement; angular.mock.$RootElementProvider = function() { this.$get = ['$injector', function($injector) { originalRootElement = angular.element('<div ng-app></div>').data('$injector', $injector); return originalRootElement; }]; }; /** * @ngdoc service * @name $controller * @description * A decorator for {@link ng.$controller} with additional `bindings` parameter, useful when testing * controllers of directives that use {@link $compile#-bindtocontroller- `bindToController`}. * * ## Example * * ```js * * // Directive definition ... * * myMod.directive('myDirective', { * controller: 'MyDirectiveController', * bindToController: { * name: '@' * } * }); * * * // Controller definition ... * * myMod.controller('MyDirectiveController', ['$log', function($log) { * this.log = function() { * $log.info(this.name); * }; * }]); * * * // In a test ... * * describe('myDirectiveController', function() { * describe('log()', function() { * it('should write the bound name to the log', inject(function($controller, $log) { * var ctrl = $controller('MyDirectiveController', { /* no locals &#42;/ }, { name: 'Clark Kent' }); * ctrl.log(); * * expect(ctrl.name).toEqual('Clark Kent'); * expect($log.info.logs).toEqual(['Clark Kent']); * })); * }); * }); * * ``` * * @param {Function|string} constructor If called with a function then it's considered to be the * controller constructor function. Otherwise it's considered to be a string which is used * to retrieve the controller constructor using the following steps: * * * check if a controller with given name is registered via `$controllerProvider` * * check if evaluating the string on the current scope returns a constructor * * The string can use the `controller as property` syntax, where the controller instance is published * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this * to work correctly. * * @param {Object} locals Injection locals for Controller. * @param {Object=} bindings Properties to add to the controller instance. This is used to simulate * the `bindToController` feature and simplify certain kinds of tests. * @return {Object} Instance of given controller. */ function createControllerDecorator() { angular.mock.$ControllerDecorator = ['$delegate', function($delegate) { return function(expression, locals, later, ident) { if (later && typeof later === 'object') { var instantiate = $delegate(expression, locals, true, ident); var instance = instantiate(); angular.extend(instance, later); return instance; } return $delegate(expression, locals, later, ident); }; }]; return angular.mock.$ControllerDecorator; } /** * @ngdoc service * @name $componentController * @description * A service that can be used to create instances of component controllers. Useful for unit-testing. * * Be aware that the controller will be instantiated and attached to the scope as specified in * the component definition object. If you do not provide a `$scope` object in the `locals` param * then the helper will create a new isolated scope as a child of `$rootScope`. * * If you are using `$element` or `$attrs` in the controller, make sure to provide them as `locals`. * The `$element` must be a jqLite-wrapped DOM element, and `$attrs` should be an object that * has all properties / functions that you are using in the controller. If this is getting too complex, * you should compile the component instead and access the component's controller via the * {@link angular.element#methods `controller`} function. * * See also the section on {@link guide/component#unit-testing-component-controllers unit-testing component controllers} * in the guide. * * @param {string} componentName the name of the component whose controller we want to instantiate * @param {Object} locals Injection locals for Controller. * @param {Object=} bindings Properties to add to the controller before invoking the constructor. This is used * to simulate the `bindToController` feature and simplify certain kinds of tests. * @param {string=} ident Override the property name to use when attaching the controller to the scope. * @return {Object} Instance of requested controller. */ angular.mock.$ComponentControllerProvider = ['$compileProvider', function ComponentControllerProvider($compileProvider) { this.$get = ['$controller','$injector', '$rootScope', function($controller, $injector, $rootScope) { return function $componentController(componentName, locals, bindings, ident) { // get all directives associated to the component name var directives = $injector.get(componentName + 'Directive'); // look for those directives that are components var candidateDirectives = directives.filter(function(directiveInfo) { // components have controller, controllerAs and restrict:'E' return directiveInfo.controller && directiveInfo.controllerAs && directiveInfo.restrict === 'E'; }); // check if valid directives found if (candidateDirectives.length === 0) { throw new Error('No component found'); } if (candidateDirectives.length > 1) { throw new Error('Too many components found'); } // get the info of the component var directiveInfo = candidateDirectives[0]; // create a scope if needed locals = locals || {}; locals.$scope = locals.$scope || $rootScope.$new(true); return $controller(directiveInfo.controller, locals, bindings, ident || directiveInfo.controllerAs); }; }]; }]; /** * @ngdoc module * @name ngMock * @packageName angular-mocks * @description * * The `ngMock` module provides support to inject and mock AngularJS services into unit tests. * In addition, ngMock also extends various core AngularJS services such that they can be * inspected and controlled in a synchronous manner within test code. * * @installation * * First, download the file: * * [Google CDN](https://developers.google.com/speed/libraries/devguide#angularjs) e.g. * `"//ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-mocks.js"` * * [NPM](https://www.npmjs.com/) e.g. `npm install angular-mocks@X.Y.Z` * * [Yarn](https://yarnpkg.com) e.g. `yarn add angular-mocks@X.Y.Z` * * [Bower](http://bower.io) e.g. `bower install angular-mocks#X.Y.Z` * * [code.angularjs.org](https://code.angularjs.org/) (discouraged for production use) e.g. * `"//code.angularjs.org/X.Y.Z/angular-mocks.js"` * * where X.Y.Z is the AngularJS version you are running. * * Then, configure your test runner to load `angular-mocks.js` after `angular.js`. * This example uses <a href="http://karma-runner.github.io/">Karma</a>: * * ``` * config.set({ * files: [ * 'build/angular.js', // and other module files you need * 'build/angular-mocks.js', * '<path/to/application/files>', * '<path/to/spec/files>' * ] * }); * ``` * * Including the `angular-mocks.js` file automatically adds the `ngMock` module, so your tests * are ready to go! */ angular.module('ngMock', ['ng']).provider({ $browser: angular.mock.$BrowserProvider, $exceptionHandler: angular.mock.$ExceptionHandlerProvider, $log: angular.mock.$LogProvider, $interval: angular.mock.$IntervalProvider, $rootElement: angular.mock.$RootElementProvider, $componentController: angular.mock.$ComponentControllerProvider }).config(['$provide', '$compileProvider', function($provide, $compileProvider) { $provide.decorator('$timeout', angular.mock.$TimeoutDecorator); $provide.decorator('$$rAF', angular.mock.$RAFDecorator); $provide.decorator('$rootScope', angular.mock.$RootScopeDecorator); $provide.decorator('$controller', createControllerDecorator($compileProvider)); $provide.decorator('$httpBackend', angular.mock.$httpBackendDecorator); }]).info({ angularVersion: '"NG_VERSION_FULL"' }); /** * @ngdoc module * @name ngMockE2E * @module ngMockE2E * @packageName angular-mocks * @description * * The `ngMockE2E` is an AngularJS module which contains mocks suitable for end-to-end testing. * Currently there is only one mock present in this module - * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock. */ angular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) { $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator); }]).info({ angularVersion: '"NG_VERSION_FULL"' }); /** * @ngdoc service * @name $httpBackend * @module ngMockE2E * @description * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of * applications that use the {@link ng.$http $http service}. * * <div class="alert alert-info"> * **Note**: For fake http backend implementation suitable for unit testing please see * {@link ngMock.$httpBackend unit-testing $httpBackend mock}. * </div> * * This implementation can be used to respond with static or dynamic responses via the `when` api * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch * templates from a webserver). * * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application * is being developed with the real backend api replaced with a mock, it is often desirable for * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch * templates or static files from the webserver). To configure the backend with this behavior * use the `passThrough` request handler of `when` instead of `respond`. * * Additionally, we don't want to manually have to flush mocked out requests like we do during unit * testing. For this reason the e2e $httpBackend flushes mocked out requests * automatically, closely simulating the behavior of the XMLHttpRequest object. * * To setup the application to run with this http backend, you have to create a module that depends * on the `ngMockE2E` and your application modules and defines the fake backend: * * ```js * var myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']); * myAppDev.run(function($httpBackend) { * var phones = [{name: 'phone1'}, {name: 'phone2'}]; * * // returns the current list of phones * $httpBackend.whenGET('/phones').respond(phones); * * // adds a new phone to the phones array * $httpBackend.whenPOST('/phones').respond(function(method, url, data) { * var phone = angular.fromJson(data); * phones.push(phone); * return [200, phone, {}]; * }); * $httpBackend.whenGET(/^\/templates\//).passThrough(); // Requests for templates are handled by the real server * //... * }); * ``` * * Afterwards, bootstrap your app with this new module. * * @example * <example name="httpbackend-e2e-testing" module="myAppE2E" deps="angular-mocks.js"> * <file name="app.js"> * var myApp = angular.module('myApp', []); * * myApp.controller('MainCtrl', function MainCtrl($http) { * var ctrl = this; * * ctrl.phones = []; * ctrl.newPhone = { * name: '' * }; * * ctrl.getPhones = function() { * $http.get('/phones').then(function(response) { * ctrl.phones = response.data; * }); * }; * * ctrl.addPhone = function(phone) { * $http.post('/phones', phone).then(function() { * ctrl.newPhone = {name: ''}; * return ctrl.getPhones(); * }); * }; * * ctrl.getPhones(); * }); * </file> * <file name="e2e.js"> * var myAppDev = angular.module('myAppE2E', ['myApp', 'ngMockE2E']); * * myAppDev.run(function($httpBackend) { * var phones = [{name: 'phone1'}, {name: 'phone2'}]; * * // returns the current list of phones * $httpBackend.whenGET('/phones').respond(phones); * * // adds a new phone to the phones array * $httpBackend.whenPOST('/phones').respond(function(method, url, data) { * var phone = angular.fromJson(data); * phones.push(phone); * return [200, phone, {}]; * }); * }); * </file> * <file name="index.html"> * <div ng-controller="MainCtrl as $ctrl"> * <form name="newPhoneForm" ng-submit="$ctrl.addPhone($ctrl.newPhone)"> * <input type="text" ng-model="$ctrl.newPhone.name"> * <input type="submit" value="Add Phone"> * </form> * <h1>Phones</h1> * <ul> * <li ng-repeat="phone in $ctrl.phones">{{phone.name}}</li> * </ul> * </div> * </file> * </example> * * */ /** * @ngdoc method * @name $httpBackend#when * @module ngMockE2E * @description * Creates a new backend definition. * * @param {string} method HTTP method. * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header * object and returns true if the headers match the current definition. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on * {@link ngMock.$httpBackend $httpBackend mock}. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. * * - respond – * ``` * { function([status,] data[, headers, statusText]) * | function(function(method, url, data, headers, params)} * ``` * – The respond method takes a set of static data to be returned or a function that can return * an array containing response status (number), response data (Array|Object|string), response * headers (Object), and the text for the status (string). * - passThrough – `{function()}` – Any request matching a backend definition with * `passThrough` handler will be passed through to the real backend (an XHR request will be made * to the server.) * - Both methods return the `requestHandler` object for possible overrides. */ /** * @ngdoc method * @name $httpBackend#whenGET * @module ngMockE2E * @description * Creates a new backend definition for GET requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on * {@link ngMock.$httpBackend $httpBackend mock}. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenHEAD * @module ngMockE2E * @description * Creates a new backend definition for HEAD requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on * {@link ngMock.$httpBackend $httpBackend mock}. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenDELETE * @module ngMockE2E * @description * Creates a new backend definition for DELETE requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(Object|function(Object))=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on * {@link ngMock.$httpBackend $httpBackend mock}. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPOST * @module ngMockE2E * @description * Creates a new backend definition for POST requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on * {@link ngMock.$httpBackend $httpBackend mock}. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPUT * @module ngMockE2E * @description * Creates a new backend definition for PUT requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on * {@link ngMock.$httpBackend $httpBackend mock}. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenPATCH * @module ngMockE2E * @description * Creates a new backend definition for PATCH requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives * data string and returns true if the data is as expected. * @param {(Object|function(Object))=} headers HTTP headers. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on * {@link ngMock.$httpBackend $httpBackend mock}. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenJSONP * @module ngMockE2E * @description * Creates a new backend definition for JSONP requests. For more info see `when()`. * * @param {string|RegExp|function(string)=} url HTTP url or function that receives a url * and returns true if the url matches the current definition. * @param {(Array)=} keys Array of keys to assign to regex matches in request url described on * {@link ngMock.$httpBackend $httpBackend mock}. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ /** * @ngdoc method * @name $httpBackend#whenRoute * @module ngMockE2E * @description * Creates a new backend definition that compares only with the requested route. * * @param {string} method HTTP method. * @param {string} url HTTP url string that supports colon param matching. * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that * control how a matched request is handled. You can save this object for later use and invoke * `respond` or `passThrough` again in order to change how a matched request is handled. */ angular.mock.e2e = {}; angular.mock.e2e.$httpBackendDecorator = ['$rootScope', '$timeout', '$delegate', '$browser', createHttpBackendMock]; /** * @ngdoc type * @name $rootScope.Scope * @module ngMock * @description * {@link ng.$rootScope.Scope Scope} type decorated with helper methods useful for testing. These * methods are automatically available on any {@link ng.$rootScope.Scope Scope} instance when * `ngMock` module is loaded. * * In addition to all the regular `Scope` methods, the following helper methods are available: */ angular.mock.$RootScopeDecorator = ['$delegate', function($delegate) { var $rootScopePrototype = Object.getPrototypeOf($delegate); $rootScopePrototype.$countChildScopes = countChildScopes; $rootScopePrototype.$countWatchers = countWatchers; return $delegate; // ------------------------------------------------------------------------------------------ // /** * @ngdoc method * @name $rootScope.Scope#$countChildScopes * @module ngMock * @this $rootScope.Scope * @description * Counts all the direct and indirect child scopes of the current scope. * * The current scope is excluded from the count. The count includes all isolate child scopes. * * @returns {number} Total number of child scopes. */ function countChildScopes() { var count = 0; // exclude the current scope var pendingChildHeads = [this.$$childHead]; var currentScope; while (pendingChildHeads.length) { currentScope = pendingChildHeads.shift(); while (currentScope) { count += 1; pendingChildHeads.push(currentScope.$$childHead); currentScope = currentScope.$$nextSibling; } } return count; } /** * @ngdoc method * @name $rootScope.Scope#$countWatchers * @this $rootScope.Scope * @module ngMock * @description * Counts all the watchers of direct and indirect child scopes of the current scope. * * The watchers of the current scope are included in the count and so are all the watchers of * isolate child scopes. * * @returns {number} Total number of watchers. */ function countWatchers() { var count = this.$$watchers ? this.$$watchers.length : 0; // include the current scope var pendingChildHeads = [this.$$childHead]; var currentScope; while (pendingChildHeads.length) { currentScope = pendingChildHeads.shift(); while (currentScope) { count += currentScope.$$watchers ? currentScope.$$watchers.length : 0; pendingChildHeads.push(currentScope.$$childHead); currentScope = currentScope.$$nextSibling; } } return count; } }]; (function(jasmineOrMocha) { if (!jasmineOrMocha) { return; } var currentSpec = null, injectorState = new InjectorState(), annotatedFunctions = [], wasInjectorCreated = function() { return !!currentSpec; }; angular.mock.$$annotate = angular.injector.$$annotate; angular.injector.$$annotate = function(fn) { if (typeof fn === 'function' && !fn.$inject) { annotatedFunctions.push(fn); } return angular.mock.$$annotate.apply(this, arguments); }; /** * @ngdoc function * @name angular.mock.module * @description * * *NOTE*: This function is also published on window for easy access.<br> * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha * * This function registers a module configuration code. It collects the configuration information * which will be used when the injector is created by {@link angular.mock.inject inject}. * * See {@link angular.mock.inject inject} for usage example * * @param {...(string|Function|Object)} fns any number of modules which are represented as string * aliases or as anonymous module initialization functions. The modules are used to * configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an * object literal is passed each key-value pair will be registered on the module via * {@link auto.$provide $provide}.value, the key being the string name (or token) to associate * with the value on the injector. */ var module = window.module = angular.mock.module = function() { var moduleFns = Array.prototype.slice.call(arguments, 0); return wasInjectorCreated() ? workFn() : workFn; ///////////////////// function workFn() { if (currentSpec.$injector) { throw new Error('Injector already created, can not register a module!'); } else { var fn, modules = currentSpec.$modules || (currentSpec.$modules = []); angular.forEach(moduleFns, function(module) { if (angular.isObject(module) && !angular.isArray(module)) { fn = ['$provide', function($provide) { angular.forEach(module, function(value, key) { $provide.value(key, value); }); }]; } else { fn = module; } if (currentSpec.$providerInjector) { currentSpec.$providerInjector.invoke(fn); } else { modules.push(fn); } }); } } }; module.$$beforeAllHook = (window.before || window.beforeAll); module.$$afterAllHook = (window.after || window.afterAll); // purely for testing ngMock itself module.$$currentSpec = function(to) { if (arguments.length === 0) return to; currentSpec = to; }; /** * @ngdoc function * @name angular.mock.module.sharedInjector * @description * * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha * * This function ensures a single injector will be used for all tests in a given describe context. * This contrasts with the default behaviour where a new injector is created per test case. * * Use sharedInjector when you want to take advantage of Jasmine's `beforeAll()`, or mocha's * `before()` methods. Call `module.sharedInjector()` before you setup any other hooks that * will create (i.e call `module()`) or use (i.e call `inject()`) the injector. * * You cannot call `sharedInjector()` from within a context already using `sharedInjector()`. * * ## Example * * Typically beforeAll is used to make many assertions about a single operation. This can * cut down test run-time as the test setup doesn't need to be re-run, and enabling focussed * tests each with a single assertion. * * ```js * describe("Deep Thought", function() { * * module.sharedInjector(); * * beforeAll(module("UltimateQuestion")); * * beforeAll(inject(function(DeepThought) { * expect(DeepThought.answer).toBeUndefined(); * DeepThought.generateAnswer(); * })); * * it("has calculated the answer correctly", inject(function(DeepThought) { * // Because of sharedInjector, we have access to the instance of the DeepThought service * // that was provided to the beforeAll() hook. Therefore we can test the generated answer * expect(DeepThought.answer).toBe(42); * })); * * it("has calculated the answer within the expected time", inject(function(DeepThought) { * expect(DeepThought.runTimeMillennia).toBeLessThan(8000); * })); * * it("has double checked the answer", inject(function(DeepThought) { * expect(DeepThought.absolutelySureItIsTheRightAnswer).toBe(true); * })); * * }); * * ``` */ module.sharedInjector = function() { if (!(module.$$beforeAllHook && module.$$afterAllHook)) { throw Error('sharedInjector() cannot be used unless your test runner defines beforeAll/afterAll'); } var initialized = false; module.$$beforeAllHook(/** @this */ function() { if (injectorState.shared) { injectorState.sharedError = Error('sharedInjector() cannot be called inside a context that has already called sharedInjector()'); throw injectorState.sharedError; } initialized = true; currentSpec = this; injectorState.shared = true; }); module.$$afterAllHook(function() { if (initialized) { injectorState = new InjectorState(); module.$$cleanup(); } else { injectorState.sharedError = null; } }); }; module.$$beforeEach = function() { if (injectorState.shared && currentSpec && currentSpec !== this) { var state = currentSpec; currentSpec = this; angular.forEach(['$injector','$modules','$providerInjector', '$injectorStrict'], function(k) { currentSpec[k] = state[k]; state[k] = null; }); } else { currentSpec = this; originalRootElement = null; annotatedFunctions = []; } }; module.$$afterEach = function() { if (injectorState.cleanupAfterEach()) { module.$$cleanup(); } }; module.$$cleanup = function() { var injector = currentSpec.$injector; annotatedFunctions.forEach(function(fn) { delete fn.$inject; }); currentSpec.$injector = null; currentSpec.$modules = null; currentSpec.$providerInjector = null; currentSpec = null; if (injector) { // Ensure `$rootElement` is instantiated, before checking `originalRootElement` var $rootElement = injector.get('$rootElement'); var rootNode = $rootElement && $rootElement[0]; var cleanUpNodes = !originalRootElement ? [] : [originalRootElement[0]]; if (rootNode && (!originalRootElement || rootNode !== originalRootElement[0])) { cleanUpNodes.push(rootNode); } angular.element.cleanData(cleanUpNodes); // Ensure `$destroy()` is available, before calling it // (a mocked `$rootScope` might not implement it (or not even be an object at all)) var $rootScope = injector.get('$rootScope'); if ($rootScope && $rootScope.$destroy) $rootScope.$destroy(); } // clean up jquery's fragment cache angular.forEach(angular.element.fragments, function(val, key) { delete angular.element.fragments[key]; }); MockXhr.$$lastInstance = null; angular.forEach(angular.callbacks, function(val, key) { delete angular.callbacks[key]; }); angular.callbacks.$$counter = 0; }; (window.beforeEach || window.setup)(module.$$beforeEach); (window.afterEach || window.teardown)(module.$$afterEach); /** * @ngdoc function * @name angular.mock.inject * @description * * *NOTE*: This function is also published on window for easy access.<br> * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha * * The inject function wraps a function into an injectable function. The inject() creates new * instance of {@link auto.$injector $injector} per test, which is then used for * resolving references. * * * ## Resolving References (Underscore Wrapping) * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable * that is declared in the scope of the `describe()` block. Since we would, most likely, want * the variable to have the same name of the reference we have a problem, since the parameter * to the `inject()` function would hide the outer variable. * * To help with this, the injected parameters can, optionally, be enclosed with underscores. * These are ignored by the injector when the reference name is resolved. * * For example, the parameter `_myService_` would be resolved as the reference `myService`. * Since it is available in the function body as `_myService_`, we can then assign it to a variable * defined in an outer scope. * * ``` * // Defined out reference variable outside * var myService; * * // Wrap the parameter in underscores * beforeEach( inject( function(_myService_){ * myService = _myService_; * })); * * // Use myService in a series of tests. * it('makes use of myService', function() { * myService.doStuff(); * }); * * ``` * * See also {@link angular.mock.module angular.mock.module} * * ## Example * Example of what a typical jasmine tests looks like with the inject method. * ```js * * angular.module('myApplicationModule', []) * .value('mode', 'app') * .value('version', 'v1.0.1'); * * * describe('MyApp', function() { * * // You need to load modules that you want to test, * // it loads only the "ng" module by default. * beforeEach(module('myApplicationModule')); * * * // inject() is used to inject arguments of all given functions * it('should provide a version', inject(function(mode, version) { * expect(version).toEqual('v1.0.1'); * expect(mode).toEqual('app'); * })); * * * // The inject and module method can also be used inside of the it or beforeEach * it('should override a version and test the new version is injected', function() { * // module() takes functions or strings (module aliases) * module(function($provide) { * $provide.value('version', 'overridden'); // override version here * }); * * inject(function(version) { * expect(version).toEqual('overridden'); * }); * }); * }); * * ``` * * @param {...Function} fns any number of functions which will be injected using the injector. */ var ErrorAddingDeclarationLocationStack = function ErrorAddingDeclarationLocationStack(e, errorForStack) { this.message = e.message; this.name = e.name; if (e.line) this.line = e.line; if (e.sourceId) this.sourceId = e.sourceId; if (e.stack && errorForStack) this.stack = e.stack + '\n' + errorForStack.stack; if (e.stackArray) this.stackArray = e.stackArray; }; ErrorAddingDeclarationLocationStack.prototype = Error.prototype; window.inject = angular.mock.inject = function() { var blockFns = Array.prototype.slice.call(arguments, 0); var errorForStack = new Error('Declaration Location'); // IE10+ and PhanthomJS do not set stack trace information, until the error is thrown if (!errorForStack.stack) { try { throw errorForStack; } catch (e) { /* empty */ } } return wasInjectorCreated() ? WorkFn.call(currentSpec) : WorkFn; ///////////////////// function WorkFn() { var modules = currentSpec.$modules || []; var strictDi = !!currentSpec.$injectorStrict; modules.unshift(['$injector', function($injector) { currentSpec.$providerInjector = $injector; }]); modules.unshift('ngMock'); modules.unshift('ng'); var injector = currentSpec.$injector; if (!injector) { if (strictDi) { // If strictDi is enabled, annotate the providerInjector blocks angular.forEach(modules, function(moduleFn) { if (typeof moduleFn === 'function') { angular.injector.$$annotate(moduleFn); } }); } injector = currentSpec.$injector = angular.injector(modules, strictDi); currentSpec.$injectorStrict = strictDi; } for (var i = 0, ii = blockFns.length; i < ii; i++) { if (currentSpec.$injectorStrict) { // If the injector is strict / strictDi, and the spec wants to inject using automatic // annotation, then annotate the function here. injector.annotate(blockFns[i]); } try { injector.invoke(blockFns[i] || angular.noop, this); } catch (e) { if (e.stack && errorForStack) { throw new ErrorAddingDeclarationLocationStack(e, errorForStack); } throw e; } finally { errorForStack = null; } } } }; angular.mock.inject.strictDi = function(value) { value = arguments.length ? !!value : true; return wasInjectorCreated() ? workFn() : workFn; function workFn() { if (value !== currentSpec.$injectorStrict) { if (currentSpec.$injector) { throw new Error('Injector already created, can not modify strict annotations'); } else { currentSpec.$injectorStrict = value; } } } }; function InjectorState() { this.shared = false; this.sharedError = null; this.cleanupAfterEach = function() { return !this.shared || this.sharedError; }; } })(window.jasmine || window.mocha);
exports.encode = require('./encode'); exports.decode = require('./decode');
'use strict'; require('should'); var Dot = require('../index'); describe('Transfer:', function() { it('Should be able to transfer properties', function() { var src = { name: 'John', stuff: { phone: { brand: 'iphone', version: 6 } } }; var tgt = { name: 'Brandon' }; var srcExpected = {name: 'John', stuff: {}}; var tgtExpected = { name: 'Brandon', wanna: { haves: { phone: { brand: 'iphone', version: 6 } } } }; Dot.transfer('stuff.phone', 'wanna.haves.phone', src, tgt); src.should.eql(srcExpected); tgt.should.eql(tgtExpected); }); it('Should process modifiers', function() { var up = function(val) { val.brand = val.brand.toUpperCase(); return val; }; var src = { name: 'John', stuff: { phone: { brand: 'iphone', version: 6 } } }; var tgt = { name: 'Brandon' }; var srcExpected = {name: 'John', stuff: {}}; var tgtExpected = { name: 'Brandon', wanna: { haves: { phone: { brand: 'IPHONE', version: 6 } } } }; Dot.transfer('stuff.phone', 'wanna.haves.phone', src, tgt, up); src.should.eql(srcExpected); tgt.should.eql(tgtExpected); }); });
define({ "enableUndoRedo": "Activare Anulare/Repetare", "toolbarVisible": "Bară de instrumente vizibilă", "toolbarOptions": "Opţiuni pentru bara de instrumente", "mergeVisible": "Unificare", "cutVisible": "Decupare", "reshapeVisible": "Remodelare", "back": "Înapoi", "label": "Strat tematic", "edit": "Editabil", "update": "Dezactivare actualizare geometrie", "fields": "Câmpuri", "actions": "Acţiuni", "editpageName": "Nume", "editpageAlias": "Pseudonim", "editpageVisible": "Vizibil", "editpageEditable": "Editabil", "noLayers": "Nu sunt disponibile straturi tematice de obiecte spaţiale editabile", "configureFields": "Configurare câmpuri strat tematic", "useFilterEdit": "Utilizaţi filtrul de şabloane de obiecte spaţiale", "display": "Afişare", "autoApplyEditWhenGeometryIsMoved": "Aplicaţi modificarea automat la mutarea geometriei", "snappingTolerance": "Setaţi toleranţa de deplasare în pixeli", "popupTolerance": "Setaţi toleranţa de ferestrei pop-up de editare a atributelor în pixeli", "stickyMoveTolerance": "Setaţi toleranţa de revenire după deplasare în pixeli", "usingSaveButton": "Nu aplicați editări atributelor până când nu apăsați pe butonul Salvare", "generalSettings": "Setări generale", "editableLayersSetting": "Setări straturi tematice editabile", "honorTheWebMapSetting": "Respectați setările din harta web", "honorTheWebMapSettingTip1": "Aceste setări includ:", "honorTheWebMapSettingTip2": "Straturile tematice editabile", "honorTheWebMapSettingTip3": "Câmpurile pe care doriți să le afișați și să le editați", "honorTheWebMapSettingTip4": "Pseudonimul, ordinea și formatul unui câmp", "customSettings": "Setări personalizate" });
'use strict'; var endsWith = require('../../utils/string').endsWith; var clone = require('../../utils/object').clone; var constants = require('../../utils/bignumber/constants'); function factory (type, config, load, typed, math) { var add = load(require('../../function/arithmetic/addScalar')); var subtract = load(require('../../function/arithmetic/subtract')); var multiply = load(require('../../function/arithmetic/multiplyScalar')); var divide = load(require('../../function/arithmetic/divideScalar')); var pow = load(require('../../function/arithmetic/pow')); var abs = load(require('../../function/arithmetic/abs')); var equal = load(require('../../function/relational/equal')); var isNumeric = load(require('../../function/utils/isNumeric')); var format = load(require('../../function/string/format')); var getTypeOf = load(require('../../function/utils/typeof')); var toNumber = load(require('../../type/number')); var Complex = load(require('../../type/complex/Complex')); /** * A unit can be constructed in the following ways: * var a = new Unit(value, name); * var b = new Unit(null, name); * var c = Unit.parse(str); * * Example usage: * var a = new Unit(5, 'cm'); // 50 mm * var b = Unit.parse('23 kg'); // 23 kg * var c = math.in(a, new Unit(null, 'm'); // 0.05 m * var d = new Unit(9.81, "m/s^2"); // 9.81 m/s^2 * * @class Unit * @constructor Unit * @param {number | BigNumber | Fraction | Complex | boolean} [value] A value like 5.2 * @param {string} [name] A unit name like "cm" or "inch", or a derived unit of the form: "u1[^ex1] [u2[^ex2] ...] [/ u3[^ex3] [u4[^ex4]]]", such as "kg m^2/s^2", where each unit appearing after the forward slash is taken to be in the denominator. "kg m^2 s^-2" is a synonym and is also acceptable. Any of the units can include a prefix. */ function Unit(value, name) { if (!(this instanceof Unit)) { throw new Error('Constructor must be called with the new operator'); } if (!(value === undefined || isNumeric(value) || value.isComplex)) { throw new TypeError('First parameter in Unit constructor must be number, BigNumber, Fraction, Complex, or undefined'); } if (name != undefined && (typeof name !== 'string' || name == '')) { throw new TypeError('Second parameter in Unit constructor must be a string'); } if (name != undefined) { var u = Unit.parse(name); this.units = u.units; this.dimensions = u.dimensions; } else { this.units = [ { unit: UNIT_NONE, prefix: PREFIXES.NONE, // link to a list with supported prefixes power: 0 } ]; this.dimensions = [0, 0, 0, 0, 0, 0, 0, 0, 0]; } this.value = (value != undefined) ? this._normalize(value) : null; this.fixPrefix = false; // if true, function format will not search for the // best prefix but leave it as initially provided. // fixPrefix is set true by the method Unit.to // The justification behind this is that if the constructor is explicitly called, // the caller wishes the units to be returned exactly as he supplied. this.isUnitListSimplified = true; } /** * Attach type information */ Unit.prototype.type = 'Unit'; Unit.prototype.isUnit = true; // private variables and functions for the Unit parser var text, index, c; function skipWhitespace() { while (c == ' ' || c == '\t') { next(); } } function isDigitDot(c) { return ((c >= '0' && c <= '9') || c == '.'); } function isDigit(c) { return ((c >= '0' && c <= '9')); } function next() { index++; c = text.charAt(index); } function revert(oldIndex) { index = oldIndex; c = text.charAt(index); } function parseNumber() { var number = ''; var oldIndex; oldIndex = index; if (c == '+') { next(); } else if (c == '-') { number += c; next(); } if (!isDigitDot(c)) { // a + or - must be followed by a digit revert(oldIndex); return null; } // get number, can have a single dot if (c == '.') { number += c; next(); if (!isDigit(c)) { // this is no legal number, it is just a dot revert(oldIndex); return null; } } else { while (isDigit(c)) { number += c; next(); } if (c == '.') { number += c; next(); } } while (isDigit(c)) { number += c; next(); } // check for exponential notation like "2.3e-4" or "1.23e50" if (c == 'E' || c == 'e') { // The grammar branches here. This could either be part of an exponent or the start of a unit that begins with the letter e, such as "4exabytes" var tentativeNumber = ''; var tentativeIndex = index; tentativeNumber += c; next(); if (c == '+' || c == '-') { tentativeNumber += c; next(); } // Scientific notation MUST be followed by an exponent (otherwise we assume it is not scientific notation) if (!isDigit(c)) { // The e or E must belong to something else, so return the number without the e or E. revert(tentativeIndex); return number; } // We can now safely say that this is scientific notation. number = number + tentativeNumber; while (isDigit(c)) { number += c; next(); } } return number; } function parseUnit() { var unitName = ''; // Alphanumeric characters only; matches [a-zA-Z0-9] var code = text.charCodeAt(index); while ( (code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122)) { unitName += c; next(); code = text.charCodeAt(index); } // Must begin with [a-zA-Z] code = unitName.charCodeAt(0); if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) { return unitName || null; } else { return null; } } function parseCharacter(toFind) { if (c === toFind) { next(); return toFind; } else { return null; } } /** * Parse a string into a unit. The value of the unit is parsed as number, * BigNumber, or Fraction depending on the math.js config setting `number`. * * Throws an exception if the provided string does not contain a valid unit or * cannot be parsed. * @memberof Unit * @param {string} str A string like "5.2 inch", "4e2 cm/s^2" * @return {Unit} unit */ Unit.parse = function (str) { text = str; index = -1; c = ''; if (typeof text !== 'string') { throw new TypeError('Invalid argument in Unit.parse, string expected'); } var unit = new Unit(); unit.units = []; // A unit should follow this pattern: // [number]unit[^number] [unit[^number]]...[/unit[^number] [unit[^number]]] // Rules: // number is any floating point number. // unit is any alphanumeric string beginning with an alpha. Units with names like e3 should be avoided because they look like the exponent of a floating point number! // The string may optionally begin with a number. // Each unit may optionally be followed by ^number. // Whitespace or a forward slash is recommended between consecutive units, although the following technically is parseable: // 2m^2kg/s^2 // it is not good form. If a unit starts with e, then it could be confused as a floating point number: // 4erg next(); skipWhitespace(); // Optional number at the start of the string var valueStr = parseNumber(); var value = null; if(valueStr) { if (config.number === 'BigNumber') { value = new type.BigNumber(valueStr); } else if (config.number === 'Fraction') { value = new type.Fraction(valueStr); } else { // number value = parseFloat(valueStr); } } skipWhitespace(); // Whitespace is not required here // Next, we read any number of unit[^number] var powerMultiplierCurrent = 1; var expectingUnit = false; // Stack to keep track of powerMultipliers applied to each parentheses group var powerMultiplierStack = []; // Running product of all elements in powerMultiplierStack var powerMultiplierStackProduct = 1; while (true) { skipWhitespace(); // Check for and consume opening parentheses, pushing powerMultiplierCurrent to the stack // A '(' will always appear directly before a unit. while (c === '(') { powerMultiplierStack.push(powerMultiplierCurrent); powerMultiplierStackProduct *= powerMultiplierCurrent; powerMultiplierCurrent = 1; next(); skipWhitespace(); } // Is there something here? if(c) { var oldC = c; var uStr = parseUnit(); if(uStr == null) { throw new SyntaxError('Unexpected "' + oldC + '" in "' + text + '" at index ' + index.toString()); } } else { // End of input. break; } // Verify the unit exists and get the prefix (if any) var res = _findUnit(uStr); if(res == null) { // Unit not found. throw new SyntaxError('Unit "' + uStr + '" not found.'); } var power = powerMultiplierCurrent * powerMultiplierStackProduct; // Is there a "^ number"? skipWhitespace(); if (parseCharacter('^')) { skipWhitespace(); var p = parseNumber(); if(p == null) { // No valid number found for the power! throw new SyntaxError('In "' + str + '", "^" must be followed by a floating-point number'); } power *= p; } // Add the unit to the list unit.units.push( { unit: res.unit, prefix: res.prefix, power: power }); for(var i=0; i<BASE_DIMENSIONS.length; i++) { unit.dimensions[i] += res.unit.dimensions[i] * power; } // Check for and consume closing parentheses, popping from the stack. // A ')' will always follow a unit. skipWhitespace(); while (c === ')') { if(powerMultiplierStack.length === 0) { throw new SyntaxError('Unmatched ")" in "' + text + '" at index ' + index.toString()); } powerMultiplierStackProduct /= powerMultiplierStack.pop(); next(); skipWhitespace(); } // "*" and "/" should mean we are expecting something to come next. // Is there a forward slash? If so, negate powerMultiplierCurrent. The next unit or paren group is in the denominator. expectingUnit = false; if (parseCharacter('*')) { // explicit multiplication powerMultiplierCurrent = 1; expectingUnit = true; } else if (parseCharacter('/')) { // division powerMultiplierCurrent = -1; expectingUnit = true; } else { // implicit multiplication powerMultiplierCurrent = 1; } // Replace the unit into the auto unit system var baseDim = res.unit.base.key; UNIT_SYSTEMS.auto[baseDim] = { unit: res.unit, prefix: res.prefix }; } // Has the string been entirely consumed? skipWhitespace(); if(c) { throw new SyntaxError('Could not parse: "' + str + '"'); } // Is there a trailing slash? if(expectingUnit) { throw new SyntaxError('Trailing characters: "' + str + '"'); } // Is the parentheses stack empty? if(powerMultiplierStack.length !== 0) { throw new SyntaxError('Unmatched "(" in "' + text + '"'); } // Are there any units at all? if(unit.units.length == 0) { throw new SyntaxError('"' + str + '" contains no units'); } unit.value = (value != undefined) ? unit._normalize(value) : null; return unit; }; /** * create a copy of this unit * @memberof Unit * @return {Unit} Returns a cloned version of the unit */ Unit.prototype.clone = function () { var unit = new Unit(); unit.fixPrefix = this.fixPrefix; unit.isUnitListSimplified = this.isUnitListSimplified; unit.value = clone(this.value); unit.dimensions = this.dimensions.slice(0); unit.units = []; for(var i = 0; i < this.units.length; i++) { unit.units[i] = { }; for (var p in this.units[i]) { if (this.units[i].hasOwnProperty(p)) { unit.units[i][p] = this.units[i][p]; } } } return unit; }; /** * Return whether the unit is derived (such as m/s, or cm^2, but not N) * @memberof Unit * @return {boolean} True if the unit is derived */ Unit.prototype._isDerived = function() { if(this.units.length === 0) { return false; } return this.units.length > 1 || Math.abs(this.units[0].power - 1.0) > 1e-15; }; /** * Normalize a value, based on its currently set unit(s) * @memberof Unit * @param {number | BigNumber | Fraction | boolean} value * @return {number | BigNumber | Fraction | boolean} normalized value * @private */ Unit.prototype._normalize = function (value) { var unitValue, unitOffset, unitPower, unitPrefixValue; var convert; if (value == null || this.units.length === 0) { return value; } else if (this._isDerived()) { // This is a derived unit, so do not apply offsets. // For example, with J kg^-1 degC^-1 you would NOT want to apply the offset. var res = value; convert = Unit._getNumberConverter(getTypeOf(value)); // convert to Fraction or BigNumber if needed for(var i=0; i < this.units.length; i++) { unitValue = convert(this.units[i].unit.value); unitPrefixValue = convert(this.units[i].prefix.value); unitPower = convert(this.units[i].power); res = multiply(res, pow(multiply(unitValue, unitPrefixValue), unitPower)); } return res; } else { // This is a single unit of power 1, like kg or degC convert = Unit._getNumberConverter(getTypeOf(value)); // convert to Fraction or BigNumber if needed unitValue = convert(this.units[0].unit.value); unitOffset = convert(this.units[0].unit.offset); unitPrefixValue = convert(this.units[0].prefix.value); return multiply(add(value, unitOffset), multiply(unitValue, unitPrefixValue)); } }; /** * Denormalize a value, based on its currently set unit(s) * @memberof Unit * @param {number} value * @param {number} [prefixValue] Optional prefix value to be used (ignored if this is a derived unit) * @return {number} denormalized value * @private */ Unit.prototype._denormalize = function (value, prefixValue) { var unitValue, unitOffset, unitPower, unitPrefixValue; var convert; if (value == null || this.units.length === 0) { return value; } else if (this._isDerived()) { // This is a derived unit, so do not apply offsets. // For example, with J kg^-1 degC^-1 you would NOT want to apply the offset. // Also, prefixValue is ignored--but we will still use the prefix value stored in each unit, since kg is usually preferable to g unless the user decides otherwise. var res = value; convert = Unit._getNumberConverter(getTypeOf(value)); // convert to Fraction or BigNumber if needed for (var i = 0; i < this.units.length; i++) { unitValue = convert(this.units[i].unit.value); unitPrefixValue = convert(this.units[i].prefix.value); unitPower = convert(this.units[i].power); res = divide(res, pow(multiply(unitValue, unitPrefixValue), unitPower)); } return res; } else { // This is a single unit of power 1, like kg or degC convert = Unit._getNumberConverter(getTypeOf(value)); // convert to Fraction or BigNumber if needed unitValue = convert(this.units[0].unit.value); unitPrefixValue = convert(this.units[0].prefix.value); unitOffset = convert(this.units[0].unit.offset); if (prefixValue == undefined) { return subtract(divide(divide(value, unitValue), unitPrefixValue), unitOffset); } else { return subtract(divide(divide(value, unitValue), prefixValue), unitOffset); } } }; /** * Find a unit from a string * @memberof Unit * @param {string} str A string like 'cm' or 'inch' * @returns {Object | null} result When found, an object with fields unit and * prefix is returned. Else, null is returned. * @private */ function _findUnit(str) { for (var name in UNITS) { if (UNITS.hasOwnProperty(name)) { if (endsWith(str, name)) { var unit = UNITS[name]; var prefixLen = (str.length - name.length); var prefixName = str.substring(0, prefixLen); var prefix = unit.prefixes[prefixName]; if (prefix !== undefined) { // store unit, prefix, and value return { unit: unit, prefix: prefix }; } } } } return null; } /** * Test if the given expression is a unit. * The unit can have a prefix but cannot have a value. * @memberof Unit * @param {string} name A string to be tested whether it is a value less unit. * The unit can have prefix, like "cm" * @return {boolean} true if the given string is a unit */ Unit.isValuelessUnit = function (name) { return (_findUnit(name) != null); }; /** * check if this unit has given base unit * If this unit is a derived unit, this will ALWAYS return false, since by definition base units are not derived. * @memberof Unit * @param {BASE_UNITS | string | undefined} base */ Unit.prototype.hasBase = function (base) { if(typeof(base) === "string") { base = BASE_UNITS[base]; } if(!base) return false; // All dimensions must be the same for(var i=0; i<BASE_DIMENSIONS.length; i++) { if (Math.abs(this.dimensions[i] - base.dimensions[i]) > 1e-12) { return false; } } return true; }; /** * Check if this unit has a base or bases equal to another base or bases * For derived units, the exponent on each base also must match * @memberof Unit * @param {Unit} other * @return {boolean} true if equal base */ Unit.prototype.equalBase = function (other) { // All dimensions must be the same for(var i=0; i<BASE_DIMENSIONS.length; i++) { if (Math.abs(this.dimensions[i] - other.dimensions[i]) > 1e-12) { return false; } } return true; }; /** * Check if this unit equals another unit * @memberof Unit * @param {Unit} other * @return {boolean} true if both units are equal */ Unit.prototype.equals = function (other) { return (this.equalBase(other) && equal(this.value, other.value)); }; /** * Multiply this unit with another one * @memberof Unit * @param {Unit} other * @return {Unit} product of this unit and the other unit */ Unit.prototype.multiply = function (other) { var res = this.clone(); for(var i = 0; i<BASE_DIMENSIONS.length; i++) { res.dimensions[i] = this.dimensions[i] + other.dimensions[i]; } // Append other's units list onto res (simplify later in Unit.prototype.format) for(var i=0; i<other.units.length; i++) { var inverted = JSON.parse(JSON.stringify(other.units[i])); res.units.push(inverted); } // If at least one operand has a value, then the result should also have a value if(this.value != null || other.value != null) { var valThis = this.value == null ? this._normalize(1) : this.value; var valOther = other.value == null ? other._normalize(1) : other.value; res.value = multiply(valThis, valOther); } else { res.value = null; } // Trigger simplification of the unit list at some future time res.isUnitListSimplified = false; return getNumericIfUnitless(res); }; /** * Divide this unit by another one * @memberof Unit * @param {Unit} other * @return {Unit} result of dividing this unit by the other unit */ Unit.prototype.divide = function (other) { var res = this.clone(); for(var i=0; i<BASE_DIMENSIONS.length; i++) { res.dimensions[i] = this.dimensions[i] - other.dimensions[i]; } // Invert and append other's units list onto res (simplify later in Unit.prototype.format) for(var i=0; i<other.units.length; i++) { // Clone other's unit var inverted = JSON.parse(JSON.stringify(other.units[i])); inverted.power = -inverted.power; res.units.push(inverted); } // If at least one operand has a value, the result should have a value if (this.value != null || other.value != null) { var valThis = this.value == null ? this._normalize(1) : this.value; var valOther = other.value == null ? other._normalize(1) : other.value; res.value = divide(valThis, valOther); } else { res.value = null; } // Trigger simplification of the unit list at some future time res.isUnitListSimplified = false; return getNumericIfUnitless(res); }; /** * Calculate the power of a unit * @memberof Unit * @param {number | Fraction | BigNumber} p * @returns {Unit} The result: this^p */ Unit.prototype.pow = function (p) { var res = this.clone(); for(var i=0; i<BASE_DIMENSIONS.length; i++) { res.dimensions[i] = this.dimensions[i] * p; } // Adjust the power of each unit in the list for(var i=0; i<res.units.length; i++) { res.units[i].power *= p; } if(res.value != null) { res.value = pow(res.value, p); // only allow numeric output, we don't want to return a Complex number //if (!isNumeric(res.value)) { // res.value = NaN; //} // Update: Complex supported now } else { res.value = null; } // Trigger lazy evaluation of the unit list res.isUnitListSimplified = false; return getNumericIfUnitless(res); }; /** * Return the numeric value of this unit if it is dimensionless, has a value, and config.predictable == false; or the original unit otherwise * @param {Unit} unit * @returns {number | Fraction | BigNumber | Unit} The numeric value of the unit if conditions are met, or the original unit otherwise */ var getNumericIfUnitless = function(unit) { if(unit.equalBase(BASE_UNITS.NONE) && unit.value !== null && !config.predictable) { return unit.value; } else { return unit; } } /** * Calculate the absolute value of a unit * @memberof Unit * @param {number | Fraction | BigNumber} x * @returns {Unit} The result: |x|, absolute value of x */ Unit.prototype.abs = function () { // This gives correct, but unexpected, results for units with an offset. // For example, abs(-283.15 degC) = -263.15 degC !!! var ret = this.clone(); ret.value = abs(ret.value); for(var i in ret.units) { if(ret.units[i].unit.name === 'VA' || ret.units[i].unit.name === 'VAR') { ret.units[i].unit = UNITS["W"]; } } return ret; }; /** * Convert the unit to a specific unit name. * @memberof Unit * @param {string | Unit} valuelessUnit A unit without value. Can have prefix, like "cm" * @returns {Unit} Returns a clone of the unit with a fixed prefix and unit. */ Unit.prototype.to = function (valuelessUnit) { var other; var value = this.value == null ? this._normalize(1) : this.value; if (typeof valuelessUnit === 'string') { //other = new Unit(null, valuelessUnit); other = Unit.parse(valuelessUnit); if (!this.equalBase(other)) { throw new Error('Units do not match'); } if (other.value !== null) { throw new Error('Cannot convert to a unit with a value'); } other.value = clone(value); other.fixPrefix = true; other.isUnitListSimplified = true; return other; } else if (valuelessUnit && valuelessUnit.isUnit) { if (!this.equalBase(valuelessUnit)) { throw new Error('Units do not match'); } if (valuelessUnit.value !== null) { throw new Error('Cannot convert to a unit with a value'); } other = valuelessUnit.clone(); other.value = clone(value); other.fixPrefix = true; other.isUnitListSimplified = true; return other; } else { throw new Error('String or Unit expected as parameter'); } }; /** * Return the value of the unit when represented with given valueless unit * @memberof Unit * @param {string | Unit} valuelessUnit For example 'cm' or 'inch' * @return {number} Returns the unit value as number. */ // TODO: deprecate Unit.toNumber? It's always better to use toNumeric Unit.prototype.toNumber = function (valuelessUnit) { return toNumber(this.toNumeric(valuelessUnit)); }; /** * Return the value of the unit in the original numeric type * @memberof Unit * @param {string | Unit} valuelessUnit For example 'cm' or 'inch' * @return {number | BigNumber | Fraction} Returns the unit value */ Unit.prototype.toNumeric = function (valuelessUnit) { var other = this.to(valuelessUnit); if(other._isDerived()) { return other._denormalize(other.value); } else { return other._denormalize(other.value, other.units[0].prefix.value); } }; /** * Get a string representation of the unit. * @memberof Unit * @return {string} */ Unit.prototype.toString = function () { return this.format(); }; /** * Get a JSON representation of the unit * @memberof Unit * @returns {Object} Returns a JSON object structured as: * `{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix": false}` */ Unit.prototype.toJSON = function () { return { mathjs: 'Unit', value: this._denormalize(this.value), unit: this.formatUnits(), fixPrefix: this.fixPrefix }; }; /** * Instantiate a Unit from a JSON object * @memberof Unit * @param {Object} json A JSON object structured as: * `{"mathjs": "Unit", "value": 2, "unit": "cm", "fixPrefix": false}` * @return {Unit} */ Unit.fromJSON = function (json) { var unit = new Unit(json.value, json.unit); unit.fixPrefix = json.fixPrefix || false; return unit; }; /** * Returns the string representation of the unit. * @memberof Unit * @return {string} */ Unit.prototype.valueOf = Unit.prototype.toString; /** * Attempt to simplify the list of units for this unit according to the dimensions array and the current unit system. After the call, this Unit will contain a list of the "best" units for formatting. * Intended to be evaluated lazily. You must set isUnitListSimplified = false before the call! After the call, isUnitListSimplified will be set to true. */ Unit.prototype.simplifyUnitListLazy = function() { if (this.isUnitListSimplified || this.value == null) { return; } var proposedUnitList = []; // Search for a matching base var matchingBase; for(var key in currentUnitSystem) { if(this.hasBase(BASE_UNITS[key])) { matchingBase = key; break; } } if(matchingBase === 'NONE') { this.units = []; } else { var matchingUnit; if(matchingBase) { // Does the unit system have a matching unit? if(currentUnitSystem.hasOwnProperty(matchingBase)) { matchingUnit = currentUnitSystem[matchingBase] } } var value; var str; if(matchingUnit) { this.units = [{ unit: matchingUnit.unit, prefix: matchingUnit.prefix, power: 1.0 }]; } else { // Multiple units or units with powers are formatted like this: // 5 (kg m^2) / (s^3 mol) // Build an representation from the base units of the current unit system for(var i=0; i<BASE_DIMENSIONS.length; i++) { var baseDim = BASE_DIMENSIONS[i]; if(Math.abs(this.dimensions[i]) > 1e-12) { proposedUnitList.push({ unit: currentUnitSystem[baseDim].unit, prefix: currentUnitSystem[baseDim].prefix, power: this.dimensions[i] }); } } // Is the proposed unit list "simpler" than the existing one? if(proposedUnitList.length < this.units.length) { // Replace this unit list with the proposed list this.units = proposedUnitList; } } } this.isUnitListSimplified = true; }; /** * Get a string representation of the units of this Unit, without the value. * @memberof Unit * @return {string} */ Unit.prototype.formatUnits = function () { // Lazy evaluation of the unit list this.simplifyUnitListLazy(); var strNum = ""; var strDen = ""; var nNum = 0; var nDen = 0; for(var i=0; i<this.units.length; i++) { if(this.units[i].power > 0) { nNum++; strNum += " " + this.units[i].prefix.name + this.units[i].unit.name; if(Math.abs(this.units[i].power - 1.0) > 1e-15) { strNum += "^" + this.units[i].power; } } else if(this.units[i].power < 0) { nDen++; } } if(nDen > 0) { for(var i=0; i<this.units.length; i++) { if(this.units[i].power < 0) { if(nNum > 0) { strDen += " " + this.units[i].prefix.name + this.units[i].unit.name; if(Math.abs(this.units[i].power + 1.0) > 1e-15) { strDen += "^" + (-this.units[i].power); } } else { strDen += " " + this.units[i].prefix.name + this.units[i].unit.name; strDen += "^" + (this.units[i].power); } } } } // Remove leading " " strNum = strNum.substr(1); strDen = strDen.substr(1); // Add parans for better copy/paste back into the eval, for example, or for better pretty print formatting if(nNum > 1 && nDen > 0) { strNum = "(" + strNum + ")"; } if(nDen > 1 && nNum > 0) { strDen = "(" + strDen + ")"; } var str = strNum; if(nNum > 0 && nDen > 0) { str += " / "; } str += strDen; return str; }; /** * Get a string representation of the Unit, with optional formatting options. * @memberof Unit * @param {Object | number | Function} [options] Formatting options. See * lib/utils/number:format for a * description of the available * options. * @return {string} */ Unit.prototype.format = function (options) { // Simplfy the unit list, if necessary this.simplifyUnitListLazy(); // Apply some custom logic for handling VA and VAR. The goal is to express the value of the unit as a real value, if possible. Otherwise, use a real-valued unit instead of a complex-valued one. var isImaginary = false; var isReal = true; if(typeof(this.value) !== 'undefined' && this.value !== null && this.value.isComplex) { // TODO: Make this better, for example, use relative magnitude of re and im rather than absolute isImaginary = Math.abs(this.value.re) < 1e-14; isReal = Math.abs(this.value.im) < 1e-14; } for(var i in this.units) { if(this.units[i].unit) { if(this.units[i].unit.name === 'VA' && isImaginary) { this.units[i].unit = UNITS["VAR"]; } else if(this.units[i].unit.name === 'VAR' && !isImaginary) { this.units[i].unit = UNITS["VA"]; } } } // Now apply the best prefix // Units must have only one unit and not have the fixPrefix flag set if (this.units.length === 1 && !this.fixPrefix) { // Units must have integer powers, otherwise the prefix will change the // outputted value by not-an-integer-power-of-ten if (Math.abs(this.units[0].power - Math.round(this.units[0].power)) < 1e-14) { // Apply the best prefix this.units[0].prefix = this._bestPrefix(); } } var value = this._denormalize(this.value); var str = (this.value !== null) ? format(value, options || {}) : ''; var unitStr = this.formatUnits(); if(this.value && this.value.isComplex) { str = "(" + str + ")"; // Surround complex values with ( ) to enable better parsing } if(unitStr.length > 0 && str.length > 0) { str += " "; } str += unitStr; return str; }; /** * Calculate the best prefix using current value. * @memberof Unit * @returns {Object} prefix * @private */ Unit.prototype._bestPrefix = function () { if (this.units.length !== 1) { throw new Error("Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!"); } if (Math.abs(this.units[0].power - Math.round(this.units[0].power)) >= 1e-14) { throw new Error("Can only compute the best prefix for single units with integer powers, like kg, s^2, N^-1, and so forth!"); } // find the best prefix value (resulting in the value of which // the absolute value of the log10 is closest to zero, // though with a little offset of 1.2 for nicer values: you get a // sequence 1mm 100mm 500mm 0.6m 1m 10m 100m 500m 0.6km 1km ... // Note: the units value can be any numeric type, but to find the best // prefix it's enough to work with limited precision of a regular number // Update: using mathjs abs since we also allow complex numbers var absValue = abs(this.value); var absUnitValue = abs(this.units[0].unit.value); var bestPrefix = this.units[0].prefix; if (absValue === 0) { return bestPrefix; } var power = this.units[0].power; var bestDiff = Math.abs( Math.log(absValue / Math.pow(bestPrefix.value * absUnitValue, power)) / Math.LN10 - 1.2); var prefixes = this.units[0].unit.prefixes; for (var p in prefixes) { if (prefixes.hasOwnProperty(p)) { var prefix = prefixes[p]; if (prefix.scientific) { var diff = Math.abs( Math.log(absValue / Math.pow(prefix.value * absUnitValue, power)) / Math.LN10 - 1.2); if (diff < bestDiff || (diff === bestDiff && prefix.name.length < bestPrefix.name.length)) { // choose the prefix with the smallest diff, or if equal, choose the one // with the shortest name (can happen with SHORTLONG for example) bestPrefix = prefix; bestDiff = diff; } } } } return bestPrefix; }; var PREFIXES = { NONE: { '': {name: '', value: 1, scientific: true} }, SHORT: { '': {name: '', value: 1, scientific: true}, 'da': {name: 'da', value: 1e1, scientific: false}, 'h': {name: 'h', value: 1e2, scientific: false}, 'k': {name: 'k', value: 1e3, scientific: true}, 'M': {name: 'M', value: 1e6, scientific: true}, 'G': {name: 'G', value: 1e9, scientific: true}, 'T': {name: 'T', value: 1e12, scientific: true}, 'P': {name: 'P', value: 1e15, scientific: true}, 'E': {name: 'E', value: 1e18, scientific: true}, 'Z': {name: 'Z', value: 1e21, scientific: true}, 'Y': {name: 'Y', value: 1e24, scientific: true}, 'd': {name: 'd', value: 1e-1, scientific: false}, 'c': {name: 'c', value: 1e-2, scientific: false}, 'm': {name: 'm', value: 1e-3, scientific: true}, 'u': {name: 'u', value: 1e-6, scientific: true}, 'n': {name: 'n', value: 1e-9, scientific: true}, 'p': {name: 'p', value: 1e-12, scientific: true}, 'f': {name: 'f', value: 1e-15, scientific: true}, 'a': {name: 'a', value: 1e-18, scientific: true}, 'z': {name: 'z', value: 1e-21, scientific: true}, 'y': {name: 'y', value: 1e-24, scientific: true} }, LONG: { '': {name: '', value: 1, scientific: true}, 'deca': {name: 'deca', value: 1e1, scientific: false}, 'hecto': {name: 'hecto', value: 1e2, scientific: false}, 'kilo': {name: 'kilo', value: 1e3, scientific: true}, 'mega': {name: 'mega', value: 1e6, scientific: true}, 'giga': {name: 'giga', value: 1e9, scientific: true}, 'tera': {name: 'tera', value: 1e12, scientific: true}, 'peta': {name: 'peta', value: 1e15, scientific: true}, 'exa': {name: 'exa', value: 1e18, scientific: true}, 'zetta': {name: 'zetta', value: 1e21, scientific: true}, 'yotta': {name: 'yotta', value: 1e24, scientific: true}, 'deci': {name: 'deci', value: 1e-1, scientific: false}, 'centi': {name: 'centi', value: 1e-2, scientific: false}, 'milli': {name: 'milli', value: 1e-3, scientific: true}, 'micro': {name: 'micro', value: 1e-6, scientific: true}, 'nano': {name: 'nano', value: 1e-9, scientific: true}, 'pico': {name: 'pico', value: 1e-12, scientific: true}, 'femto': {name: 'femto', value: 1e-15, scientific: true}, 'atto': {name: 'atto', value: 1e-18, scientific: true}, 'zepto': {name: 'zepto', value: 1e-21, scientific: true}, 'yocto': {name: 'yocto', value: 1e-24, scientific: true} }, SQUARED: { '': {name: '', value: 1, scientific: true}, 'da': {name: 'da', value: 1e2, scientific: false}, 'h': {name: 'h', value: 1e4, scientific: false}, 'k': {name: 'k', value: 1e6, scientific: true}, 'M': {name: 'M', value: 1e12, scientific: true}, 'G': {name: 'G', value: 1e18, scientific: true}, 'T': {name: 'T', value: 1e24, scientific: true}, 'P': {name: 'P', value: 1e30, scientific: true}, 'E': {name: 'E', value: 1e36, scientific: true}, 'Z': {name: 'Z', value: 1e42, scientific: true}, 'Y': {name: 'Y', value: 1e48, scientific: true}, 'd': {name: 'd', value: 1e-2, scientific: false}, 'c': {name: 'c', value: 1e-4, scientific: false}, 'm': {name: 'm', value: 1e-6, scientific: true}, 'u': {name: 'u', value: 1e-12, scientific: true}, 'n': {name: 'n', value: 1e-18, scientific: true}, 'p': {name: 'p', value: 1e-24, scientific: true}, 'f': {name: 'f', value: 1e-30, scientific: true}, 'a': {name: 'a', value: 1e-36, scientific: true}, 'z': {name: 'z', value: 1e-42, scientific: true}, 'y': {name: 'y', value: 1e-48, scientific: true} }, CUBIC: { '': {name: '', value: 1, scientific: true}, 'da': {name: 'da', value: 1e3, scientific: false}, 'h': {name: 'h', value: 1e6, scientific: false}, 'k': {name: 'k', value: 1e9, scientific: true}, 'M': {name: 'M', value: 1e18, scientific: true}, 'G': {name: 'G', value: 1e27, scientific: true}, 'T': {name: 'T', value: 1e36, scientific: true}, 'P': {name: 'P', value: 1e45, scientific: true}, 'E': {name: 'E', value: 1e54, scientific: true}, 'Z': {name: 'Z', value: 1e63, scientific: true}, 'Y': {name: 'Y', value: 1e72, scientific: true}, 'd': {name: 'd', value: 1e-3, scientific: false}, 'c': {name: 'c', value: 1e-6, scientific: false}, 'm': {name: 'm', value: 1e-9, scientific: true}, 'u': {name: 'u', value: 1e-18, scientific: true}, 'n': {name: 'n', value: 1e-27, scientific: true}, 'p': {name: 'p', value: 1e-36, scientific: true}, 'f': {name: 'f', value: 1e-45, scientific: true}, 'a': {name: 'a', value: 1e-54, scientific: true}, 'z': {name: 'z', value: 1e-63, scientific: true}, 'y': {name: 'y', value: 1e-72, scientific: true} }, BINARY_SHORT: { '': {name: '', value: 1, scientific: true}, 'k': {name: 'k', value: 1e3, scientific: true}, 'M': {name: 'M', value: 1e6, scientific: true}, 'G': {name: 'G', value: 1e9, scientific: true}, 'T': {name: 'T', value: 1e12, scientific: true}, 'P': {name: 'P', value: 1e15, scientific: true}, 'E': {name: 'E', value: 1e18, scientific: true}, 'Z': {name: 'Z', value: 1e21, scientific: true}, 'Y': {name: 'Y', value: 1e24, scientific: true}, 'Ki': {name: 'Ki', value: 1024, scientific: true}, 'Mi': {name: 'Mi', value: Math.pow(1024, 2), scientific: true}, 'Gi': {name: 'Gi', value: Math.pow(1024, 3), scientific: true}, 'Ti': {name: 'Ti', value: Math.pow(1024, 4), scientific: true}, 'Pi': {name: 'Pi', value: Math.pow(1024, 5), scientific: true}, 'Ei': {name: 'Ei', value: Math.pow(1024, 6), scientific: true}, 'Zi': {name: 'Zi', value: Math.pow(1024, 7), scientific: true}, 'Yi': {name: 'Yi', value: Math.pow(1024, 8), scientific: true} }, BINARY_LONG: { '': {name: '', value: 1, scientific: true}, 'kilo': {name: 'kilo', value: 1e3, scientific: true}, 'mega': {name: 'mega', value: 1e6, scientific: true}, 'giga': {name: 'giga', value: 1e9, scientific: true}, 'tera': {name: 'tera', value: 1e12, scientific: true}, 'peta': {name: 'peta', value: 1e15, scientific: true}, 'exa': {name: 'exa', value: 1e18, scientific: true}, 'zetta': {name: 'zetta', value: 1e21, scientific: true}, 'yotta': {name: 'yotta', value: 1e24, scientific: true}, 'kibi': {name: 'kibi', value: 1024, scientific: true}, 'mebi': {name: 'mebi', value: Math.pow(1024, 2), scientific: true}, 'gibi': {name: 'gibi', value: Math.pow(1024, 3), scientific: true}, 'tebi': {name: 'tebi', value: Math.pow(1024, 4), scientific: true}, 'pebi': {name: 'pebi', value: Math.pow(1024, 5), scientific: true}, 'exi': {name: 'exi', value: Math.pow(1024, 6), scientific: true}, 'zebi': {name: 'zebi', value: Math.pow(1024, 7), scientific: true}, 'yobi': {name: 'yobi', value: Math.pow(1024, 8), scientific: true} }, BTU: { '': {name: '', value: 1, scientific: true}, 'MM': {name: 'MM', value: 1e6, scientific: true} } }; // Add a prefix list for both short and long prefixes (for ohm in particular, since Mohm and megaohm are both acceptable): PREFIXES.SHORTLONG = {}; for (var key in PREFIXES.SHORT) { if(PREFIXES.SHORT.hasOwnProperty(key)) { PREFIXES.SHORTLONG[key] = PREFIXES.SHORT[key]; } } for (var key in PREFIXES.LONG) { if(PREFIXES.LONG.hasOwnProperty(key)) { PREFIXES.SHORTLONG[key] = PREFIXES.LONG[key]; } } /* Internally, each unit is represented by a value and a dimension array. The elements of the dimensions array have the following meaning: * Index Dimension * ----- --------- * 0 Length * 1 Mass * 2 Time * 3 Current * 4 Temperature * 5 Luminous intensity * 6 Amount of substance * 7 Angle * 8 Bit (digital) * For example, the unit "298.15 K" is a pure temperature and would have a value of 298.15 and a dimension array of [0, 0, 0, 0, 1, 0, 0, 0, 0]. The unit "1 cal / (gm °C)" can be written in terms of the 9 fundamental dimensions as [length^2] / ([time^2] * [temperature]), and would a value of (after conversion to SI) 4184.0 and a dimensions array of [2, 0, -2, 0, -1, 0, 0, 0, 0]. * */ var BASE_DIMENSIONS = ["MASS", "LENGTH", "TIME", "CURRENT", "TEMPERATURE", "LUMINOUS_INTENSITY", "AMOUNT_OF_SUBSTANCE", "ANGLE", "BIT"]; var BASE_UNITS = { NONE: { dimensions: [0, 0, 0, 0, 0, 0, 0, 0, 0] }, MASS: { dimensions: [1, 0, 0, 0, 0, 0, 0, 0, 0] }, LENGTH: { dimensions: [0, 1, 0, 0, 0, 0, 0, 0, 0] }, TIME: { dimensions: [0, 0, 1, 0, 0, 0, 0, 0, 0] }, CURRENT: { dimensions: [0, 0, 0, 1, 0, 0, 0, 0, 0] }, TEMPERATURE: { dimensions: [0, 0, 0, 0, 1, 0, 0, 0, 0] }, LUMINOUS_INTENSITY: { dimensions: [0, 0, 0, 0, 0, 1, 0, 0, 0] }, AMOUNT_OF_SUBSTANCE: { dimensions: [0, 0, 0, 0, 0, 0, 1, 0, 0] }, FORCE: { dimensions: [1, 1, -2, 0, 0, 0, 0, 0, 0] }, SURFACE: { dimensions: [0, 2, 0, 0, 0, 0, 0, 0, 0] }, VOLUME: { dimensions: [0, 3, 0, 0, 0, 0, 0, 0, 0] }, ENERGY: { dimensions: [1, 2, -2, 0, 0, 0, 0, 0, 0] }, POWER: { dimensions: [1, 2, -3, 0, 0, 0, 0, 0, 0] }, PRESSURE: { dimensions: [1, -1, -2, 0, 0, 0, 0, 0, 0] }, ELECTRIC_CHARGE: { dimensions: [0, 0, 1, 1, 0, 0, 0, 0, 0] }, ELECTRIC_CAPACITANCE: { dimensions: [-1, -2, 4, 2, 0, 0, 0, 0, 0] }, ELECTRIC_POTENTIAL: { dimensions: [1, 2, -3, -1, 0, 0, 0, 0, 0] }, ELECTRIC_RESISTANCE: { dimensions: [1, 2, -3, -2, 0, 0, 0, 0, 0] }, ELECTRIC_INDUCTANCE: { dimensions: [1, 2, -2, -2, 0, 0, 0, 0, 0] }, ELECTRIC_CONDUCTANCE: { dimensions: [-1, -2, 3, 2, 0, 0, 0, 0, 0] }, MAGNETIC_FLUX: { dimensions: [1, 2, -2, -1, 0, 0, 0, 0, 0] }, MAGNETIC_FLUX_DENSITY: { dimensions: [1, 0, -2, -1, 0, 0, 0, 0, 0] }, FREQUENCY: { dimensions: [0, 0, -1, 0, 0, 0, 0, 0, 0] }, ANGLE: { dimensions: [0, 0, 0, 0, 0, 0, 0, 1, 0] }, BIT: { dimensions: [0, 0, 0, 0, 0, 0, 0, 0, 1] } }; for(var key in BASE_UNITS) { BASE_UNITS[key].key = key; } var BASE_UNIT_NONE = {}; var UNIT_NONE = {name: '', base: BASE_UNIT_NONE, value: 1, offset: 0, dimensions: [0,0,0,0,0,0,0,0,0]}; var UNITS = { // length meter: { name: 'meter', base: BASE_UNITS.LENGTH, prefixes: PREFIXES.LONG, value: 1, offset: 0 }, inch: { name: 'inch', base: BASE_UNITS.LENGTH, prefixes: PREFIXES.NONE, value: 0.0254, offset: 0 }, foot: { name: 'foot', base: BASE_UNITS.LENGTH, prefixes: PREFIXES.NONE, value: 0.3048, offset: 0 }, yard: { name: 'yard', base: BASE_UNITS.LENGTH, prefixes: PREFIXES.NONE, value: 0.9144, offset: 0 }, mile: { name: 'mile', base: BASE_UNITS.LENGTH, prefixes: PREFIXES.NONE, value: 1609.344, offset: 0 }, link: { name: 'link', base: BASE_UNITS.LENGTH, prefixes: PREFIXES.NONE, value: 0.201168, offset: 0 }, rod: { name: 'rod', base: BASE_UNITS.LENGTH, prefixes: PREFIXES.NONE, value: 5.029210, offset: 0 }, chain: { name: 'chain', base: BASE_UNITS.LENGTH, prefixes: PREFIXES.NONE, value: 20.1168, offset: 0 }, angstrom: { name: 'angstrom', base: BASE_UNITS.LENGTH, prefixes: PREFIXES.NONE, value: 1e-10, offset: 0 }, m: { name: 'm', base: BASE_UNITS.LENGTH, prefixes: PREFIXES.SHORT, value: 1, offset: 0 }, 'in': { name: 'in', base: BASE_UNITS.LENGTH, prefixes: PREFIXES.NONE, value: 0.0254, offset: 0 }, ft: { name: 'ft', base: BASE_UNITS.LENGTH, prefixes: PREFIXES.NONE, value: 0.3048, offset: 0 }, yd: { name: 'yd', base: BASE_UNITS.LENGTH, prefixes: PREFIXES.NONE, value: 0.9144, offset: 0 }, mi: { name: 'mi', base: BASE_UNITS.LENGTH, prefixes: PREFIXES.NONE, value: 1609.344, offset: 0 }, li: { name: 'li', base: BASE_UNITS.LENGTH, prefixes: PREFIXES.NONE, value: 0.201168, offset: 0 }, rd: { name: 'rd', base: BASE_UNITS.LENGTH, prefixes: PREFIXES.NONE, value: 5.029210, offset: 0 }, ch: { name: 'ch', base: BASE_UNITS.LENGTH, prefixes: PREFIXES.NONE, value: 20.1168, offset: 0 }, mil: { name: 'mil', base: BASE_UNITS.LENGTH, prefixes: PREFIXES.NONE, value: 0.0000254, offset: 0 }, // 1/1000 inch // Surface m2: { name: 'm2', base: BASE_UNITS.SURFACE, prefixes: PREFIXES.SQUARED, value: 1, offset: 0 }, sqin: { name: 'sqin', base: BASE_UNITS.SURFACE, prefixes: PREFIXES.NONE, value: 0.00064516, offset: 0 }, // 645.16 mm2 sqft: { name: 'sqft', base: BASE_UNITS.SURFACE, prefixes: PREFIXES.NONE, value: 0.09290304, offset: 0 }, // 0.09290304 m2 sqyd: { name: 'sqyd', base: BASE_UNITS.SURFACE, prefixes: PREFIXES.NONE, value: 0.83612736, offset: 0 }, // 0.83612736 m2 sqmi: { name: 'sqmi', base: BASE_UNITS.SURFACE, prefixes: PREFIXES.NONE, value: 2589988.110336, offset: 0 }, // 2.589988110336 km2 sqrd: { name: 'sqrd', base: BASE_UNITS.SURFACE, prefixes: PREFIXES.NONE, value: 25.29295, offset: 0 }, // 25.29295 m2 sqch: { name: 'sqch', base: BASE_UNITS.SURFACE, prefixes: PREFIXES.NONE, value: 404.6873, offset: 0 }, // 404.6873 m2 sqmil: { name: 'sqmil', base: BASE_UNITS.SURFACE, prefixes: PREFIXES.NONE, value: 6.4516e-10, offset: 0 }, // 6.4516 * 10^-10 m2 acre: { name: 'acre', base: BASE_UNITS.SURFACE, prefixes: PREFIXES.NONE, value: 4046.86, offset: 0 }, // 4046.86 m2 hectare: { name: 'hectare', base: BASE_UNITS.SURFACE, prefixes: PREFIXES.NONE, value: 10000, offset: 0 }, // 10000 m2 // Volume m3: { name: 'm3', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.CUBIC, value: 1, offset: 0 }, L: { name: 'L', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.SHORT, value: 0.001, offset: 0 }, // litre l: { name: 'l', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.SHORT, value: 0.001, offset: 0 }, // litre litre: { name: 'litre', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.LONG, value: 0.001, offset: 0 }, cuin: { name: 'cuin', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 1.6387064e-5, offset: 0 }, // 1.6387064e-5 m3 cuft: { name: 'cuft', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.028316846592, offset: 0 }, // 28.316 846 592 L cuyd: { name: 'cuyd', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.764554857984, offset: 0 }, // 764.554 857 984 L teaspoon: { name: 'teaspoon', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.000005, offset: 0 }, // 5 mL tablespoon: { name: 'tablespoon', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.000015, offset: 0 }, // 15 mL //{name: 'cup', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.000240, offset: 0}, // 240 mL // not possible, we have already another cup drop: { name: 'drop', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 5e-8, offset: 0 }, // 0.05 mL = 5e-8 m3 gtt: { name: 'gtt', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 5e-8, offset: 0 }, // 0.05 mL = 5e-8 m3 // Liquid volume minim: { name: 'minim', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.00000006161152, offset: 0 }, // 0.06161152 mL fluiddram: { name: 'fluiddram', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.0000036966911, offset: 0 }, // 3.696691 mL fluidounce: { name: 'fluidounce', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.00002957353, offset: 0 }, // 29.57353 mL gill: { name: 'gill', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.0001182941, offset: 0 }, // 118.2941 mL cc: { name: 'cc', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 1e-6, offset: 0 }, // 1e-6 L cup: { name: 'cup', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.0002365882, offset: 0 }, // 236.5882 mL pint: { name: 'pint', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.0004731765, offset: 0 }, // 473.1765 mL quart: { name: 'quart', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.0009463529, offset: 0 }, // 946.3529 mL gallon: { name: 'gallon', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.003785412, offset: 0 }, // 3.785412 L beerbarrel: { name: 'beerbarrel', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.1173478, offset: 0 }, // 117.3478 L oilbarrel: { name: 'oilbarrel', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.1589873, offset: 0 }, // 158.9873 L hogshead: { name: 'hogshead', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.2384810, offset: 0 }, // 238.4810 L //{name: 'min', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.00000006161152, offset: 0}, // 0.06161152 mL // min is already in use as minute fldr: { name: 'fldr', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.0000036966911, offset: 0 }, // 3.696691 mL floz: { name: 'floz', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.00002957353, offset: 0 }, // 29.57353 mL gi: { name: 'gi', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.0001182941, offset: 0 }, // 118.2941 mL cp: { name: 'cp', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.0002365882, offset: 0 }, // 236.5882 mL pt: { name: 'pt', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.0004731765, offset: 0 }, // 473.1765 mL qt: { name: 'qt', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.0009463529, offset: 0 }, // 946.3529 mL gal: { name: 'gal', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.003785412, offset: 0 }, // 3.785412 L bbl: { name: 'bbl', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.1173478, offset: 0 }, // 117.3478 L obl: { name: 'obl', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.1589873, offset: 0 }, // 158.9873 L //{name: 'hogshead', base: BASE_UNITS.VOLUME, prefixes: PREFIXES.NONE, value: 0.2384810, offset: 0}, // 238.4810 L // TODO: hh? // Mass g: { name: 'g', base: BASE_UNITS.MASS, prefixes: PREFIXES.SHORT, value: 0.001, offset: 0 }, gram: { name: 'gram', base: BASE_UNITS.MASS, prefixes: PREFIXES.LONG, value: 0.001, offset: 0 }, ton: { name: 'ton', base: BASE_UNITS.MASS, prefixes: PREFIXES.SHORT, value: 907.18474, offset: 0 }, tonne: { name: 'tonne', base: BASE_UNITS.MASS, prefixes: PREFIXES.SHORT, value: 1000, offset: 0 }, grain: { name: 'grain', base: BASE_UNITS.MASS, prefixes: PREFIXES.NONE, value: 64.79891e-6, offset: 0 }, dram: { name: 'dram', base: BASE_UNITS.MASS, prefixes: PREFIXES.NONE, value: 1.7718451953125e-3, offset: 0 }, ounce: { name: 'ounce', base: BASE_UNITS.MASS, prefixes: PREFIXES.NONE, value: 28.349523125e-3, offset: 0 }, poundmass: { name: 'poundmass', base: BASE_UNITS.MASS, prefixes: PREFIXES.NONE, value: 453.59237e-3, offset: 0 }, hundredweight: { name: 'hundredweight', base: BASE_UNITS.MASS, prefixes: PREFIXES.NONE, value: 45.359237, offset: 0 }, stick: { name: 'stick', base: BASE_UNITS.MASS, prefixes: PREFIXES.NONE, value: 115e-3, offset: 0 }, stone: { name: 'stone', base: BASE_UNITS.MASS, prefixes: PREFIXES.NONE, value: 6.35029318, offset: 0 }, gr: { name: 'gr', base: BASE_UNITS.MASS, prefixes: PREFIXES.NONE, value: 64.79891e-6, offset: 0 }, dr: { name: 'dr', base: BASE_UNITS.MASS, prefixes: PREFIXES.NONE, value: 1.7718451953125e-3, offset: 0 }, oz: { name: 'oz', base: BASE_UNITS.MASS, prefixes: PREFIXES.NONE, value: 28.349523125e-3, offset: 0 }, lbm: { name: 'lbm', base: BASE_UNITS.MASS, prefixes: PREFIXES.NONE, value: 453.59237e-3, offset: 0 }, cwt: { name: 'cwt', base: BASE_UNITS.MASS, prefixes: PREFIXES.NONE, value: 45.359237, offset: 0 }, // Time s: { name: 's', base: BASE_UNITS.TIME, prefixes: PREFIXES.SHORT, value: 1, offset: 0 }, min: { name: 'min', base: BASE_UNITS.TIME, prefixes: PREFIXES.NONE, value: 60, offset: 0 }, h: { name: 'h', base: BASE_UNITS.TIME, prefixes: PREFIXES.NONE, value: 3600, offset: 0 }, second: { name: 'second', base: BASE_UNITS.TIME, prefixes: PREFIXES.LONG, value: 1, offset: 0 }, sec: { name: 'sec', base: BASE_UNITS.TIME, prefixes: PREFIXES.LONG, value: 1, offset: 0 }, minute: { name: 'minute', base: BASE_UNITS.TIME, prefixes: PREFIXES.NONE, value: 60, offset: 0 }, hour: { name: 'hour', base: BASE_UNITS.TIME, prefixes: PREFIXES.NONE, value: 3600, offset: 0 }, day: { name: 'day', base: BASE_UNITS.TIME, prefixes: PREFIXES.NONE, value: 86400, offset: 0 }, week: { name: 'week', base: BASE_UNITS.TIME, prefixes: PREFIXES.NONE, value: 7*86400, offset: 0 }, month: { name: 'month', base: BASE_UNITS.TIME, prefixes: PREFIXES.NONE, value: 2629800, //1/12th of Julian year offset: 0 }, year: { name: 'year', base: BASE_UNITS.TIME, prefixes: PREFIXES.NONE, value: 31557600, //Julian year offset: 0 }, decade: { name: 'year', base: BASE_UNITS.TIME, prefixes: PREFIXES.NONE, value: 315576000, //Julian decade offset: 0 }, century: { name: 'century', base: BASE_UNITS.TIME, prefixes: PREFIXES.NONE, value: 3155760000, //Julian century offset: 0 }, millennium: { name: 'millennium', base: BASE_UNITS.TIME, prefixes: PREFIXES.NONE, value: 31557600000, //Julian millennium offset: 0 }, // Frequency hertz: { name: 'Hertz', base: BASE_UNITS.FREQUENCY, prefixes: PREFIXES.LONG, value: 1, offset: 0, reciprocal: true }, Hz: { name: 'Hz', base: BASE_UNITS.FREQUENCY, prefixes: PREFIXES.SHORT, value: 1, offset: 0, reciprocal: true }, // Angle rad: { name: 'rad', base: BASE_UNITS.ANGLE, prefixes: PREFIXES.NONE, value: 1, offset: 0 }, // deg = rad / (2*pi) * 360 = rad / 0.017453292519943295769236907684888 deg: { name: 'deg', base: BASE_UNITS.ANGLE, prefixes: PREFIXES.NONE, value: null, // will be filled in by calculateAngleValues() offset: 0 }, // grad = rad / (2*pi) * 400 = rad / 0.015707963267948966192313216916399 grad: { name: 'grad', base: BASE_UNITS.ANGLE, prefixes: PREFIXES.NONE, value: null, // will be filled in by calculateAngleValues() offset: 0 }, // cycle = rad / (2*pi) = rad / 6.2831853071795864769252867665793 cycle: { name: 'cycle', base: BASE_UNITS.ANGLE, prefixes: PREFIXES.NONE, value: null, // will be filled in by calculateAngleValues() offset: 0 }, // arcsec = rad / (3600 * (360 / 2 * pi)) = rad / 0.0000048481368110953599358991410235795 arcsec: { name: 'arcsec', base: BASE_UNITS.ANGLE, prefixes: PREFIXES.NONE, value: null, // will be filled in by calculateAngleValues() offset: 0 }, // arcmin = rad / (60 * (360 / 2 * pi)) = rad / 0.00029088820866572159615394846141477 arcmin: { name: 'arcmin', base: BASE_UNITS.ANGLE, prefixes: PREFIXES.NONE, value: null, // will be filled in by calculateAngleValues() offset: 0 }, // Electric current A: { name: 'A', base: BASE_UNITS.CURRENT, prefixes: PREFIXES.SHORT, value: 1, offset: 0 }, ampere: { name: 'ampere', base: BASE_UNITS.CURRENT, prefixes: PREFIXES.LONG, value: 1, offset: 0 }, // Temperature // K(C) = °C + 273.15 // K(F) = (°F + 459.67) / 1.8 // K(R) = °R / 1.8 K: { name: 'K', base: BASE_UNITS.TEMPERATURE, prefixes: PREFIXES.NONE, value: 1, offset: 0 }, degC: { name: 'degC', base: BASE_UNITS.TEMPERATURE, prefixes: PREFIXES.NONE, value: 1, offset: 273.15 }, degF: { name: 'degF', base: BASE_UNITS.TEMPERATURE, prefixes: PREFIXES.NONE, value: 1 / 1.8, offset: 459.67 }, degR: { name: 'degR', base: BASE_UNITS.TEMPERATURE, prefixes: PREFIXES.NONE, value: 1 / 1.8, offset: 0 }, kelvin: { name: 'kelvin', base: BASE_UNITS.TEMPERATURE, prefixes: PREFIXES.NONE, value: 1, offset: 0 }, celsius: { name: 'celsius', base: BASE_UNITS.TEMPERATURE, prefixes: PREFIXES.NONE, value: 1, offset: 273.15 }, fahrenheit: { name: 'fahrenheit', base: BASE_UNITS.TEMPERATURE, prefixes: PREFIXES.NONE, value: 1 / 1.8, offset: 459.67 }, rankine: { name: 'rankine', base: BASE_UNITS.TEMPERATURE, prefixes: PREFIXES.NONE, value: 1 / 1.8, offset: 0 }, // amount of substance mol: { name: 'mol', base: BASE_UNITS.AMOUNT_OF_SUBSTANCE, prefixes: PREFIXES.SHORT, value: 1, offset: 0 }, mole: { name: 'mole', base: BASE_UNITS.AMOUNT_OF_SUBSTANCE, prefixes: PREFIXES.LONG, value: 1, offset: 0 }, // luminous intensity cd: { name: 'cd', base: BASE_UNITS.LUMINOUS_INTENSITY, prefixes: PREFIXES.NONE, value: 1, offset: 0 }, candela: { name: 'candela', base: BASE_UNITS.LUMINOUS_INTENSITY, prefixes: PREFIXES.NONE, value: 1, offset: 0 }, // TODO: units STERADIAN //{name: 'sr', base: BASE_UNITS.STERADIAN, prefixes: PREFIXES.NONE, value: 1, offset: 0}, //{name: 'steradian', base: BASE_UNITS.STERADIAN, prefixes: PREFIXES.NONE, value: 1, offset: 0}, // Force N: { name: 'N', base: BASE_UNITS.FORCE, prefixes: PREFIXES.SHORT, value: 1, offset: 0 }, newton: { name: 'newton', base: BASE_UNITS.FORCE, prefixes: PREFIXES.LONG, value: 1, offset: 0 }, dyn: { name: 'dyn', base: BASE_UNITS.FORCE, prefixes: PREFIXES.SHORT, value: 0.00001, offset: 0 }, dyne: { name: 'dyne', base: BASE_UNITS.FORCE, prefixes: PREFIXES.LONG, value: 0.00001, offset: 0 }, lbf: { name: 'lbf', base: BASE_UNITS.FORCE, prefixes: PREFIXES.NONE, value: 4.4482216152605, offset: 0 }, poundforce: { name: 'poundforce', base: BASE_UNITS.FORCE, prefixes: PREFIXES.NONE, value: 4.4482216152605, offset: 0 }, kip: { name: 'kip', base: BASE_UNITS.FORCE, prefixes: PREFIXES.LONG, value: 4448.2216, offset: 0 }, // Energy J: { name: 'J', base: BASE_UNITS.ENERGY, prefixes: PREFIXES.SHORT, value: 1, offset: 0 }, joule: { name: 'joule', base: BASE_UNITS.ENERGY, prefixes: PREFIXES.SHORT, value: 1, offset: 0 }, erg: { name: 'erg', base: BASE_UNITS.ENERGY, prefixes: PREFIXES.NONE, value: 1e-5, offset: 0 }, Wh: { name: 'Wh', base: BASE_UNITS.ENERGY, prefixes: PREFIXES.SHORT, value: 3600, offset: 0 }, BTU: { name: 'BTU', base: BASE_UNITS.ENERGY, prefixes: PREFIXES.BTU, value: 1055.05585262, offset: 0 }, eV: { name: 'eV', base: BASE_UNITS.ENERGY, prefixes: PREFIXES.SHORT, value: 1.602176565e-19, offset: 0 }, electronvolt: { name: 'electronvolt', base: BASE_UNITS.ENERGY, prefixes: PREFIXES.LONG, value: 1.602176565e-19, offset: 0 }, // Power W: { name: 'W', base: BASE_UNITS.POWER, prefixes: PREFIXES.SHORT, value: 1, offset: 0 }, watt: { name: 'W', base: BASE_UNITS.POWER, prefixes: PREFIXES.LONG, value: 1, offset: 0 }, hp: { name: 'hp', base: BASE_UNITS.POWER, prefixes: PREFIXES.NONE, value: 745.6998715386, offset: 0 }, // Electrical power units VAR: { name: 'VAR', base: BASE_UNITS.POWER, prefixes: PREFIXES.SHORT, value: Complex.I, offset: 0 }, VA: { name: 'VA', base: BASE_UNITS.POWER, prefixes: PREFIXES.SHORT, value: 1, offset: 0 }, // Pressure Pa: { name: 'Pa', base: BASE_UNITS.PRESSURE, prefixes: PREFIXES.SHORT, value: 1, offset: 0 }, psi: { name: 'psi', base: BASE_UNITS.PRESSURE, prefixes: PREFIXES.NONE, value: 6894.75729276459, offset: 0 }, atm: { name: 'atm', base: BASE_UNITS.PRESSURE, prefixes: PREFIXES.NONE, value: 101325, offset: 0 }, bar: { name: 'bar', base: BASE_UNITS.PRESSURE, prefixes: PREFIXES.NONE, value: 100000, offset: 0 }, torr: { name: 'torr', base: BASE_UNITS.PRESSURE, prefixes: PREFIXES.NONE, value: 133.322, offset: 0 }, mmHg: { name: 'mmHg', base: BASE_UNITS.PRESSURE, prefixes: PREFIXES.NONE, value: 133.322, offset: 0 }, mmH2O: { name: 'mmH2O', base: BASE_UNITS.PRESSURE, prefixes: PREFIXES.NONE, value: 9.80665, offset: 0 }, cmH2O: { name: 'cmH2O', base: BASE_UNITS.PRESSURE, prefixes: PREFIXES.NONE, value: 98.0665, offset: 0 }, // Electric charge coulomb: { name: 'coulomb', base: BASE_UNITS.ELECTRIC_CHARGE, prefixes: PREFIXES.LONG, value: 1, offset: 0 }, C: { name: 'C', base: BASE_UNITS.ELECTRIC_CHARGE, prefixes: PREFIXES.SHORT, value: 1, offset: 0 }, // Electric capacitance farad: { name: 'farad', base: BASE_UNITS.ELECTRIC_CAPACITANCE, prefixes: PREFIXES.LONG, value: 1, offset: 0 }, F: { name: 'F', base: BASE_UNITS.ELECTRIC_CAPACITANCE, prefixes: PREFIXES.SHORT, value: 1, offset: 0 }, // Electric potential volt: { name: 'volt', base: BASE_UNITS.ELECTRIC_POTENTIAL, prefixes: PREFIXES.LONG, value: 1, offset: 0 }, V: { name: 'V', base: BASE_UNITS.ELECTRIC_POTENTIAL, prefixes: PREFIXES.SHORT, value: 1, offset: 0 }, // Electric resistance ohm: { name: 'ohm', base: BASE_UNITS.ELECTRIC_RESISTANCE, prefixes: PREFIXES.SHORTLONG, // Both Mohm and megaohm are acceptable value: 1, offset: 0 }, /* * Unicode breaks in browsers if charset is not specified Ω: { name: 'Ω', base: BASE_UNITS.ELECTRIC_RESISTANCE, prefixes: PREFIXES.SHORT, value: 1, offset: 0 }, */ // Electric inductance henry: { name: 'henry', base: BASE_UNITS.ELECTRIC_INDUCTANCE, prefixes: PREFIXES.LONG, value: 1, offset: 0 }, H: { name: 'H', base: BASE_UNITS.ELECTRIC_INDUCTANCE, prefixes: PREFIXES.SHORT, value: 1, offset: 0 }, // Electric conductance siemens: { name: 'siemens', base: BASE_UNITS.ELECTRIC_CONDUCTANCE, prefixes: PREFIXES.LONG, value: 1, offset: 0 }, S: { name: 'S', base: BASE_UNITS.ELECTRIC_CONDUCTANCE, prefixes: PREFIXES.SHORT, value: 1, offset: 0 }, // Magnetic flux weber: { name: 'weber', base: BASE_UNITS.MAGNETIC_FLUX, prefixes: PREFIXES.LONG, value: 1, offset: 0 }, Wb: { name: 'Wb', base: BASE_UNITS.MAGNETIC_FLUX, prefixes: PREFIXES.SHORT, value: 1, offset: 0 }, // Magnetic flux density tesla: { name: 'tesla', base: BASE_UNITS.MAGNETIC_FLUX_DENSITY, prefixes: PREFIXES.LONG, value: 1, offset: 0 }, T: { name: 'T', base: BASE_UNITS.MAGNETIC_FLUX_DENSITY, prefixes: PREFIXES.SHORT, value: 1, offset: 0 }, // Binary b: { name: 'b', base: BASE_UNITS.BIT, prefixes: PREFIXES.BINARY_SHORT, value: 1, offset: 0 }, bits: { name: 'bits', base: BASE_UNITS.BIT, prefixes: PREFIXES.BINARY_LONG, value: 1, offset: 0 }, B: { name: 'B', base: BASE_UNITS.BIT, prefixes: PREFIXES.BINARY_SHORT, value: 8, offset: 0 }, bytes: { name: 'bytes', base: BASE_UNITS.BIT, prefixes: PREFIXES.BINARY_LONG, value: 8, offset: 0 } }; // aliases (formerly plurals) var ALIASES = { meters: 'meter', inches: 'inch', feet: 'foot', yards: 'yard', miles: 'mile', links: 'link', rods: 'rod', chains: 'chain', angstroms: 'angstrom', lt: 'l', litres: 'litre', liter: 'litre', liters: 'litre', teaspoons: 'teaspoon', tablespoons: 'tablespoon', minims: 'minim', fluiddrams: 'fluiddram', fluidounces: 'fluidounce', gills: 'gill', cups: 'cup', pints: 'pint', quarts: 'quart', gallons: 'gallon', beerbarrels: 'beerbarrel', oilbarrels: 'oilbarrel', hogsheads: 'hogshead', gtts: 'gtt', grams: 'gram', tons: 'ton', tonnes: 'tonne', grains: 'grain', drams: 'dram', ounces: 'ounce', poundmasses: 'poundmass', hundredweights: 'hundredweight', sticks: 'stick', lb: 'lbm', lbs: 'lbm', kips: 'kip', acres: 'acre', hectares: 'hectare', sqfeet: 'sqft', sqyard: 'sqyd', sqmile: 'sqmi', sqmiles: 'sqmi', mmhg: 'mmHg', mmh2o: 'mmH2O', cmh2o: 'cmH2O', seconds: 'second', secs: 'second', minutes: 'minute', mins: 'minute', hours: 'hour', hr: 'hour', hrs: 'hour', days: 'day', weeks: 'week', months: 'month', years: 'year', hertz: 'hertz', radians: 'rad', degree: 'deg', degrees: 'deg', gradian: 'grad', gradians: 'grad', cycles: 'cycle', arcsecond: 'arcsec', arcseconds: 'arcsec', arcminute: 'arcmin', arcminutes: 'arcmin', BTUs: 'BTU', watts: 'watt', joules: 'joule', amperes: 'ampere', coulombs: 'coulomb', volts: 'volt', ohms: 'ohm', farads: 'farad', webers: 'weber', teslas: 'tesla', electronvolts: 'electronvolt', moles: 'mole' }; /** * Calculate the values for the angle units. * Value is calculated as number or BigNumber depending on the configuration * @param {{number: 'number' | 'BigNumber'}} config */ function calculateAngleValues (config) { if (config.number === 'BigNumber') { var pi = constants.pi(type.BigNumber); UNITS.rad.value = new type.BigNumber(1); UNITS.deg.value = pi.div(180); // 2 * pi / 360; UNITS.grad.value = pi.div(200); // 2 * pi / 400; UNITS.cycle.value = pi.times(2); // 2 * pi UNITS.arcsec.value = pi.div(648000); // 2 * pi / 360 / 3600 UNITS.arcmin.value = pi.div(10800); // 2 * pi / 360 / 60 } else { // number UNITS.rad.value = 1; UNITS.deg.value = Math.PI / 180; // 2 * pi / 360; UNITS.grad.value = Math.PI / 200; // 2 * pi / 400; UNITS.cycle.value = Math.PI * 2; // 2 * pi UNITS.arcsec.value = Math.PI / 648000; // 2 * pi / 360 / 3600; UNITS.arcmin.value = Math.PI / 10800; // 2 * pi / 360 / 60; } } // apply the angle values now calculateAngleValues(config); // recalculate the values on change of configuration math.on('config', function (curr, prev) { if (curr.number !== prev.number) { calculateAngleValues(curr); } }); /** * A unit system is a set of dimensionally independent base units plus a set of derived units, formed by multiplication and division of the base units, that are by convention used with the unit system. * A user perhaps could issue a command to select a preferred unit system, or use the default (see below). * Auto unit system: The default unit system is updated on the fly anytime a unit is parsed. The corresponding unit in the default unit system is updated, so that answers are given in the same units the user supplies. */ var UNIT_SYSTEMS = { si: { // Base units NONE: {unit: UNIT_NONE, prefix: PREFIXES.NONE['']}, LENGTH: {unit: UNITS.m, prefix: PREFIXES.SHORT['']}, MASS: {unit: UNITS.g, prefix: PREFIXES.SHORT['k']}, TIME: {unit: UNITS.s, prefix: PREFIXES.SHORT['']}, CURRENT: {unit: UNITS.A, prefix: PREFIXES.SHORT['']}, TEMPERATURE: {unit: UNITS.K, prefix: PREFIXES.SHORT['']}, LUMINOUS_INTENSITY: {unit: UNITS.cd, prefix: PREFIXES.SHORT['']}, AMOUNT_OF_SUBSTANCE: {unit: UNITS.mol, prefix: PREFIXES.SHORT['']}, ANGLE: {unit: UNITS.rad, prefix: PREFIXES.SHORT['']}, BIT: {unit: UNITS.bit, prefix: PREFIXES.SHORT['']}, // Derived units FORCE: {unit: UNITS.N, prefix: PREFIXES.SHORT['']}, ENERGY: {unit: UNITS.J, prefix: PREFIXES.SHORT['']}, POWER: {unit: UNITS.W, prefix: PREFIXES.SHORT['']}, PRESSURE: {unit: UNITS.Pa, prefix: PREFIXES.SHORT['']}, ELECTRIC_CHARGE: {unit: UNITS.C, prefix: PREFIXES.SHORT['']}, ELECTRIC_CAPACITANCE: {unit: UNITS.F, prefix: PREFIXES.SHORT['']}, ELECTRIC_POTENTIAL: {unit: UNITS.V, prefix: PREFIXES.SHORT['']}, ELECTRIC_RESISTANCE: {unit: UNITS.ohm, prefix: PREFIXES.SHORT['']}, ELECTRIC_INDUCTANCE: {unit: UNITS.H, prefix: PREFIXES.SHORT['']}, ELECTRIC_CONDUCTANCE: {unit: UNITS.S, prefix: PREFIXES.SHORT['']}, MAGNETIC_FLUX: {unit: UNITS.Wb, prefix: PREFIXES.SHORT['']}, MAGNETIC_FLUX_DENSITY: {unit: UNITS.T, prefix: PREFIXES.SHORT['']}, FREQUENCY: {unit: UNITS.Hz, prefix: PREFIXES.SHORT['']} } }; // Clone to create the other unit systems UNIT_SYSTEMS.cgs = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si)); UNIT_SYSTEMS.cgs.LENGTH = {unit: UNITS.m, prefix: PREFIXES.SHORT['c']}; UNIT_SYSTEMS.cgs.MASS = {unit: UNITS.g, prefix: PREFIXES.SHORT['']}; UNIT_SYSTEMS.cgs.FORCE = {unit: UNITS.dyn, prefix: PREFIXES.SHORT['']}; UNIT_SYSTEMS.cgs.ENERGY = {unit: UNITS.erg, prefix: PREFIXES.NONE['']}; // there are wholly 4 unique cgs systems for electricity and magnetism, // so let's not worry about it unless somebody complains UNIT_SYSTEMS.us = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si)); UNIT_SYSTEMS.us.LENGTH = {unit: UNITS.ft, prefix: PREFIXES.NONE['']}; UNIT_SYSTEMS.us.MASS = {unit: UNITS.lbm, prefix: PREFIXES.NONE['']}; UNIT_SYSTEMS.us.TEMPERATURE = {unit: UNITS.degF, prefix: PREFIXES.NONE['']}; UNIT_SYSTEMS.us.FORCE = {unit: UNITS.lbf, prefix: PREFIXES.NONE['']}; UNIT_SYSTEMS.us.ENERGY = {unit: UNITS.BTU, prefix: PREFIXES.BTU['']}; UNIT_SYSTEMS.us.POWER = {unit: UNITS.hp, prefix: PREFIXES.NONE['']}; UNIT_SYSTEMS.us.PRESSURE = {unit: UNITS.psi, prefix: PREFIXES.NONE['']}; // Add additional unit systems here. // Choose a unit system to seed the auto unit system. UNIT_SYSTEMS.auto = JSON.parse(JSON.stringify(UNIT_SYSTEMS.si)); // Set the current unit system var currentUnitSystem = UNIT_SYSTEMS.auto; /** * Set a unit system for formatting derived units. * @param {string} [name] The name of the unit system. */ Unit.setUnitSystem = function(name) { if(UNIT_SYSTEMS.hasOwnProperty(name)) { currentUnitSystem = UNIT_SYSTEMS[name]; } else { throw new Error('Unit system ' + name + ' does not exist. Choices are: ' + Object.keys(UNIT_SYSTEMS).join(', ')); } }; /** * Return the current unit system. * @return {string} The current unit system. */ Unit.getUnitSystem = function() { for(var key in UNIT_SYSTEMS) { if(UNIT_SYSTEMS[key] === currentUnitSystem) { return key; } } }; /** * Converters to convert from number to an other numeric type like BigNumber * or Fraction */ Unit.typeConverters = { BigNumber: function (x) { return new type.BigNumber(x + ''); // stringify to prevent constructor error }, Fraction: function (x) { return new type.Fraction(x); }, Complex: function (x) { return x; }, number: function (x) { return x; } }; /** * Retrieve the right convertor function corresponding with the type * of provided exampleValue. * * @param {string} type A string 'number', 'BigNumber', or 'Fraction' * In case of an unknown type, * @return {Function} */ Unit._getNumberConverter = function (type) { if (!Unit.typeConverters[type]) { throw new TypeError('Unsupported type "' + type + '"'); } return Unit.typeConverters[type]; }; // Add dimensions to each built-in unit for (var key in UNITS) { var unit = UNITS[key]; unit.dimensions = unit.base.dimensions; } // Create aliases for (var name in ALIASES) { /* istanbul ignore next (we cannot really test next statement) */ if (ALIASES.hasOwnProperty(name)) { var unit = UNITS[ALIASES[name]]; var alias = Object.create(unit); alias.name = name; UNITS[name] = alias; } } Unit.PREFIXES = PREFIXES; Unit.BASE_UNITS = BASE_UNITS; Unit.UNITS = UNITS; Unit.UNIT_SYSTEMS = UNIT_SYSTEMS; return Unit; } exports.name = 'Unit'; exports.path = 'type'; exports.factory = factory; exports.math = true; // request access to the math namespace
'use strict'; exports.config = { baseUrl: 'http://localhost:9000/', specs: [ 'src/**/*e2e.js' ], exclude: [], framework: 'jasmine2', allScriptsTimeout: 110000, jasmineNodeOpts: { showTiming: true, showColors: true, isVerbose: false, includeStackTrace: false, defaultTimeoutInterval: 400000 }, directConnect: true, capabilities: { 'browserName': 'chrome' }, onPrepare: function () { var SpecReporter = require('jasmine-spec-reporter'); // add jasmine spec reporter jasmine.getEnv().addReporter(new SpecReporter({displayStacktrace: true})); browser.ignoreSynchronization = true; }, /** * Angular 2 configuration * * useAllAngular2AppRoots: tells Protractor to wait for any angular2 apps on the page instead of just the one matching * `rootEl` * */ useAllAngular2AppRoots: true };
export default function isGapiReady(state) { return state.getIn(['clients', 'gapi', 'ready']); }
/* eslint-disable react/prop-types */ 'use strict'; var _extends = require('babel-runtime/helpers/extends')['default']; var _objectWithoutProperties = require('babel-runtime/helpers/object-without-properties')['default']; var _Object$isFrozen = require('babel-runtime/core-js/object/is-frozen')['default']; var _Object$keys = require('babel-runtime/core-js/object/keys')['default']; var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default']; exports.__esModule = true; var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactDom = require('react-dom'); var _reactDom2 = _interopRequireDefault(_reactDom); var _utilsDomUtils = require('./utils/domUtils'); var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils); var _domHelpersUtilScrollbarSize = require('dom-helpers/util/scrollbarSize'); var _domHelpersUtilScrollbarSize2 = _interopRequireDefault(_domHelpersUtilScrollbarSize); var _utilsEventListener = require('./utils/EventListener'); var _utilsEventListener2 = _interopRequireDefault(_utilsEventListener); var _utilsCreateChainedFunction = require('./utils/createChainedFunction'); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var _reactPropTypesLibElementType = require('react-prop-types/lib/elementType'); var _reactPropTypesLibElementType2 = _interopRequireDefault(_reactPropTypesLibElementType); var _domHelpersUtilInDOM = require('dom-helpers/util/inDOM'); var _domHelpersUtilInDOM2 = _interopRequireDefault(_domHelpersUtilInDOM); var _domHelpersQueryContains = require('dom-helpers/query/contains'); var _domHelpersQueryContains2 = _interopRequireDefault(_domHelpersQueryContains); var _domHelpersActiveElement = require('dom-helpers/activeElement'); var _domHelpersActiveElement2 = _interopRequireDefault(_domHelpersActiveElement); var _reactOverlaysLibPortal = require('react-overlays/lib/Portal'); var _reactOverlaysLibPortal2 = _interopRequireDefault(_reactOverlaysLibPortal); var _Fade = require('./Fade'); var _Fade2 = _interopRequireDefault(_Fade); var _ModalDialog = require('./ModalDialog'); var _ModalDialog2 = _interopRequireDefault(_ModalDialog); var _ModalBody = require('./ModalBody'); var _ModalBody2 = _interopRequireDefault(_ModalBody); var _ModalHeader = require('./ModalHeader'); var _ModalHeader2 = _interopRequireDefault(_ModalHeader); var _ModalTitle = require('./ModalTitle'); var _ModalTitle2 = _interopRequireDefault(_ModalTitle); var _ModalFooter = require('./ModalFooter'); var _ModalFooter2 = _interopRequireDefault(_ModalFooter); /** * Gets the correct clientHeight of the modal container * when the body/window/document you need to use the docElement clientHeight * @param {HTMLElement} container * @param {ReactElement|HTMLElement} context * @return {Number} */ function containerClientHeight(container, context) { var doc = _utilsDomUtils2['default'].ownerDocument(context); return container === doc.body || container === doc.documentElement ? doc.documentElement.clientHeight : container.clientHeight; } function getContainer(context) { return context.props.container && _reactDom2['default'].findDOMNode(context.props.container) || _utilsDomUtils2['default'].ownerDocument(context).body; } var currentFocusListener = undefined; /** * Firefox doesn't have a focusin event so using capture is easiest way to get bubbling * IE8 can't do addEventListener, but does have onfocusin, so we use that in ie8 * * We only allow one Listener at a time to avoid stack overflows * * @param {ReactElement|HTMLElement} context * @param {Function} handler */ function onFocus(context, handler) { var doc = _utilsDomUtils2['default'].ownerDocument(context); var useFocusin = !doc.addEventListener; var remove = undefined; if (currentFocusListener) { currentFocusListener.remove(); } if (useFocusin) { document.attachEvent('onfocusin', handler); remove = function () { return document.detachEvent('onfocusin', handler); }; } else { document.addEventListener('focus', handler, true); remove = function () { return document.removeEventListener('focus', handler, true); }; } currentFocusListener = { remove: remove }; return currentFocusListener; } var Modal = _react2['default'].createClass({ displayName: 'Modal', propTypes: _extends({}, _reactOverlaysLibPortal2['default'].propTypes, _ModalDialog2['default'].propTypes, { /** * Include a backdrop component. Specify 'static' for a backdrop that doesn't trigger an "onHide" when clicked. */ backdrop: _react2['default'].PropTypes.oneOf(['static', true, false]), /** * Close the modal when escape key is pressed */ keyboard: _react2['default'].PropTypes.bool, /** * Open and close the Modal with a slide and fade animation. */ animation: _react2['default'].PropTypes.bool, /** * A Component type that provides the modal content Markup. This is a useful prop when you want to use your own * styles and markup to create a custom modal component. */ dialogComponent: _reactPropTypesLibElementType2['default'], /** * When `true` The modal will automatically shift focus to itself when it opens, and replace it to the last focused element when it closes. * Generally this should never be set to false as it makes the Modal less accessible to assistive technologies, like screen-readers. */ autoFocus: _react2['default'].PropTypes.bool, /** * When `true` The modal will prevent focus from leaving the Modal while open. * Consider leaving the default value here, as it is necessary to make the Modal work well with assistive technologies, * such as screen readers. */ enforceFocus: _react2['default'].PropTypes.bool, /** * Hide this from automatic props documentation generation. * @private */ bsStyle: _react2['default'].PropTypes.string, /** * When `true` The modal will show itself. */ show: _react2['default'].PropTypes.bool }), getDefaultProps: function getDefaultProps() { return { bsClass: 'modal', dialogComponent: _ModalDialog2['default'], show: false, animation: true, backdrop: true, keyboard: true, autoFocus: true, enforceFocus: true }; }, getInitialState: function getInitialState() { return { exited: !this.props.show }; }, render: function render() { var _props = this.props; var children = _props.children; var animation = _props.animation; var backdrop = _props.backdrop; var props = _objectWithoutProperties(_props, ['children', 'animation', 'backdrop']); var onExit = props.onExit; var onExiting = props.onExiting; var onEnter = props.onEnter; var onEntering = props.onEntering; var onEntered = props.onEntered; var show = !!props.show; var Dialog = props.dialogComponent; var mountModal = show || animation && !this.state.exited; if (!mountModal) { return null; } var modal = _react2['default'].createElement( Dialog, _extends({}, props, { ref: this._setDialogRef, className: _classnames2['default'](this.props.className, { 'in': show && !animation }), onClick: backdrop === true ? this.handleBackdropClick : null }), this.renderContent() ); if (animation) { modal = _react2['default'].createElement( _Fade2['default'], { transitionAppear: true, unmountOnExit: true, 'in': show, timeout: Modal.TRANSITION_DURATION, onExit: onExit, onExiting: onExiting, onExited: this.handleHidden, onEnter: onEnter, onEntering: onEntering, onEntered: onEntered }, modal ); } if (backdrop) { modal = this.renderBackdrop(modal); } return _react2['default'].createElement( _reactOverlaysLibPortal2['default'], { container: props.container }, modal ); }, renderContent: function renderContent() { var _this = this; return _react2['default'].Children.map(this.props.children, function (child) { // TODO: use context in 0.14 if (child && child.type && child.type.__isModalHeader) { return _react.cloneElement(child, { onHide: _utilsCreateChainedFunction2['default'](_this.props.onHide, child.props.onHide) }); } return child; }); }, renderBackdrop: function renderBackdrop(modal) { var _props2 = this.props; var animation = _props2.animation; var bsClass = _props2.bsClass; var duration = Modal.BACKDROP_TRANSITION_DURATION; // Don't handle clicks for "static" backdrops var onClick = this.props.backdrop === true ? this.handleBackdropClick : null; var backdrop = _react2['default'].createElement('div', { ref: 'backdrop', className: _classnames2['default'](bsClass + '-backdrop', { 'in': this.props.show && !animation }), onClick: onClick }); return _react2['default'].createElement( 'div', { ref: 'modal' }, animation ? _react2['default'].createElement( _Fade2['default'], { transitionAppear: true, 'in': this.props.show, timeout: duration }, backdrop ) : backdrop, modal ); }, _setDialogRef: function _setDialogRef(ref) { // issue #1074 // due to: https://github.com/facebook/react/blob/v0.13.3/src/core/ReactCompositeComponent.js#L842 // // when backdrop is `false` react hasn't had a chance to reassign the refs to a usable object, b/c there are no other // "classic" refs on the component (or they haven't been processed yet) // TODO: Remove the need for this in next breaking release if (_Object$isFrozen(this.refs) && !_Object$keys(this.refs).length) { this.refs = {}; } this.refs.dialog = ref; // maintains backwards compat with older component breakdown if (!this.props.backdrop) { this.refs.modal = ref; } }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.show) { this.setState({ exited: false }); } else if (!nextProps.animation) { // Otherwise let handleHidden take care of marking exited. this.setState({ exited: true }); } }, componentWillUpdate: function componentWillUpdate(nextProps) { if (nextProps.show) { this.checkForFocus(); } }, componentDidMount: function componentDidMount() { if (this.props.show) { this.onShow(); } }, componentDidUpdate: function componentDidUpdate(prevProps) { var animation = this.props.animation; if (prevProps.show && !this.props.show && !animation) { // otherwise handleHidden will call this. this.onHide(); } else if (!prevProps.show && this.props.show) { this.onShow(); } }, componentWillUnmount: function componentWillUnmount() { if (this.props.show) { this.onHide(); } }, onShow: function onShow() { var _this2 = this; var doc = _utilsDomUtils2['default'].ownerDocument(this); var win = _utilsDomUtils2['default'].ownerWindow(this); this._onDocumentKeyupListener = _utilsEventListener2['default'].listen(doc, 'keyup', this.handleDocumentKeyUp); this._onWindowResizeListener = _utilsEventListener2['default'].listen(win, 'resize', this.handleWindowResize); if (this.props.enforceFocus) { this._onFocusinListener = onFocus(this, this.enforceFocus); } var container = getContainer(this); container.className += container.className.length ? ' modal-open' : 'modal-open'; this._containerIsOverflowing = container.scrollHeight > containerClientHeight(container, this); this._originalPadding = container.style.paddingRight; if (this._containerIsOverflowing) { container.style.paddingRight = parseInt(this._originalPadding || 0, 10) + _domHelpersUtilScrollbarSize2['default']() + 'px'; } this.setState(this._getStyles(), function () { return _this2.focusModalContent(); }); }, onHide: function onHide() { this._onDocumentKeyupListener.remove(); this._onWindowResizeListener.remove(); if (this._onFocusinListener) { this._onFocusinListener.remove(); } var container = getContainer(this); container.style.paddingRight = this._originalPadding; container.className = container.className.replace(/ ?modal-open/, ''); this.restoreLastFocus(); }, handleHidden: function handleHidden() { this.setState({ exited: true }); this.onHide(); if (this.props.onExited) { var _props3; (_props3 = this.props).onExited.apply(_props3, arguments); } }, handleBackdropClick: function handleBackdropClick(e) { if (e.target !== e.currentTarget) { return; } this.props.onHide(); }, handleDocumentKeyUp: function handleDocumentKeyUp(e) { if (this.props.keyboard && e.keyCode === 27) { this.props.onHide(); } }, handleWindowResize: function handleWindowResize() { this.setState(this._getStyles()); }, checkForFocus: function checkForFocus() { if (_domHelpersUtilInDOM2['default']) { this.lastFocus = _domHelpersActiveElement2['default'](document); } }, focusModalContent: function focusModalContent() { var modalContent = _reactDom2['default'].findDOMNode(this.refs.dialog); var current = _domHelpersActiveElement2['default'](_utilsDomUtils2['default'].ownerDocument(this)); var focusInModal = current && _domHelpersQueryContains2['default'](modalContent, current); if (modalContent && this.props.autoFocus && !focusInModal) { this.lastFocus = current; modalContent.focus(); } }, restoreLastFocus: function restoreLastFocus() { if (this.lastFocus && this.lastFocus.focus) { this.lastFocus.focus(); this.lastFocus = null; } }, enforceFocus: function enforceFocus() { if (!this.isMounted()) { return; } var active = _domHelpersActiveElement2['default'](_utilsDomUtils2['default'].ownerDocument(this)); var modal = _reactDom2['default'].findDOMNode(this.refs.dialog); if (modal && modal !== active && !_domHelpersQueryContains2['default'](modal, active)) { modal.focus(); } }, _getStyles: function _getStyles() { if (!_domHelpersUtilInDOM2['default']) { return {}; } var node = _reactDom2['default'].findDOMNode(this.refs.modal); var scrollHt = node.scrollHeight; var container = getContainer(this); var containerIsOverflowing = this._containerIsOverflowing; var modalIsOverflowing = scrollHt > containerClientHeight(container, this); return { dialogStyles: { paddingRight: containerIsOverflowing && !modalIsOverflowing ? _domHelpersUtilScrollbarSize2['default']() : void 0, paddingLeft: !containerIsOverflowing && modalIsOverflowing ? _domHelpersUtilScrollbarSize2['default']() : void 0 } }; } }); Modal.Body = _ModalBody2['default']; Modal.Header = _ModalHeader2['default']; Modal.Title = _ModalTitle2['default']; Modal.Footer = _ModalFooter2['default']; Modal.Dialog = _ModalDialog2['default']; Modal.TRANSITION_DURATION = 300; Modal.BACKDROP_TRANSITION_DURATION = 150; exports['default'] = Modal; module.exports = exports['default'];
var S_ITER$0 = typeof Symbol!=='undefined'&&Symbol&&Symbol.iterator||'@@iterator';var S_MARK$0 = typeof Symbol!=='undefined'&&Symbol&&Symbol["__setObjectSetter__"];function ITER$0(v,f){if(v){if(Array.isArray(v))return f?v.slice():v;var i,r;if(S_MARK$0)S_MARK$0(v);if(typeof v==='object'&&typeof (f=v[S_ITER$0])==='function'){i=f.call(v);r=[];}else if((v+'')==='[object Generator]'){i=v;r=[];};if(S_MARK$0)S_MARK$0(void 0);if(r) {while((f=i['next']()),f['done']!==true)r.push(f['value']);return r;}}throw new Error(v+' is not iterable')}; { var i = 0; var a = []; var c = ["c"]; var b = [-2, -1, "|"].concat(ITER$0(( a.push(i++),a /*<*/), true), (new Array(2)), ["idx", 9, i, "-"], ITER$0((a.push(i++),a), true), ["idx", i, "-"], ITER$0((a.push(i++),a), true), ["idx", i, "-"], ITER$0(c), (new Array(3))); console.log( b.join("|") === [-2, -1, "|", 0, , , "idx", 9, 1, "-", 0, 1, "idx", 2, "-", 0, 1, 2, "idx", 3, "-", "c", , , , ].join("|") ) } { var a$0 = [1, 2, 3]; var b$0 = [0].concat(ITER$0(a$0, true), [4], ITER$0(a$0.reverse())); console.log( b$0.join("|") === [0, 1, 2, 3, 4, 3, 2, 1].join("|") ) } { var a$1 = [0, 1, 5, 6, 7, 8, 9]; console.log( a$1.join("|") === [0, 1, 5, 6, 7, 8, 9].join("|") ) } function testSequenceExpression(a, b, c, d) { console.log(a[0] === 1, a[1] === 2, a.length === 2, b === 3, c === 4, d[0] === 5, d.length === 1) } testSequenceExpression.apply(null, [([1, 2])].concat(ITER$0((1, 2, 3, [3, 4, [5]])))) function testVoidSequenceExpression(a, b, c) { console.log(a[0] === void 0, a.length === 1, b === void 0, c[0] === void 0, c.length === 0) } testVoidSequenceExpression.apply(null, [('ololo', [, ]), , ([ ])]) function testVoid(a, b, c) { console.log(a[0] === void 0, a.length === 1, b === void 0, c[0] === void 0, c.length === 0) } testVoid.apply(null, [[, ], , [ ]]) function test(a, b, c) { console.log(a === 1, b === 2, c.join() === "3") } test.apply(null, [1, 2,[3]]) test.apply(null, [1, 2, [3]]) test.apply(null, ITER$0(([9,8,7],[1,2,[3]]))) { var a$2 = [5, 6, 7]; var b$1 = ( function(a, b, c) {return [ a, b, c ]}).apply(null, ITER$0(a$2)) console.log(b$1.join("|") === [5, 6, 7].join("|")) } { var a$3 = [9, void 0, void 0, 6, 5, 4]; var b$2 = ( function() {var SLICE$0 = Array.prototype.slice;var a = arguments[0];if(a === void 0)a = 9;var b = arguments[1];if(b === void 0)b = 8;var c = arguments[2];if(c === void 0)c = 7;var rest = SLICE$0.call(arguments, 3);return [ a, b, c].concat(ITER$0(rest) )}).apply(null, ITER$0(a$3)) console.log(b$2.join("|") === [9, 8, 7, 6, 5, 4].join("|")) } { var b$3 = [2]; var a$4 = [1].concat(ITER$0(b$3)); console.log(a$4.join("|") === [1, 2].join("|")) }
import * as THREE from '../../build/three.module.js'; import { UIPanel, UIRow, UIHorizontalRule } from './libs/ui.js'; import { AddObjectCommand } from './commands/AddObjectCommand.js'; function MenubarAdd( editor ) { var strings = editor.strings; var container = new UIPanel(); container.setClass( 'menu' ); var title = new UIPanel(); title.setClass( 'title' ); title.setTextContent( strings.getKey( 'menubar/add' ) ); container.add( title ); var options = new UIPanel(); options.setClass( 'options' ); container.add( options ); // Group var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/group' ) ); option.onClick( function () { var mesh = new THREE.Group(); mesh.name = 'Group'; editor.execute( new AddObjectCommand( editor, mesh ) ); } ); options.add( option ); // options.add( new UIHorizontalRule() ); // Box var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/box' ) ); option.onClick( function () { var geometry = new THREE.BoxGeometry( 1, 1, 1, 1, 1, 1 ); var mesh = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial() ); mesh.name = 'Box'; editor.execute( new AddObjectCommand( editor, mesh ) ); } ); options.add( option ); // Circle var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/circle' ) ); option.onClick( function () { var geometry = new THREE.CircleGeometry( 1, 8, 0, Math.PI * 2 ); var mesh = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial() ); mesh.name = 'Circle'; editor.execute( new AddObjectCommand( editor, mesh ) ); } ); options.add( option ); // Cylinder var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/cylinder' ) ); option.onClick( function () { var geometry = new THREE.CylinderGeometry( 1, 1, 1, 8, 1, false, 0, Math.PI * 2 ); var mesh = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial() ); mesh.name = 'Cylinder'; editor.execute( new AddObjectCommand( editor, mesh ) ); } ); options.add( option ); // Dodecahedron var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/dodecahedron' ) ); option.onClick( function () { var geometry = new THREE.DodecahedronGeometry( 1, 0 ); var mesh = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial() ); mesh.name = 'Dodecahedron'; editor.execute( new AddObjectCommand( editor, mesh ) ); } ); options.add( option ); // Icosahedron var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/icosahedron' ) ); option.onClick( function () { var geometry = new THREE.IcosahedronGeometry( 1, 0 ); var mesh = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial() ); mesh.name = 'Icosahedron'; editor.execute( new AddObjectCommand( editor, mesh ) ); } ); options.add( option ); // Lathe var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/lathe' ) ); option.onClick( function () { var points = [ new THREE.Vector2( 0, 0 ), new THREE.Vector2( 0.4, 0 ), new THREE.Vector2( 0.35, 0.05 ), new THREE.Vector2( 0.1, 0.075 ), new THREE.Vector2( 0.08, 0.1 ), new THREE.Vector2( 0.08, 0.4 ), new THREE.Vector2( 0.1, 0.42 ), new THREE.Vector2( 0.14, 0.48 ), new THREE.Vector2( 0.2, 0.5 ), new THREE.Vector2( 0.25, 0.54 ), new THREE.Vector2( 0.3, 1.2 ) ]; var geometry = new THREE.LatheGeometry( points, 12, 0, Math.PI * 2 ); var mesh = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial( { side: THREE.DoubleSide } ) ); mesh.name = 'Lathe'; editor.execute( new AddObjectCommand( editor, mesh ) ); } ); options.add( option ); // Octahedron var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/octahedron' ) ); option.onClick( function () { var geometry = new THREE.OctahedronGeometry( 1, 0 ); var mesh = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial() ); mesh.name = 'Octahedron'; editor.execute( new AddObjectCommand( editor, mesh ) ); } ); options.add( option ); // Plane var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/plane' ) ); option.onClick( function () { var geometry = new THREE.PlaneGeometry( 1, 1, 1, 1 ); var material = new THREE.MeshStandardMaterial(); var mesh = new THREE.Mesh( geometry, material ); mesh.name = 'Plane'; editor.execute( new AddObjectCommand( editor, mesh ) ); } ); options.add( option ); // Ring var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/ring' ) ); option.onClick( function () { var geometry = new THREE.RingGeometry( 0.5, 1, 8, 1, 0, Math.PI * 2 ); var mesh = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial() ); mesh.name = 'Ring'; editor.execute( new AddObjectCommand( editor, mesh ) ); } ); options.add( option ); // Sphere var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/sphere' ) ); option.onClick( function () { var geometry = new THREE.SphereGeometry( 1, 8, 6, 0, Math.PI * 2, 0, Math.PI ); var mesh = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial() ); mesh.name = 'Sphere'; editor.execute( new AddObjectCommand( editor, mesh ) ); } ); options.add( option ); // Sprite var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/sprite' ) ); option.onClick( function () { var sprite = new THREE.Sprite( new THREE.SpriteMaterial() ); sprite.name = 'Sprite'; editor.execute( new AddObjectCommand( editor, sprite ) ); } ); options.add( option ); // Tetrahedron var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/tetrahedron' ) ); option.onClick( function () { var geometry = new THREE.TetrahedronGeometry( 1, 0 ); var mesh = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial() ); mesh.name = 'Tetrahedron'; editor.execute( new AddObjectCommand( editor, mesh ) ); } ); options.add( option ); // Torus var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/torus' ) ); option.onClick( function () { var geometry = new THREE.TorusGeometry( 1, 0.4, 8, 6, Math.PI * 2 ); var mesh = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial() ); mesh.name = 'Torus'; editor.execute( new AddObjectCommand( editor, mesh ) ); } ); options.add( option ); // TorusKnot var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/torusknot' ) ); option.onClick( function () { var geometry = new THREE.TorusKnotGeometry( 1, 0.4, 64, 8, 2, 3 ); var mesh = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial() ); mesh.name = 'TorusKnot'; editor.execute( new AddObjectCommand( editor, mesh ) ); } ); options.add( option ); // Tube var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/tube' ) ); option.onClick( function () { var path = new THREE.CatmullRomCurve3( [ new THREE.Vector3( 2, 2, - 2 ), new THREE.Vector3( 2, - 2, - 0.6666666666666667 ), new THREE.Vector3( - 2, - 2, 0.6666666666666667 ), new THREE.Vector3( - 2, 2, 2 ) ] ); var geometry = new THREE.TubeGeometry( path, 64, 1, 8, false ); var mesh = new THREE.Mesh( geometry, new THREE.MeshStandardMaterial() ); mesh.name = 'Tube'; editor.execute( new AddObjectCommand( editor, mesh ) ); } ); options.add( option ); /* // Teapot var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( 'Teapot' ); option.onClick( function () { var size = 50; var segments = 10; var bottom = true; var lid = true; var body = true; var fitLid = false; var blinnScale = true; var material = new THREE.MeshStandardMaterial(); var geometry = new TeapotGeometry( size, segments, bottom, lid, body, fitLid, blinnScale ); var mesh = new THREE.Mesh( geometry, material ); mesh.name = 'Teapot'; editor.addObject( mesh ); editor.select( mesh ); } ); options.add( option ); */ // options.add( new UIHorizontalRule() ); // AmbientLight var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/ambientlight' ) ); option.onClick( function () { var color = 0x222222; var light = new THREE.AmbientLight( color ); light.name = 'AmbientLight'; editor.execute( new AddObjectCommand( editor, light ) ); } ); options.add( option ); // DirectionalLight var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/directionallight' ) ); option.onClick( function () { var color = 0xffffff; var intensity = 1; var light = new THREE.DirectionalLight( color, intensity ); light.name = 'DirectionalLight'; light.target.name = 'DirectionalLight Target'; light.position.set( 5, 10, 7.5 ); editor.execute( new AddObjectCommand( editor, light ) ); } ); options.add( option ); // HemisphereLight var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/hemispherelight' ) ); option.onClick( function () { var skyColor = 0x00aaff; var groundColor = 0xffaa00; var intensity = 1; var light = new THREE.HemisphereLight( skyColor, groundColor, intensity ); light.name = 'HemisphereLight'; light.position.set( 0, 10, 0 ); editor.execute( new AddObjectCommand( editor, light ) ); } ); options.add( option ); // PointLight var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/pointlight' ) ); option.onClick( function () { var color = 0xffffff; var intensity = 1; var distance = 0; var light = new THREE.PointLight( color, intensity, distance ); light.name = 'PointLight'; editor.execute( new AddObjectCommand( editor, light ) ); } ); options.add( option ); // SpotLight var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/spotlight' ) ); option.onClick( function () { var color = 0xffffff; var intensity = 1; var distance = 0; var angle = Math.PI * 0.1; var penumbra = 0; var light = new THREE.SpotLight( color, intensity, distance, angle, penumbra ); light.name = 'SpotLight'; light.target.name = 'SpotLight Target'; light.position.set( 5, 10, 7.5 ); editor.execute( new AddObjectCommand( editor, light ) ); } ); options.add( option ); // options.add( new UIHorizontalRule() ); // OrthographicCamera var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/orthographiccamera' ) ); option.onClick( function () { var aspect = editor.camera.aspect; var camera = new THREE.OrthographicCamera( - aspect, aspect ); camera.name = 'OrthographicCamera'; editor.execute( new AddObjectCommand( editor, camera ) ); } ); options.add( option ); // PerspectiveCamera var option = new UIRow(); option.setClass( 'option' ); option.setTextContent( strings.getKey( 'menubar/add/perspectivecamera' ) ); option.onClick( function () { var camera = new THREE.PerspectiveCamera(); camera.name = 'PerspectiveCamera'; editor.execute( new AddObjectCommand( editor, camera ) ); } ); options.add( option ); return container; } export { MenubarAdd };
'use strict'; /* jshint -W110 */ var Support = require(__dirname + '/../support') , DataTypes = require(__dirname + '/../../../lib/data-types') , util = require('util') , expectsql = Support.expectsql , current = Support.sequelize , sql = current.dialect.QueryGenerator; // Notice: [] will be replaced by dialect specific tick/quote character when there is not dialect specific expectation but only a default expectation suite(Support.getTestDialectTeaser('SQL'), function() { suite('whereQuery', function () { var testsql = function (params, options, expectation) { if (expectation === undefined) { expectation = options; options = undefined; } test(util.inspect(params, {depth: 10})+(options && ', '+util.inspect(options) || ''), function () { return expectsql(sql.whereQuery(params, options), expectation); }); }; testsql({}, { default: '' }); testsql([], { default: '' }); testsql({id: 1}, { default: 'WHERE [id] = 1' }); testsql({id: 1}, {prefix: 'User'}, { default: 'WHERE [User].[id] = 1' }); test("{ id: 1 }, { prefix: current.literal(sql.quoteTable.call(current.dialect.QueryGenerator, {schema: 'yolo', tableName: 'User'})) }", function () { expectsql(sql.whereQuery({id: 1}, {prefix: current.literal(sql.quoteTable.call(current.dialect.QueryGenerator, {schema: 'yolo', tableName: 'User'}))}), { default: 'WHERE [yolo.User].[id] = 1', postgres: 'WHERE "yolo"."User"."id" = 1', mssql: 'WHERE [yolo].[User].[id] = 1', oracle: 'WHERE "yolo"."User"."id" = 1' }); }); testsql({ name: 'a project', $or: [ { id: [1,2,3] }, { id: { $gt: 10 } } ] }, { default: "WHERE [name] = 'a project' AND ([id] IN (1, 2, 3) OR [id] > 10)" }); testsql({ name: 'a project', id: { $or: [ [1,2,3], { $gt: 10 } ] } }, { default: "WHERE [name] = 'a project' AND ([id] IN (1, 2, 3) OR [id] > 10)" }); }); suite('whereItemQuery', function () { var testsql = function (key, value, options, expectation) { if (expectation === undefined) { expectation = options; options = undefined; } test(key+': '+util.inspect(value, {depth: 10})+(options && ', '+util.inspect(options) || ''), function () { return expectsql(sql.whereItemQuery(key, value, options), expectation); }); }; testsql(undefined, 'lol=1', { default: 'lol=1' }); testsql('deleted', null, { default: '`deleted` IS NULL', postgres: '"deleted" IS NULL', mssql: '[deleted] IS NULL', oracle: '"deleted" IS NULL', }); suite('$in', function () { testsql('equipment', { $in: [1, 3] }, { default: '[equipment] IN (1, 3)' }); testsql('equipment', { $in: [] }, { default: '[equipment] IN (NULL)' }); testsql('muscles', { in: [2, 4] }, { default: '[muscles] IN (2, 4)' }); testsql('equipment', { $in: current.literal( '(select order_id from product_orders where product_id = 3)' ) }, { default: '[equipment] IN (select order_id from product_orders where product_id = 3)' }); }); if(current.dialect.supports.BUFFER !== false) { suite('Buffer', function () { testsql('field', new Buffer('Sequelize'), { postgres: '"field" = E\'\\\\x53657175656c697a65\'', sqlite: "`field` = X'53657175656c697a65'", mysql: "`field` = X'53657175656c697a65'", mssql: '[field] = 0x53657175656c697a65' }); }); } suite('$not', function () { testsql('deleted', { $not: true }, { default: '[deleted] IS NOT true', mssql: "[deleted] IS NOT 'true'", sqlite: '`deleted` IS NOT 1', oracle: '"deleted" IS NOT 1' }); testsql('deleted', { $not: null }, { default: '[deleted] IS NOT NULL' }); testsql('muscles', { $not: 3 }, { default: '[muscles] != 3' }); }); suite('$notIn', function () { testsql('equipment', { $notIn: [] }, { default: '[equipment] NOT IN (NULL)' }); testsql('equipment', { $notIn: [4, 19] }, { default: '[equipment] NOT IN (4, 19)' }); testsql('equipment', { $notIn: current.literal( '(select order_id from product_orders where product_id = 3)' ) }, { default: '[equipment] NOT IN (select order_id from product_orders where product_id = 3)' }); }); suite('$ne', function () { testsql('email', { $ne: 'jack.bauer@gmail.com' }, { default: "[email] != 'jack.bauer@gmail.com'" }); }); suite('$and/$or/$not', function () { suite('$or', function () { testsql('email', { $or: ['maker@mhansen.io', 'janzeh@gmail.com'] }, { default: '([email] = \'maker@mhansen.io\' OR [email] = \'janzeh@gmail.com\')' }); testsql('rank', { $or: { $lt: 100, $eq: null } }, { default: '([rank] < 100 OR [rank] IS NULL)' }); testsql('$or', [ {email: 'maker@mhansen.io'}, {email: 'janzeh@gmail.com'} ], { default: '([email] = \'maker@mhansen.io\' OR [email] = \'janzeh@gmail.com\')' }); testsql('$or', { email: 'maker@mhansen.io', name: 'Mick Hansen' }, { default: '([email] = \'maker@mhansen.io\' OR [name] = \'Mick Hansen\')' }); testsql('$or', { equipment: [1, 3], muscles: { $in: [2, 4] } }, { default: '([equipment] IN (1, 3) OR [muscles] IN (2, 4))' }); testsql('$or', [ { roleName: 'NEW' }, { roleName: 'CLIENT', type: 'CLIENT' } ], { default: "([roleName] = 'NEW' OR ([roleName] = 'CLIENT' AND [type] = 'CLIENT'))" }); test('sequelize.or({group_id: 1}, {user_id: 2})', function () { expectsql(sql.whereItemQuery(undefined, this.sequelize.or({group_id: 1}, {user_id: 2})), { default: '([group_id] = 1 OR [user_id] = 2)' }); }); test("sequelize.or({group_id: 1}, {user_id: 2, role: 'admin'})", function () { expectsql(sql.whereItemQuery(undefined, this.sequelize.or({group_id: 1}, {user_id: 2, role: 'admin'})), { default: "([group_id] = 1 OR ([user_id] = 2 AND [role] = 'admin'))" }); }); }); suite('$and', function () { testsql('$and', { shared: 1, $or: { group_id: 1, user_id: 2 } }, { default: "([shared] = 1 AND ([group_id] = 1 OR [user_id] = 2))" }); testsql('$and', [ { name: { $like: '%hello' } }, { name: { $like: 'hello%' } } ], { default: "([name] LIKE '%hello' AND [name] LIKE 'hello%')" }); testsql('rank', { $and: { $ne: 15, $between: [10, 20] } }, { default: '([rank] != 15 AND [rank] BETWEEN 10 AND 20)' }); testsql('name', { $and: [ {like : '%someValue1%'}, {like : '%someValue2%'} ] }, { default: "([name] LIKE '%someValue1%' AND [name] LIKE '%someValue2%')" }); test('sequelize.and({shared: 1, sequelize.or({group_id: 1}, {user_id: 2}))', function () { expectsql(sql.whereItemQuery(undefined, this.sequelize.and({shared: 1}, this.sequelize.or({group_id: 1}, {user_id: 2}))), { default: '([shared] = 1 AND ([group_id] = 1 OR [user_id] = 2))' }); }); }); suite('$not', function () { testsql('$not', { shared: 1, $or: { group_id: 1, user_id: 2 } }, { default: 'NOT ([shared] = 1 AND ([group_id] = 1 OR [user_id] = 2))' }); }); }); suite('$gt', function () { testsql('rank', { $gt: 2 }, { default: '[rank] > 2' }); }); suite('$like', function () { testsql('username', { $like: '%swagger' }, { default: "[username] LIKE '%swagger'" }); }); suite('$between', function () { testsql('date', { $between: ['2013-01-01', '2013-01-11'] }, { default: "[date] BETWEEN '2013-01-01' AND '2013-01-11'" }); testsql('date', { between: ['2012-12-10', '2013-01-02'], nbetween: ['2013-01-04', '2013-01-20'] }, { default: "([date] BETWEEN '2012-12-10' AND '2013-01-02' AND [date] NOT BETWEEN '2013-01-04' AND '2013-01-20')" }); }); suite('$notBetween', function () { testsql('date', { $notBetween: ['2013-01-01', '2013-01-11'] }, { default: "[date] NOT BETWEEN '2013-01-01' AND '2013-01-11'" }); }); if (current.dialect.supports.ARRAY) { suite('ARRAY', function () { suite('$contains', function () { testsql('muscles', { $contains: [2, 3] }, { postgres: '"muscles" @> ARRAY[2,3]' }); testsql('muscles', { $contained: [6, 8] }, { postgres: '"muscles" <@ ARRAY[6,8]' }); testsql('muscles', { $contains: [2, 5] }, { field: { type: DataTypes.ARRAY(DataTypes.INTEGER) } }, { postgres: '"muscles" @> ARRAY[2,5]::INTEGER[]' }); }); suite('$overlap', function () { testsql('muscles', { $overlap: [3, 11] }, { postgres: '"muscles" && ARRAY[3,11]' }); testsql('muscles', { $overlap: [3, 1] }, { postgres: '"muscles" && ARRAY[3,1]' }); testsql('muscles', { '&&': [9, 182] }, { postgres: '"muscles" && ARRAY[9,182]' }); }); suite('$any', function() { testsql('userId', { $any: [4, 5, 6] }, { postgres: '"userId" = ANY (ARRAY[4,5,6])' }); testsql('userId', { $any: [2, 5] }, { field: { type: DataTypes.ARRAY(DataTypes.INTEGER) } }, { postgres: '"userId" = ANY (ARRAY[2,5]::INTEGER[])' }); suite('$values', function () { testsql('userId', { $any: { $values: [4, 5, 6] } }, { postgres: '"userId" = ANY (VALUES (4), (5), (6))' }); testsql('userId', { $any: { $values: [2, 5] } }, { field: { type: DataTypes.ARRAY(DataTypes.INTEGER) } }, { postgres: '"userId" = ANY (VALUES (2), (5))' }); }); }); suite('$all', function() { testsql('userId', { $all: [4, 5, 6] }, { postgres: '"userId" = ALL (ARRAY[4,5,6])' }); testsql('userId', { $all: [2, 5] }, { field: { type: DataTypes.ARRAY(DataTypes.INTEGER) } }, { postgres: '"userId" = ALL (ARRAY[2,5]::INTEGER[])' }); suite('$values', function () { testsql('userId', { $all: { $values: [4, 5, 6] } }, { postgres: '"userId" = ALL (VALUES (4), (5), (6))' }); testsql('userId', { $all: { $values: [2, 5] } }, { field: { type: DataTypes.ARRAY(DataTypes.INTEGER) } }, { postgres: '"userId" = ALL (VALUES (2), (5))' }); }); }); suite('$like', function() { testsql('userId', { $like: { $any: ['foo', 'bar', 'baz'] } }, { postgres: "\"userId\" LIKE ANY ARRAY['foo','bar','baz']" }); testsql('userId', { $iLike: { $any: ['foo', 'bar', 'baz'] } }, { postgres: "\"userId\" ILIKE ANY ARRAY['foo','bar','baz']" }); testsql('userId', { $notLike: { $any: ['foo', 'bar', 'baz'] } }, { postgres: "\"userId\" NOT LIKE ANY ARRAY['foo','bar','baz']" }); testsql('userId', { $notILike: { $any: ['foo', 'bar', 'baz'] } }, { postgres: "\"userId\" NOT ILIKE ANY ARRAY['foo','bar','baz']" }); }); }); } if (current.dialect.supports.JSON) { suite('JSON', function () { test('sequelize.json("profile->>\'id\', sequelize.cast(2, \'text\')")', function () { expectsql(sql.whereItemQuery(undefined, this.sequelize.json("profile->>'id'", this.sequelize.cast('12346-78912', 'text'))), { postgres: "profile->>'id' = CAST('12346-78912' AS TEXT)" }); }); testsql('data', { nested: { attribute: 'value' } }, { field: { type: new DataTypes.JSONB() }, prefix: 'User' }, { default: "([User].[data]#>>'{nested, attribute}') = 'value'" }); testsql('data', { nested: { attribute: 'value', prop: { $ne: 'None' } } }, { field: { type: new DataTypes.JSONB() }, prefix: 'User' }, { default: "(([User].[data]#>>'{nested, attribute}') = 'value' AND ([User].[data]#>>'{nested, prop}') != 'None')" }); testsql('data', { name: { last: 'Simpson' }, employment: { $ne: 'None' } }, { field: { type: new DataTypes.JSONB() }, prefix: 'User' }, { default: "(([User].[data]#>>'{name, last}') = 'Simpson' AND ([User].[data]#>>'{employment}') != 'None')" }); testsql('data.nested.attribute', 'value', { model: { rawAttributes: { data: { type: new DataTypes.JSONB() } } } }, { default: "([data]#>>'{nested, attribute}') = 'value'" }); testsql('data.nested.attribute', { $in: [3, 7] }, { model: { rawAttributes: { data: { type: new DataTypes.JSONB() } } } }, { default: "([data]#>>'{nested, attribute}') IN (3, 7)" }); testsql('data', { nested: { attribute: { $gt: 2 } } }, { field: { type: new DataTypes.JSONB() } }, { default: "([data]#>>'{nested, attribute}')::double precision > 2" }); testsql('data', { nested: { "attribute::integer": { $gt: 2 } } }, { field: { type: new DataTypes.JSONB() } }, { default: "([data]#>>'{nested, attribute}')::integer > 2" }); var dt = new Date(); testsql('data', { nested: { attribute: { $gt: dt } } }, { field: { type: new DataTypes.JSONB() } }, { default: "([data]#>>'{nested, attribute}')::timestamptz > "+sql.escape(dt) }); testsql('data', { $contains: { company: 'Magnafone' } }, { field: { type: new DataTypes.JSONB() } }, { default: '[data] @> \'{"company":"Magnafone"}\'' }); }); } suite('fn', function () { test('{name: this.sequelize.fn(\'LOWER\', \'DERP\')}', function () { expectsql(sql.whereQuery({name: this.sequelize.fn('LOWER', 'DERP')}), { default: "WHERE [name] = LOWER('DERP')" }); }); }); }); });
/*global define*/ /*jslint white:true,browser:true*/ define([ 'jquery', 'bluebird', 'kb_common/html', '../validation', 'common/events', 'common/runtime', 'common/ui', 'common/props', 'base/js/namespace', '../subdataMethods/manager', 'bootstrap', 'css!font-awesome' ], function( $, Promise, html, Validation, Events, Runtime, UI, Props, Jupyter, SubdataMethods ) { 'use strict'; /* * spec * textsubdata_options * allow_custom: 0/1 * multiselection: 0/1 * placholder: text * show_src_obj: 0/1 * subdata_selection: * parameter_id: string * path_to_subdata: array<string> * selection_id: string * subdata_included: array<string> * */ // Constants var t = html.tag, div = t('div'), p = t('p'), span = t('span'), input = t('input'), option = t('option'), button = t('button'); function factory(config) { var spec = config.parameterSpec, appSpec = config.appSpec, runtime = Runtime.make(), workspaceId = runtime.getEnv('workspaceId'), busConnection = runtime.bus().connect(), channel = busConnection.channel(config.channelName), parent, container, model, subdataMethods, isAvailableValuesInitialized = false, options = { objectSelectionPageSize: 20 }, ui; subdataMethods = SubdataMethods.make(); function buildOptions() { var availableValues = model.getItem('availableValues'), value = model.getItem('value') || [], selectOptions = [option({ value: '' }, '')]; if (!availableValues) { return selectOptions; } return selectOptions.concat(availableValues.map(function(availableValue) { var selected = false, optionLabel = availableValue.id, optionValue = availableValue.id; // TODO: pull the value out of the object if (value.indexOf(availableValue.id) >= 0) { selected = true; } return option({ value: optionValue, selected: selected }, optionLabel); })); } function buildCount() { var availableValues = model.getItem('availableValues') || [], value = model.getItem('value') || []; return String(value.length) + ' / ' + String(availableValues.length) + ' items'; } function filterItems(items, filter) { if (!filter) { return items; } var re = new RegExp(filter); return items.filter(function(item) { if (item.text && item.text.match(re, 'i')) { return true; } return false; }); } function doFilterItems() { var items = model.getItem('availableValues', []), filteredItems = filterItems(items, model.getItem('filter')); // for now we just reset the from/to range to the beginning. model.setItem('filteredAvailableItems', filteredItems); doFirstPage(); } function didChange() { validate() .then(function(result) { if (result.isValid) { model.setItem('value', result.value); updateInputControl('value'); channel.emit('changed', { newValue: result.value }); } else if (result.diagnosis === 'required-missing') { model.setItem('value', result.value); updateInputControl('value'); channel.emit('changed', { newValue: result.value }); } channel.emit('validation', { errorMessage: result.errorMessage, diagnosis: result.diagnosis }); }); } function doAddItem(itemId) { var selectedItems = model.getItem('selectedItems', []); selectedItems.push(itemId); model.setItem('selectedItems', selectedItems); didChange(); } function doRemoveSelectedItem(indexOfitemToRemove) { var selectedItems = model.getItem('selectedItems', []), prevAllowSelection = spec.ui.multiSelection || selectedItems.length === 0; selectedItems.splice(indexOfitemToRemove, 1); var newAllowSelection = spec.ui.multiSelection || selectedItems.length === 0; if (newAllowSelection && !prevAllowSelection) { // update text areas to have md-col-7 (from md-col-10) $(ui.getElement('input-container')).find('.row > .col-md-10').switchClass('col-md-10', 'col-md-7'); $(ui.getElement('input-container')).find('.col-md-3.hidden').removeClass('hidden'); // update button areas to remove hidden class } model.setItem('selectedItems', selectedItems); didChange(); } function doRemoveSelectedAvailableItem(idToRemove) { var selectedItems = model.getItem('selectedItems', []); model.setItem('selectedItems', selectedItems.filter(function(id) { if (idToRemove === id) { return false; } return true; })); didChange(); } function renderAvailableItems() { var selected = model.getItem('selectedItems', []), allowSelection = (spec.ui.multiSelection || selected.length === 0), items = model.getItem('filteredAvailableItems', []), from = model.getItem('showFrom'), to = model.getItem('showTo'), itemsToShow = items.slice(from, to), events = Events.make({ node: container }), content; if (itemsToShow.length === 0) { content = div({ style: { textAlign: 'center' } }, 'no available values'); } else { content = itemsToShow.map(function(item, index) { var isSelected = selected.some(function(id) { return (item.id === id); }), disabled = isSelected; return div({ class: 'row', style: { border: '1px #CCC solid' } }, [ div({ class: 'col-md-2', style: { verticalAlign: 'middle', borderRadius: '3px', padding: '2px', backgroundColor: '#EEE', color: '#444', textAlign: 'right', paddingRight: '6px', fontFamily: 'monospace' } }, String(from + index + 1)), div({ class: 'col-md-8', style: { padding: '2px' } }, item.text), div({ class: 'col-md-2', style: { padding: '2px', textAlign: 'right', verticalAlign: 'top' } }, [ (function() { if (disabled) { return span({ class: 'kb-btn-icon', type: 'button', dataToggle: 'tooltip', title: 'Remove from selected', id: events.addEvent({ type: 'click', handler: function() { doRemoveSelectedAvailableItem(item.id); } }) }, [ span({ class: 'fa fa-minus-circle', style: { color: 'red', fontSize: '200%' } }) ]); } if (allowSelection) { return span({ class: 'kb-btn-icon', type: 'button', dataToggle: 'tooltip', title: 'Add to selected', dataItemId: item.id, id: events.addEvent({ type: 'click', handler: function() { doAddItem(item.id); } }) }, [span({ class: 'fa fa-plus-circle', style: { color: 'green', fontSize: '200%' } })]); } return span({ class: 'kb-btn-icon', type: 'button', dataToggle: 'tooltip', title: 'Can\'t add - remove one first', dataItemId: item.id }, span({ class: 'fa fa-ban', style: { color: 'silver', fontSize: '200%' } })); }()) ]) ]); }) .join('\n'); } ui.setContent('available-items', content); events.attachEvents(); ui.enableTooltips('available-items'); } function renderSelectedItems() { var selectedItems = model.getItem('selectedItems', []), valuesMap = model.getItem('availableValuesMap', {}), events = Events.make({ node: container }), content; if (selectedItems.length === 0) { content = div({ style: { textAlign: 'center' } }, 'no selected values'); } else { content = selectedItems.map(function(itemId, index) { var item = valuesMap[itemId]; if (item === undefined || item === null) { item = { text: itemId }; } return div({ class: 'row', style: { border: '1px #CCC solid', borderCollapse: 'collapse', boxSizing: 'border-box' } }, [ div({ class: 'col-md-2', style: { verticalAlign: 'middle', borderRadius: '3px', padding: '2px', backgroundColor: '#EEE', color: '#444', textAlign: 'right', paddingRight: '6px', fontFamily: 'monospace' } }, String(index + 1)), div({ class: 'col-md-8', style: { xdisplay: 'inline-block', xwidth: '90%', padding: '2px' } }, item.text), div({ class: 'col-md-2', style: { padding: '2px', textAlign: 'right', verticalAlign: 'top' } }, [ span({ class: 'kb-btn-icon', type: 'button', dataToggle: 'tooltip', title: 'Remove from selected' }, span({ class: 'fa fa-minus-circle', style: { color: 'red', fontSize: '200%' } })) ]) ]); }).join('\n'); } ui.setContent('selected-items', content); events.attachEvents(); ui.enableTooltips('selected-items'); } function renderSearchBox() { var items = model.getItem('availableValues', []), events = Events.make({ node: container }), content; //if (items.length === 0) { // content = ''; //} else { content = input({ class: 'form-contol', style: { xwidth: '100%' }, placeholder: 'search', value: model.getItem('filter') || '', id: events.addEvents({ events: [{ type: 'keyup', handler: function(e) { doSearchKeyUp(e); } }, { type: 'focus', handler: function() { Jupyter.narrative.disableKeyboardManager(); } }, { type: 'blur', handler: function() { console.log('SingleSubData Search BLUR'); // Jupyter.narrative.enableKeyboardManager(); } }, { type: 'click', handler: function() { Jupyter.narrative.disableKeyboardManager(); } } ] }) }); //} ui.setContent('search-box', content); events.attachEvents(); } function renderStats() { var availableItems = model.getItem('availableValues', []), filteredItems = model.getItem('filteredAvailableItems', []), content; if (availableItems.length === 0) { content = span({ style: { fontStyle: 'italic' } }, [ ' - no available items' ]); } else { content = span({ style: { fontStyle: 'italic' } }, [ ' - filtering ', span([ String(filteredItems.length), ' of ', String(availableItems.length) ]) ]); } ui.setContent('stats', content); } function renderToolbar() { var items = model.getItem('filteredAvailableItems', []), events = Events.make({ node: container }), content; if (items.length === 0) { content = ''; } else { content = div([ button({ type: 'button', class: 'btn btn-default', style: { xwidth: '100%' }, id: events.addEvent({ type: 'click', handler: function() { doFirstPage(); } }) }, ui.buildIcon({ name: 'step-forward', rotate: 270 })), button({ class: 'btn btn-default', type: 'button', style: { xwidth: '50%' }, id: events.addEvent({ type: 'click', handler: function() { doPreviousPage(); } }) }, ui.buildIcon({ name: 'caret-up' })), button({ class: 'btn btn-default', type: 'button', style: { xwidth: '100%' }, id: events.addEvent({ type: 'click', handler: function() { doNextPage(); } }) }, ui.buildIcon({ name: 'caret-down' })), button({ type: 'button', class: 'btn btn-default', style: { xwidth: '100%' }, id: events.addEvent({ type: 'click', handler: function() { doLastPage(); } }) }, ui.buildIcon({ name: 'step-forward', rotate: 90 })) ]); } ui.setContent('toolbar', content); events.attachEvents(); } function setPageStart(newFrom) { var from = model.getItem('showFrom'), to = model.getItem('to'), newTo, total = model.getItem('filteredAvailableItems', []).length, pageSize = 5; if (newFrom <= 0) { newFrom = 0; } else if (newFrom >= total) { newFrom = total - pageSize; if (newFrom < 0) { newFrom = 0; } } if (newFrom !== from) { model.setItem('showFrom', newFrom); } newTo = newFrom + pageSize; if (newTo >= total) { newTo = total; } if (newTo !== to) { model.setItem('showTo', newTo); } } function movePageStart(diff) { setPageStart(model.getItem('showFrom') + diff); } function doPreviousPage() { movePageStart(-5); } function doNextPage() { movePageStart(5); } function doFirstPage() { setPageStart(0); } function doLastPage() { setPageStart(model.getItem('filteredAvailableItems').length); } function doSearchKeyUp(e) { if (e.target.value.length > 2) { model.setItem('filter', e.target.value); doFilterItems(); } else { if (model.getItem('filter')) { model.setItem('filter', null); doFilterItems(); } } } function makeInputControl(events) { // There is an input control, and a dropdown, // TODO select2 after we get a handle on this... var availableValues = model.getItem('availableValues'); if (!availableValues) { return p({ class: 'form-control-static', style: { fontStyle: 'italic', whiteSpace: 'normal', padding: '3px', border: '1px silver solid' } }, 'Items will be available after selecting a value for ' + spec.data.constraints.subdataSelection.parameter_id); } return div([ ui.buildCollapsiblePanel({ title: span(['Available Items', span({ dataElement: 'stats' })]), classes: ['kb-panel-light'], body: div({ dataElement: 'available-items-area', style: { marginTop: '10px' } }, [ div({ class: 'row' }, [ div({ class: 'col-md-6' }, [ span({ dataElement: 'search-box' }) ]), div({ class: 'col-md-6', style: { textAlign: 'right' }, dataElement: 'toolbar' }) ]), div({ class: 'row', style: { marginTop: '4px' } }, [ div({ class: 'col-md-12' }, div({ style: { border: '1px silver solid' }, dataElement: 'available-items' })) ]) ]) }), ui.buildPanel({ title: 'Selected Items', classes: ['kb-panel-light'], body: div({ style: { border: '1px silver solid' }, dataElement: 'selected-items' }) }) ]); } /* * Given an existing input control, and new model state, update the * control to suite the new data. * Cases: * * - change in source data - fetch new data, populate available values, * reset selected values, remove existing options, add new options. * * - change in selected items - remove all selections, add new selections * */ function updateInputControl(changedProperty) { switch (changedProperty) { case 'value': // just change the selections. var count = buildCount(); ui.setContent('input-control.count', count); break; case 'availableValues': // rebuild the options // re-apply the selections from the value var options = buildOptions(); ui.setContent('input-control.input', options); ui.setContent('input-control.count', count); break; case 'referenceObjectName': // refetch the available values // set available values // update input control for available values // set value to null } } /* * If the parameter is optional, and is empty, return null. * If it allows multiple values, wrap single results in an array * There is a weird twist where if it ... * well, hmm, the only consumer of this, isValid, expects the values * to mirror the input rows, so we shouldn't really filter out any * values. */ function getInputValue() { // var control = ui.getElement('input-container.input'); // if (!control) { // return null; // } // var input = control.selectedOptions, // i, values = []; // for (i = 0; i < input.length; i += 1) { // values.push(input.item(i).value); // } // // cute ... allows selecting multiple values but does not expect a sequence... // return values; return model.getItem('selectedItems'); } function resetModelValue() { model.reset(); model.setItem('value', spec.defaultValue); } function validate() { return Promise.try(function() { var rawValue = getInputValue(), validationOptions = { required: spec.data.constraints.required }; return Validation.validateStringSet(rawValue, validationOptions); }) } var subdataInfo = subdataMethods.getSubdataInfo(appSpec, spec); function fetchData() { var referenceObjectName = model.getItem('referenceObjectName'), referenceObjectRef = workspaceId + '/' + referenceObjectName, params = model.getItem('required-params'); if (!referenceObjectName) { return; } return subdataMethods.customFetchData({ referenceObjectRef: referenceObjectRef, params: params, getRef: subdataInfo.getRef, included: subdataInfo.included, extractItems: subdataInfo.extractItems }); } function fetchDatax() { var referenceObjectName = model.getItem('referenceObjectName'), referenceObjectRef = spec.data.constraints.subdataSelection.constant_ref; if (!referenceObjectRef) { if (!referenceObjectName) { return []; } referenceObjectRef = workspaceId + '/' + referenceObjectName; } return subdataMethods.fetchData({ referenceObjectRef: referenceObjectRef, spec: spec }); } function syncAvailableValues() { return Promise.try(function() { return fetchData(); }) .then(function(data) { if (!data) { return ' no data? '; } // If default values have been provided, prepend them to the data. // We use the raw default values here since we are not really using // it as the default value, but as a set of additional items // to select. var defaultValues = spec.defaultValue; if (defaultValues && (defaultValues instanceof Array) && (defaultValues.length > 0)) { defaultValues.forEach(function(itemId) { if (itemId && itemId.trim().length > 0) { data.unshift({ id: itemId, text: itemId }); } }); } // The data represents the total available subdata, with all // necessary fields for display. We build from that three // additional structures // - a map of id to object // - a set of available ids // - a set of selected ids // - a set of filtered ids model.setItem('availableValues', data); isAvailableValuesInitialized = true; // TODO: generate all of this in the fetchData -- it will be a bit faster. var map = {}; data.forEach(function(datum) { map[datum.id] = datum; }); //var availableIds = data.map(function (datum) { // return datum.id; //}); model.setItem('availableValuesMap', map); doFilterItems(); }); } function autoValidate() { return validate() .then(function(result) { channel.emit('validation', { errorMessage: result.errorMessage, diagnosis: result.diagnosis }); }); } /* * Creates the markup * Places it into the ui node * Hooks up event listeners */ function render() { return Promise.try(function() { // check to see if we have to render inputControl. var events = Events.make({ node: container }), inputControl = makeInputControl(events), content = div({ class: 'input-group', style: { width: '100%' } }, inputControl); ui.setContent('input-container', content); renderSearchBox(); renderStats(); renderToolbar(); renderAvailableItems(); renderSelectedItems(); events.attachEvents(); }) .then(function() { return autoValidate(); }) .catch(function(err) { console.error('ERROR in render', err); }); } /* * In the layout we set up an environment in which one or more parameter * rows may be inserted. * For the objectInput, there is only ever one control. */ function layout(events) { var content = div({ dataElement: 'main-panel' }, [ div({ dataElement: 'input-container' }) ]); return { content: content, events: events }; } function updateParam(paramId, value) { var newValue; if (value === '') { newValue = null; } else { newValue = value; } if (newValue === model.getItem(['required-params', paramId])) { return; } model.setItem('value', []); model.setItem(['required-params', paramId], newValue); // If any of the required parameters are missing, we need to reset the // primary value. // TODO: we need to get this via the message bus!!! if (subdataInfo.params.dependencies.some(function(paramId) { return (model.getItem(['required-params', paramId], null) === null); })) { resetModelValue(); } // If we have a change in the primary reference object, we need to // resync the values derived from it (available values). if (paramId === subdataInfo.params.referenceObject) { model.setItem('referenceObjectName', newValue); return syncAvailableValues(); } } function registerEvents() { /* * Issued when thre is a need to have all params reset to their * default value. */ channel.on('reset-to-defaults', function(message) { resetModelValue(); // model.reset(); // TODO: this should really be set when the linked field is reset... model.setItem('availableValues', []); model.setItem('referenceObjectName', null); doFilterItems(); renderSearchBox(); renderStats(); renderToolbar(); renderAvailableItems(); renderSelectedItems(); // updateInputControl('availableValues'); // updateInputControl('value'); }); /* * Issued when there is an update for this param. */ channel.on('update', function(message) { model.setItem('value', message.value); updateInputControl('value'); }); /* * Called when for an update to any param. This is necessary for * any parameter which has a dependency upon any other. * */ // channel.listen({ // key: { // type: 'parameter-changed', // parameter: spec.data.constraints.subdataSelection.constant_ref // }, // handle: function(message) { // var newValue = message.newValue; // if (message.newValue === '') { // newValue = null; // } // // reset the entire model. // model.reset(); // model.setItem('referenceObjectName', newValue); // syncAvailableValues() // .then(function() { // updateInputControl('availableValues'); // }) // .catch(function(err) { // console.error('ERROR syncing available values', err); // }); // } // }); if (subdataInfo.params.dependencies) { subdataInfo.params.dependencies.forEach(function(paramId) { channel.listen({ key: { type: 'parameter-changed', parameter: paramId }, handle: function(message) { updateParam(paramId, message.newValue); } }); channel.listen({ key: { type: 'parameter-value', parameter: paramId }, handle: function(message) { updateParam(paramId, message.newValue); } }); channel.request({ parameterName: paramId }, { key: { type: 'get-parameter' } }) .then(function(message) { updateParam(paramId, message.value); }) .catch(function(err) { console.error('ERROR getting parameter', err); }); }); } // channel.listen({ // key: { // type: 'parameter-changed', // parameter: spec.data.constraints.subdataSelection.parameter_id // }, // handle: function(message) { // var newValue = message.newValue; // if (message.newValue === '') { // newValue = null; // } // // reset the entire model. // model.reset(); // model.setItem('referenceObjectName', newValue); // syncAvailableValues() // .then(function() { // updateInputControl('availableValues'); // }) // .catch(function(err) { // console.error('ERROR syncing available values', err); // }); // } // }); // channel.listen({ // key: { // type: 'parameter-value', // parameter: spec.data.constraints.subdataSelection.parameter_id // }, // handle: function(message) { // var newValue = message.newValue; // if (message.newValue === '') { // newValue = null; // } // model.reset(); // model.setItem('referenceObjectName', newValue); // syncAvailableValues() // .then(function() { // updateInputControl('availableValues'); // }) // .catch(function(err) { // console.error('ERROR syncing available values', err); // }); // } // }); // This control has a dependency relationship in that its // selection of available values is dependent upon a sub-property // of an object referenced by another parameter. // Rather than explicitly refer to that parameter, we have a // generic capability to receive updates for that value, after // which we re-fetch the values, and re-render the control. // bus.on('update-reference-object', function (message) { // model.setItem('referenceObjectName', value) // setReferenceValue(message.objectRef); // }); // channel.emit('sync'); channel.request({ parameterName: spec.id }, { key: { type: 'get-parameter' } }) .then(function(message) { // console.log('Now i got it again', message); }); } // MODIFICATION EVENTS /* * More refinement of modifications. * * - initial run * - reference data updated * - added "reset" method to props (model) to allow graceful zapping * of the model state. * - item added to selected * - item removed from selected * - search term available * - search term removed * - filtered data updated * */ // LIFECYCLE API function start(arg) { return Promise.try(function() { parent = arg.node; container = parent.appendChild(document.createElement('div')); ui = UI.make({ node: container }); var events = Events.make(), theLayout = layout(events); container.innerHTML = theLayout.content; if (config.initialValue) { model.setItem('selectedItems', config.initialValue); } render(); events.attachEvents(container); registerEvents(); channel.emit('sync-params', { parameters: subdataInfo.params.dependencies }); }); } function stop() { return Promise.try(function() { if (parent && container) { parent.removeChild(container); } busConnection.stop(); }); } // MAIN model = Props.make({ data: { referenceObjectName: null, availableValues: [], selectedItems: [], value: null, showFrom: 0, showTo: 5 }, onUpdate: function(props) { renderStats(); renderToolbar(); renderAvailableItems(); renderSelectedItems(); } }); return { start: start, stop: stop }; } return { make: function(config) { return factory(config); } }; });
import details from './details'; export default function (){ details(); }
module.exports = { purge: ['./components/**/*.tsx', './pages/**/*.tsx'], theme: { extend: { colors: { 'accent-1': '#FAFAFA', 'accent-2': '#EAEAEA', 'accent-7': '#333', success: '#0070f3', cyan: '#79FFE1', }, spacing: { 28: '7rem', }, letterSpacing: { tighter: '-.04em', }, lineHeight: { tight: 1.2, }, fontSize: { '5xl': '2.5rem', '6xl': '2.75rem', '7xl': '4.5rem', '8xl': '6.25rem', }, boxShadow: { small: '0 5px 10px rgba(0, 0, 0, 0.12)', medium: '0 8px 30px rgba(0, 0, 0, 0.12)', }, }, }, }
// // Stub out `require` in rhino // function require(arg) { return less[arg.split('/')[1]]; }; // ecma-5.js // // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License // -- tlrobinson Tom Robinson // dantman Daniel Friesen // // Array // if (!Array.isArray) { Array.isArray = function(obj) { return Object.prototype.toString.call(obj) === "[object Array]" || (obj instanceof Array); }; } if (!Array.prototype.forEach) { Array.prototype.forEach = function(block, thisObject) { var len = this.length >>> 0; for (var i = 0; i < len; i++) { if (i in this) { block.call(thisObject, this[i], i, this); } } }; } if (!Array.prototype.map) { Array.prototype.map = function(fun /*, thisp*/) { var len = this.length >>> 0; var res = new Array(len); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) { res[i] = fun.call(thisp, this[i], i, this); } } return res; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (block /*, thisp */) { var values = []; var thisp = arguments[1]; for (var i = 0; i < this.length; i++) { if (block.call(thisp, this[i])) { values.push(this[i]); } } return values; }; } if (!Array.prototype.reduce) { Array.prototype.reduce = function(fun /*, initial*/) { var len = this.length >>> 0; var i = 0; // no value to return if no initial value and an empty array if (len === 0 && arguments.length === 1) throw new TypeError(); if (arguments.length >= 2) { var rv = arguments[1]; } else { do { if (i in this) { rv = this[i++]; break; } // if array contains no values, no initial value to return if (++i >= len) throw new TypeError(); } while (true); } for (; i < len; i++) { if (i in this) { rv = fun.call(null, rv, this[i], i, this); } } return rv; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (value /*, fromIndex */ ) { var length = this.length; var i = arguments[1] || 0; if (!length) return -1; if (i >= length) return -1; if (i < 0) i += length; for (; i < length; i++) { if (!Object.prototype.hasOwnProperty.call(this, i)) { continue } if (value === this[i]) return i; } return -1; }; } // // Object // if (!Object.keys) { Object.keys = function (object) { var keys = []; for (var name in object) { if (Object.prototype.hasOwnProperty.call(object, name)) { keys.push(name); } } return keys; }; } // // String // if (!String.prototype.trim) { String.prototype.trim = function () { return String(this).replace(/^\s\s*/, '').replace(/\s\s*$/, ''); }; } var less, tree; if (typeof environment === "object" && ({}).toString.call(environment) === "[object Environment]") { // Rhino // Details on how to detect Rhino: https://github.com/ringo/ringojs/issues/88 if (typeof(window) === 'undefined') { less = {} } else { less = window.less = {} } tree = less.tree = {}; less.mode = 'rhino'; } else if (typeof(window) === 'undefined') { // Node.js less = exports, tree = require('./tree'); less.mode = 'node'; } else { // Browser if (typeof(window.less) === 'undefined') { window.less = {} } less = window.less, tree = window.less.tree = {}; less.mode = 'browser'; } // // less.js - parser // // A relatively straight-forward predictive parser. // There is no tokenization/lexing stage, the input is parsed // in one sweep. // // To make the parser fast enough to run in the browser, several // optimization had to be made: // // - Matching and slicing on a huge input is often cause of slowdowns. // The solution is to chunkify the input into smaller strings. // The chunks are stored in the `chunks` var, // `j` holds the current chunk index, and `current` holds // the index of the current chunk in relation to `input`. // This gives us an almost 4x speed-up. // // - In many cases, we don't need to match individual tokens; // for example, if a value doesn't hold any variables, operations // or dynamic references, the parser can effectively 'skip' it, // treating it as a literal. // An example would be '1px solid #000' - which evaluates to itself, // we don't need to know what the individual components are. // The drawback, of course is that you don't get the benefits of // syntax-checking on the CSS. This gives us a 50% speed-up in the parser, // and a smaller speed-up in the code-gen. // // // Token matching is done with the `$` function, which either takes // a terminal string or regexp, or a non-terminal function to call. // It also takes care of moving all the indices forwards. // // less.Parser = function Parser(env) { var input, // LeSS input string i, // current index in `input` j, // current chunk temp, // temporarily holds a chunk's state, for backtracking memo, // temporarily holds `i`, when backtracking furthest, // furthest index the parser has gone to chunks, // chunkified input current, // index of current chunk, in `input` parser; var that = this; // This function is called after all files // have been imported through `@import`. var finish = function () {}; var imports = this.imports = { paths: env && env.paths || [], // Search paths, when importing queue: [], // Files which haven't been imported yet files: {}, // Holds the imported parse trees contents: {}, // Holds the imported file contents mime: env && env.mime, // MIME type of .less files error: null, // Error in parsing/evaluating an import push: function (path, callback) { var that = this; this.queue.push(path); // // Import a file asynchronously // less.Parser.importer(path, this.paths, function (e, root, contents) { that.queue.splice(that.queue.indexOf(path), 1); // Remove the path from the queue that.files[path] = root; // Store the root that.contents[path] = contents; if (e && !that.error) { that.error = e } callback(e, root); if (that.queue.length === 0) { finish() } // Call `finish` if we're done importing }, env); } }; function save() { temp = chunks[j], memo = i, current = i } function restore() { chunks[j] = temp, i = memo, current = i } function sync() { if (i > current) { chunks[j] = chunks[j].slice(i - current); current = i; } } // // Parse from a token, regexp or string, and move forward if match // function $(tok) { var match, args, length, c, index, endIndex, k, mem; // // Non-terminal // if (tok instanceof Function) { return tok.call(parser.parsers); // // Terminal // // Either match a single character in the input, // or match a regexp in the current chunk (chunk[j]). // } else if (typeof(tok) === 'string') { match = input.charAt(i) === tok ? tok : null; length = 1; sync (); } else { sync (); if (match = tok.exec(chunks[j])) { length = match[0].length; } else { return null; } } // The match is confirmed, add the match length to `i`, // and consume any extra white-space characters (' ' || '\n') // which come after that. The reason for this is that LeSS's // grammar is mostly white-space insensitive. // if (match) { mem = i += length; endIndex = i + chunks[j].length - length; while (i < endIndex) { c = input.charCodeAt(i); if (! (c === 32 || c === 10 || c === 9)) { break } i++; } chunks[j] = chunks[j].slice(length + (i - mem)); current = i; if (chunks[j].length === 0 && j < chunks.length - 1) { j++ } if(typeof(match) === 'string') { return match; } else { return match.length === 1 ? match[0] : match; } } } function expect(arg, msg) { var result = $(arg); if (! result) { error(msg || (typeof(arg) === 'string' ? "expected '" + arg + "' got '" + input.charAt(i) + "'" : "unexpected token")); } else { return result; } } function error(msg, type) { throw { index: i, type: type || 'Syntax', message: msg }; } // Same as $(), but don't change the state of the parser, // just return the match. function peek(tok) { if (typeof(tok) === 'string') { return input.charAt(i) === tok; } else { if (tok.test(chunks[j])) { return true; } else { return false; } } } function basename(pathname) { if (less.mode === 'node') { return require('path').basename(pathname); } else { return pathname.match(/[^\/]+$/)[0]; } } function getInput(e, env) { if (e.filename && env.filename && (e.filename !== env.filename)) { return parser.imports.contents[basename(e.filename)]; } else { return input; } } function getLocation(index, input) { for (var n = index, column = -1; n >= 0 && input.charAt(n) !== '\n'; n--) { column++ } return { line: typeof(index) === 'number' ? (input.slice(0, index).match(/\n/g) || "").length : null, column: column }; } function LessError(e, env) { var input = getInput(e, env), loc = getLocation(e.index, input), line = loc.line, col = loc.column, lines = input.split('\n'); this.type = e.type || 'Syntax'; this.message = e.message; this.filename = e.filename || env.filename; this.index = e.index; this.line = typeof(line) === 'number' ? line + 1 : null; this.callLine = e.call && (getLocation(e.call, input).line + 1); this.callExtract = lines[getLocation(e.call, input).line]; this.stack = e.stack; this.column = col; this.extract = [ lines[line - 1], lines[line], lines[line + 1] ]; } this.env = env = env || {}; // The optimization level dictates the thoroughness of the parser, // the lower the number, the less nodes it will create in the tree. // This could matter for debugging, or if you want to access // the individual nodes in the tree. this.optimization = ('optimization' in this.env) ? this.env.optimization : 1; this.env.filename = this.env.filename || null; // // The Parser // return parser = { imports: imports, // // Parse an input string into an abstract syntax tree, // call `callback` when done. // parse: function (str, callback) { var root, start, end, zone, line, lines, buff = [], c, error = null; i = j = current = furthest = 0; input = str.replace(/\r\n/g, '\n'); // Split the input into chunks. chunks = (function (chunks) { var j = 0, skip = /[^"'`\{\}\/\(\)\\]+/g, comment = /\/\*(?:[^*]|\*+[^\/*])*\*+\/|\/\/.*/g, string = /"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'|`((?:[^`\\\r\n]|\\.)*)`/g, level = 0, match, chunk = chunks[0], inParam; for (var i = 0, c, cc; i < input.length; i++) { skip.lastIndex = i; if (match = skip.exec(input)) { if (match.index === i) { i += match[0].length; chunk.push(match[0]); } } c = input.charAt(i); comment.lastIndex = string.lastIndex = i; if (match = string.exec(input)) { if (match.index === i) { i += match[0].length; chunk.push(match[0]); c = input.charAt(i); } } if (!inParam && c === '/') { cc = input.charAt(i + 1); if (cc === '/' || cc === '*') { if (match = comment.exec(input)) { if (match.index === i) { i += match[0].length; chunk.push(match[0]); c = input.charAt(i); } } } } switch (c) { case '{': if (! inParam) { level ++; chunk.push(c); break } case '}': if (! inParam) { level --; chunk.push(c); chunks[++j] = chunk = []; break } case '(': if (! inParam) { inParam = true; chunk.push(c); break } case ')': if ( inParam) { inParam = false; chunk.push(c); break } default: chunk.push(c); } } if (level > 0) { error = new(LessError)({ index: i, type: 'Parse', message: "missing closing `}`", filename: env.filename }, env); } return chunks.map(function (c) { return c.join('') });; })([[]]); if (error) { return callback(error); } // Start with the primary rule. // The whole syntax tree is held under a Ruleset node, // with the `root` property set to true, so no `{}` are // output. The callback is called when the input is parsed. try { root = new(tree.Ruleset)([], $(this.parsers.primary)); root.root = true; } catch (e) { return callback(new(LessError)(e, env)); } root.toCSS = (function (evaluate) { var line, lines, column; return function (options, variables) { var frames = [], importError; options = options || {}; // // Allows setting variables with a hash, so: // // `{ color: new(tree.Color)('#f01') }` will become: // // new(tree.Rule)('@color', // new(tree.Value)([ // new(tree.Expression)([ // new(tree.Color)('#f01') // ]) // ]) // ) // if (typeof(variables) === 'object' && !Array.isArray(variables)) { variables = Object.keys(variables).map(function (k) { var value = variables[k]; if (! (value instanceof tree.Value)) { if (! (value instanceof tree.Expression)) { value = new(tree.Expression)([value]); } value = new(tree.Value)([value]); } return new(tree.Rule)('@' + k, value, false, 0); }); frames = [new(tree.Ruleset)(null, variables)]; } try { var css = evaluate.call(this, { frames: frames }) .toCSS([], { compress: options.compress || false }); } catch (e) { throw new(LessError)(e, env); } if ((importError = parser.imports.error)) { // Check if there was an error during importing if (importError instanceof LessError) throw importError; else throw new(LessError)(importError, env); } if (options.yuicompress && less.mode === 'node') { return require('./cssmin').compressor.cssmin(css); } else if (options.compress) { return css.replace(/(\s)+/g, "$1"); } else { return css; } }; })(root.eval); // If `i` is smaller than the `input.length - 1`, // it means the parser wasn't able to parse the whole // string, so we've got a parsing error. // // We try to extract a \n delimited string, // showing the line where the parse error occured. // We split it up into two parts (the part which parsed, // and the part which didn't), so we can color them differently. if (i < input.length - 1) { i = furthest; lines = input.split('\n'); line = (input.slice(0, i).match(/\n/g) || "").length + 1; for (var n = i, column = -1; n >= 0 && input.charAt(n) !== '\n'; n--) { column++ } error = { type: "Parse", message: "Syntax Error on line " + line, index: i, filename: env.filename, line: line, column: column, extract: [ lines[line - 2], lines[line - 1], lines[line] ] }; } if (this.imports.queue.length > 0) { finish = function () { callback(error, root) }; } else { callback(error, root); } }, // // Here in, the parsing rules/functions // // The basic structure of the syntax tree generated is as follows: // // Ruleset -> Rule -> Value -> Expression -> Entity // // Here's some LESS code: // // .class { // color: #fff; // border: 1px solid #000; // width: @w + 4px; // > .child {...} // } // // And here's what the parse tree might look like: // // Ruleset (Selector '.class', [ // Rule ("color", Value ([Expression [Color #fff]])) // Rule ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]])) // Rule ("width", Value ([Expression [Operation "+" [Variable "@w"][Dimension 4px]]])) // Ruleset (Selector [Element '>', '.child'], [...]) // ]) // // In general, most rules will try to parse a token with the `$()` function, and if the return // value is truly, will return a new node, of the relevant type. Sometimes, we need to check // first, before parsing, that's when we use `peek()`. // parsers: { // // The `primary` rule is the *entry* and *exit* point of the parser. // The rules here can appear at any level of the parse tree. // // The recursive nature of the grammar is an interplay between the `block` // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule, // as represented by this simplified grammar: // // primary → (ruleset | rule)+ // ruleset → selector+ block // block → '{' primary '}' // // Only at one point is the primary rule not called from the // block rule: at the root level. // primary: function () { var node, root = []; while ((node = $(this.mixin.definition) || $(this.rule) || $(this.ruleset) || $(this.mixin.call) || $(this.comment) || $(this.directive)) || $(/^[\s\n]+/)) { node && root.push(node); } return root; }, // We create a Comment node for CSS comments `/* */`, // but keep the LeSS comments `//` silent, by just skipping // over them. comment: function () { var comment; if (input.charAt(i) !== '/') return; if (input.charAt(i + 1) === '/') { return new(tree.Comment)($(/^\/\/.*/), true); } else if (comment = $(/^\/\*(?:[^*]|\*+[^\/*])*\*+\/\n?/)) { return new(tree.Comment)(comment); } }, // // Entities are tokens which can be found inside an Expression // entities: { // // A string, which supports escaping " and ' // // "milky way" 'he\'s the one!' // quoted: function () { var str, j = i, e; if (input.charAt(j) === '~') { j++, e = true } // Escaped strings if (input.charAt(j) !== '"' && input.charAt(j) !== "'") return; e && $('~'); if (str = $(/^"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'/)) { return new(tree.Quoted)(str[0], str[1] || str[2], e); } }, // // A catch-all word, such as: // // black border-collapse // keyword: function () { var k; if (k = $(/^[_A-Za-z-][_A-Za-z0-9-]*/)) { if (tree.colors.hasOwnProperty(k)) { // detect named color return new(tree.Color)(tree.colors[k].slice(1)); } else { return new(tree.Keyword)(k); } } }, // // A function call // // rgb(255, 0, 255) // // We also try to catch IE's `alpha()`, but let the `alpha` parser // deal with the details. // // The arguments are parsed with the `entities.arguments` parser. // call: function () { var name, args, index = i; if (! (name = /^([\w-]+|%|progid:[\w\.]+)\(/.exec(chunks[j]))) return; name = name[1].toLowerCase(); if (name === 'url') { return null } else { i += name.length } if (name === 'alpha') { return $(this.alpha) } $('('); // Parse the '(' and consume whitespace. args = $(this.entities.arguments); if (! $(')')) return; if (name) { return new(tree.Call)(name, args, index, env.filename) } }, arguments: function () { var args = [], arg; while (arg = $(this.entities.assignment) || $(this.expression)) { args.push(arg); if (! $(',')) { break } } return args; }, literal: function () { return $(this.entities.dimension) || $(this.entities.color) || $(this.entities.quoted); }, // Assignments are argument entities for calls. // They are present in ie filter properties as shown below. // // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* ) // assignment: function () { var key, value; if ((key = $(/^\w+(?=\s?=)/i)) && $('=') && (value = $(this.entity))) { return new(tree.Assignment)(key, value); } }, // // Parse url() tokens // // We use a specific rule for urls, because they don't really behave like // standard function calls. The difference is that the argument doesn't have // to be enclosed within a string, so it can't be parsed as an Expression. // url: function () { var value; if (input.charAt(i) !== 'u' || !$(/^url\(/)) return; value = $(this.entities.quoted) || $(this.entities.variable) || $(this.entities.dataURI) || $(/^[-\w%@$\/.&=:;#+?~]+/) || ""; expect(')'); return new(tree.URL)((value.value || value.data || value instanceof tree.Variable) ? value : new(tree.Anonymous)(value), imports.paths); }, dataURI: function () { var obj; if ($(/^data:/)) { obj = {}; obj.mime = $(/^[^\/]+\/[^,;)]+/) || ''; obj.charset = $(/^;\s*charset=[^,;)]+/) || ''; obj.base64 = $(/^;\s*base64/) || ''; obj.data = $(/^,\s*[^)]+/); if (obj.data) { return obj } } }, // // A Variable entity, such as `@fink`, in // // width: @fink + 2px // // We use a different parser for variable definitions, // see `parsers.variable`. // variable: function () { var name, index = i; if (input.charAt(i) === '@' && (name = $(/^@@?[\w-]+/))) { return new(tree.Variable)(name, index, env.filename); } }, // // A Hexadecimal color // // #4F3C2F // // `rgb` and `hsl` colors are parsed through the `entities.call` parser. // color: function () { var rgb; if (input.charAt(i) === '#' && (rgb = $(/^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})/))) { return new(tree.Color)(rgb[1]); } }, // // A Dimension, that is, a number and a unit // // 0.5em 95% // dimension: function () { var value, c = input.charCodeAt(i); if ((c > 57 || c < 45) || c === 47) return; if (value = $(/^(-?\d*\.?\d+)(px|%|em|rem|pc|ex|in|deg|s|ms|pt|cm|mm|rad|grad|turn)?/)) { return new(tree.Dimension)(value[1], value[2]); } }, // // JavaScript code to be evaluated // // `window.location.href` // javascript: function () { var str, j = i, e; if (input.charAt(j) === '~') { j++, e = true } // Escaped strings if (input.charAt(j) !== '`') { return } e && $('~'); if (str = $(/^`([^`]*)`/)) { return new(tree.JavaScript)(str[1], i, e); } } }, // // The variable part of a variable definition. Used in the `rule` parser // // @fink: // variable: function () { var name; if (input.charAt(i) === '@' && (name = $(/^(@[\w-]+)\s*:/))) { return name[1] } }, // // A font size/line-height shorthand // // small/12px // // We need to peek first, or we'll match on keywords and dimensions // shorthand: function () { var a, b; if (! peek(/^[@\w.%-]+\/[@\w.-]+/)) return; if ((a = $(this.entity)) && $('/') && (b = $(this.entity))) { return new(tree.Shorthand)(a, b); } }, // // Mixins // mixin: { // // A Mixin call, with an optional argument list // // #mixins > .square(#fff); // .rounded(4px, black); // .button; // // The `while` loop is there because mixins can be // namespaced, but we only support the child and descendant // selector for now. // call: function () { var elements = [], e, c, args, index = i, s = input.charAt(i), important = false; if (s !== '.' && s !== '#') { return } while (e = $(/^[#.](?:[\w-]|\\(?:[a-fA-F0-9]{1,6} ?|[^a-fA-F0-9]))+/)) { elements.push(new(tree.Element)(c, e, i)); c = $('>'); } $('(') && (args = $(this.entities.arguments)) && $(')'); if ($(this.important)) { important = true; } if (elements.length > 0 && ($(';') || peek('}'))) { return new(tree.mixin.Call)(elements, args || [], index, env.filename, important); } }, // // A Mixin definition, with a list of parameters // // .rounded (@radius: 2px, @color) { // ... // } // // Until we have a finer grained state-machine, we have to // do a look-ahead, to make sure we don't have a mixin call. // See the `rule` function for more information. // // We start by matching `.rounded (`, and then proceed on to // the argument list, which has optional default values. // We store the parameters in `params`, with a `value` key, // if there is a value, such as in the case of `@radius`. // // Once we've got our params list, and a closing `)`, we parse // the `{...}` block. // definition: function () { var name, params = [], match, ruleset, param, value, cond, variadic = false; if ((input.charAt(i) !== '.' && input.charAt(i) !== '#') || peek(/^[^{]*(;|})/)) return; save(); if (match = $(/^([#.](?:[\w-]|\\(?:[a-fA-F0-9]{1,6} ?|[^a-fA-F0-9]))+)\s*\(/)) { name = match[1]; do { if (input.charAt(i) === '.' && $(/^\.{3}/)) { variadic = true; break; } else if (param = $(this.entities.variable) || $(this.entities.literal) || $(this.entities.keyword)) { // Variable if (param instanceof tree.Variable) { if ($(':')) { value = expect(this.expression, 'expected expression'); params.push({ name: param.name, value: value }); } else if ($(/^\.{3}/)) { params.push({ name: param.name, variadic: true }); variadic = true; break; } else { params.push({ name: param.name }); } } else { params.push({ value: param }); } } else { break; } } while ($(',')) expect(')'); if ($(/^when/)) { // Guard cond = expect(this.conditions, 'expected condition'); } ruleset = $(this.block); if (ruleset) { return new(tree.mixin.Definition)(name, params, ruleset, cond, variadic); } else { restore(); } } } }, // // Entities are the smallest recognized token, // and can be found inside a rule's value. // entity: function () { return $(this.entities.literal) || $(this.entities.variable) || $(this.entities.url) || $(this.entities.call) || $(this.entities.keyword) || $(this.entities.javascript) || $(this.comment); }, // // A Rule terminator. Note that we use `peek()` to check for '}', // because the `block` rule will be expecting it, but we still need to make sure // it's there, if ';' was ommitted. // end: function () { return $(';') || peek('}'); }, // // IE's alpha function // // alpha(opacity=88) // alpha: function () { var value; if (! $(/^\(opacity=/i)) return; if (value = $(/^\d+/) || $(this.entities.variable)) { expect(')'); return new(tree.Alpha)(value); } }, // // A Selector Element // // div // + h1 // #socks // input[type="text"] // // Elements are the building blocks for Selectors, // they are made out of a `Combinator` (see combinator rule), // and an element name, such as a tag a class, or `*`. // element: function () { var e, t, c, v; c = $(this.combinator); e = $(/^(?:\d+\.\d+|\d+)%/) || $(/^(?:[.#]?|:*)(?:[\w-]|\\(?:[a-fA-F0-9]{1,6} ?|[^a-fA-F0-9]))+/) || $('*') || $(this.attribute) || $(/^\([^)@]+\)/); if (! e) { $('(') && (v = $(this.entities.variable)) && $(')') && (e = new(tree.Paren)(v)); } if (e) { return new(tree.Element)(c, e, i) } if (c.value && c.value.charAt(0) === '&') { return new(tree.Element)(c, null, i); } }, // // Combinators combine elements together, in a Selector. // // Because our parser isn't white-space sensitive, special care // has to be taken, when parsing the descendant combinator, ` `, // as it's an empty space. We have to check the previous character // in the input, to see if it's a ` ` character. More info on how // we deal with this in *combinator.js*. // combinator: function () { var match, c = input.charAt(i); if (c === '>' || c === '+' || c === '~') { i++; while (input.charAt(i) === ' ') { i++ } return new(tree.Combinator)(c); } else if (c === '&') { match = '&'; i++; if(input.charAt(i) === ' ') { match = '& '; } while (input.charAt(i) === ' ') { i++ } return new(tree.Combinator)(match); } else if (input.charAt(i - 1) === ' ') { return new(tree.Combinator)(" "); } else { return new(tree.Combinator)(null); } }, // // A CSS Selector // // .class > div + h1 // li a:hover // // Selectors are made out of one or more Elements, see above. // selector: function () { var sel, e, elements = [], c, match; if ($('(')) { sel = $(this.entity); expect(')'); return new(tree.Selector)([new(tree.Element)('', sel, i)]); } while (e = $(this.element)) { c = input.charAt(i); elements.push(e) if (c === '{' || c === '}' || c === ';' || c === ',') { break } } if (elements.length > 0) { return new(tree.Selector)(elements) } }, tag: function () { return $(/^[a-zA-Z][a-zA-Z-]*[0-9]?/) || $('*'); }, attribute: function () { var attr = '', key, val, op; if (! $('[')) return; if (key = $(/^[a-zA-Z-]+/) || $(this.entities.quoted)) { if ((op = $(/^[|~*$^]?=/)) && (val = $(this.entities.quoted) || $(/^[\w-]+/))) { attr = [key, op, val.toCSS ? val.toCSS() : val].join(''); } else { attr = key } } if (! $(']')) return; if (attr) { return "[" + attr + "]" } }, // // The `block` rule is used by `ruleset` and `mixin.definition`. // It's a wrapper around the `primary` rule, with added `{}`. // block: function () { var content; if ($('{') && (content = $(this.primary)) && $('}')) { return content; } }, // // div, .class, body > p {...} // ruleset: function () { var selectors = [], s, rules, match; save(); while (s = $(this.selector)) { selectors.push(s); $(this.comment); if (! $(',')) { break } $(this.comment); } if (selectors.length > 0 && (rules = $(this.block))) { return new(tree.Ruleset)(selectors, rules, env.strictImports); } else { // Backtrack furthest = i; restore(); } }, rule: function () { var name, value, c = input.charAt(i), important, match; save(); if (c === '.' || c === '#' || c === '&') { return } if (name = $(this.variable) || $(this.property)) { if ((name.charAt(0) != '@') && (match = /^([^@+\/'"*`(;{}-]*);/.exec(chunks[j]))) { i += match[0].length - 1; value = new(tree.Anonymous)(match[1]); } else if (name === "font") { value = $(this.font); } else { value = $(this.value); } important = $(this.important); if (value && $(this.end)) { return new(tree.Rule)(name, value, important, memo); } else { furthest = i; restore(); } } }, // // An @import directive // // @import "lib"; // // Depending on our environemnt, importing is done differently: // In the browser, it's an XHR request, in Node, it would be a // file-system operation. The function used for importing is // stored in `import`, which we pass to the Import constructor. // "import": function () { var path, features, index = i; if ($(/^@import\s+/) && (path = $(this.entities.quoted) || $(this.entities.url))) { features = $(this.mediaFeatures); if ($(';')) { return new(tree.Import)(path, imports, features, index); } } }, mediaFeature: function () { var e, p, nodes = []; do { if (e = $(this.entities.keyword)) { nodes.push(e); } else if ($('(')) { p = $(this.property); e = $(this.entity); if ($(')')) { if (p && e) { nodes.push(new(tree.Paren)(new(tree.Rule)(p, e, null, i, true))); } else if (e) { nodes.push(new(tree.Paren)(e)); } else { return null; } } else { return null } } } while (e); if (nodes.length > 0) { return new(tree.Expression)(nodes); } }, mediaFeatures: function () { var e, features = []; do { if (e = $(this.mediaFeature)) { features.push(e); if (! $(',')) { break } } else if (e = $(this.entities.variable)) { features.push(e); if (! $(',')) { break } } } while (e); return features.length > 0 ? features : null; }, media: function () { var features, rules; if ($(/^@media/)) { features = $(this.mediaFeatures); if (rules = $(this.block)) { return new(tree.Media)(rules, features); } } }, // // A CSS Directive // // @charset "utf-8"; // directive: function () { var name, value, rules, types, e, nodes; if (input.charAt(i) !== '@') return; if (value = $(this['import']) || $(this.media)) { return value; } else if (name = $(/^@page|@keyframes/) || $(/^@(?:-webkit-|-moz-|-o-|-ms-)[a-z0-9-]+/)) { types = ($(/^[^{]+/) || '').trim(); if (rules = $(this.block)) { return new(tree.Directive)(name + " " + types, rules); } } else if (name = $(/^@[-a-z]+/)) { if (name === '@font-face') { if (rules = $(this.block)) { return new(tree.Directive)(name, rules); } } else if ((value = $(this.entity)) && $(';')) { return new(tree.Directive)(name, value); } } }, font: function () { var value = [], expression = [], weight, shorthand, font, e; while (e = $(this.shorthand) || $(this.entity)) { expression.push(e); } value.push(new(tree.Expression)(expression)); if ($(',')) { while (e = $(this.expression)) { value.push(e); if (! $(',')) { break } } } return new(tree.Value)(value); }, // // A Value is a comma-delimited list of Expressions // // font-family: Baskerville, Georgia, serif; // // In a Rule, a Value represents everything after the `:`, // and before the `;`. // value: function () { var e, expressions = [], important; while (e = $(this.expression)) { expressions.push(e); if (! $(',')) { break } } if (expressions.length > 0) { return new(tree.Value)(expressions); } }, important: function () { if (input.charAt(i) === '!') { return $(/^! *important/); } }, sub: function () { var e; if ($('(') && (e = $(this.expression)) && $(')')) { return e; } }, multiplication: function () { var m, a, op, operation; if (m = $(this.operand)) { while (!peek(/^\/\*/) && (op = ($('/') || $('*'))) && (a = $(this.operand))) { operation = new(tree.Operation)(op, [operation || m, a]); } return operation || m; } }, addition: function () { var m, a, op, operation; if (m = $(this.multiplication)) { while ((op = $(/^[-+]\s+/) || (input.charAt(i - 1) != ' ' && ($('+') || $('-')))) && (a = $(this.multiplication))) { operation = new(tree.Operation)(op, [operation || m, a]); } return operation || m; } }, conditions: function () { var a, b, index = i, condition; if (a = $(this.condition)) { while ($(',') && (b = $(this.condition))) { condition = new(tree.Condition)('or', condition || a, b, index); } return condition || a; } }, condition: function () { var a, b, c, op, index = i, negate = false; if ($(/^not/)) { negate = true } expect('('); if (a = $(this.addition) || $(this.entities.keyword) || $(this.entities.quoted)) { if (op = $(/^(?:>=|=<|[<=>])/)) { if (b = $(this.addition) || $(this.entities.keyword) || $(this.entities.quoted)) { c = new(tree.Condition)(op, a, b, index, negate); } else { error('expected expression'); } } else { c = new(tree.Condition)('=', a, new(tree.Keyword)('true'), index, negate); } expect(')'); return $(/^and/) ? new(tree.Condition)('and', c, $(this.condition)) : c; } }, // // An operand is anything that can be part of an operation, // such as a Color, or a Variable // operand: function () { var negate, p = input.charAt(i + 1); if (input.charAt(i) === '-' && (p === '@' || p === '(')) { negate = $('-') } var o = $(this.sub) || $(this.entities.dimension) || $(this.entities.color) || $(this.entities.variable) || $(this.entities.call); return negate ? new(tree.Operation)('*', [new(tree.Dimension)(-1), o]) : o; }, // // Expressions either represent mathematical operations, // or white-space delimited Entities. // // 1px solid black // @var * 2 // expression: function () { var e, delim, entities = [], d; while (e = $(this.addition) || $(this.entity)) { entities.push(e); } if (entities.length > 0) { return new(tree.Expression)(entities); } }, property: function () { var name; if (name = $(/^(\*?-?[-a-z_0-9]+)\s*:/)) { return name[1]; } } } }; }; if (less.mode === 'browser' || less.mode === 'rhino') { // // Used by `@import` directives // less.Parser.importer = function (path, paths, callback, env) { if (!/^([a-z]+:)?\//.test(path) && paths.length > 0) { path = paths[0] + path; } // We pass `true` as 3rd argument, to force the reload of the import. // This is so we can get the syntax tree as opposed to just the CSS output, // as we need this to evaluate the current stylesheet. loadStyleSheet({ href: path, title: path, type: env.mime }, function (e) { if (e && typeof(env.errback) === "function") { env.errback.call(null, path, paths, callback, env); } else { callback.apply(null, arguments); } }, true); }; } (function (tree) { tree.functions = { rgb: function (r, g, b) { return this.rgba(r, g, b, 1.0); }, rgba: function (r, g, b, a) { var rgb = [r, g, b].map(function (c) { return number(c) }), a = number(a); return new(tree.Color)(rgb, a); }, hsl: function (h, s, l) { return this.hsla(h, s, l, 1.0); }, hsla: function (h, s, l, a) { h = (number(h) % 360) / 360; s = number(s); l = number(l); a = number(a); var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; var m1 = l * 2 - m2; return this.rgba(hue(h + 1/3) * 255, hue(h) * 255, hue(h - 1/3) * 255, a); function hue(h) { h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h); if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; else if (h * 2 < 1) return m2; else if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6; else return m1; } }, hue: function (color) { return new(tree.Dimension)(Math.round(color.toHSL().h)); }, saturation: function (color) { return new(tree.Dimension)(Math.round(color.toHSL().s * 100), '%'); }, lightness: function (color) { return new(tree.Dimension)(Math.round(color.toHSL().l * 100), '%'); }, alpha: function (color) { return new(tree.Dimension)(color.toHSL().a); }, saturate: function (color, amount) { var hsl = color.toHSL(); hsl.s += amount.value / 100; hsl.s = clamp(hsl.s); return hsla(hsl); }, desaturate: function (color, amount) { var hsl = color.toHSL(); hsl.s -= amount.value / 100; hsl.s = clamp(hsl.s); return hsla(hsl); }, lighten: function (color, amount) { var hsl = color.toHSL(); hsl.l += amount.value / 100; hsl.l = clamp(hsl.l); return hsla(hsl); }, darken: function (color, amount) { var hsl = color.toHSL(); hsl.l -= amount.value / 100; hsl.l = clamp(hsl.l); return hsla(hsl); }, fadein: function (color, amount) { var hsl = color.toHSL(); hsl.a += amount.value / 100; hsl.a = clamp(hsl.a); return hsla(hsl); }, fadeout: function (color, amount) { var hsl = color.toHSL(); hsl.a -= amount.value / 100; hsl.a = clamp(hsl.a); return hsla(hsl); }, fade: function (color, amount) { var hsl = color.toHSL(); hsl.a = amount.value / 100; hsl.a = clamp(hsl.a); return hsla(hsl); }, spin: function (color, amount) { var hsl = color.toHSL(); var hue = (hsl.h + amount.value) % 360; hsl.h = hue < 0 ? 360 + hue : hue; return hsla(hsl); }, // // Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein // http://sass-lang.com // mix: function (color1, color2, weight) { var p = weight.value / 100.0; var w = p * 2 - 1; var a = color1.toHSL().a - color2.toHSL().a; var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0; var w2 = 1 - w1; var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2, color1.rgb[1] * w1 + color2.rgb[1] * w2, color1.rgb[2] * w1 + color2.rgb[2] * w2]; var alpha = color1.alpha * p + color2.alpha * (1 - p); return new(tree.Color)(rgb, alpha); }, greyscale: function (color) { return this.desaturate(color, new(tree.Dimension)(100)); }, e: function (str) { return new(tree.Anonymous)(str instanceof tree.JavaScript ? str.evaluated : str); }, escape: function (str) { return new(tree.Anonymous)(encodeURI(str.value).replace(/=/g, "%3D").replace(/:/g, "%3A").replace(/#/g, "%23").replace(/;/g, "%3B").replace(/\(/g, "%28").replace(/\)/g, "%29")); }, '%': function (quoted /* arg, arg, ...*/) { var args = Array.prototype.slice.call(arguments, 1), str = quoted.value; for (var i = 0; i < args.length; i++) { str = str.replace(/%[sda]/i, function(token) { var value = token.match(/s/i) ? args[i].value : args[i].toCSS(); return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value; }); } str = str.replace(/%%/g, '%'); return new(tree.Quoted)('"' + str + '"', str); }, round: function (n) { return this._math('round', n); }, ceil: function (n) { return this._math('ceil', n); }, floor: function (n) { return this._math('floor', n); }, _math: function (fn, n) { if (n instanceof tree.Dimension) { return new(tree.Dimension)(Math[fn](number(n)), n.unit); } else if (typeof(n) === 'number') { return Math[fn](n); } else { throw { type: "Argument", message: "argument must be a number" }; } }, argb: function (color) { return new(tree.Anonymous)(color.toARGB()); }, percentage: function (n) { return new(tree.Dimension)(n.value * 100, '%'); }, color: function (n) { if (n instanceof tree.Quoted) { return new(tree.Color)(n.value.slice(1)); } else { throw { type: "Argument", message: "argument must be a string" }; } }, iscolor: function (n) { return this._isa(n, tree.Color); }, isnumber: function (n) { return this._isa(n, tree.Dimension); }, isstring: function (n) { return this._isa(n, tree.Quoted); }, iskeyword: function (n) { return this._isa(n, tree.Keyword); }, isurl: function (n) { return this._isa(n, tree.URL); }, ispixel: function (n) { return (n instanceof tree.Dimension) && n.unit === 'px' ? tree.True : tree.False; }, ispercentage: function (n) { return (n instanceof tree.Dimension) && n.unit === '%' ? tree.True : tree.False; }, isem: function (n) { return (n instanceof tree.Dimension) && n.unit === 'em' ? tree.True : tree.False; }, _isa: function (n, Type) { return (n instanceof Type) ? tree.True : tree.False; } }; function hsla(hsla) { return tree.functions.hsla(hsla.h, hsla.s, hsla.l, hsla.a); } function number(n) { if (n instanceof tree.Dimension) { return parseFloat(n.unit == '%' ? n.value / 100 : n.value); } else if (typeof(n) === 'number') { return n; } else { throw { error: "RuntimeError", message: "color functions take numbers as parameters" }; } } function clamp(val) { return Math.min(1, Math.max(0, val)); } })(require('./tree')); (function (tree) { tree.colors = { 'aliceblue':'#f0f8ff', 'antiquewhite':'#faebd7', 'aqua':'#00ffff', 'aquamarine':'#7fffd4', 'azure':'#f0ffff', 'beige':'#f5f5dc', 'bisque':'#ffe4c4', 'black':'#000000', 'blanchedalmond':'#ffebcd', 'blue':'#0000ff', 'blueviolet':'#8a2be2', 'brown':'#a52a2a', 'burlywood':'#deb887', 'cadetblue':'#5f9ea0', 'chartreuse':'#7fff00', 'chocolate':'#d2691e', 'coral':'#ff7f50', 'cornflowerblue':'#6495ed', 'cornsilk':'#fff8dc', 'crimson':'#dc143c', 'cyan':'#00ffff', 'darkblue':'#00008b', 'darkcyan':'#008b8b', 'darkgoldenrod':'#b8860b', 'darkgray':'#a9a9a9', 'darkgrey':'#a9a9a9', 'darkgreen':'#006400', 'darkkhaki':'#bdb76b', 'darkmagenta':'#8b008b', 'darkolivegreen':'#556b2f', 'darkorange':'#ff8c00', 'darkorchid':'#9932cc', 'darkred':'#8b0000', 'darksalmon':'#e9967a', 'darkseagreen':'#8fbc8f', 'darkslateblue':'#483d8b', 'darkslategray':'#2f4f4f', 'darkslategrey':'#2f4f4f', 'darkturquoise':'#00ced1', 'darkviolet':'#9400d3', 'deeppink':'#ff1493', 'deepskyblue':'#00bfff', 'dimgray':'#696969', 'dimgrey':'#696969', 'dodgerblue':'#1e90ff', 'firebrick':'#b22222', 'floralwhite':'#fffaf0', 'forestgreen':'#228b22', 'fuchsia':'#ff00ff', 'gainsboro':'#dcdcdc', 'ghostwhite':'#f8f8ff', 'gold':'#ffd700', 'goldenrod':'#daa520', 'gray':'#808080', 'grey':'#808080', 'green':'#008000', 'greenyellow':'#adff2f', 'honeydew':'#f0fff0', 'hotpink':'#ff69b4', 'indianred':'#cd5c5c', 'indigo':'#4b0082', 'ivory':'#fffff0', 'khaki':'#f0e68c', 'lavender':'#e6e6fa', 'lavenderblush':'#fff0f5', 'lawngreen':'#7cfc00', 'lemonchiffon':'#fffacd', 'lightblue':'#add8e6', 'lightcoral':'#f08080', 'lightcyan':'#e0ffff', 'lightgoldenrodyellow':'#fafad2', 'lightgray':'#d3d3d3', 'lightgrey':'#d3d3d3', 'lightgreen':'#90ee90', 'lightpink':'#ffb6c1', 'lightsalmon':'#ffa07a', 'lightseagreen':'#20b2aa', 'lightskyblue':'#87cefa', 'lightslategray':'#778899', 'lightslategrey':'#778899', 'lightsteelblue':'#b0c4de', 'lightyellow':'#ffffe0', 'lime':'#00ff00', 'limegreen':'#32cd32', 'linen':'#faf0e6', 'magenta':'#ff00ff', 'maroon':'#800000', 'mediumaquamarine':'#66cdaa', 'mediumblue':'#0000cd', 'mediumorchid':'#ba55d3', 'mediumpurple':'#9370d8', 'mediumseagreen':'#3cb371', 'mediumslateblue':'#7b68ee', 'mediumspringgreen':'#00fa9a', 'mediumturquoise':'#48d1cc', 'mediumvioletred':'#c71585', 'midnightblue':'#191970', 'mintcream':'#f5fffa', 'mistyrose':'#ffe4e1', 'moccasin':'#ffe4b5', 'navajowhite':'#ffdead', 'navy':'#000080', 'oldlace':'#fdf5e6', 'olive':'#808000', 'olivedrab':'#6b8e23', 'orange':'#ffa500', 'orangered':'#ff4500', 'orchid':'#da70d6', 'palegoldenrod':'#eee8aa', 'palegreen':'#98fb98', 'paleturquoise':'#afeeee', 'palevioletred':'#d87093', 'papayawhip':'#ffefd5', 'peachpuff':'#ffdab9', 'peru':'#cd853f', 'pink':'#ffc0cb', 'plum':'#dda0dd', 'powderblue':'#b0e0e6', 'purple':'#800080', 'red':'#ff0000', 'rosybrown':'#bc8f8f', 'royalblue':'#4169e1', 'saddlebrown':'#8b4513', 'salmon':'#fa8072', 'sandybrown':'#f4a460', 'seagreen':'#2e8b57', 'seashell':'#fff5ee', 'sienna':'#a0522d', 'silver':'#c0c0c0', 'skyblue':'#87ceeb', 'slateblue':'#6a5acd', 'slategray':'#708090', 'slategrey':'#708090', 'snow':'#fffafa', 'springgreen':'#00ff7f', 'steelblue':'#4682b4', 'tan':'#d2b48c', 'teal':'#008080', 'thistle':'#d8bfd8', 'tomato':'#ff6347', 'turquoise':'#40e0d0', 'violet':'#ee82ee', 'wheat':'#f5deb3', 'white':'#ffffff', 'whitesmoke':'#f5f5f5', 'yellow':'#ffff00', 'yellowgreen':'#9acd32' }; })(require('./tree')); (function (tree) { tree.Alpha = function (val) { this.value = val; }; tree.Alpha.prototype = { toCSS: function () { return "alpha(opacity=" + (this.value.toCSS ? this.value.toCSS() : this.value) + ")"; }, eval: function (env) { if (this.value.eval) { this.value = this.value.eval(env) } return this; } }; })(require('../tree')); (function (tree) { tree.Anonymous = function (string) { this.value = string.value || string; }; tree.Anonymous.prototype = { toCSS: function () { return this.value; }, eval: function () { return this } }; })(require('../tree')); (function (tree) { tree.Assignment = function (key, val) { this.key = key; this.value = val; }; tree.Assignment.prototype = { toCSS: function () { return this.key + '=' + (this.value.toCSS ? this.value.toCSS() : this.value); }, eval: function (env) { if (this.value.eval) { this.value = this.value.eval(env) } return this; } }; })(require('../tree'));(function (tree) { // // A function call node. // tree.Call = function (name, args, index, filename) { this.name = name; this.args = args; this.index = index; this.filename = filename; }; tree.Call.prototype = { // // When evaluating a function call, // we either find the function in `tree.functions` [1], // in which case we call it, passing the evaluated arguments, // or we simply print it out as it appeared originally [2]. // // The *functions.js* file contains the built-in functions. // // The reason why we evaluate the arguments, is in the case where // we try to pass a variable to a function, like: `saturate(@color)`. // The function should receive the value, not the variable. // eval: function (env) { var args = this.args.map(function (a) { return a.eval(env) }); if (this.name in tree.functions) { // 1. try { return tree.functions[this.name].apply(tree.functions, args); } catch (e) { throw { type: e.type || "Runtime", message: "error evaluating function `" + this.name + "`" + (e.message ? ': ' + e.message : ''), index: this.index, filename: this.filename }; } } else { // 2. return new(tree.Anonymous)(this.name + "(" + args.map(function (a) { return a.toCSS() }).join(', ') + ")"); } }, toCSS: function (env) { return this.eval(env).toCSS(); } }; })(require('../tree')); (function (tree) { // // RGB Colors - #ff0014, #eee // tree.Color = function (rgb, a) { // // The end goal here, is to parse the arguments // into an integer triplet, such as `128, 255, 0` // // This facilitates operations and conversions. // if (Array.isArray(rgb)) { this.rgb = rgb; } else if (rgb.length == 6) { this.rgb = rgb.match(/.{2}/g).map(function (c) { return parseInt(c, 16); }); } else { this.rgb = rgb.split('').map(function (c) { return parseInt(c + c, 16); }); } this.alpha = typeof(a) === 'number' ? a : 1; }; tree.Color.prototype = { eval: function () { return this }, // // If we have some transparency, the only way to represent it // is via `rgba`. Otherwise, we use the hex representation, // which has better compatibility with older browsers. // Values are capped between `0` and `255`, rounded and zero-padded. // toCSS: function () { if (this.alpha < 1.0) { return "rgba(" + this.rgb.map(function (c) { return Math.round(c); }).concat(this.alpha).join(', ') + ")"; } else { return '#' + this.rgb.map(function (i) { i = Math.round(i); i = (i > 255 ? 255 : (i < 0 ? 0 : i)).toString(16); return i.length === 1 ? '0' + i : i; }).join(''); } }, // // Operations have to be done per-channel, if not, // channels will spill onto each other. Once we have // our result, in the form of an integer triplet, // we create a new Color node to hold the result. // operate: function (op, other) { var result = []; if (! (other instanceof tree.Color)) { other = other.toColor(); } for (var c = 0; c < 3; c++) { result[c] = tree.operate(op, this.rgb[c], other.rgb[c]); } return new(tree.Color)(result, this.alpha + other.alpha); }, toHSL: function () { var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2, d = max - min; if (max === min) { h = s = 0; } else { s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h * 360, s: s, l: l, a: a }; }, toARGB: function () { var argb = [Math.round(this.alpha * 255)].concat(this.rgb); return '#' + argb.map(function (i) { i = Math.round(i); i = (i > 255 ? 255 : (i < 0 ? 0 : i)).toString(16); return i.length === 1 ? '0' + i : i; }).join(''); } }; })(require('../tree')); (function (tree) { tree.Comment = function (value, silent) { this.value = value; this.silent = !!silent; }; tree.Comment.prototype = { toCSS: function (env) { return env.compress ? '' : this.value; }, eval: function () { return this } }; })(require('../tree')); (function (tree) { tree.Condition = function (op, l, r, i, negate) { this.op = op.trim(); this.lvalue = l; this.rvalue = r; this.index = i; this.negate = negate; }; tree.Condition.prototype.eval = function (env) { var a = this.lvalue.eval(env), b = this.rvalue.eval(env); var i = this.index, result; var result = (function (op) { switch (op) { case 'and': return a && b; case 'or': return a || b; default: if (a.compare) { result = a.compare(b); } else if (b.compare) { result = b.compare(a); } else { throw { type: "Type", message: "Unable to perform comparison", index: i }; } switch (result) { case -1: return op === '<' || op === '=<'; case 0: return op === '=' || op === '>=' || op === '=<'; case 1: return op === '>' || op === '>='; } } })(this.op); return this.negate ? !result : result; }; })(require('../tree')); (function (tree) { // // A number with a unit // tree.Dimension = function (value, unit) { this.value = parseFloat(value); this.unit = unit || null; }; tree.Dimension.prototype = { eval: function () { return this }, toColor: function () { return new(tree.Color)([this.value, this.value, this.value]); }, toCSS: function () { var css = this.value + this.unit; return css; }, // In an operation between two Dimensions, // we default to the first Dimension's unit, // so `1px + 2em` will yield `3px`. // In the future, we could implement some unit // conversions such that `100cm + 10mm` would yield // `101cm`. operate: function (op, other) { return new(tree.Dimension) (tree.operate(op, this.value, other.value), this.unit || other.unit); }, // TODO: Perform unit conversion before comparing compare: function (other) { if (other instanceof tree.Dimension) { if (other.value > this.value) { return -1; } else if (other.value < this.value) { return 1; } else { return 0; } } else { return -1; } } }; })(require('../tree')); (function (tree) { tree.Directive = function (name, value, features) { this.name = name; if (Array.isArray(value)) { this.ruleset = new(tree.Ruleset)([], value); this.ruleset.allowImports = true; } else { this.value = value; } }; tree.Directive.prototype = { toCSS: function (ctx, env) { if (this.ruleset) { this.ruleset.root = true; return this.name + (env.compress ? '{' : ' {\n ') + this.ruleset.toCSS(ctx, env).trim().replace(/\n/g, '\n ') + (env.compress ? '}': '\n}\n'); } else { return this.name + ' ' + this.value.toCSS() + ';\n'; } }, eval: function (env) { env.frames.unshift(this); this.ruleset = this.ruleset && this.ruleset.eval(env); env.frames.shift(); return this; }, variable: function (name) { return tree.Ruleset.prototype.variable.call(this.ruleset, name) }, find: function () { return tree.Ruleset.prototype.find.apply(this.ruleset, arguments) }, rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.ruleset) } }; })(require('../tree')); (function (tree) { tree.Element = function (combinator, value, index) { this.combinator = combinator instanceof tree.Combinator ? combinator : new(tree.Combinator)(combinator); if (typeof(value) === 'string') { this.value = value.trim(); } else if (value) { this.value = value; } else { this.value = ""; } this.index = index; }; tree.Element.prototype.eval = function (env) { return new(tree.Element)(this.combinator, this.value.eval ? this.value.eval(env) : this.value, this.index); }; tree.Element.prototype.toCSS = function (env) { return this.combinator.toCSS(env || {}) + (this.value.toCSS ? this.value.toCSS(env) : this.value); }; tree.Combinator = function (value) { if (value === ' ') { this.value = ' '; } else if (value === '& ') { this.value = '& '; } else { this.value = value ? value.trim() : ""; } }; tree.Combinator.prototype.toCSS = function (env) { return { '' : '', ' ' : ' ', '&' : '', '& ' : ' ', ':' : ' :', '+' : env.compress ? '+' : ' + ', '~' : env.compress ? '~' : ' ~ ', '>' : env.compress ? '>' : ' > ' }[this.value]; }; })(require('../tree')); (function (tree) { tree.Expression = function (value) { this.value = value }; tree.Expression.prototype = { eval: function (env) { if (this.value.length > 1) { return new(tree.Expression)(this.value.map(function (e) { return e.eval(env); })); } else if (this.value.length === 1) { return this.value[0].eval(env); } else { return this; } }, toCSS: function (env) { return this.value.map(function (e) { return e.toCSS ? e.toCSS(env) : ''; }).join(' '); } }; })(require('../tree')); (function (tree) { // // CSS @import node // // The general strategy here is that we don't want to wait // for the parsing to be completed, before we start importing // the file. That's because in the context of a browser, // most of the time will be spent waiting for the server to respond. // // On creation, we push the import path to our import queue, though // `import,push`, we also pass it a callback, which it'll call once // the file has been fetched, and parsed. // tree.Import = function (path, imports, features, index) { var that = this; this.index = index; this._path = path; this.features = features && new(tree.Value)(features); // The '.less' extension is optional if (path instanceof tree.Quoted) { this.path = /\.(le?|c)ss(\?.*)?$/.test(path.value) ? path.value : path.value + '.less'; } else { this.path = path.value.value || path.value; } this.css = /css(\?.*)?$/.test(this.path); // Only pre-compile .less files if (! this.css) { imports.push(this.path, function (e, root) { if (e) { e.index = index } that.root = root || new(tree.Ruleset)([], []); }); } }; // // The actual import node doesn't return anything, when converted to CSS. // The reason is that it's used at the evaluation stage, so that the rules // it imports can be treated like any other rules. // // In `eval`, we make sure all Import nodes get evaluated, recursively, so // we end up with a flat structure, which can easily be imported in the parent // ruleset. // tree.Import.prototype = { toCSS: function (env) { var features = this.features ? ' ' + this.features.toCSS(env) : ''; if (this.css) { return "@import " + this._path.toCSS() + features + ';\n'; } else { return ""; } }, eval: function (env) { var ruleset, features = this.features && this.features.eval(env); if (this.css) { return this; } else { ruleset = new(tree.Ruleset)([], this.root.rules.slice(0)); for (var i = 0; i < ruleset.rules.length; i++) { if (ruleset.rules[i] instanceof tree.Import) { Array.prototype .splice .apply(ruleset.rules, [i, 1].concat(ruleset.rules[i].eval(env))); } } return this.features ? new(tree.Media)(ruleset.rules, this.features.value) : ruleset.rules; } } }; })(require('../tree')); (function (tree) { tree.JavaScript = function (string, index, escaped) { this.escaped = escaped; this.expression = string; this.index = index; }; tree.JavaScript.prototype = { eval: function (env) { var result, that = this, context = {}; var expression = this.expression.replace(/@\{([\w-]+)\}/g, function (_, name) { return tree.jsify(new(tree.Variable)('@' + name, that.index).eval(env)); }); try { expression = new(Function)('return (' + expression + ')'); } catch (e) { throw { message: "JavaScript evaluation error: `" + expression + "`" , index: this.index }; } for (var k in env.frames[0].variables()) { context[k.slice(1)] = { value: env.frames[0].variables()[k].value, toJS: function () { return this.value.eval(env).toCSS(); } }; } try { result = expression.call(context); } catch (e) { throw { message: "JavaScript evaluation error: '" + e.name + ': ' + e.message + "'" , index: this.index }; } if (typeof(result) === 'string') { return new(tree.Quoted)('"' + result + '"', result, this.escaped, this.index); } else if (Array.isArray(result)) { return new(tree.Anonymous)(result.join(', ')); } else { return new(tree.Anonymous)(result); } } }; })(require('../tree')); (function (tree) { tree.Keyword = function (value) { this.value = value }; tree.Keyword.prototype = { eval: function () { return this }, toCSS: function () { return this.value }, compare: function (other) { if (other instanceof tree.Keyword) { return other.value === this.value ? 0 : 1; } else { return -1; } } }; tree.True = new(tree.Keyword)('true'); tree.False = new(tree.Keyword)('false'); })(require('../tree')); (function (tree) { tree.Media = function (value, features) { var el = new(tree.Element)('&', null, 0), selectors = [new(tree.Selector)([el])]; this.features = new(tree.Value)(features); this.ruleset = new(tree.Ruleset)(selectors, value); this.ruleset.allowImports = true; }; tree.Media.prototype = { toCSS: function (ctx, env) { var features = this.features.toCSS(env); this.ruleset.root = (ctx.length === 0 || ctx[0].multiMedia); return '@media ' + features + (env.compress ? '{' : ' {\n ') + this.ruleset.toCSS(ctx, env).trim().replace(/\n/g, '\n ') + (env.compress ? '}': '\n}\n'); }, eval: function (env) { if (!env.mediaBlocks) { env.mediaBlocks = []; env.mediaPath = []; } var blockIndex = env.mediaBlocks.length; env.mediaPath.push(this); env.mediaBlocks.push(this); var media = new(tree.Media)([], []); media.features = this.features.eval(env); env.frames.unshift(this.ruleset); media.ruleset = this.ruleset.eval(env); env.frames.shift(); env.mediaBlocks[blockIndex] = media; env.mediaPath.pop(); return env.mediaPath.length === 0 ? media.evalTop(env) : media.evalNested(env) }, variable: function (name) { return tree.Ruleset.prototype.variable.call(this.ruleset, name) }, find: function () { return tree.Ruleset.prototype.find.apply(this.ruleset, arguments) }, rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.ruleset) }, evalTop: function (env) { var result = this; // Render all dependent Media blocks. if (env.mediaBlocks.length > 1) { var el = new(tree.Element)('&', null, 0); var selectors = [new(tree.Selector)([el])]; result = new(tree.Ruleset)(selectors, env.mediaBlocks); result.multiMedia = true; } delete env.mediaBlocks; delete env.mediaPath; return result; }, evalNested: function (env) { var i, value, path = env.mediaPath.concat([this]); // Extract the media-query conditions separated with `,` (OR). for (i = 0; i < path.length; i++) { value = path[i].features instanceof tree.Value ? path[i].features.value : path[i].features; path[i] = Array.isArray(value) ? value : [value]; } // Trace all permutations to generate the resulting media-query. // // (a, b and c) with nested (d, e) -> // a and d // a and e // b and c and d // b and c and e this.features = new(tree.Value)(this.permute(path).map(function (path) { path = path.map(function (fragment) { return fragment.toCSS ? fragment : new(tree.Anonymous)(fragment); }); for(i = path.length - 1; i > 0; i--) { path.splice(i, 0, new(tree.Anonymous)("and")); } return new(tree.Expression)(path); })); // Fake a tree-node that doesn't output anything. return new(tree.Ruleset)([], []); }, permute: function (arr) { if (arr.length === 0) { return []; } else if (arr.length === 1) { return arr[0]; } else { var result = []; var rest = this.permute(arr.slice(1)); for (var i = 0; i < rest.length; i++) { for (var j = 0; j < arr[0].length; j++) { result.push([arr[0][j]].concat(rest[i])); } } return result; } } }; })(require('../tree')); (function (tree) { tree.mixin = {}; tree.mixin.Call = function (elements, args, index, filename, important) { this.selector = new(tree.Selector)(elements); this.arguments = args; this.index = index; this.filename = filename; this.important = important; }; tree.mixin.Call.prototype = { eval: function (env) { var mixins, args, rules = [], match = false; for (var i = 0; i < env.frames.length; i++) { if ((mixins = env.frames[i].find(this.selector)).length > 0) { args = this.arguments && this.arguments.map(function (a) { return a.eval(env) }); for (var m = 0; m < mixins.length; m++) { if (mixins[m].match(args, env)) { try { Array.prototype.push.apply( rules, mixins[m].eval(env, this.arguments, this.important).rules); match = true; } catch (e) { throw { message: e.message, index: this.index, filename: this.filename, stack: e.stack }; } } } if (match) { return rules; } else { throw { type: 'Runtime', message: 'No matching definition was found for `' + this.selector.toCSS().trim() + '(' + this.arguments.map(function (a) { return a.toCSS(); }).join(', ') + ")`", index: this.index, filename: this.filename }; } } } throw { type: 'Name', message: this.selector.toCSS().trim() + " is undefined", index: this.index, filename: this.filename }; } }; tree.mixin.Definition = function (name, params, rules, condition, variadic) { this.name = name; this.selectors = [new(tree.Selector)([new(tree.Element)(null, name)])]; this.params = params; this.condition = condition; this.variadic = variadic; this.arity = params.length; this.rules = rules; this._lookups = {}; this.required = params.reduce(function (count, p) { if (!p.name || (p.name && !p.value)) { return count + 1 } else { return count } }, 0); this.parent = tree.Ruleset.prototype; this.frames = []; }; tree.mixin.Definition.prototype = { toCSS: function () { return "" }, variable: function (name) { return this.parent.variable.call(this, name) }, variables: function () { return this.parent.variables.call(this) }, find: function () { return this.parent.find.apply(this, arguments) }, rulesets: function () { return this.parent.rulesets.apply(this) }, evalParams: function (env, args) { var frame = new(tree.Ruleset)(null, []), varargs; for (var i = 0, val, name; i < this.params.length; i++) { if (name = this.params[i].name) { if (this.params[i].variadic && args) { varargs = []; for (var j = i; j < args.length; j++) { varargs.push(args[j].eval(env)); } frame.rules.unshift(new(tree.Rule)(name, new(tree.Expression)(varargs).eval(env))); } else if (val = (args && args[i]) || this.params[i].value) { frame.rules.unshift(new(tree.Rule)(name, val.eval(env))); } else { throw { type: 'Runtime', message: "wrong number of arguments for " + this.name + ' (' + args.length + ' for ' + this.arity + ')' }; } } } return frame; }, eval: function (env, args, important) { var frame = this.evalParams(env, args), context, _arguments = [], rules, start; for (var i = 0; i < Math.max(this.params.length, args && args.length); i++) { _arguments.push(args[i] || this.params[i].value); } frame.rules.unshift(new(tree.Rule)('@arguments', new(tree.Expression)(_arguments).eval(env))); rules = important ? this.rules.map(function (r) { return new(tree.Rule)(r.name, r.value, '!important', r.index); }) : this.rules.slice(0); return new(tree.Ruleset)(null, rules).eval({ frames: [this, frame].concat(this.frames, env.frames) }); }, match: function (args, env) { var argsLength = (args && args.length) || 0, len, frame; if (! this.variadic) { if (argsLength < this.required) { return false } if (argsLength > this.params.length) { return false } if ((this.required > 0) && (argsLength > this.params.length)) { return false } } if (this.condition && !this.condition.eval({ frames: [this.evalParams(env, args)].concat(env.frames) })) { return false } len = Math.min(argsLength, this.arity); for (var i = 0; i < len; i++) { if (!this.params[i].name) { if (args[i].eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) { return false; } } } return true; } }; })(require('../tree')); (function (tree) { tree.Operation = function (op, operands) { this.op = op.trim(); this.operands = operands; }; tree.Operation.prototype.eval = function (env) { var a = this.operands[0].eval(env), b = this.operands[1].eval(env), temp; if (a instanceof tree.Dimension && b instanceof tree.Color) { if (this.op === '*' || this.op === '+') { temp = b, b = a, a = temp; } else { throw { name: "OperationError", message: "Can't substract or divide a color from a number" }; } } return a.operate(this.op, b); }; tree.operate = function (op, a, b) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; } }; })(require('../tree')); (function (tree) { tree.Paren = function (node) { this.value = node; }; tree.Paren.prototype = { toCSS: function (env) { return '(' + this.value.toCSS(env) + ')'; }, eval: function (env) { return new(tree.Paren)(this.value.eval(env)); } }; })(require('../tree')); (function (tree) { tree.Quoted = function (str, content, escaped, i) { this.escaped = escaped; this.value = content || ''; this.quote = str.charAt(0); this.index = i; }; tree.Quoted.prototype = { toCSS: function () { if (this.escaped) { return this.value; } else { return this.quote + this.value + this.quote; } }, eval: function (env) { var that = this; var value = this.value.replace(/`([^`]+)`/g, function (_, exp) { return new(tree.JavaScript)(exp, that.index, true).eval(env).value; }).replace(/@\{([\w-]+)\}/g, function (_, name) { var v = new(tree.Variable)('@' + name, that.index).eval(env); return ('value' in v) ? v.value : v.toCSS(); }); return new(tree.Quoted)(this.quote + value + this.quote, value, this.escaped, this.index); } }; })(require('../tree')); (function (tree) { tree.Rule = function (name, value, important, index, inline) { this.name = name; this.value = (value instanceof tree.Value) ? value : new(tree.Value)([value]); this.important = important ? ' ' + important.trim() : ''; this.index = index; this.inline = inline || false; if (name.charAt(0) === '@') { this.variable = true; } else { this.variable = false } }; tree.Rule.prototype.toCSS = function (env) { if (this.variable) { return "" } else { return this.name + (env.compress ? ':' : ': ') + this.value.toCSS(env) + this.important + (this.inline ? "" : ";"); } }; tree.Rule.prototype.eval = function (context) { return new(tree.Rule)(this.name, this.value.eval(context), this.important, this.index, this.inline); }; tree.Shorthand = function (a, b) { this.a = a; this.b = b; }; tree.Shorthand.prototype = { toCSS: function (env) { return this.a.toCSS(env) + "/" + this.b.toCSS(env); }, eval: function () { return this } }; })(require('../tree')); (function (tree) { tree.Ruleset = function (selectors, rules, strictImports) { this.selectors = selectors; this.rules = rules; this._lookups = {}; this.strictImports = strictImports; }; tree.Ruleset.prototype = { eval: function (env) { var selectors = this.selectors && this.selectors.map(function (s) { return s.eval(env) }); var ruleset = new(tree.Ruleset)(selectors, this.rules.slice(0), this.strictImports); ruleset.root = this.root; ruleset.allowImports = this.allowImports; // push the current ruleset to the frames stack env.frames.unshift(ruleset); // Evaluate imports if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) { for (var i = 0; i < ruleset.rules.length; i++) { if (ruleset.rules[i] instanceof tree.Import) { Array.prototype.splice .apply(ruleset.rules, [i, 1].concat(ruleset.rules[i].eval(env))); } } } // Store the frames around mixin definitions, // so they can be evaluated like closures when the time comes. for (var i = 0; i < ruleset.rules.length; i++) { if (ruleset.rules[i] instanceof tree.mixin.Definition) { ruleset.rules[i].frames = env.frames.slice(0); } } // Evaluate mixin calls. for (var i = 0; i < ruleset.rules.length; i++) { if (ruleset.rules[i] instanceof tree.mixin.Call) { Array.prototype.splice .apply(ruleset.rules, [i, 1].concat(ruleset.rules[i].eval(env))); } } // Evaluate everything else for (var i = 0, rule; i < ruleset.rules.length; i++) { rule = ruleset.rules[i]; if (! (rule instanceof tree.mixin.Definition)) { ruleset.rules[i] = rule.eval ? rule.eval(env) : rule; } } // Pop the stack env.frames.shift(); return ruleset; }, match: function (args) { return !args || args.length === 0; }, variables: function () { if (this._variables) { return this._variables } else { return this._variables = this.rules.reduce(function (hash, r) { if (r instanceof tree.Rule && r.variable === true) { hash[r.name] = r; } return hash; }, {}); } }, variable: function (name) { return this.variables()[name]; }, rulesets: function () { if (this._rulesets) { return this._rulesets } else { return this._rulesets = this.rules.filter(function (r) { return (r instanceof tree.Ruleset) || (r instanceof tree.mixin.Definition); }); } }, find: function (selector, self) { self = self || this; var rules = [], rule, match, key = selector.toCSS(); if (key in this._lookups) { return this._lookups[key] } this.rulesets().forEach(function (rule) { if (rule !== self) { for (var j = 0; j < rule.selectors.length; j++) { if (match = selector.match(rule.selectors[j])) { if (selector.elements.length > rule.selectors[j].elements.length) { Array.prototype.push.apply(rules, rule.find( new(tree.Selector)(selector.elements.slice(1)), self)); } else { rules.push(rule); } break; } } } }); return this._lookups[key] = rules; }, // // Entry point for code generation // // `context` holds an array of arrays. // toCSS: function (context, env) { var css = [], // The CSS output rules = [], // node.Rule instances rulesets = [], // node.Ruleset instances paths = [], // Current selectors selector, // The fully rendered selector rule; if (! this.root) { if (context.length === 0) { paths = this.selectors.map(function (s) { return [s] }); } else { this.joinSelectors(paths, context, this.selectors); } } // Compile rules and rulesets for (var i = 0; i < this.rules.length; i++) { rule = this.rules[i]; if (rule.rules || (rule instanceof tree.Directive) || (rule instanceof tree.Media)) { rulesets.push(rule.toCSS(paths, env)); } else if (rule instanceof tree.Comment) { if (!rule.silent) { if (this.root) { rulesets.push(rule.toCSS(env)); } else { rules.push(rule.toCSS(env)); } } } else { if (rule.toCSS && !rule.variable) { rules.push(rule.toCSS(env)); } else if (rule.value && !rule.variable) { rules.push(rule.value.toString()); } } } rulesets = rulesets.join(''); // If this is the root node, we don't render // a selector, or {}. // Otherwise, only output if this ruleset has rules. if (this.root) { css.push(rules.join(env.compress ? '' : '\n')); } else { if (rules.length > 0) { selector = paths.map(function (p) { return p.map(function (s) { return s.toCSS(env); }).join('').trim(); }).join( env.compress ? ',' : ',\n'); css.push(selector, (env.compress ? '{' : ' {\n ') + rules.join(env.compress ? '' : '\n ') + (env.compress ? '}' : '\n}\n')); } } css.push(rulesets); return css.join('') + (env.compress ? '\n' : ''); }, joinSelectors: function (paths, context, selectors) { for (var s = 0; s < selectors.length; s++) { this.joinSelector(paths, context, selectors[s]); } }, joinSelector: function (paths, context, selector) { var before = [], after = [], beforeElements = [], afterElements = [], hasParentSelector = false, el; for (var i = 0; i < selector.elements.length; i++) { el = selector.elements[i]; if (el.combinator.value.charAt(0) === '&') { hasParentSelector = true; } if (hasParentSelector) afterElements.push(el); else beforeElements.push(el); } if (! hasParentSelector) { afterElements = beforeElements; beforeElements = []; } if (beforeElements.length > 0) { before.push(new(tree.Selector)(beforeElements)); } if (afterElements.length > 0) { after.push(new(tree.Selector)(afterElements)); } for (var c = 0; c < context.length; c++) { paths.push(before.concat(context[c]).concat(after)); } } }; })(require('../tree')); (function (tree) { tree.Selector = function (elements) { this.elements = elements; if (this.elements[0].combinator.value === "") { this.elements[0].combinator.value = ' '; } }; tree.Selector.prototype.match = function (other) { var len = this.elements.length, olen = other.elements.length, max = Math.min(len, olen); if (len < olen) { return false; } else { for (var i = 0; i < max; i++) { if (this.elements[i].value !== other.elements[i].value) { return false; } } } return true; }; tree.Selector.prototype.eval = function (env) { return new(tree.Selector)(this.elements.map(function (e) { return e.eval(env); })); }; tree.Selector.prototype.toCSS = function (env) { if (this._css) { return this._css } return this._css = this.elements.map(function (e) { if (typeof(e) === 'string') { return ' ' + e.trim(); } else { return e.toCSS(env); } }).join(''); }; })(require('../tree')); (function (tree) { tree.URL = function (val, paths) { if (val.data) { this.attrs = val; } else { // Add the base path if the URL is relative and we are in the browser if (typeof(window) !== 'undefined' && !/^(?:https?:\/\/|file:\/\/|data:|\/)/.test(val.value) && paths.length > 0) { val.value = paths[0] + (val.value.charAt(0) === '/' ? val.value.slice(1) : val.value); } this.value = val; this.paths = paths; } }; tree.URL.prototype = { toCSS: function () { return "url(" + (this.attrs ? 'data:' + this.attrs.mime + this.attrs.charset + this.attrs.base64 + this.attrs.data : this.value.toCSS()) + ")"; }, eval: function (ctx) { return this.attrs ? this : new(tree.URL)(this.value.eval(ctx), this.paths); } }; })(require('../tree')); (function (tree) { tree.Value = function (value) { this.value = value; this.is = 'value'; }; tree.Value.prototype = { eval: function (env) { if (this.value.length === 1) { return this.value[0].eval(env); } else { return new(tree.Value)(this.value.map(function (v) { return v.eval(env); })); } }, toCSS: function (env) { return this.value.map(function (e) { return e.toCSS(env); }).join(env.compress ? ',' : ', '); } }; })(require('../tree')); (function (tree) { tree.Variable = function (name, index, file) { this.name = name, this.index = index, this.file = file }; tree.Variable.prototype = { eval: function (env) { var variable, v, name = this.name; if (name.indexOf('@@') == 0) { name = '@' + new(tree.Variable)(name.slice(1)).eval(env).value; } if (variable = tree.find(env.frames, function (frame) { if (v = frame.variable(name)) { return v.value.eval(env); } })) { return variable } else { throw { type: 'Name', message: "variable " + name + " is undefined", filename: this.file, index: this.index }; } } }; })(require('../tree')); (function (tree) { tree.find = function (obj, fun) { for (var i = 0, r; i < obj.length; i++) { if (r = fun.call(obj, obj[i])) { return r } } return null; }; tree.jsify = function (obj) { if (Array.isArray(obj.value) && (obj.value.length > 1)) { return '[' + obj.value.map(function (v) { return v.toCSS(false) }).join(', ') + ']'; } else { return obj.toCSS(false); } }; })(require('./tree')); var name; function writeError(e) { print("[ERROR] " + e.message + " (line:" + e.line + ", column:" + e.column + ")"); } function loadStyleSheet(sheet, callback, reload, remaining) { var sheetName = name.slice(0, name.lastIndexOf('/') + 1) + sheet.href; var input = readFile(sheetName); var parser = new less.Parser({ paths: [sheet.href.replace(/[\w\.-]+$/, '')] }); parser.parse(input, function (e, root) { if (e) { writeError(e); quit(1); } callback(null, root, sheet, { local: false, lastModified: 0, remaining: remaining }); }); // callback({}, sheet, { local: true, remaining: remaining }); } function writeFile(filename, content) { var fstream = new java.io.FileWriter(filename); var out = new java.io.BufferedWriter(fstream); out.write(content); out.close(); } // Command line integration via Rhino (function (args) { name = args[0]; var output = args[1]; if (!name) { print('No files present in the fileset; Check your pattern match in build.xml'); quit(1); } path = name.split("/");path.pop();path=path.join("/") var input = readFile(name); if (!input) { print('lesscss: couldn\'t open file ' + name); quit(1); } var result; var parser = new less.Parser(); parser.parse(input, function (e, root) { if (e) { writeError(e); quit(1); } else { result = root.toCSS(); if (output) { writeFile(output, result); print("Written to " + output); } else { print(result); } quit(0); } }); print("done"); }(arguments));
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const models = require('./index'); /** * A copy activity source for a MongoDB database. * * @extends models['CopySource'] */ class MongoDbSource extends models['CopySource'] { /** * Create a MongoDbSource. * @member {object} [query] Database query. Should be a SQL-92 query * expression. Type: string (or Expression with resultType string). */ constructor() { super(); } /** * Defines the metadata of MongoDbSource * * @returns {object} metadata of MongoDbSource * */ mapper() { return { required: false, serializedName: 'MongoDbSource', type: { name: 'Composite', className: 'MongoDbSource', modelProperties: { sourceRetryCount: { required: false, serializedName: 'sourceRetryCount', type: { name: 'Object' } }, sourceRetryWait: { required: false, serializedName: 'sourceRetryWait', type: { name: 'Object' } }, type: { required: true, serializedName: 'type', type: { name: 'String' } }, query: { required: false, serializedName: 'query', type: { name: 'Object' } } } } }; } } module.exports = MongoDbSource;
// track the outbound link with Google Analytics GoogleAnalyticsTracker = $.klass({ onclick: function() { var uri = this.element.attr("href"); this.track(uri); }, track: function(uri) { if (this.isOutbound(uri)) { host = URI.parse(uri).host.replace(/^www\./, ""); pageTracker._trackEvent('Outbound links [' + host + ']', 'Click', uri); } }, isOutbound: function(uri) { if(URI.parse(uri).host != URI.parse(window.location).host) { return true; } else { return false; } } }); jQuery(function($) { if (typeof(pageTracker) != 'undefined') { $("a[href^=http]").attach(GoogleAnalyticsTracker); } });
var _ = require("lodash"); var dd = require("react-dd"); var React = require("react"); require("../bootstrap.min.css"); require("react-loose-forms.bootstrap3").install(require("react-loose-forms/InputTypes")); var TicketForm = require("./TicketForm"); var App = dd.createClass({ getInitialState: function(){ return { opened_ticket_id: null, tickets: _.object(_.map([ {product: "Dehydrated Boulders", description: "When I opened your box, they fell into my glass of water... as a result I broke both my legs :(", date: "2015 Jul 27", level: "High"}, {product: "Jet-Propelled Unicycle", description: "The jet's were installed backwards!", date: "2015 Jul 28", level: "High"}, {product: "DIY Tornado Kit", description: "I planted 10 tornado seeds in my neighbors yard, but 3 of them attacked my house!", date: "2015 Jul 26", level: "Medium"}, {product: "Earthquake Pills", description: "I ate them, but it didn't do anything!?!?", date: "2015 Jul 25", level: "Low"}, {product: "Iron Carrot", description: "I chipped my tooth!", date: "2015 Jul 25", level: "Low"} ], function(t, i){ var t2 = _.assign({id: "111" + i}, t); return [t2.id, t2]; })) }; }, __saveTicket: function(data){ console.log(JSON.stringify(data, false, 2)); var opened_ticket_id = this.state.opened_ticket_id; var opened_ticket = this.state.tickets[opened_ticket_id]; if(opened_ticket){ this.setState({tickets: _.assign(this.state.tickets, _.object([ [opened_ticket_id, _.assign(opened_ticket, data)] ]))}); }else{ var new_id = _.uniqueId("new"); this.setState({tickets: _.assign(this.state.tickets, _.object([ [new_id, _.assign(data, {id: new_id, date: "today"})] ]))}); } }, __openTicketOnClick: function(id){ var self = this; return function(e){ e.preventDefault(); self.setState({opened_ticket_id: id}); }; }, render: function(){ var tickets = this.state.tickets; var opened_ticket_id = this.state.opened_ticket_id; var opened_ticket = tickets[opened_ticket_id]; return dd.div({className: "container-fluid"}, dd.h1(null, "ACME Bug Tracker"), dd.div({className: "row"}, dd.div({className: "col-sm-6"}, dd.table({className: "table"}, dd.thead(null, dd.tr(null, dd.th(null, "Date"), dd.th(null, "Product"), dd.th(null, "Description"), dd.th(null, "Level") ) ), dd.tbody(null, _.map(tickets, function(ticket, id){ var is_open = opened_ticket && (opened_ticket.id === id); return dd.tr({key: id, onClick: this.__openTicketOnClick(id), className: is_open ? "active" : null}, dd.td(null, dd[is_open ? "b" : "span"](null, ticket.date)), dd.td(null, dd[is_open ? "b" : "span"](null, ticket.product)), dd.td(null, dd[is_open ? "b" : "span"](null, ticket.description)), dd.td(null, dd[is_open ? "b" : "span"](null, ticket.level)) ); }, this) ) ) ), opened_ticket ? dd.div({className: "col-sm-6"}, dd.div({style: {width: 500}}, dd.div({className: "well"}, dd.h3({style: {marginTop: 0}}, "Ticket #" + opened_ticket.id, dd.small({className: "pull-right"}, opened_ticket.date) ), TicketForm({ onSubmit: this.__saveTicket, ticket: opened_ticket }) ) ) ) : null ) ); } }); React.render(App(), document.body);
'use strict'; exports.__esModule = true; exports['default'] = bufferTime; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } 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; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _Subscriber2 = require('../Subscriber'); var _Subscriber3 = _interopRequireDefault(_Subscriber2); var _schedulersNextTick = require('../schedulers/nextTick'); var _schedulersNextTick2 = _interopRequireDefault(_schedulersNextTick); /** * buffers values from the source for a specific time period. Optionally allows new buffers to be set up at an interval. * @param {number} the amount of time to fill each buffer for before emitting them and clearing them. * @param {number} [bufferCreationInterval] the interval at which to start new buffers. * @param {Scheduler} [scheduler] (optional, defaults to `nextTick` scheduler) The scheduler on which to schedule the * intervals that determine buffer boundaries. * @returns {Observable<T[]>} an observable of arrays of buffered values. */ function bufferTime(bufferTimeSpan) { var bufferCreationInterval = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; var scheduler = arguments.length <= 2 || arguments[2] === undefined ? _schedulersNextTick2['default'] : arguments[2]; return this.lift(new BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, scheduler)); } var BufferTimeOperator = (function () { function BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, scheduler) { _classCallCheck(this, BufferTimeOperator); this.bufferTimeSpan = bufferTimeSpan; this.bufferCreationInterval = bufferCreationInterval; this.scheduler = scheduler; } BufferTimeOperator.prototype.call = function call(subscriber) { return new BufferTimeSubscriber(subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.scheduler); }; return BufferTimeOperator; })(); var BufferTimeSubscriber = (function (_Subscriber) { _inherits(BufferTimeSubscriber, _Subscriber); function BufferTimeSubscriber(destination, bufferTimeSpan, bufferCreationInterval, scheduler) { _classCallCheck(this, BufferTimeSubscriber); _Subscriber.call(this, destination); this.bufferTimeSpan = bufferTimeSpan; this.bufferCreationInterval = bufferCreationInterval; this.scheduler = scheduler; this.buffers = []; var buffer = this.openBuffer(); if (bufferCreationInterval !== null && bufferCreationInterval >= 0) { var closeState = { subscriber: this, buffer: buffer }; var creationState = { bufferTimeSpan: bufferTimeSpan, bufferCreationInterval: bufferCreationInterval, subscriber: this, scheduler: scheduler }; this.add(scheduler.schedule(dispatchBufferClose, bufferTimeSpan, closeState)); this.add(scheduler.schedule(dispatchBufferCreation, bufferCreationInterval, creationState)); } else { var timeSpanOnlyState = { subscriber: this, buffer: buffer, bufferTimeSpan: bufferTimeSpan }; this.add(scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState)); } } BufferTimeSubscriber.prototype._next = function _next(value) { var buffers = this.buffers; var len = buffers.length; for (var i = 0; i < len; i++) { buffers[i].push(value); } }; BufferTimeSubscriber.prototype._error = function _error(err) { this.buffers.length = 0; this.destination.error(err); }; BufferTimeSubscriber.prototype._complete = function _complete() { var buffers = this.buffers; while (buffers.length > 0) { this.destination.next(buffers.shift()); } this.destination.complete(); }; BufferTimeSubscriber.prototype.openBuffer = function openBuffer() { var buffer = []; this.buffers.push(buffer); return buffer; }; BufferTimeSubscriber.prototype.closeBuffer = function closeBuffer(buffer) { this.destination.next(buffer); var buffers = this.buffers; buffers.splice(buffers.indexOf(buffer), 1); }; return BufferTimeSubscriber; })(_Subscriber3['default']); function dispatchBufferTimeSpanOnly(state) { var subscriber = state.subscriber; var prevBuffer = state.buffer; if (prevBuffer) { subscriber.closeBuffer(prevBuffer); } state.buffer = subscriber.openBuffer(); if (!subscriber.isUnsubscribed) { this.schedule(state, state.bufferTimeSpan); } } function dispatchBufferCreation(state) { var bufferCreationInterval = state.bufferCreationInterval; var bufferTimeSpan = state.bufferTimeSpan; var subscriber = state.subscriber; var scheduler = state.scheduler; var buffer = subscriber.openBuffer(); var action = this; if (!subscriber.isUnsubscribed) { action.add(scheduler.schedule(dispatchBufferClose, bufferTimeSpan, { subscriber: subscriber, buffer: buffer })); action.schedule(state, bufferCreationInterval); } } function dispatchBufferClose(_ref) { var subscriber = _ref.subscriber; var buffer = _ref.buffer; subscriber.closeBuffer(buffer); } //# sourceMappingURL=bufferTime.js.map module.exports = exports['default']; //# sourceMappingURL=bufferTime.js.map
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><defs><path id="a" d="M0 0h24v24H0V0z" /></defs><path d="M12 5V1L7 6l5 5V7c3.3 0 6 2.7 6 6s-2.7 6-6 6-6-2.7-6-6H4c0 4.4 3.6 8 8 8s8-3.6 8-8-3.6-8-8-8zm-2.4 8.5h.4c.2 0 .4-.1.5-.2s.2-.2.2-.4v-.2s-.1-.1-.1-.2-.1-.1-.2-.1h-.5s-.1.1-.2.1-.1.1-.1.2v.2h-1c0-.2 0-.3.1-.5s.2-.3.3-.4.3-.2.4-.2.4-.1.5-.1c.2 0 .4 0 .6.1s.3.1.5.2.2.2.3.4.1.3.1.5v.3s-.1.2-.1.3-.1.2-.2.2-.2.1-.3.2c.2.1.4.2.5.4s.2.4.2.6c0 .2 0 .4-.1.5s-.2.3-.3.4-.3.2-.5.2-.4.1-.6.1c-.2 0-.4 0-.5-.1s-.3-.1-.5-.2-.2-.2-.3-.4-.1-.4-.1-.6h.8v.2s.1.1.1.2.1.1.2.1h.5s.1-.1.2-.1.1-.1.1-.2v-.5s-.1-.1-.1-.2-.1-.1-.2-.1h-.6v-.7zm5.7.7c0 .3 0 .6-.1.8l-.3.6s-.3.3-.5.3-.4.1-.6.1-.4 0-.6-.1-.3-.2-.5-.3-.2-.3-.3-.6-.1-.5-.1-.8v-.7c0-.3 0-.6.1-.8l.3-.6s.3-.3.5-.3.4-.1.6-.1.4 0 .6.1.3.2.5.3.2.3.3.6.1.5.1.8v.7zm-.8-.8v-.5c0-.1-.1-.2-.1-.3s-.1-.1-.2-.2-.2-.1-.3-.1-.2 0-.3.1l-.2.2s-.1.2-.1.3v2s.1.2.1.3.1.1.2.2.2.1.3.1.2 0 .3-.1l.2-.2s.1-.2.1-.3v-1.5z" /></React.Fragment> , 'Replay30');
//>>built define("dgrid1/extensions/nls/tr/columnHider",{popupLabel:"S\u00fctunlar\u0131 g\u00f6ster ya da gizle"});
"use strict"; var fs = require ("fs"); var path = require ("path"); var parse = require ("./parse"); var INCLUDE_KEY = "include"; var INDEX_FILE = "index.properties"; var cast = function (value){ if (value === null || value === "null") return null; if (value === "undefined") return undefined; if (value === "true") return true; if (value === "false") return false; var v = Number (value); return isNaN (v) ? value : v; }; var expand = function (o, str, options, cb){ if (!options.variables || !str) return cb (null, str); var stack = []; var c; var cp; var key = ""; var section = null; var v; var holder; var t; var n; for (var i=0; i<str.length; i++){ c = str[i]; if (cp === "$" && c === "{"){ key = key.substring (0, key.length - 1); stack.push ({ key: key, section: section }); key = ""; section = null; continue; }else if (stack.length){ if (options.sections && c === "|"){ section = key; key = ""; continue; }else if (c === "}"){ holder = section !== null ? searchValue (o, section, true) : o; if (!holder){ return cb (new Error ("The section \"" + section + "\" does not " + "exist")); } v = options.namespaces ? searchValue (holder, key) : holder[key]; if (v === undefined){ //Read the external vars v = options.namespaces ? searchValue (options._vars, key) : options._vars[key] if (v === undefined){ return cb (new Error ("The property \"" + key + "\" does not " + "exist")); } } t = stack.pop (); section = t.section; key = t.key + (v === null ? "" : v); continue; } } cp = c; key += c; } if (stack.length !== 0){ return cb (new Error ("Malformed variable: " + str)); } cb (null, key); }; var searchValue = function (o, chain, section){ var n = chain.split ("."); var str; for (var i=0; i<n.length-1; i++){ str = n[i]; if (o[str] === undefined) return; o = o[str]; } var v = o[n[n.length - 1]]; if (section){ if (typeof v !== "object") return; return v; }else{ if (typeof v === "object") return; return v; } }; var namespaceKey = function (o, key, value){ var n = key.split ("."); var str; for (var i=0; i<n.length-1; i++){ str = n[i]; if (o[str] === undefined){ o[str] = {}; }else if (typeof o[str] !== "object"){ throw new Error ("Invalid namespace chain in the property name '" + key + "' ('" + str + "' has already a value)"); } o = o[str]; } o[n[n.length - 1]] = value; }; var namespaceSection = function (o, section){ var n = section.split ("."); var str; for (var i=0; i<n.length; i++){ str = n[i]; if (o[str] === undefined){ o[str] = {}; }else if (typeof o[str] !== "object"){ throw new Error ("Invalid namespace chain in the section name '" + section + "' ('" + str + "' has already a value)"); } o = o[str]; } return o; }; var merge = function (o1, o2){ for (var p in o2){ try{ if (o1[p].constructor === Object){ o1[p] = merge (o1[p], o2[p]); }else{ o1[p] = o2[p]; } }catch (e){ o1[p] = o2[p]; } } return o1; } var build = function (data, options, dirname, cb){ var o = {}; if (options.namespaces){ var n = {}; } var control = { abort: false, skipSection: false }; if (options.include){ var remainingIncluded = 0; var include = function (value){ if (currentSection !== null){ return abort (new Error ("Cannot include files from inside a " + "section: " + currentSection)); } var p = path.resolve (dirname, value); if (options._included[p]) return; options._included[p] = true; remainingIncluded++; control.pause = true; read (p, options, function (error, included){ if (error) return abort (error); remainingIncluded--; merge (options.namespaces ? n : o, included); control.pause = false; if (!control.parsed){ parse (data, options, handlers, control); if (control.error) return abort (control.error); } if (!remainingIncluded) cb (null, options.namespaces ? n : o); }); }; } if (!data){ if (cb) return cb (null, o); return o; } var currentSection = null; var currentSectionStr = null; var abort = function (error){ control.abort = true; if (cb) return cb (error); throw error; }; var handlers = {}; var reviver = { assert: function (){ return this.isProperty ? reviverLine.value : true; } }; var reviverLine = {}; //Line handler //For speed reasons, if "namespaces" is enabled, the old object is still //populated, e.g.: ${a.b} reads the "a.b" property from { "a.b": 1 }, instead //of having a unique object { a: { b: 1 } } which is slower to search for //the "a.b" value //If "a.b" is not found, then the external vars are read. If "namespaces" is //enabled, the var "a.b" is split and it searches the a.b value. If it is not //enabled, then the var "a.b" searches the "a.b" value var line; var error; if (options.reviver){ if (options.sections){ line = function (key, value){ if (options.include && key === INCLUDE_KEY) return include (value); reviverLine.value = value; reviver.isProperty = true; reviver.isSection = false; value = options.reviver.call (reviver, key, value, currentSectionStr); if (value !== undefined){ if (options.namespaces){ try{ namespaceKey (currentSection === null ? n : currentSection, key, value); }catch (error){ abort (error); } }else{ if (currentSection === null) o[key] = value; else currentSection[key] = value; } } }; }else{ line = function (key, value){ if (options.include && key === INCLUDE_KEY) return include (value); reviverLine.value = value; reviver.isProperty = true; reviver.isSection = false; value = options.reviver.call (reviver, key, value); if (value !== undefined){ if (options.namespaces){ try{ namespaceKey (n, key, value); }catch (error){ abort (error); } }else{ o[key] = value; } } }; } }else{ if (options.sections){ line = function (key, value){ if (options.include && key === INCLUDE_KEY) return include (value); if (options.namespaces){ try{ namespaceKey (currentSection === null ? n : currentSection, key, value); }catch (error){ abort (error); } }else{ if (currentSection === null) o[key] = value; else currentSection[key] = value; } }; }else{ line = function (key, value){ if (options.include && key === INCLUDE_KEY) return include (value); if (options.namespaces){ try{ namespaceKey (n, key, value); }catch (error){ abort (error); } }else{ o[key] = value; } }; } } //Section handler var section; if (options.sections){ if (options.reviver){ section = function (section){ currentSectionStr = section; reviverLine.section = section; reviver.isProperty = false; reviver.isSection = true; var add = options.reviver.call (reviver, null, null, section); if (add){ if (options.namespaces){ try{ currentSection = namespaceSection (n, section); }catch (error){ abort (error); } }else{ currentSection = o[section] = {}; } }else{ control.skipSection = true; } }; }else{ section = function (section){ currentSectionStr = section; if (options.namespaces){ try{ currentSection = namespaceSection (n, section); }catch (error){ abort (error); } }else{ currentSection = o[section] = {}; } }; } } //Variables if (options.variables){ handlers.line = function (key, value){ expand (options.namespaces ? n : o, key, options, function (error, key){ if (error) return abort (error); expand (options.namespaces ? n : o, value, options, function (error, value){ if (error) return abort (error); line (key, cast (value || null)); }); }); }; if (options.sections){ handlers.section = function (s){ expand (options.namespaces ? n : o, s, options, function (error, s){ if (error) return abort (error); section (s); }); }; } }else{ handlers.line = function (key, value){ line (key, cast (value || null)); }; if (options.sections){ handlers.section = section; } } parse (data, options, handlers, control); if (control.error) return abort (control.error); if (control.abort || control.pause) return; if (cb) return cb (null, options.namespaces ? n : o); return options.namespaces ? n : o; }; var read = function (f, options, cb){ fs.stat (f, function (error, stats){ if (error) return cb (error); var dirname; if (stats.isDirectory ()){ dirname = f; f = path.join (f, INDEX_FILE); }else{ dirname = path.dirname (f); } fs.readFile (f, { encoding: "utf8" }, function (error, data){ if (error) return cb (error); build (data, options, dirname, cb); }); }); }; module.exports = function (data, options, cb){ if (typeof options === "function"){ cb = options; options = {}; } options = options || {}; var code; if (options.include){ if (!cb) throw new Error ("A callback must be passed if the 'include' " + "option is enabled"); options._included = {}; } options = options || {}; options._strict = options.strict && (options.comments || options.separators); options._vars = options.vars || {}; var comments = options.comments || []; if (!Array.isArray (comments)) comments = [comments]; var c = {}; comments.forEach (function (comment){ code = comment.charCodeAt (0); if (comment.length > 1 || code < 33 || code > 126){ throw new Error ("The comment token must be a single printable ASCII " + "character"); } c[comment] = true; }); options._comments = c; var separators = options.separators || []; if (!Array.isArray (separators)) separators = [separators]; var s = {}; separators.forEach (function (separator){ code = separator.charCodeAt (0); if (separator.length > 1 || code < 33 || code > 126){ throw new Error ("The separator token must be a single printable ASCII " + "character"); } s[separator] = true; }); options._separators = s; if (options.path){ if (!cb) throw new Error ("A callback must be passed if the 'path' " + "option is enabled"); if (options.include){ read (data, options, cb); }else{ fs.readFile (data, { encoding: "utf8" }, function (error, data){ if (error) return cb (error); build (data, options, ".", cb); }); } }else{ return build (data, options, ".", cb); } };
export class ImageShape{constructor(){this.height=100,this.replaceColor=!0,this.src="",this.width=100,this.fill=!0,this.close=!0}get replace_color(){return this.replaceColor}set replace_color(i){this.replaceColor=i}load(i){var o;if(void 0!==i){void 0!==i.height&&(this.height=i.height);const e=null!==(o=i.replaceColor)&&void 0!==o?o:i.replace_color;void 0!==e&&(this.replaceColor=e),void 0!==i.src&&(this.src=i.src),void 0!==i.width&&(this.width=i.width)}}};
import './chunk-1fafdf15.js'; import './helpers.js'; import './chunk-6985c8ce.js'; import { I as Icon } from './chunk-cdfca85b.js'; export { I as BIcon } from './chunk-cdfca85b.js'; import { r as registerComponent, u as use } from './chunk-cca88db8.js'; var Plugin = { install: function install(Vue) { registerComponent(Vue, Icon); } }; use(Plugin); export default Plugin;
"use strict"; import Constants from "../constants"; import Dispatcher from "../dispatcher"; import Api from "./api"; export default { loadAccounts(){ Dispatcher.dispatch({action: Constants.ACCOUNTS_LOADING}); Api.get(Constants.ACCOUNTS_LOADED, "api/accounts/"); }, loadUsers(accountId, page){ if(!page){ page = 1; } var perPage = 100; Dispatcher.dispatch({action: Constants.USERS_LOADING, payload: accountId}); Api.get(Constants.USERS_LOADED, "api/accounts/" + accountId + "/users?page=" + page + "&per_page=" + perPage); }, changeNav(){ Dispatcher.dispatch({action: Constants.NAV_CHANGED}); }, resetUsersStore(){ Dispatcher.dispatch({action: Constants.RESET_USERS}); }, changeMainTab(payload){ Dispatcher.dispatch({ action: Constants.CHANGE_MAIN_TAB_PENDING, mainTab: payload.text }); }, getUserData(payload){ Dispatcher.dispatch({action: Constants.LOADING_USER_DATA, userList: payload.userList}); }, setCurrentSelectedUser(payload){ Dispatcher.dispatch({action: Constants.LOADING_SELECTED_USER_DATA, currentSelectedUser: payload.currentSelectedUser}); }, updateUser(accountID, userID, payload){ Dispatcher.dispatch({action: Constants.USER_UPDATING}); Api.put(Constants.USER_UPDATED, "api/accounts/"+ accountID + "/users/" + userID, payload); }, addToSelectedUsers(payload){ Dispatcher.dispatch({action: Constants.ADD_USER, payload: payload}); }, removeFromSelectedUsers(payload){ Dispatcher.dispatch({action: Constants.REMOVE_USER, payload: payload}); }, // deleteUsers(payload){ // for(var i=0; i<payload.length; i++){ // var url = "api/accounts/" + payload[i].account_id + "/users/" + payload[i].id; // Dispatcher.dispatch({action: Constants.DELETING_USERS}); // Api.del(Constants.DELETE_USERS, url); // } // this.loadUsers(payload[0].account_id, 1); // }, deleteUser(user){ var url = "api/accounts/" + user.account_id + "/users/" + user.id; Dispatcher.dispatch({action: Constants.DELETING_USERS}); Api.del(Constants.DELETE_USERS, url); }, createUser(accountId, payload){ Dispatcher.dispatch({action: Constants.CREATING_USER}); Api.post(Constants.CREATED_USER, '/api/accounts/'+ accountId +'/users', payload); }, };
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ const es = require('event-stream'); /** Ugly hack for gulp-tsb */ function handleDeletions() { return es.mapSync(f => { if (/\.ts$/.test(f.relative) && !f.contents) { f.contents = Buffer.from(''); f.stat = { mtime: new Date() }; } return f; }); } let watch = void 0; if (!watch) { watch = process.platform === 'win32' ? require('./watch-win32') : require('gulp-watch'); } module.exports = function () { return watch.apply(null, arguments) .pipe(handleDeletions()); };
/* Zepto v1.1.3 - zepto event ajax form ie - zeptojs.com/license */ var Zepto = (function() { var undefined, key, $, classList, emptyArray = [], slice = emptyArray.slice, filter = emptyArray.filter, document = window.document, elementDisplay = {}, classCache = {}, cssNumber = { 'column-count': 1, 'columns': 1, 'font-weight': 1, 'line-height': 1,'opacity': 1, 'z-index': 1, 'zoom': 1 }, fragmentRE = /^\s*<(\w+|!)[^>]*>/, singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rootNodeRE = /^(?:body|html)$/i, capitalRE = /([A-Z])/g, // special attributes that should be get/set via method calls methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'], adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ], table = document.createElement('table'), tableRow = document.createElement('tr'), containers = { 'tr': document.createElement('tbody'), 'tbody': table, 'thead': table, 'tfoot': table, 'td': tableRow, 'th': tableRow, '*': document.createElement('div') }, readyRE = /complete|loaded|interactive/, simpleSelectorRE = /^[\w-]*$/, class2type = {}, toString = class2type.toString, zepto = {}, camelize, uniq, tempParent = document.createElement('div'), propMap = { 'tabindex': 'tabIndex', 'readonly': 'readOnly', 'for': 'htmlFor', 'class': 'className', 'maxlength': 'maxLength', 'cellspacing': 'cellSpacing', 'cellpadding': 'cellPadding', 'rowspan': 'rowSpan', 'colspan': 'colSpan', 'usemap': 'useMap', 'frameborder': 'frameBorder', 'contenteditable': 'contentEditable' }, isArray = Array.isArray || function(object){ return object instanceof Array } zepto.matches = function(element, selector) { if (!selector || !element || element.nodeType !== 1) return false var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector || element.oMatchesSelector || element.matchesSelector if (matchesSelector) return matchesSelector.call(element, selector) // fall back to performing a selector: var match, parent = element.parentNode, temp = !parent if (temp) (parent = tempParent).appendChild(element) match = ~zepto.qsa(parent, selector).indexOf(element) temp && tempParent.removeChild(element) return match } function type(obj) { return obj == null ? String(obj) : class2type[toString.call(obj)] || "object" } function isFunction(value) { return type(value) == "function" } function isWindow(obj) { return obj != null && obj == obj.window } function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE } function isObject(obj) { return type(obj) == "object" } function isPlainObject(obj) { return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype } function likeArray(obj) { return typeof obj.length == 'number' } function compact(array) { return filter.call(array, function(item){ return item != null }) } function flatten(array) { return array.length > 0 ? $.fn.concat.apply([], array) : array } camelize = function(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) } function dasherize(str) { return str.replace(/::/g, '/') .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') .replace(/([a-z\d])([A-Z])/g, '$1_$2') .replace(/_/g, '-') .toLowerCase() } uniq = function(array){ return filter.call(array, function(item, idx){ return array.indexOf(item) == idx }) } function classRE(name) { return name in classCache ? classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)')) } function maybeAddPx(name, value) { return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value } function defaultDisplay(nodeName) { var element, display if (!elementDisplay[nodeName]) { element = document.createElement(nodeName) document.body.appendChild(element) display = getComputedStyle(element, '').getPropertyValue("display") element.parentNode.removeChild(element) display == "none" && (display = "block") elementDisplay[nodeName] = display } return elementDisplay[nodeName] } function children(element) { return 'children' in element ? slice.call(element.children) : $.map(element.childNodes, function(node){ if (node.nodeType == 1) return node }) } // `$.zepto.fragment` takes a html string and an optional tag name // to generate DOM nodes nodes from the given html string. // The generated DOM nodes are returned as an array. // This function can be overriden in plugins for example to make // it compatible with browsers that don't support the DOM fully. zepto.fragment = function(html, name, properties) { var dom, nodes, container // A special case optimization for a single tag if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1)) if (!dom) { if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>") if (name === undefined) name = fragmentRE.test(html) && RegExp.$1 if (!(name in containers)) name = '*' container = containers[name] container.innerHTML = '' + html dom = $.each(slice.call(container.childNodes), function(){ container.removeChild(this) }) } if (isPlainObject(properties)) { nodes = $(dom) $.each(properties, function(key, value) { if (methodAttributes.indexOf(key) > -1) nodes[key](value) else nodes.attr(key, value) }) } return dom } // `$.zepto.Z` swaps out the prototype of the given `dom` array // of nodes with `$.fn` and thus supplying all the Zepto functions // to the array. Note that `__proto__` is not supported on Internet // Explorer. This method can be overriden in plugins. zepto.Z = function(dom, selector) { dom = dom || [] dom.__proto__ = $.fn dom.selector = selector || '' return dom } // `$.zepto.isZ` should return `true` if the given object is a Zepto // collection. This method can be overriden in plugins. zepto.isZ = function(object) { return object instanceof zepto.Z } // `$.zepto.init` is Zepto's counterpart to jQuery's `$.fn.init` and // takes a CSS selector and an optional context (and handles various // special cases). // This method can be overriden in plugins. zepto.init = function(selector, context) { var dom // If nothing given, return an empty Zepto collection if (!selector) return zepto.Z() // Optimize for string selectors else if (typeof selector == 'string') { selector = selector.trim() // If it's a html fragment, create nodes from it // Note: In both Chrome 21 and Firefox 15, DOM error 12 // is thrown if the fragment doesn't begin with < if (selector[0] == '<' && fragmentRE.test(selector)) dom = zepto.fragment(selector, RegExp.$1, context), selector = null // If there's a context, create a collection on that context first, and select // nodes from there else if (context !== undefined) return $(context).find(selector) // If it's a CSS selector, use it to select nodes. else dom = zepto.qsa(document, selector) } // If a function is given, call it when the DOM is ready else if (isFunction(selector)) return $(document).ready(selector) // If a Zepto collection is given, just return it else if (zepto.isZ(selector)) return selector else { // normalize array if an array of nodes is given if (isArray(selector)) dom = compact(selector) // Wrap DOM nodes. else if (isObject(selector)) dom = [selector], selector = null // If it's a html fragment, create nodes from it else if (fragmentRE.test(selector)) dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null // If there's a context, create a collection on that context first, and select // nodes from there else if (context !== undefined) return $(context).find(selector) // And last but no least, if it's a CSS selector, use it to select nodes. else dom = zepto.qsa(document, selector) } // create a new Zepto collection from the nodes found return zepto.Z(dom, selector) } // `$` will be the base `Zepto` object. When calling this // function just call `$.zepto.init, which makes the implementation // details of selecting nodes and creating Zepto collections // patchable in plugins. $ = function(selector, context){ return zepto.init(selector, context) } function extend(target, source, deep) { for (key in source) if (deep && (isPlainObject(source[key]) || isArray(source[key]))) { if (isPlainObject(source[key]) && !isPlainObject(target[key])) target[key] = {} if (isArray(source[key]) && !isArray(target[key])) target[key] = [] extend(target[key], source[key], deep) } else if (source[key] !== undefined) target[key] = source[key] } // Copy all but undefined properties from one or more // objects to the `target` object. $.extend = function(target){ var deep, args = slice.call(arguments, 1) if (typeof target == 'boolean') { deep = target target = args.shift() } args.forEach(function(arg){ extend(target, arg, deep) }) return target } // `$.zepto.qsa` is Zepto's CSS selector implementation which // uses `document.querySelectorAll` and optimizes for some special cases, like `#id`. // This method can be overriden in plugins. zepto.qsa = function(element, selector){ var found, maybeID = selector[0] == '#', maybeClass = !maybeID && selector[0] == '.', nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, // Ensure that a 1 char tag name still gets checked isSimple = simpleSelectorRE.test(nameOnly) return (isDocument(element) && isSimple && maybeID) ? ( (found = element.getElementById(nameOnly)) ? [found] : [] ) : (element.nodeType !== 1 && element.nodeType !== 9) ? [] : slice.call( isSimple && !maybeID ? maybeClass ? element.getElementsByClassName(nameOnly) : // If it's simple, it could be a class element.getElementsByTagName(selector) : // Or a tag element.querySelectorAll(selector) // Or it's not simple, and we need to query all ) } function filtered(nodes, selector) { return selector == null ? $(nodes) : $(nodes).filter(selector) } $.contains = function(parent, node) { return parent !== node && parent.contains(node) } function funcArg(context, arg, idx, payload) { return isFunction(arg) ? arg.call(context, idx, payload) : arg } function setAttribute(node, name, value) { value == null ? node.removeAttribute(name) : node.setAttribute(name, value) } // access className property while respecting SVGAnimatedString function className(node, value){ var klass = node.className, svg = klass && klass.baseVal !== undefined if (value === undefined) return svg ? klass.baseVal : klass svg ? (klass.baseVal = value) : (node.className = value) } // "true" => true // "false" => false // "null" => null // "42" => 42 // "42.5" => 42.5 // "08" => "08" // JSON => parse if valid // String => self function deserializeValue(value) { var num try { return value ? value == "true" || ( value == "false" ? false : value == "null" ? null : !/^0/.test(value) && !isNaN(num = Number(value)) ? num : /^[\[\{]/.test(value) ? $.parseJSON(value) : value ) : value } catch(e) { return value } } $.type = type $.isFunction = isFunction $.isWindow = isWindow $.isArray = isArray $.isPlainObject = isPlainObject $.isEmptyObject = function(obj) { var name for (name in obj) return false return true } $.inArray = function(elem, array, i){ return emptyArray.indexOf.call(array, elem, i) } $.camelCase = camelize $.trim = function(str) { return str == null ? "" : String.prototype.trim.call(str) } // plugin compatibility $.uuid = 0 $.support = { } $.expr = { } $.map = function(elements, callback){ var value, values = [], i, key if (likeArray(elements)) for (i = 0; i < elements.length; i++) { value = callback(elements[i], i) if (value != null) values.push(value) } else for (key in elements) { value = callback(elements[key], key) if (value != null) values.push(value) } return flatten(values) } $.each = function(elements, callback){ var i, key if (likeArray(elements)) { for (i = 0; i < elements.length; i++) if (callback.call(elements[i], i, elements[i]) === false) return elements } else { for (key in elements) if (callback.call(elements[key], key, elements[key]) === false) return elements } return elements } $.grep = function(elements, callback){ return filter.call(elements, callback) } if (window.JSON) $.parseJSON = JSON.parse // Populate the class2type map $.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase() }) // Define methods that will be available on all // Zepto collections $.fn = { // Because a collection acts like an array // copy over these useful array functions. forEach: emptyArray.forEach, reduce: emptyArray.reduce, push: emptyArray.push, sort: emptyArray.sort, indexOf: emptyArray.indexOf, concat: emptyArray.concat, // `map` and `slice` in the jQuery API work differently // from their array counterparts map: function(fn){ return $($.map(this, function(el, i){ return fn.call(el, i, el) })) }, slice: function(){ return $(slice.apply(this, arguments)) }, ready: function(callback){ // need to check if document.body exists for IE as that browser reports // document ready when it hasn't yet created the body element if (readyRE.test(document.readyState) && document.body) callback($) else document.addEventListener('DOMContentLoaded', function(){ callback($) }, false) return this }, get: function(idx){ return idx === undefined ? slice.call(this) : this[idx >= 0 ? idx : idx + this.length] }, toArray: function(){ return this.get() }, size: function(){ return this.length }, remove: function(){ return this.each(function(){ if (this.parentNode != null) this.parentNode.removeChild(this) }) }, each: function(callback){ emptyArray.every.call(this, function(el, idx){ return callback.call(el, idx, el) !== false }) return this }, filter: function(selector){ if (isFunction(selector)) return this.not(this.not(selector)) return $(filter.call(this, function(element){ return zepto.matches(element, selector) })) }, add: function(selector,context){ return $(uniq(this.concat($(selector,context)))) }, is: function(selector){ return this.length > 0 && zepto.matches(this[0], selector) }, not: function(selector){ var nodes=[] if (isFunction(selector) && selector.call !== undefined) this.each(function(idx){ if (!selector.call(this,idx)) nodes.push(this) }) else { var excludes = typeof selector == 'string' ? this.filter(selector) : (likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) : $(selector) this.forEach(function(el){ if (excludes.indexOf(el) < 0) nodes.push(el) }) } return $(nodes) }, has: function(selector){ return this.filter(function(){ return isObject(selector) ? $.contains(this, selector) : $(this).find(selector).size() }) }, eq: function(idx){ return idx === -1 ? this.slice(idx) : this.slice(idx, + idx + 1) }, first: function(){ var el = this[0] return el && !isObject(el) ? el : $(el) }, last: function(){ var el = this[this.length - 1] return el && !isObject(el) ? el : $(el) }, find: function(selector){ var result, $this = this if (typeof selector == 'object') result = $(selector).filter(function(){ var node = this return emptyArray.some.call($this, function(parent){ return $.contains(parent, node) }) }) else if (this.length == 1) result = $(zepto.qsa(this[0], selector)) else result = this.map(function(){ return zepto.qsa(this, selector) }) return result }, closest: function(selector, context){ var node = this[0], collection = false if (typeof selector == 'object') collection = $(selector) while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector))) node = node !== context && !isDocument(node) && node.parentNode return $(node) }, parents: function(selector){ var ancestors = [], nodes = this while (nodes.length > 0) nodes = $.map(nodes, function(node){ if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < 0) { ancestors.push(node) return node } }) return filtered(ancestors, selector) }, parent: function(selector){ return filtered(uniq(this.pluck('parentNode')), selector) }, children: function(selector){ return filtered(this.map(function(){ return children(this) }), selector) }, contents: function() { return this.map(function() { return slice.call(this.childNodes) }) }, siblings: function(selector){ return filtered(this.map(function(i, el){ return filter.call(children(el.parentNode), function(child){ return child!==el }) }), selector) }, empty: function(){ return this.each(function(){ this.innerHTML = '' }) }, // `pluck` is borrowed from Prototype.js pluck: function(property){ return $.map(this, function(el){ return el[property] }) }, show: function(){ return this.each(function(){ this.style.display == "none" && (this.style.display = '') if (getComputedStyle(this, '').getPropertyValue("display") == "none") this.style.display = defaultDisplay(this.nodeName) }) }, replaceWith: function(newContent){ return this.before(newContent).remove() }, wrap: function(structure){ var func = isFunction(structure) if (this[0] && !func) var dom = $(structure).get(0), clone = dom.parentNode || this.length > 1 return this.each(function(index){ $(this).wrapAll( func ? structure.call(this, index) : clone ? dom.cloneNode(true) : dom ) }) }, wrapAll: function(structure){ if (this[0]) { $(this[0]).before(structure = $(structure)) var children // drill down to the inmost element while ((children = structure.children()).length) structure = children.first() $(structure).append(this) } return this }, wrapInner: function(structure){ var func = isFunction(structure) return this.each(function(index){ var self = $(this), contents = self.contents(), dom = func ? structure.call(this, index) : structure contents.length ? contents.wrapAll(dom) : self.append(dom) }) }, unwrap: function(){ this.parent().each(function(){ $(this).replaceWith($(this).children()) }) return this }, clone: function(){ return this.map(function(){ return this.cloneNode(true) }) }, hide: function(){ return this.css("display", "none") }, toggle: function(setting){ return this.each(function(){ var el = $(this) ;(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide() }) }, prev: function(selector){ return $(this.pluck('previousElementSibling')).filter(selector || '*') }, next: function(selector){ return $(this.pluck('nextElementSibling')).filter(selector || '*') }, html: function(html){ return arguments.length === 0 ? (this.length > 0 ? this[0].innerHTML : null) : this.each(function(idx){ var originHtml = this.innerHTML $(this).empty().append( funcArg(this, html, idx, originHtml) ) }) }, text: function(text){ return arguments.length === 0 ? (this.length > 0 ? this[0].textContent : null) : this.each(function(){ this.textContent = (text === undefined) ? '' : ''+text }) }, attr: function(name, value){ var result return (typeof name == 'string' && value === undefined) ? (this.length == 0 || this[0].nodeType !== 1 ? undefined : (name == 'value' && this[0].nodeName == 'INPUT') ? this.val() : (!(result = this[0].getAttribute(name)) && name in this[0]) ? this[0][name] : result ) : this.each(function(idx){ if (this.nodeType !== 1) return if (isObject(name)) for (key in name) setAttribute(this, key, name[key]) else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name))) }) }, removeAttr: function(name){ return this.each(function(){ this.nodeType === 1 && setAttribute(this, name) }) }, prop: function(name, value){ name = propMap[name] || name return (value === undefined) ? (this[0] && this[0][name]) : this.each(function(idx){ this[name] = funcArg(this, value, idx, this[name]) }) }, data: function(name, value){ var data = this.attr('data-' + name.replace(capitalRE, '-$1').toLowerCase(), value) return data !== null ? deserializeValue(data) : undefined }, val: function(value){ return arguments.length === 0 ? (this[0] && (this[0].multiple ? $(this[0]).find('option').filter(function(){ return this.selected }).pluck('value') : this[0].value) ) : this.each(function(idx){ this.value = funcArg(this, value, idx, this.value) }) }, offset: function(coordinates){ if (coordinates) return this.each(function(index){ var $this = $(this), coords = funcArg(this, coordinates, index, $this.offset()), parentOffset = $this.offsetParent().offset(), props = { top: coords.top - parentOffset.top, left: coords.left - parentOffset.left } if ($this.css('position') == 'static') props['position'] = 'relative' $this.css(props) }) if (this.length==0) return null var obj = this[0].getBoundingClientRect() return { left: obj.left + window.pageXOffset, top: obj.top + window.pageYOffset, width: Math.round(obj.width), height: Math.round(obj.height) } }, css: function(property, value){ if (arguments.length < 2) { var element = this[0], computedStyle = getComputedStyle(element, '') if(!element) return if (typeof property == 'string') return element.style[camelize(property)] || computedStyle.getPropertyValue(property) else if (isArray(property)) { var props = {} $.each(isArray(property) ? property: [property], function(_, prop){ props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop)) }) return props } } var css = '' if (type(property) == 'string') { if (!value && value !== 0) this.each(function(){ this.style.removeProperty(dasherize(property)) }) else css = dasherize(property) + ":" + maybeAddPx(property, value) } else { for (key in property) if (!property[key] && property[key] !== 0) this.each(function(){ this.style.removeProperty(dasherize(key)) }) else css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';' } return this.each(function(){ this.style.cssText += ';' + css }) }, index: function(element){ return element ? this.indexOf($(element)[0]) : this.parent().children().indexOf(this[0]) }, hasClass: function(name){ if (!name) return false return emptyArray.some.call(this, function(el){ return this.test(className(el)) }, classRE(name)) }, addClass: function(name){ if (!name) return this return this.each(function(idx){ classList = [] var cls = className(this), newName = funcArg(this, name, idx, cls) newName.split(/\s+/g).forEach(function(klass){ if (!$(this).hasClass(klass)) classList.push(klass) }, this) classList.length && className(this, cls + (cls ? " " : "") + classList.join(" ")) }) }, removeClass: function(name){ return this.each(function(idx){ if (name === undefined) return className(this, '') classList = className(this) funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass){ classList = classList.replace(classRE(klass), " ") }) className(this, classList.trim()) }) }, toggleClass: function(name, when){ if (!name) return this return this.each(function(idx){ var $this = $(this), names = funcArg(this, name, idx, className(this)) names.split(/\s+/g).forEach(function(klass){ (when === undefined ? !$this.hasClass(klass) : when) ? $this.addClass(klass) : $this.removeClass(klass) }) }) }, scrollTop: function(value){ if (!this.length) return var hasScrollTop = 'scrollTop' in this[0] if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset return this.each(hasScrollTop ? function(){ this.scrollTop = value } : function(){ this.scrollTo(this.scrollX, value) }) }, scrollLeft: function(value){ if (!this.length) return var hasScrollLeft = 'scrollLeft' in this[0] if (value === undefined) return hasScrollLeft ? this[0].scrollLeft : this[0].pageXOffset return this.each(hasScrollLeft ? function(){ this.scrollLeft = value } : function(){ this.scrollTo(value, this.scrollY) }) }, position: function() { if (!this.length) return var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rootNodeRE.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset() // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( $(elem).css('margin-top') ) || 0 offset.left -= parseFloat( $(elem).css('margin-left') ) || 0 // Add offsetParent borders parentOffset.top += parseFloat( $(offsetParent[0]).css('border-top-width') ) || 0 parentOffset.left += parseFloat( $(offsetParent[0]).css('border-left-width') ) || 0 // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left } }, offsetParent: function() { return this.map(function(){ var parent = this.offsetParent || document.body while (parent && !rootNodeRE.test(parent.nodeName) && $(parent).css("position") == "static") parent = parent.offsetParent return parent }) } } // for now $.fn.detach = $.fn.remove // Generate the `width` and `height` functions ;['width', 'height'].forEach(function(dimension){ var dimensionProperty = dimension.replace(/./, function(m){ return m[0].toUpperCase() }) $.fn[dimension] = function(value){ var offset, el = this[0] if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] : isDocument(el) ? el.documentElement['scroll' + dimensionProperty] : (offset = this.offset()) && offset[dimension] else return this.each(function(idx){ el = $(this) el.css(dimension, funcArg(this, value, idx, el[dimension]())) }) } }) function traverseNode(node, fun) { fun(node) for (var key in node.childNodes) traverseNode(node.childNodes[key], fun) } // Generate the `after`, `prepend`, `before`, `append`, // `insertAfter`, `insertBefore`, `appendTo`, and `prependTo` methods. adjacencyOperators.forEach(function(operator, operatorIndex) { var inside = operatorIndex % 2 //=> prepend, append $.fn[operator] = function(){ // arguments can be nodes, arrays of nodes, Zepto objects and HTML strings var argType, nodes = $.map(arguments, function(arg) { argType = type(arg) return argType == "object" || argType == "array" || arg == null ? arg : zepto.fragment(arg) }), parent, copyByClone = this.length > 1 if (nodes.length < 1) return this return this.each(function(_, target){ parent = inside ? target : target.parentNode // convert all methods to a "before" operation target = operatorIndex == 0 ? target.nextSibling : operatorIndex == 1 ? target.firstChild : operatorIndex == 2 ? target : null nodes.forEach(function(node){ if (copyByClone) node = node.cloneNode(true) else if (!parent) return $(node).remove() traverseNode(parent.insertBefore(node, target), function(el){ if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' && (!el.type || el.type === 'text/javascript') && !el.src) window['eval'].call(window, el.innerHTML) }) }) }) } // after => insertAfter // prepend => prependTo // before => insertBefore // append => appendTo $.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){ $(html)[operator](this) return this } }) zepto.Z.prototype = $.fn // Export internal API functions in the `$.zepto` namespace zepto.uniq = uniq zepto.deserializeValue = deserializeValue $.zepto = zepto return $ })() window.Zepto = Zepto window.$ === undefined && (window.$ = Zepto) ;(function($){ var _zid = 1, undefined, slice = Array.prototype.slice, isFunction = $.isFunction, isString = function(obj){ return typeof obj == 'string' }, handlers = {}, specialEvents={}, focusinSupported = 'onfocusin' in window, focus = { focus: 'focusin', blur: 'focusout' }, hover = { mouseenter: 'mouseover', mouseleave: 'mouseout' } specialEvents.click = specialEvents.mousedown = specialEvents.mouseup = specialEvents.mousemove = 'MouseEvents' function zid(element) { return element._zid || (element._zid = _zid++) } function findHandlers(element, event, fn, selector) { event = parse(event) if (event.ns) var matcher = matcherFor(event.ns) return (handlers[zid(element)] || []).filter(function(handler) { return handler && (!event.e || handler.e == event.e) && (!event.ns || matcher.test(handler.ns)) && (!fn || zid(handler.fn) === zid(fn)) && (!selector || handler.sel == selector) }) } function parse(event) { var parts = ('' + event).split('.') return {e: parts[0], ns: parts.slice(1).sort().join(' ')} } function matcherFor(ns) { return new RegExp('(?:^| )' + ns.replace(' ', ' .* ?') + '(?: |$)') } function eventCapture(handler, captureSetting) { return handler.del && (!focusinSupported && (handler.e in focus)) || !!captureSetting } function realEvent(type) { return hover[type] || (focusinSupported && focus[type]) || type } function add(element, events, fn, data, selector, delegator, capture){ var id = zid(element), set = (handlers[id] || (handlers[id] = [])) events.split(/\s/).forEach(function(event){ if (event == 'ready') return $(document).ready(fn) var handler = parse(event) handler.fn = fn handler.sel = selector // emulate mouseenter, mouseleave if (handler.e in hover) fn = function(e){ var related = e.relatedTarget if (!related || (related !== this && !$.contains(this, related))) return handler.fn.apply(this, arguments) } handler.del = delegator var callback = delegator || fn handler.proxy = function(e){ e = compatible(e) if (e.isImmediatePropagationStopped()) return e.data = data var result = callback.apply(element, e._args == undefined ? [e] : [e].concat(e._args)) if (result === false) e.preventDefault(), e.stopPropagation() return result } handler.i = set.length set.push(handler) if ('addEventListener' in element) element.addEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture)) }) } function remove(element, events, fn, selector, capture){ var id = zid(element) ;(events || '').split(/\s/).forEach(function(event){ findHandlers(element, event, fn, selector).forEach(function(handler){ delete handlers[id][handler.i] if ('removeEventListener' in element) element.removeEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture)) }) }) } $.event = { add: add, remove: remove } $.proxy = function(fn, context) { if (isFunction(fn)) { var proxyFn = function(){ return fn.apply(context, arguments) } proxyFn._zid = zid(fn) return proxyFn } else if (isString(context)) { return $.proxy(fn[context], fn) } else { throw new TypeError("expected function") } } $.fn.bind = function(event, data, callback){ return this.on(event, data, callback) } $.fn.unbind = function(event, callback){ return this.off(event, callback) } $.fn.one = function(event, selector, data, callback){ return this.on(event, selector, data, callback, 1) } var returnTrue = function(){return true}, returnFalse = function(){return false}, ignoreProperties = /^([A-Z]|returnValue$|layer[XY]$)/, eventMethods = { preventDefault: 'isDefaultPrevented', stopImmediatePropagation: 'isImmediatePropagationStopped', stopPropagation: 'isPropagationStopped' } function compatible(event, source) { if (source || !event.isDefaultPrevented) { source || (source = event) $.each(eventMethods, function(name, predicate) { var sourceMethod = source[name] event[name] = function(){ this[predicate] = returnTrue return sourceMethod && sourceMethod.apply(source, arguments) } event[predicate] = returnFalse }) if (source.defaultPrevented !== undefined ? source.defaultPrevented : 'returnValue' in source ? source.returnValue === false : source.getPreventDefault && source.getPreventDefault()) event.isDefaultPrevented = returnTrue } return event } function createProxy(event) { var key, proxy = { originalEvent: event } for (key in event) if (!ignoreProperties.test(key) && event[key] !== undefined) proxy[key] = event[key] return compatible(proxy, event) } $.fn.delegate = function(selector, event, callback){ return this.on(event, selector, callback) } $.fn.undelegate = function(selector, event, callback){ return this.off(event, selector, callback) } $.fn.live = function(event, callback){ $(document.body).delegate(this.selector, event, callback) return this } $.fn.die = function(event, callback){ $(document.body).undelegate(this.selector, event, callback) return this } $.fn.on = function(event, selector, data, callback, one){ var autoRemove, delegator, $this = this if (event && !isString(event)) { $.each(event, function(type, fn){ $this.on(type, selector, data, fn, one) }) return $this } if (!isString(selector) && !isFunction(callback) && callback !== false) callback = data, data = selector, selector = undefined if (isFunction(data) || data === false) callback = data, data = undefined if (callback === false) callback = returnFalse return $this.each(function(_, element){ if (one) autoRemove = function(e){ remove(element, e.type, callback) return callback.apply(this, arguments) } if (selector) delegator = function(e){ var evt, match = $(e.target).closest(selector, element).get(0) if (match && match !== element) { evt = $.extend(createProxy(e), {currentTarget: match, liveFired: element}) return (autoRemove || callback).apply(match, [evt].concat(slice.call(arguments, 1))) } } add(element, event, callback, data, selector, delegator || autoRemove) }) } $.fn.off = function(event, selector, callback){ var $this = this if (event && !isString(event)) { $.each(event, function(type, fn){ $this.off(type, selector, fn) }) return $this } if (!isString(selector) && !isFunction(callback) && callback !== false) callback = selector, selector = undefined if (callback === false) callback = returnFalse return $this.each(function(){ remove(this, event, callback, selector) }) } $.fn.trigger = function(event, args){ event = (isString(event) || $.isPlainObject(event)) ? $.Event(event) : compatible(event) event._args = args return this.each(function(){ // items in the collection might not be DOM elements if('dispatchEvent' in this) this.dispatchEvent(event) else $(this).triggerHandler(event, args) }) } // triggers event handlers on current element just as if an event occurred, // doesn't trigger an actual event, doesn't bubble $.fn.triggerHandler = function(event, args){ var e, result this.each(function(i, element){ e = createProxy(isString(event) ? $.Event(event) : event) e._args = args e.target = element $.each(findHandlers(element, event.type || event), function(i, handler){ result = handler.proxy(e) if (e.isImmediatePropagationStopped()) return false }) }) return result } // shortcut methods for `.bind(event, fn)` for each event type ;('focusin focusout load resize scroll unload click dblclick '+ 'mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave '+ 'change select keydown keypress keyup error').split(' ').forEach(function(event) { $.fn[event] = function(callback) { return callback ? this.bind(event, callback) : this.trigger(event) } }) ;['focus', 'blur'].forEach(function(name) { $.fn[name] = function(callback) { if (callback) this.bind(name, callback) else this.each(function(){ try { this[name]() } catch(e) {} }) return this } }) $.Event = function(type, props) { if (!isString(type)) props = type, type = props.type var event = document.createEvent(specialEvents[type] || 'Events'), bubbles = true if (props) for (var name in props) (name == 'bubbles') ? (bubbles = !!props[name]) : (event[name] = props[name]) event.initEvent(type, bubbles, true) return compatible(event) } })(Zepto) ;(function($){ var jsonpID = 0, document = window.document, key, name, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, scriptTypeRE = /^(?:text|application)\/javascript/i, xmlTypeRE = /^(?:text|application)\/xml/i, jsonType = 'application/json', htmlType = 'text/html', blankRE = /^\s*$/ // trigger a custom event and return false if it was cancelled function triggerAndReturn(context, eventName, data) { var event = $.Event(eventName) $(context).trigger(event, data) return !event.isDefaultPrevented() } // trigger an Ajax "global" event function triggerGlobal(settings, context, eventName, data) { if (settings.global) return triggerAndReturn(context || document, eventName, data) } // Number of active Ajax requests $.active = 0 function ajaxStart(settings) { if (settings.global && $.active++ === 0) triggerGlobal(settings, null, 'ajaxStart') } function ajaxStop(settings) { if (settings.global && !(--$.active)) triggerGlobal(settings, null, 'ajaxStop') } // triggers an extra global event "ajaxBeforeSend" that's like "ajaxSend" but cancelable function ajaxBeforeSend(xhr, settings) { var context = settings.context if (settings.beforeSend.call(context, xhr, settings) === false || triggerGlobal(settings, context, 'ajaxBeforeSend', [xhr, settings]) === false) return false triggerGlobal(settings, context, 'ajaxSend', [xhr, settings]) } function ajaxSuccess(data, xhr, settings, deferred) { var context = settings.context, status = 'success' settings.success.call(context, data, status, xhr) if (deferred) deferred.resolveWith(context, [data, status, xhr]) triggerGlobal(settings, context, 'ajaxSuccess', [xhr, settings, data]) ajaxComplete(status, xhr, settings) } // type: "timeout", "error", "abort", "parsererror" function ajaxError(error, type, xhr, settings, deferred) { var context = settings.context settings.error.call(context, xhr, type, error) if (deferred) deferred.rejectWith(context, [xhr, type, error]) triggerGlobal(settings, context, 'ajaxError', [xhr, settings, error || type]) ajaxComplete(type, xhr, settings) } // status: "success", "notmodified", "error", "timeout", "abort", "parsererror" function ajaxComplete(status, xhr, settings) { var context = settings.context settings.complete.call(context, xhr, status) triggerGlobal(settings, context, 'ajaxComplete', [xhr, settings]) ajaxStop(settings) } // Empty function, used as default callback function empty() {} $.ajaxJSONP = function(options, deferred){ if (!('type' in options)) return $.ajax(options) var _callbackName = options.jsonpCallback, callbackName = ($.isFunction(_callbackName) ? _callbackName() : _callbackName) || ('jsonp' + (++jsonpID)), script = document.createElement('script'), originalCallback = window[callbackName], responseData, abort = function(errorType) { $(script).triggerHandler('error', errorType || 'abort') }, xhr = { abort: abort }, abortTimeout if (deferred) deferred.promise(xhr) $(script).on('load error', function(e, errorType){ clearTimeout(abortTimeout) $(script).off().remove() if (e.type == 'error' || !responseData) { ajaxError(null, errorType || 'error', xhr, options, deferred) } else { ajaxSuccess(responseData[0], xhr, options, deferred) } window[callbackName] = originalCallback if (responseData && $.isFunction(originalCallback)) originalCallback(responseData[0]) originalCallback = responseData = undefined }) if (ajaxBeforeSend(xhr, options) === false) { abort('abort') return xhr } window[callbackName] = function(){ responseData = arguments } script.src = options.url.replace(/\?(.+)=\?/, '?$1=' + callbackName) document.head.appendChild(script) if (options.timeout > 0) abortTimeout = setTimeout(function(){ abort('timeout') }, options.timeout) return xhr } $.ajaxSettings = { // Default type of request type: 'GET', // Callback that is executed before request beforeSend: empty, // Callback that is executed if the request succeeds success: empty, // Callback that is executed the the server drops error error: empty, // Callback that is executed on request complete (both: error and success) complete: empty, // The context for the callbacks context: null, // Whether to trigger "global" Ajax events global: true, // Transport xhr: function () { return new window.XMLHttpRequest() }, // MIME types mapping // IIS returns Javascript as "application/x-javascript" accepts: { script: 'text/javascript, application/javascript, application/x-javascript', json: jsonType, xml: 'application/xml, text/xml', html: htmlType, text: 'text/plain' }, // Whether the request is to another domain crossDomain: false, // Default timeout timeout: 0, // Whether data should be serialized to string processData: true, // Whether the browser should be allowed to cache GET responses cache: true } function mimeToDataType(mime) { if (mime) mime = mime.split(';', 2)[0] return mime && ( mime == htmlType ? 'html' : mime == jsonType ? 'json' : scriptTypeRE.test(mime) ? 'script' : xmlTypeRE.test(mime) && 'xml' ) || 'text' } function appendQuery(url, query) { if (query == '') return url return (url + '&' + query).replace(/[&?]{1,2}/, '?') } // serialize payload and append it to the URL for GET requests function serializeData(options) { if (options.processData && options.data && $.type(options.data) != "string") options.data = $.param(options.data, options.traditional) if (options.data && (!options.type || options.type.toUpperCase() == 'GET')) options.url = appendQuery(options.url, options.data), options.data = undefined } $.ajax = function(options){ var settings = $.extend({}, options || {}), deferred = $.Deferred && $.Deferred() for (key in $.ajaxSettings) if (settings[key] === undefined) settings[key] = $.ajaxSettings[key] ajaxStart(settings) if (!settings.crossDomain) settings.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(settings.url) && RegExp.$2 != window.location.host if (!settings.url) settings.url = window.location.toString() serializeData(settings) if (settings.cache === false) settings.url = appendQuery(settings.url, '_=' + Date.now()) var dataType = settings.dataType, hasPlaceholder = /\?.+=\?/.test(settings.url) if (dataType == 'jsonp' || hasPlaceholder) { if (!hasPlaceholder) settings.url = appendQuery(settings.url, settings.jsonp ? (settings.jsonp + '=?') : settings.jsonp === false ? '' : 'callback=?') return $.ajaxJSONP(settings, deferred) } var mime = settings.accepts[dataType], headers = { }, setHeader = function(name, value) { headers[name.toLowerCase()] = [name, value] }, protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol, xhr = settings.xhr(), nativeSetHeader = xhr.setRequestHeader, abortTimeout if (deferred) deferred.promise(xhr) if (!settings.crossDomain) setHeader('X-Requested-With', 'XMLHttpRequest') setHeader('Accept', mime || '*/*') if (mime = settings.mimeType || mime) { if (mime.indexOf(',') > -1) mime = mime.split(',', 2)[0] xhr.overrideMimeType && xhr.overrideMimeType(mime) } if (settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() != 'GET')) setHeader('Content-Type', settings.contentType || 'application/x-www-form-urlencoded') if (settings.headers) for (name in settings.headers) setHeader(name, settings.headers[name]) xhr.setRequestHeader = setHeader xhr.onreadystatechange = function(){ if (xhr.readyState == 4) { xhr.onreadystatechange = empty clearTimeout(abortTimeout) var result, error = false if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:')) { dataType = dataType || mimeToDataType(settings.mimeType || xhr.getResponseHeader('content-type')) result = xhr.responseText try { // http://perfectionkills.com/global-eval-what-are-the-options/ if (dataType == 'script') (1,eval)(result) else if (dataType == 'xml') result = xhr.responseXML else if (dataType == 'json') result = blankRE.test(result) ? null : $.parseJSON(result) } catch (e) { error = e } if (error) ajaxError(error, 'parsererror', xhr, settings, deferred) else ajaxSuccess(result, xhr, settings, deferred) } else { ajaxError(xhr.statusText || null, xhr.status ? 'error' : 'abort', xhr, settings, deferred) } } } if (ajaxBeforeSend(xhr, settings) === false) { xhr.abort() ajaxError(null, 'abort', xhr, settings, deferred) return xhr } if (settings.xhrFields) for (name in settings.xhrFields) xhr[name] = settings.xhrFields[name] var async = 'async' in settings ? settings.async : true xhr.open(settings.type, settings.url, async, settings.username, settings.password) for (name in headers) nativeSetHeader.apply(xhr, headers[name]) if (settings.timeout > 0) abortTimeout = setTimeout(function(){ xhr.onreadystatechange = empty xhr.abort() ajaxError(null, 'timeout', xhr, settings, deferred) }, settings.timeout) // avoid sending empty string (#319) xhr.send(settings.data ? settings.data : null) return xhr } // handle optional data/success arguments function parseArguments(url, data, success, dataType) { if ($.isFunction(data)) dataType = success, success = data, data = undefined if (!$.isFunction(success)) dataType = success, success = undefined return { url: url , data: data , success: success , dataType: dataType } } $.get = function(/* url, data, success, dataType */){ return $.ajax(parseArguments.apply(null, arguments)) } $.post = function(/* url, data, success, dataType */){ var options = parseArguments.apply(null, arguments) options.type = 'POST' return $.ajax(options) } $.getJSON = function(/* url, data, success */){ var options = parseArguments.apply(null, arguments) options.dataType = 'json' return $.ajax(options) } $.fn.load = function(url, data, success){ if (!this.length) return this var self = this, parts = url.split(/\s/), selector, options = parseArguments(url, data, success), callback = options.success if (parts.length > 1) options.url = parts[0], selector = parts[1] options.success = function(response){ self.html(selector ? $('<div>').html(response.replace(rscript, "")).find(selector) : response) callback && callback.apply(self, arguments) } $.ajax(options) return this } var escape = encodeURIComponent function serialize(params, obj, traditional, scope){ var type, array = $.isArray(obj), hash = $.isPlainObject(obj) $.each(obj, function(key, value) { type = $.type(value) if (scope) key = traditional ? scope : scope + '[' + (hash || type == 'object' || type == 'array' ? key : '') + ']' // handle data in serializeArray() format if (!scope && array) params.add(value.name, value.value) // recurse into nested objects else if (type == "array" || (!traditional && type == "object")) serialize(params, value, traditional, key) else params.add(key, value) }) } $.param = function(obj, traditional){ var params = [] params.add = function(k, v){ this.push(escape(k) + '=' + escape(v)) } serialize(params, obj, traditional) return params.join('&').replace(/%20/g, '+') } })(Zepto) ;(function($){ $.fn.serializeArray = function() { var result = [], el $([].slice.call(this.get(0).elements)).each(function(){ el = $(this) var type = el.attr('type') if (this.nodeName.toLowerCase() != 'fieldset' && !this.disabled && type != 'submit' && type != 'reset' && type != 'button' && ((type != 'radio' && type != 'checkbox') || this.checked)) result.push({ name: el.attr('name'), value: el.val() }) }) return result } $.fn.serialize = function(){ var result = [] this.serializeArray().forEach(function(elm){ result.push(encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value)) }) return result.join('&') } $.fn.submit = function(callback) { if (callback) this.bind('submit', callback) else if (this.length) { var event = $.Event('submit') this.eq(0).trigger(event) if (!event.isDefaultPrevented()) this.get(0).submit() } return this } })(Zepto) ;(function($){ // __proto__ doesn't exist on IE<11, so redefine // the Z function to use object extension instead if (!('__proto__' in {})) { $.extend($.zepto, { Z: function(dom, selector){ dom = dom || [] $.extend(dom, $.fn) dom.selector = selector || '' dom.__Z = true return dom }, // this is a kludge but works isZ: function(object){ return $.type(object) === 'array' && '__Z' in object } }) } // getComputedStyle shouldn't freak out when called // without a valid element as argument try { getComputedStyle(undefined) } catch(e) { var nativeGetComputedStyle = getComputedStyle; window.getComputedStyle = function(element){ try { return nativeGetComputedStyle(element) } catch(e) { return null } } } })(Zepto) // Zepto.js // (c) 2010-2014 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. ;(function($){ function detect(ua){ var os = this.os = {}, browser = this.browser = {}, webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/), android = ua.match(/(Android);?[\s\/]+([\d.]+)?/), osx = !!ua.match(/\(Macintosh\; Intel /), ipad = ua.match(/(iPad).*OS\s([\d_]+)/), ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/), iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/), webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/), touchpad = webos && ua.match(/TouchPad/), kindle = ua.match(/Kindle\/([\d.]+)/), silk = ua.match(/Silk\/([\d._]+)/), blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/), bb10 = ua.match(/(BB10).*Version\/([\d.]+)/), rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/), playbook = ua.match(/PlayBook/), chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/), firefox = ua.match(/Firefox\/([\d.]+)/), ie = ua.match(/MSIE\s([\d.]+)/) || ua.match(/Trident\/[\d](?=[^\?]+).*rv:([0-9.].)/), webview = !chrome && ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/), safari = webview || ua.match(/Version\/([\d.]+)([^S](Safari)|[^M]*(Mobile)[^S]*(Safari))/) // Todo: clean this up with a better OS/browser seperation: // - discern (more) between multiple browsers on android // - decide if kindle fire in silk mode is android or not // - Firefox on Android doesn't specify the Android version // - possibly devide in os, device and browser hashes if (browser.webkit = !!webkit) browser.version = webkit[1] if (android) os.android = true, os.version = android[2] if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.') if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.') if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null if (webos) os.webos = true, os.version = webos[2] if (touchpad) os.touchpad = true if (blackberry) os.blackberry = true, os.version = blackberry[2] if (bb10) os.bb10 = true, os.version = bb10[2] if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2] if (playbook) browser.playbook = true if (kindle) os.kindle = true, os.version = kindle[1] if (silk) browser.silk = true, browser.version = silk[1] if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true if (chrome) browser.chrome = true, browser.version = chrome[1] if (firefox) browser.firefox = true, browser.version = firefox[1] if (ie) browser.ie = true, browser.version = ie[1] if (safari && (osx || os.ios)) {browser.safari = true; if (osx) browser.version = safari[1]} if (webview) browser.webview = true os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) || (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/))) os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos || blackberry || bb10 || (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) || (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/)))) } detect.call($, navigator.userAgent) // make available to unit tests $.__detect = detect })(Zepto) // Zepto.js // (c) 2010-2014 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. ;(function($){ var touch = {}, touchTimeout, tapTimeout, swipeTimeout, longTapTimeout, longTapDelay = 750, gesture function swipeDirection(x1, x2, y1, y2) { return Math.abs(x1 - x2) >= Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down') } function longTap() { longTapTimeout = null if (touch.last) { touch.el.trigger('longTap') touch = {} } } function cancelLongTap() { if (longTapTimeout) clearTimeout(longTapTimeout) longTapTimeout = null } function cancelAll() { if (touchTimeout) clearTimeout(touchTimeout) if (tapTimeout) clearTimeout(tapTimeout) if (swipeTimeout) clearTimeout(swipeTimeout) if (longTapTimeout) clearTimeout(longTapTimeout) touchTimeout = tapTimeout = swipeTimeout = longTapTimeout = null touch = {} } function isPrimaryTouch(event){ return (event.pointerType == 'touch' || event.pointerType == event.MSPOINTER_TYPE_TOUCH) && event.isPrimary } function isPointerEventType(e, type){ return (e.type == 'pointer'+type || e.type.toLowerCase() == 'mspointer'+type) } $(document).ready(function(){ var now, delta, deltaX = 0, deltaY = 0, firstTouch, _isPointerType if ('MSGesture' in window) { gesture = new MSGesture() gesture.target = document.body } $(document) .bind('MSGestureEnd', function(e){ var swipeDirectionFromVelocity = e.velocityX > 1 ? 'Right' : e.velocityX < -1 ? 'Left' : e.velocityY > 1 ? 'Down' : e.velocityY < -1 ? 'Up' : null; if (swipeDirectionFromVelocity) { touch.el.trigger('swipe') touch.el.trigger('swipe'+ swipeDirectionFromVelocity) } }) .on('touchstart MSPointerDown pointerdown', function(e){ if((_isPointerType = isPointerEventType(e, 'down')) && !isPrimaryTouch(e)) return firstTouch = _isPointerType ? e : e.touches[0] if (e.touches && e.touches.length === 1 && touch.x2) { // Clear out touch movement data if we have it sticking around // This can occur if touchcancel doesn't fire due to preventDefault, etc. touch.x2 = undefined touch.y2 = undefined } now = Date.now() delta = now - (touch.last || now) touch.el = $('tagName' in firstTouch.target ? firstTouch.target : firstTouch.target.parentNode) touchTimeout && clearTimeout(touchTimeout) touch.x1 = firstTouch.pageX touch.y1 = firstTouch.pageY if (delta > 0 && delta <= 250) touch.isDoubleTap = true touch.last = now longTapTimeout = setTimeout(longTap, longTapDelay) // adds the current touch contact for IE gesture recognition if (gesture && _isPointerType) gesture.addPointer(e.pointerId); }) .on('touchmove MSPointerMove pointermove', function(e){ if((_isPointerType = isPointerEventType(e, 'move')) && !isPrimaryTouch(e)) return firstTouch = _isPointerType ? e : e.touches[0] cancelLongTap() touch.x2 = firstTouch.pageX touch.y2 = firstTouch.pageY deltaX += Math.abs(touch.x1 - touch.x2) deltaY += Math.abs(touch.y1 - touch.y2) }) .on('touchend MSPointerUp pointerup', function(e){ if((_isPointerType = isPointerEventType(e, 'up')) && !isPrimaryTouch(e)) return cancelLongTap() // swipe if ((touch.x2 && Math.abs(touch.x1 - touch.x2) > 30) || (touch.y2 && Math.abs(touch.y1 - touch.y2) > 30)) swipeTimeout = setTimeout(function() { touch.el.trigger('swipe') touch.el.trigger('swipe' + (swipeDirection(touch.x1, touch.x2, touch.y1, touch.y2))) touch = {} }, 0) // normal tap else if ('last' in touch) // don't fire tap when delta position changed by more than 30 pixels, // for instance when moving to a point and back to origin if (deltaX < 30 && deltaY < 30) { // delay by one tick so we can cancel the 'tap' event if 'scroll' fires // ('tap' fires before 'scroll') tapTimeout = setTimeout(function() { // trigger universal 'tap' with the option to cancelTouch() // (cancelTouch cancels processing of single vs double taps for faster 'tap' response) var event = $.Event('tap') event.cancelTouch = cancelAll touch.el.trigger(event) // trigger double tap immediately if (touch.isDoubleTap) { if (touch.el) touch.el.trigger('doubleTap') touch = {} } // trigger single tap after 250ms of inactivity else { touchTimeout = setTimeout(function(){ touchTimeout = null if (touch.el) touch.el.trigger('singleTap') touch = {} }, 250) } }, 0) } else { touch = {} } deltaX = deltaY = 0 }) // when the browser window loses focus, // for example when a modal dialog is shown, // cancel all ongoing events .on('touchcancel MSPointerCancel pointercancel', cancelAll) // scrolling the window indicates intention of the user // to scroll, not tap or swipe, so cancel all ongoing events $(window).on('scroll', cancelAll) }) ;['swipe', 'swipeLeft', 'swipeRight', 'swipeUp', 'swipeDown', 'doubleTap', 'tap', 'singleTap', 'longTap'].forEach(function(eventName){ $.fn[eventName] = function(callback){ return this.on(eventName, callback) } }) })(Zepto)
import React from 'react' import { Field, reduxForm } from 'redux-form' const SimpleForm = props => { const { handleSubmit, pristine, reset, submitting } = props return ( <form onSubmit={handleSubmit}> <div> <label>First Name</label> <div> <Field name="firstName" component="input" type="text" placeholder="First Name" /> </div> </div> <div> <label>Last Name</label> <div> <Field name="lastName" component="input" type="text" placeholder="Last Name" /> </div> </div> <div> <label>Email</label> <div> <Field name="email" component="input" type="email" placeholder="Email" /> </div> </div> <div> <label>Sex</label> <div> <label> <Field name="sex" component="input" type="radio" value="male" />{' '} Male </label> <label> <Field name="sex" component="input" type="radio" value="female" />{' '} Female </label> </div> </div> <div> <label>Favorite Color</label> <div> <Field name="favoriteColor" component="select"> <option /> <option value="ff0000">Red</option> <option value="00ff00">Green</option> <option value="0000ff">Blue</option> </Field> </div> </div> <div> <label htmlFor="employed">Employed</label> <div> <Field name="employed" id="employed" component="input" type="checkbox" /> </div> </div> <div> <label>Notes</label> <div> <Field name="notes" component="textarea" /> </div> </div> <div> <button type="submit" disabled={pristine || submitting}> Submit </button> <button type="button" disabled={pristine || submitting} onClick={reset}> Clear Values </button> </div> </form> ) } export default reduxForm({ form: 'simple' // a unique identifier for this form })(SimpleForm)
module.exports = { all: ['test/**/*.html'] };
var filechange='tutorial2/tutorial2.ydb';
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'format', 'uk', { label: 'Форматування', panelTitle: 'Форматування параграфа', tag_address: 'Адреса', tag_div: 'Нормальний (div)', tag_h1: 'Заголовок 1', tag_h2: 'Заголовок 2', tag_h3: 'Заголовок 3', tag_h4: 'Заголовок 4', tag_h5: 'Заголовок 5', tag_h6: 'Заголовок 6', tag_p: 'Нормальний', tag_pre: 'Форматований' });
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- if (this.WScript && this.WScript.LoadScriptFile) { this.WScript.LoadScriptFile("..\\UnitTestFramework\\UnitTestFramework.js"); } function getPropertiesString(obj) { var props = [] for (var x in obj) { props.push(x); } props = props.sort(); return props.join(); } var Tests = [function () { var obj = {}; // Starts with preinitialized object literal type T0 obj.a1 = 1; // New type T1 with inlineSlotCapacity 0, a1 goes to auxSlot of capacity 4, new TypePath obj.a2 = 2; // New type T2, a2 goes to auxSlot [1], TypePath remains same with capacity 10 obj.a3 = 3; // New Type T3, a3 goes to auxSlot[2], TypePath remains same with capacity 10 delete obj.a3; // Go to Type T3, Both current type T3 and predecessor type T2 are not ObjectHeaderInline no movement needed assert.isTrue(obj.a1 === 1); assert.isTrue(obj.a2 === 2); assert.isTrue(obj.a3 === undefined); }, function () { var obj = {}; // Starts with preinitialized object literal type T0 obj.b1 = 1; // New type T1 with inlineSlotCapacity 0, b1 goes to auxSlot of capacity 4, new TypePath obj.b2 = 2; // New type T2, b2 goes to auxSlot [1], TypePath remains same with capacity 10 var obj1 = {}; obj1.b1 = 1; // Share same type T1 with obj, T1 is marked as Shared obj1.b3 = 3; // Branched TypePath and created new Type T3, T1 have 2 successors delete obj1.b3; // Go to Type T1, Both current type T3 and predecessor type T1 are not ObjectHeaderInline no movement needed assert.isTrue(obj.b1 === 1); assert.isTrue(obj.b2 === 2); assert.isTrue(obj.b3 === undefined); assert.isTrue(obj1.b1 === 1); assert.isTrue(obj1.b2 === undefined); assert.isTrue(obj1.b3 === undefined); }, function () { var obj = { c1: 1 }; // Type T0, ObjectHeaderInlined with inlineSlotCapacity 2, c1 goes to inlineSlot[0] same as auxSlot address obj.c2 = 2; // New type T1 a2 goes to inlineSlot 1 delete obj.c2; // Goes back to T0, Both current type T1 and predecessor type T0 are ObjectHeaderInline with same inlineSlotCapacity so no movement assert.isTrue(obj.c1 === 1); assert.isTrue(obj.c2 === undefined); }, function () { var obj = { d1: 1, d2: 2 }; // Type T, ObjectHeaderInlined with inlineSlotCapacity 2, d1 goes to inlineSlot[0] and d2 to inlineSlot[1] var obj1 = { d1: 1, d2: 2 }; // Share Type with Obj and now its marked Shared delete obj.d2; // Goes back to T0, Both current type and predecessor type are ObjectHeaderInline with same inlineSlotCapacity so no movement assert.isTrue(obj.d1 === 1); assert.isTrue(obj.d2 === undefined); assert.isTrue(obj1.d1 === 1); assert.isTrue(obj1.d2 === 2); }, function () { function foo() { this.e1 = 1; // Type T1 this.e2 = 2; // Type T2 this.e3 = 3; // Type T3 this.e4 = 4; // Type T4 this.e5 = 5; // Type T5 } var obj = new foo(); var obj1 = new foo(); // This will shrink the inlineSlotCapacity from 8 to 6 var obj2 = new foo(); delete obj1.e5; // Move to Type T4 assert.isTrue(obj.e1 === 1); assert.isTrue(obj.e2 === 2); assert.isTrue(obj.e3 === 3); assert.isTrue(obj.e4 === 4); assert.isTrue(obj.e5 === 5); assert.isTrue(obj1.e1 === 1); assert.isTrue(obj1.e2 === 2); assert.isTrue(obj1.e3 === 3); assert.isTrue(obj1.e4 === 4); assert.isTrue(obj1.e5 === undefined); assert.isTrue(obj2.e1 === 1); assert.isTrue(obj2.e2 === 2); assert.isTrue(obj2.e3 === 3); assert.isTrue(obj2.e4 === 4); assert.isTrue(obj2.e5 === 5); }, function () { function foo() { this.f1 = 1; this.f2 = 2; this.f3 = 3; this.f4 = 4; this.f5 = 5; this.f6 = 6; this.f7 = 7; this.f8 = 8; } var obj = new foo(); var obj1 = new foo(); // No shrinking as current inlineSlot 8 is aligned var obj2 = new foo(); delete obj1.f8; // Move to Type till f7 assert.isTrue(obj1.f1 === 1); assert.isTrue(obj1.f2 === 2); assert.isTrue(obj1.f3 === 3); assert.isTrue(obj1.f4 === 4); assert.isTrue(obj1.f5 === 5); assert.isTrue(obj1.f6 === 6); assert.isTrue(obj1.f7 === 7); assert.isTrue(obj1.f8 === undefined); }, function () { function foo() { this.g1 = 1; this.g2 = 2; this.g3 = 3; this.g4 = 4; this.g5 = 5; this.g6 = 6; this.g7 = 7; this.g8 = 8; } var obj = new foo(); obj.g9 = 9; // Create auxSlots, Move g1-g6 to inlineSlots and g7-g8 to auxSlot. Add g9 to auxSlot delete obj.g9; // ReOptimize - shift g1-g6 up and move g7-g8 to inlineSlot assert.isTrue(obj.g1 === 1); assert.isTrue(obj.g2 === 2); assert.isTrue(obj.g3 === 3); assert.isTrue(obj.g4 === 4); assert.isTrue(obj.g5 === 5); assert.isTrue(obj.g6 === 6); assert.isTrue(obj.g7 === 7); assert.isTrue(obj.g8 === 8); assert.isTrue(obj.g9 === undefined); }, function () { var obj = {}; obj.h1 = 1; // Type T1, inlineSlotSize 0, h1 in auxSlot[0] obj.h2 = 2; // Type T2, h2 in auxSlot[1] obj[0] = 4; // Created objectArray obj.h3 = 3; // Type T3, h3 in auxSlot[2] delete obj.h3; // Move to T2 assert.isTrue(obj.h1 === 1); assert.isTrue(obj.h2 === 2); assert.isTrue(obj.h3 === undefined); assert.isTrue(obj[0] === 4); }, function () { function foo() { this.i1 = 1, this.i2 = 2 } var obj = new foo(); var obj1 = new foo(); var obj2 = new foo(); obj[0] = 10; // DeoptimizeObjectHeaderInlining and create objectArray, no predecessor type obj[1] = 11; delete obj.i2; // No predecessor type assert.isTrue(obj.i1 === 1); assert.isTrue(obj.i2 === undefined); assert.isTrue(obj[0] === 10); assert.isTrue(obj[1] === 11); }, function () { var obj = { j1: 1, j2: 2, j3: 3, j4: 4 } // Populate forInCache for (var i in obj) {} var expectedProps = "j1j2j3j4"; var elemCount = 0; var propsString = ""; for (var i in obj) { propsString += i; elemCount++; if (elemCount == 2) { delete obj.j4; // delete last property } else if (elemCount == 3) { obj.j4 = 5; // Add property back } } assert.isTrue(propsString === expectedProps); }, function () { var obj = { k1: 1, k2: 2, k3: 3, k4: 4 } // Populate forInCache for (var i in obj) {} var expectedProps = "k1k2k3k4"; var elemCount = 0; var propsString = ""; for (var i in obj) { propsString += i; elemCount++; if (elemCount == 2) { delete obj.k4; // delete last property obj.k4 = 5; // Add property back obj.k5 = 6; // Shouldn't be enumerated } } assert.isTrue(propsString === expectedProps); }, function () { var obj = { l1: 1, l2: 2, l3: 3 } // No prepopulated cache var expectedProps = "l1l2l3"; var elemCount = 0; var propsString = ""; for (var i in obj) { propsString += i; elemCount++; if (elemCount == 2) { delete obj.l3; // delete last property obj.l3 = 5 // Add property back } } assert.isTrue(propsString === expectedProps); }, function () { var obj = { m1: 1, m2: 2, m3: 3 }; // Same type as obj var obj1 = { m1: 1, m2: 2, m3: 3 }; // No prepopulated cache var expectedProps = "m1m2m3"; var elemCount = 0; var propsString = ""; for (var i in obj1) { propsString += i; elemCount++; if (elemCount == 2) { delete obj.l3; // No optimization as forInCache is type based obj.l3 = 5 // Add property back } } assert.isTrue(propsString === expectedProps); }, function () { var obj = { n1: 1, n2: 2 }; obj.n3 = 3; // Converted to auxSlots, predecessor type is ObjectHeaderInlined obj[10] = 10; // Added objectArray delete obj.n3; assert.isTrue(obj[10] === 10); assert.isTrue(obj.n3 === undefined); }, function () { var arrObj0 = {}; var func1 = function () { delete arrObj0.length; arrObj0 = { method0: function () {}, method1: function () {} }; }; var func4 = function () { arrObj0[15] = 1; func1(); return arrObj0.length = arrObj0; }; func4(); func4(); }, function () { var obj1 = {}; obj1.o1 = 1; var obj2 = {}; obj2.o2 = 1; // Set a property (last) obj2.__proto__ = obj1; // Modify the prototype delete obj2.o2; // Trigger delete last property assert.areEqual(1, obj2.o1, ""); }, function () { var obj1 = {}; obj1.p1 = 1; var obj2 = {}; obj2.__proto__ = obj1; // Change prototype first obj2.p2 = 1; // Add a last property delete obj2.p2; // Trigger delete last property assert.areEqual(1, obj2.p1, ""); }, function () { var obj1 = {}; obj1.q1 = 1; obj1.q2 = 1; var obj2 = {}; obj2.q3 = 1; // Add last property to object obj1.q4 = 1; // Add another property to prototype obj2.__proto__ = obj1; // Change prototype delete obj2.q3; // Delete last property assert.areEqual('q1,q2,q4', getPropertiesString(obj2), ""); }, function () { var obj1 = {}; obj1.r1 = 1; obj1.r2 = 1; var obj2 = {}; obj2.r3 = 1; // Add a property obj2.r4 = 1; // Add another (last) property obj2.__proto__ = obj1; // Change prototype delete obj2.r4; // Trigger delete last property assert.areEqual('r1,r2,r3', getPropertiesString(obj2), ""); delete obj2.r3; assert.areEqual('r1,r2', getPropertiesString(obj2), ""); } ] for (var i = 0; i < 3; ++i) { for (var j = 0; j < Tests.length; ++j) { Tests[j](); } } WScript.Echo("Pass");
function init(app) { app.get("/products", function(req, content, callback) { setTimeout(function () { callback(null, { list: [{name: "jerry"}, {name: "tomy"}], totalCount: 100 + Math.floor(100 * Math.random()) }) }, 500) }) } module.exports = init
// make sure we send things immediately for tests, we don't want batching appInsights.maxBatchInterval = 0; // hook the send method of XHLHttpRequest so that we can validate that errors are logged var originalSend = window.XMLHttpRequest.prototype.send; window.XMLHttpRequest.prototype.send = function (data) { // don't use typescript lambda top.postMessage(data, "*"); return originalSend.apply(this, arguments); }; // don't break snippet tests window['queueTest'] = function () { };
/*jshint node:true */ /* The MIT License (MIT) Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, 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. */ 'use strict'; var regexp_has_sticky = RegExp.prototype.hasOwnProperty('sticky'); function InputScanner(input_string) { this.__input = input_string || ''; this.__input_length = this.__input.length; this.__position = 0; } InputScanner.prototype.restart = function() { this.__position = 0; }; InputScanner.prototype.back = function() { if (this.__position > 0) { this.__position -= 1; } }; InputScanner.prototype.hasNext = function() { return this.__position < this.__input_length; }; InputScanner.prototype.next = function() { var val = null; if (this.hasNext()) { val = this.__input.charAt(this.__position); this.__position += 1; } return val; }; InputScanner.prototype.peek = function(index) { var val = null; index = index || 0; index += this.__position; if (index >= 0 && index < this.__input_length) { val = this.__input.charAt(index); } return val; }; // This is a JavaScript only helper function (not in python) // Javascript doesn't have a match method // and not all implementation support "sticky" flag. // If they do not support sticky then both this.match() and this.test() method // must get the match and check the index of the match. // If sticky is supported and set, this method will use it. // Otherwise it will check that global is set, and fall back to the slower method. InputScanner.prototype.__match = function(pattern, index) { pattern.lastIndex = index; var pattern_match = pattern.exec(this.__input); if (pattern_match && !(regexp_has_sticky && pattern.sticky)) { if (pattern_match.index !== index) { pattern_match = null; } } return pattern_match; }; InputScanner.prototype.test = function(pattern, index) { index = index || 0; index += this.__position; if (index >= 0 && index < this.__input_length) { return !!this.__match(pattern, index); } else { return false; } }; InputScanner.prototype.testChar = function(pattern, index) { // test one character regex match var val = this.peek(index); pattern.lastIndex = 0; return val !== null && pattern.test(val); }; InputScanner.prototype.match = function(pattern) { var pattern_match = this.__match(pattern, this.__position); if (pattern_match) { this.__position += pattern_match[0].length; } else { pattern_match = null; } return pattern_match; }; InputScanner.prototype.read = function(starting_pattern, until_pattern, until_after) { var val = ''; var match; if (starting_pattern) { match = this.match(starting_pattern); if (match) { val += match[0]; } } if (until_pattern && (match || !starting_pattern)) { val += this.readUntil(until_pattern, until_after); } return val; }; InputScanner.prototype.readUntil = function(pattern, until_after) { var val = ''; var match_index = this.__position; pattern.lastIndex = this.__position; var pattern_match = pattern.exec(this.__input); if (pattern_match) { match_index = pattern_match.index; if (until_after) { match_index += pattern_match[0].length; } } else { match_index = this.__input_length; } val = this.__input.substring(this.__position, match_index); this.__position = match_index; return val; }; InputScanner.prototype.readUntilAfter = function(pattern) { return this.readUntil(pattern, true); }; InputScanner.prototype.get_regexp = function(pattern, match_from) { var result = null; var flags = 'g'; if (match_from && regexp_has_sticky) { flags = 'y'; } // strings are converted to regexp if (typeof pattern === "string" && pattern !== '') { // result = new RegExp(pattern.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), flags); result = new RegExp(pattern, flags); } else if (pattern) { result = new RegExp(pattern.source, flags); } return result; }; InputScanner.prototype.get_literal_regexp = function(literal_string) { return RegExp(literal_string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')); }; /* css beautifier legacy helpers */ InputScanner.prototype.peekUntilAfter = function(pattern) { var start = this.__position; var val = this.readUntilAfter(pattern); this.__position = start; return val; }; InputScanner.prototype.lookBack = function(testVal) { var start = this.__position - 1; return start >= testVal.length && this.__input.substring(start - testVal.length, start) .toLowerCase() === testVal; }; module.exports.InputScanner = InputScanner;
import Home from './home' export default{ path: '/personal', component: Home }
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.wrapWord = void 0; const slice_ansi_1 = __importDefault(require("slice-ansi")); const strip_ansi_1 = __importDefault(require("strip-ansi")); const calculateStringLengths = (input, size) => { let subject = strip_ansi_1.default(input); const chunks = []; // https://regex101.com/r/gY5kZ1/1 const re = new RegExp('(^.{1,' + String(size) + '}(\\s+|$))|(^.{1,' + String(size - 1) + '}(\\\\|/|_|\\.|,|;|-))'); do { let chunk; const match = re.exec(subject); if (match) { chunk = match[0]; subject = subject.slice(chunk.length); const trimmedLength = chunk.trim().length; const offset = chunk.length - trimmedLength; chunks.push([trimmedLength, offset]); } else { chunk = subject.slice(0, size); subject = subject.slice(size); chunks.push([chunk.length, 0]); } } while (subject.length); return chunks; }; const wrapWord = (input, size) => { const result = []; let startIndex = 0; calculateStringLengths(input, size).forEach(([length, offset]) => { result.push(slice_ansi_1.default(input, startIndex, startIndex + length)); startIndex += length + offset; }); return result; }; exports.wrapWord = wrapWord;
/** * node-compress-commons * * Copyright (c) 2014 Chris Talkington, contributors. * Licensed under the MIT license. * https://github.com/ctalkington/node-compress-commons/blob/master/LICENSE-MIT */ var inherits = require('util').inherits; var crc32 = require('buffer-crc32'); var CRC32Stream = require('crc32-stream'); var DeflateCRC32Stream = CRC32Stream.DeflateCRC32Stream; var ArchiveOutputStream = require('../archive-output-stream'); var ZipArchiveEntry = require('./zip-archive-entry'); var GeneralPurposeBit = require('./general-purpose-bit'); var constants = require('./constants'); var util = require('../../util'); var zipUtil = require('./util'); var ZipArchiveOutputStream = module.exports = function(options) { if (!(this instanceof ZipArchiveOutputStream)) { return new ZipArchiveOutputStream(options); } options = this.options = this._defaults(options); ArchiveOutputStream.call(this, options); this._entry = null; this._entries = []; this._archive = { centralLength: 0, centralOffset: 0, comment: '', finish: false, finished: false, processing: false }; }; inherits(ZipArchiveOutputStream, ArchiveOutputStream); ZipArchiveOutputStream.prototype._afterAppend = function(ae) { this._entries.push(ae); if (ae.getGeneralPurposeBit().usesDataDescriptor()) { this._writeDataDescriptor(ae); } this._archive.processing = false; this._entry = null; if (this._archive.finish && !this._archive.finished) { this._finish(); } }; ZipArchiveOutputStream.prototype._appendBuffer = function(ae, source, callback) { if (source.length === 0) { ae.setMethod(constants.METHOD_STORED); } var method = ae.getMethod(); if (method === constants.METHOD_STORED) { ae.setSize(source.length); ae.setCompressedSize(source.length); ae.setCrc(crc32.unsigned(source)); } this._writeLocalFileHeader(ae); if (method === constants.METHOD_STORED) { this.write(source); this._afterAppend(ae); callback(null, ae); return; } else if (method === constants.METHOD_DEFLATED) { this._smartStream(ae, callback).end(source); return; } else { callback(new Error('compression method ' + method + ' not implemented')); return; } }; ZipArchiveOutputStream.prototype._appendStream = function(ae, source, callback) { ae.getGeneralPurposeBit().useDataDescriptor(true); ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR); this._writeLocalFileHeader(ae); var smart = this._smartStream(ae, callback); source.pipe(smart); }; ZipArchiveOutputStream.prototype._defaults = function(o) { if (typeof o !== 'object') { o = {}; } if (typeof o.zlib !== 'object') { o.zlib = {}; } if (typeof o.zlib.level !== 'number') { o.zlib.level = constants.ZLIB_BEST_SPEED; } return o; }; ZipArchiveOutputStream.prototype._finish = function() { this._archive.centralOffset = this.offset; this._entries.forEach(function(ae) { this._writeCentralFileHeader(ae); }.bind(this)); this._archive.centralLength = this.offset - this._archive.centralOffset; if (this.isZip64()) { this._writeCentralDirectoryZip64(); } this._writeCentralDirectoryEnd(); this._archive.processing = false; this._archive.finish = true; this._archive.finished = true; this.end(); }; ZipArchiveOutputStream.prototype._normalizeEntry = function(ae) { if (ae.getMethod() === -1) { ae.setMethod(constants.METHOD_DEFLATED); } if (ae.getMethod() === constants.METHOD_DEFLATED) { ae.getGeneralPurposeBit().useDataDescriptor(true); ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR); } if (ae.getTime() === -1) { ae.setTime(new Date()); } ae._offsets = { file: 0, data: 0, contents: 0, }; }; ZipArchiveOutputStream.prototype._smartStream = function(ae, callback) { var deflate = ae.getMethod() === constants.METHOD_DEFLATED; var process = deflate ? new DeflateCRC32Stream(this.options.zlib) : new CRC32Stream(); function handleStuff(err) { ae.setCrc(process.digest()); ae.setSize(process.size()); ae.setCompressedSize(process.size(true)); this._afterAppend(ae); callback(null, ae); } process.once('error', callback); process.once('end', handleStuff.bind(this)); process.pipe(this, { end: false }); return process; }; ZipArchiveOutputStream.prototype._writeCentralDirectoryEnd = function() { var records = this._entries.length; var size = this._archive.centralLength; var offset = this._archive.centralOffset; if (this.isZip64()) { records = constants.ZIP64_MAGIC_SHORT; size = constants.ZIP64_MAGIC; offset = constants.ZIP64_MAGIC; } // signature this.write(zipUtil.getLongBytes(constants.SIG_EOCD)); // disk numbers this.write(constants.SHORT_ZERO); this.write(constants.SHORT_ZERO); // number of entries this.write(zipUtil.getShortBytes(records)); this.write(zipUtil.getShortBytes(records)); // length and location of CD this.write(zipUtil.getLongBytes(size)); this.write(zipUtil.getLongBytes(offset)); // archive comment var comment = this.getComment(); var commentLength = Buffer.byteLength(comment); this.write(zipUtil.getShortBytes(commentLength)); this.write(comment); }; ZipArchiveOutputStream.prototype._writeCentralDirectoryZip64 = function() { // signature this.write(constants.SIG_ZIP64_EOCD); // size of the ZIP64 EOCD record this.write(zipUtil.getEightBytes((constants.SHORT * 2) + (constants.LONG * 2) + (8 * 4))); // version made by this.write(zipUtil.getShortBytes((ae.getPlatform() << 8) | constants.VERSION_MADEBY)); // version to extract this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract())); // disk numbers this.write(constants.LONG_ZERO); this.write(constants.LONG_ZERO); // number of entries this.write(zipUtil.getEightBytes(this._entries.length)); this.write(zipUtil.getEightBytes(this._entries.length)); // length and location of CD this.write(zipUtil.getEightBytes(this._archive.centralLength)); this.write(zipUtil.getEightBytes(this._archive.centralOffset)); // extensible data sector // not implemented at this time // end of central directory locator this.write(costants.SIG_ZIP64_EOCD_LOC); // disk number holding the ZIP64 EOCD record this.write(constants.LONG_ZERO); // relative offset of the ZIP64 EOCD record this.write(zipUtil.getEightBytes(this._archive.centralOffset + this._archive.centralLength)); // total number of disks this.write(this.getLongBytes(1)); }; ZipArchiveOutputStream.prototype._writeCentralFileHeader = function(ae) { var gpb = ae.getGeneralPurposeBit(); var method = ae.getMethod(); var offsets = ae._offsets; var size = ae.getSize(); var compressedSize = ae.getCompressedSize(); if (ae.isZip64() || offsets.file > constants.ZIP64_MAGIC) { size = constants.ZIP64_MAGIC; compressedSize = constants.ZIP64_MAGIC; ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64); var extraBuf = new Buffer(28); extraBuf.write(zipUtil.getShortBytes(constants.ZIP64_EXTRA_ID)); extraBuf.write(zipUtil.getShortBytes(24)); extraBuf.write(zipUtil.getEightBytes(ae.getSize())); extraBuf.write(zipUtil.getEightBytes(ae.getCompressedSize())); extraBuf.write(zipUtil.getEightBytes(offsets.file)); ae.setExtra(extraBuf); } // signature this.write(zipUtil.getLongBytes(constants.SIG_CFH)); // version made by this.write(zipUtil.getShortBytes((ae.getPlatform() << 8) | constants.VERSION_MADEBY)); // version to extract and general bit flag this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract())); this.write(gpb.encode()); // compression method this.write(zipUtil.getShortBytes(method)); // datetime this.write(zipUtil.getLongBytes(ae.getTimeDos())); // crc32 checksum this.write(zipUtil.getLongBytes(ae.getCrc())); // sizes this.write(zipUtil.getLongBytes(compressedSize)); this.write(zipUtil.getLongBytes(size)); var name = ae.getName(); var comment = ae.getComment(); var extra = ae.getCentralDirectoryExtra(); if (gpb.usesUTF8ForNames()) { name = new Buffer(name); comment = new Buffer(comment); } // name length this.write(zipUtil.getShortBytes(name.length)); // extra length this.write(zipUtil.getShortBytes(extra.length)); // comments length this.write(zipUtil.getShortBytes(comment.length)); // disk number start this.write(constants.SHORT_ZERO); // internal attributes this.write(zipUtil.getShortBytes(ae.getInternalAttributes())); // external attributes this.write(zipUtil.getLongBytes(ae.getExternalAttributes())); // relative offset of LFH if (offsets.file > constants.ZIP64_MAGIC) { this.write(zipUtil.getLongBytes(constants.ZIP64_MAGIC)); } else { this.write(zipUtil.getLongBytes(offsets.file)); } // name this.write(name); // extra this.write(extra); // comment this.write(comment); }; ZipArchiveOutputStream.prototype._writeDataDescriptor = function(ae) { // signature this.write(zipUtil.getLongBytes(constants.SIG_DD)); // crc32 checksum this.write(zipUtil.getLongBytes(ae.getCrc())); // sizes if (ae.isZip64()) { this.write(zipUtil.getEightBytes(ae.getCompressedSize())); this.write(zipUtil.getEightBytes(ae.getSize())); } else { this.write(zipUtil.getLongBytes(ae.getCompressedSize())); this.write(zipUtil.getLongBytes(ae.getSize())); } }; ZipArchiveOutputStream.prototype._writeLocalFileHeader = function(ae) { var gpb = ae.getGeneralPurposeBit(); var method = ae.getMethod(); var name = ae.getName(); var extra = ae.getLocalFileDataExtra(); if (ae.isZip64()) { gpb.useDataDescriptor(true); ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64); } if (gpb.usesUTF8ForNames()) { name = new Buffer(name); } ae._offsets.file = this.offset; // signature this.write(zipUtil.getLongBytes(constants.SIG_LFH)); // version to extract and general bit flag this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract())); this.write(gpb.encode()); // compression method this.write(zipUtil.getShortBytes(method)); // datetime this.write(zipUtil.getLongBytes(ae.getTimeDos())); ae._offsets.data = this.offset; // crc32 checksum and sizes if (gpb.usesDataDescriptor()) { this.write(constants.LONG_ZERO); this.write(constants.LONG_ZERO); this.write(constants.LONG_ZERO); } else { this.write(zipUtil.getLongBytes(ae.getCrc())); this.write(zipUtil.getLongBytes(ae.getCompressedSize())); this.write(zipUtil.getLongBytes(ae.getSize())); } // name length this.write(zipUtil.getShortBytes(name.length)); // extra length this.write(zipUtil.getShortBytes(extra.length)); // name this.write(name); // extra this.write(extra); ae._offsets.contents = this.offset; }; ZipArchiveOutputStream.prototype.getComment = function(comment) { return this._archive.comment !== null ? this._archive.comment : ''; }; ZipArchiveOutputStream.prototype.isZip64 = function() { return this._entries.length > constants.ZIP64_MAGIC_SHORT || this._archive.centralLength > constants.ZIP64_MAGIC || this._archive.centralOffset > constants.ZIP64_MAGIC; }; ZipArchiveOutputStream.prototype.setComment = function(comment) { this._archive.comment = comment; };