code stringlengths 2 1.05M |
|---|
/*
Copyright (c) 2015-present NAVER Corp.
name: @egjs/flicking
license: MIT
author: NAVER Corp.
repository: https://github.com/naver/egjs-flicking
version: 3.4.5
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, (global.eg = global.eg || {}, global.eg.Flicking = factory()));
}(this, function () { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
};
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
/*
Copyright (c) 2017 NAVER Corp.
@egjs/component project is licensed under the MIT license
@egjs/component JavaScript library
https://naver.github.io/egjs-component
@version 2.1.2
*/
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
function isUndefined(value) {
return typeof value === "undefined";
}
/**
* A class used to manage events in a component
* @ko 컴포넌트의 이벤트을 관리할 수 있게 하는 클래스
* @alias eg.Component
*/
var Component =
/*#__PURE__*/
function () {
var Component =
/*#__PURE__*/
function () {
/**
* Version info string
* @ko 버전정보 문자열
* @name VERSION
* @static
* @type {String}
* @example
* eg.Component.VERSION; // ex) 2.0.0
* @memberof eg.Component
*/
/**
* @support {"ie": "7+", "ch" : "latest", "ff" : "latest", "sf" : "latest", "edge" : "latest", "ios" : "7+", "an" : "2.1+ (except 3.x)"}
*/
function Component() {
this._eventHandler = {};
this.options = {};
}
/**
* Triggers a custom event.
* @ko 커스텀 이벤트를 발생시킨다
* @param {String} eventName The name of the custom event to be triggered <ko>발생할 커스텀 이벤트의 이름</ko>
* @param {Object} customEvent Event data to be sent when triggering a custom event <ko>커스텀 이벤트가 발생할 때 전달할 데이터</ko>
* @return {Boolean} Indicates whether the event has occurred. If the stop() method is called by a custom event handler, it will return false and prevent the event from occurring. <a href="https://github.com/naver/egjs-component/wiki/How-to-make-Component-event-design%3F">Ref</a> <ko>이벤트 발생 여부. 커스텀 이벤트 핸들러에서 stop() 메서드를 호출하면 'false'를 반환하고 이벤트 발생을 중단한다. <a href="https://github.com/naver/egjs-component/wiki/How-to-make-Component-event-design%3F">참고</a></ko>
* @example
class Some extends eg.Component {
some(){
if(this.trigger("beforeHi")){ // When event call to stop return false.
this.trigger("hi");// fire hi event.
}
}
}
const some = new Some();
some.on("beforeHi", (e) => {
if(condition){
e.stop(); // When event call to stop, `hi` event not call.
}
});
some.on("hi", (e) => {
// `currentTarget` is component instance.
console.log(some === e.currentTarget); // true
});
// If you want to more know event design. You can see article.
// https://github.com/naver/egjs-component/wiki/How-to-make-Component-event-design%3F
*/
var _proto = Component.prototype;
_proto.trigger = function trigger(eventName, customEvent) {
if (customEvent === void 0) {
customEvent = {};
}
var handlerList = this._eventHandler[eventName] || [];
var hasHandlerList = handlerList.length > 0;
if (!hasHandlerList) {
return true;
} // If detach method call in handler in first time then handler list calls.
handlerList = handlerList.concat();
customEvent.eventType = eventName;
var isCanceled = false;
var arg = [customEvent];
var i = 0;
customEvent.stop = function () {
isCanceled = true;
};
customEvent.currentTarget = this;
for (var _len = arguments.length, restParam = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
restParam[_key - 2] = arguments[_key];
}
if (restParam.length >= 1) {
arg = arg.concat(restParam);
}
for (i = 0; handlerList[i]; i++) {
handlerList[i].apply(this, arg);
}
return !isCanceled;
};
/**
* Executed event just one time.
* @ko 이벤트가 한번만 실행된다.
* @param {eventName} eventName The name of the event to be attached <ko>등록할 이벤트의 이름</ko>
* @param {Function} handlerToAttach The handler function of the event to be attached <ko>등록할 이벤트의 핸들러 함수</ko>
* @return {eg.Component} An instance of a component itself<ko>컴포넌트 자신의 인스턴스</ko>
* @example
class Some extends eg.Component {
hi() {
alert("hi");
}
thing() {
this.once("hi", this.hi);
}
}
var some = new Some();
some.thing();
some.trigger("hi");
// fire alert("hi");
some.trigger("hi");
// Nothing happens
*/
_proto.once = function once(eventName, handlerToAttach) {
if (typeof eventName === "object" && isUndefined(handlerToAttach)) {
var eventHash = eventName;
var i;
for (i in eventHash) {
this.once(i, eventHash[i]);
}
return this;
} else if (typeof eventName === "string" && typeof handlerToAttach === "function") {
var self = this;
this.on(eventName, function listener() {
for (var _len2 = arguments.length, arg = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
arg[_key2] = arguments[_key2];
}
handlerToAttach.apply(self, arg);
self.off(eventName, listener);
});
}
return this;
};
/**
* Checks whether an event has been attached to a component.
* @ko 컴포넌트에 이벤트가 등록됐는지 확인한다.
* @param {String} eventName The name of the event to be attached <ko>등록 여부를 확인할 이벤트의 이름</ko>
* @return {Boolean} Indicates whether the event is attached. <ko>이벤트 등록 여부</ko>
* @example
class Some extends eg.Component {
some() {
this.hasOn("hi");// check hi event.
}
}
*/
_proto.hasOn = function hasOn(eventName) {
return !!this._eventHandler[eventName];
};
/**
* Attaches an event to a component.
* @ko 컴포넌트에 이벤트를 등록한다.
* @param {eventName} eventName The name of the event to be attached <ko>등록할 이벤트의 이름</ko>
* @param {Function} handlerToAttach The handler function of the event to be attached <ko>등록할 이벤트의 핸들러 함수</ko>
* @return {eg.Component} An instance of a component itself<ko>컴포넌트 자신의 인스턴스</ko>
* @example
class Some extends eg.Component {
hi() {
console.log("hi");
}
some() {
this.on("hi",this.hi); //attach event
}
}
*/
_proto.on = function on(eventName, handlerToAttach) {
if (typeof eventName === "object" && isUndefined(handlerToAttach)) {
var eventHash = eventName;
var name;
for (name in eventHash) {
this.on(name, eventHash[name]);
}
return this;
} else if (typeof eventName === "string" && typeof handlerToAttach === "function") {
var handlerList = this._eventHandler[eventName];
if (isUndefined(handlerList)) {
this._eventHandler[eventName] = [];
handlerList = this._eventHandler[eventName];
}
handlerList.push(handlerToAttach);
}
return this;
};
/**
* Detaches an event from the component.
* @ko 컴포넌트에 등록된 이벤트를 해제한다
* @param {eventName} eventName The name of the event to be detached <ko>해제할 이벤트의 이름</ko>
* @param {Function} handlerToDetach The handler function of the event to be detached <ko>해제할 이벤트의 핸들러 함수</ko>
* @return {eg.Component} An instance of a component itself <ko>컴포넌트 자신의 인스턴스</ko>
* @example
class Some extends eg.Component {
hi() {
console.log("hi");
}
some() {
this.off("hi",this.hi); //detach event
}
}
*/
_proto.off = function off(eventName, handlerToDetach) {
// All event detach.
if (isUndefined(eventName)) {
this._eventHandler = {};
return this;
} // All handler of specific event detach.
if (isUndefined(handlerToDetach)) {
if (typeof eventName === "string") {
this._eventHandler[eventName] = undefined;
return this;
} else {
var eventHash = eventName;
var name;
for (name in eventHash) {
this.off(name, eventHash[name]);
}
return this;
}
} // The handler of specific event detach.
var handlerList = this._eventHandler[eventName];
if (handlerList) {
var k;
var handlerFunction;
for (k = 0; (handlerFunction = handlerList[k]) !== undefined; k++) {
if (handlerFunction === handlerToDetach) {
handlerList = handlerList.splice(k, 1);
break;
}
}
}
return this;
};
return Component;
}();
Component.VERSION = "2.1.2";
return Component;
}();
/*! Hammer.JS - v2.0.15 - 2019-04-04
* http://naver.github.io/egjs
*
* Forked By Naver egjs
* Copyright (c) hammerjs
* Licensed under the MIT license */
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
/**
* @private
* extend object.
* means that properties in dest will be overwritten by the ones in src.
* @param {Object} target
* @param {...Object} objects_to_assign
* @returns {Object} target
*/
var assign;
if (typeof Object.assign !== 'function') {
assign = function assign(target) {
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source !== undefined && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};
} else {
assign = Object.assign;
}
var assign$1 = assign;
var VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];
var TEST_ELEMENT = typeof document === "undefined" ? {
style: {}
} : document.createElement('div');
var TYPE_FUNCTION = 'function';
var round = Math.round,
abs = Math.abs;
var now = Date.now;
/**
* @private
* get the prefixed property
* @param {Object} obj
* @param {String} property
* @returns {String|Undefined} prefixed
*/
function prefixed(obj, property) {
var prefix;
var prop;
var camelProp = property[0].toUpperCase() + property.slice(1);
var i = 0;
while (i < VENDOR_PREFIXES.length) {
prefix = VENDOR_PREFIXES[i];
prop = prefix ? prefix + camelProp : property;
if (prop in obj) {
return prop;
}
i++;
}
return undefined;
}
/* eslint-disable no-new-func, no-nested-ternary */
var win;
if (typeof window === "undefined") {
// window is undefined in node.js
win = {};
} else {
win = window;
}
var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction');
var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined;
function getTouchActionProps() {
if (!NATIVE_TOUCH_ACTION) {
return false;
}
var touchMap = {};
var cssSupports = win.CSS && win.CSS.supports;
['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y', 'none'].forEach(function (val) {
// If css.supports is not supported but there is native touch-action assume it supports
// all values. This is the case for IE 10 and 11.
return touchMap[val] = cssSupports ? win.CSS.supports('touch-action', val) : true;
});
return touchMap;
}
var TOUCH_ACTION_COMPUTE = 'compute';
var TOUCH_ACTION_AUTO = 'auto';
var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented
var TOUCH_ACTION_NONE = 'none';
var TOUCH_ACTION_PAN_X = 'pan-x';
var TOUCH_ACTION_PAN_Y = 'pan-y';
var TOUCH_ACTION_MAP = getTouchActionProps();
var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;
var SUPPORT_TOUCH = 'ontouchstart' in win;
var SUPPORT_POINTER_EVENTS = prefixed(win, 'PointerEvent') !== undefined;
var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);
var INPUT_TYPE_TOUCH = 'touch';
var INPUT_TYPE_PEN = 'pen';
var INPUT_TYPE_MOUSE = 'mouse';
var INPUT_TYPE_KINECT = 'kinect';
var COMPUTE_INTERVAL = 25;
var INPUT_START = 1;
var INPUT_MOVE = 2;
var INPUT_END = 4;
var INPUT_CANCEL = 8;
var DIRECTION_NONE = 1;
var DIRECTION_LEFT = 2;
var DIRECTION_RIGHT = 4;
var DIRECTION_UP = 8;
var DIRECTION_DOWN = 16;
var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;
var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;
var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;
var PROPS_XY = ['x', 'y'];
var PROPS_CLIENT_XY = ['clientX', 'clientY'];
/**
* @private
* walk objects and arrays
* @param {Object} obj
* @param {Function} iterator
* @param {Object} context
*/
function each(obj, iterator, context) {
var i;
if (!obj) {
return;
}
if (obj.forEach) {
obj.forEach(iterator, context);
} else if (obj.length !== undefined) {
i = 0;
while (i < obj.length) {
iterator.call(context, obj[i], i, obj);
i++;
}
} else {
for (i in obj) {
obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
}
}
}
/**
* @private
* let a boolean value also be a function that must return a boolean
* this first item in args will be used as the context
* @param {Boolean|Function} val
* @param {Array} [args]
* @returns {Boolean}
*/
function boolOrFn(val, args) {
if (typeof val === TYPE_FUNCTION) {
return val.apply(args ? args[0] || undefined : undefined, args);
}
return val;
}
/**
* @private
* small indexOf wrapper
* @param {String} str
* @param {String} find
* @returns {Boolean} found
*/
function inStr(str, find) {
return str.indexOf(find) > -1;
}
/**
* @private
* when the touchActions are collected they are not a valid value, so we need to clean things up. *
* @param {String} actions
* @returns {*}
*/
function cleanTouchActions(actions) {
// none
if (inStr(actions, TOUCH_ACTION_NONE)) {
return TOUCH_ACTION_NONE;
}
var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); // if both pan-x and pan-y are set (different recognizers
// for different directions, e.g. horizontal pan but vertical swipe?)
// we need none (as otherwise with pan-x pan-y combined none of these
// recognizers will work, since the browser would handle all panning
if (hasPanX && hasPanY) {
return TOUCH_ACTION_NONE;
} // pan-x OR pan-y
if (hasPanX || hasPanY) {
return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
} // manipulation
if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
return TOUCH_ACTION_MANIPULATION;
}
return TOUCH_ACTION_AUTO;
}
/**
* @private
* Touch Action
* sets the touchAction property or uses the js alternative
* @param {Manager} manager
* @param {String} value
* @constructor
*/
var TouchAction =
/*#__PURE__*/
function () {
function TouchAction(manager, value) {
this.manager = manager;
this.set(value);
}
/**
* @private
* set the touchAction value on the element or enable the polyfill
* @param {String} value
*/
var _proto = TouchAction.prototype;
_proto.set = function set(value) {
// find out the touch-action by the event handlers
if (value === TOUCH_ACTION_COMPUTE) {
value = this.compute();
}
if (NATIVE_TOUCH_ACTION && this.manager.element.style && TOUCH_ACTION_MAP[value]) {
this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;
}
this.actions = value.toLowerCase().trim();
};
/**
* @private
* just re-set the touchAction value
*/
_proto.update = function update() {
this.set(this.manager.options.touchAction);
};
/**
* @private
* compute the value for the touchAction property based on the recognizer's settings
* @returns {String} value
*/
_proto.compute = function compute() {
var actions = [];
each(this.manager.recognizers, function (recognizer) {
if (boolOrFn(recognizer.options.enable, [recognizer])) {
actions = actions.concat(recognizer.getTouchAction());
}
});
return cleanTouchActions(actions.join(' '));
};
/**
* @private
* this method is called on each input cycle and provides the preventing of the browser behavior
* @param {Object} input
*/
_proto.preventDefaults = function preventDefaults(input) {
var srcEvent = input.srcEvent;
var direction = input.offsetDirection; // if the touch action did prevented once this session
if (this.manager.session.prevented) {
srcEvent.preventDefault();
return;
}
var actions = this.actions;
var hasNone = inStr(actions, TOUCH_ACTION_NONE) && !TOUCH_ACTION_MAP[TOUCH_ACTION_NONE];
var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y];
var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X];
if (hasNone) {
// do not prevent defaults if this is a tap gesture
var isTapPointer = input.pointers.length === 1;
var isTapMovement = input.distance < 2;
var isTapTouchTime = input.deltaTime < 250;
if (isTapPointer && isTapMovement && isTapTouchTime) {
return;
}
}
if (hasPanX && hasPanY) {
// `pan-x pan-y` means browser handles all scrolling/panning, do not prevent
return;
}
if (hasNone || hasPanY && direction & DIRECTION_HORIZONTAL || hasPanX && direction & DIRECTION_VERTICAL) {
return this.preventSrc(srcEvent);
}
};
/**
* @private
* call preventDefault to prevent the browser's default behavior (scrolling in most cases)
* @param {Object} srcEvent
*/
_proto.preventSrc = function preventSrc(srcEvent) {
this.manager.session.prevented = true;
srcEvent.preventDefault();
};
return TouchAction;
}();
/**
* @private
* find if a node is in the given parent
* @method hasParent
* @param {HTMLElement} node
* @param {HTMLElement} parent
* @return {Boolean} found
*/
function hasParent(node, parent) {
while (node) {
if (node === parent) {
return true;
}
node = node.parentNode;
}
return false;
}
/**
* @private
* get the center of all the pointers
* @param {Array} pointers
* @return {Object} center contains `x` and `y` properties
*/
function getCenter(pointers) {
var pointersLength = pointers.length; // no need to loop when only one touch
if (pointersLength === 1) {
return {
x: round(pointers[0].clientX),
y: round(pointers[0].clientY)
};
}
var x = 0;
var y = 0;
var i = 0;
while (i < pointersLength) {
x += pointers[i].clientX;
y += pointers[i].clientY;
i++;
}
return {
x: round(x / pointersLength),
y: round(y / pointersLength)
};
}
/**
* @private
* create a simple clone from the input used for storage of firstInput and firstMultiple
* @param {Object} input
* @returns {Object} clonedInputData
*/
function simpleCloneInputData(input) {
// make a simple copy of the pointers because we will get a reference if we don't
// we only need clientXY for the calculations
var pointers = [];
var i = 0;
while (i < input.pointers.length) {
pointers[i] = {
clientX: round(input.pointers[i].clientX),
clientY: round(input.pointers[i].clientY)
};
i++;
}
return {
timeStamp: now(),
pointers: pointers,
center: getCenter(pointers),
deltaX: input.deltaX,
deltaY: input.deltaY
};
}
/**
* @private
* calculate the absolute distance between two points
* @param {Object} p1 {x, y}
* @param {Object} p2 {x, y}
* @param {Array} [props] containing x and y keys
* @return {Number} distance
*/
function getDistance(p1, p2, props) {
if (!props) {
props = PROPS_XY;
}
var x = p2[props[0]] - p1[props[0]];
var y = p2[props[1]] - p1[props[1]];
return Math.sqrt(x * x + y * y);
}
/**
* @private
* calculate the angle between two coordinates
* @param {Object} p1
* @param {Object} p2
* @param {Array} [props] containing x and y keys
* @return {Number} angle
*/
function getAngle(p1, p2, props) {
if (!props) {
props = PROPS_XY;
}
var x = p2[props[0]] - p1[props[0]];
var y = p2[props[1]] - p1[props[1]];
return Math.atan2(y, x) * 180 / Math.PI;
}
/**
* @private
* get the direction between two points
* @param {Number} x
* @param {Number} y
* @return {Number} direction
*/
function getDirection(x, y) {
if (x === y) {
return DIRECTION_NONE;
}
if (abs(x) >= abs(y)) {
return x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
}
return y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
}
function computeDeltaXY(session, input) {
var center = input.center; // let { offsetDelta:offset = {}, prevDelta = {}, prevInput = {} } = session;
// jscs throwing error on defalut destructured values and without defaults tests fail
var offset = session.offsetDelta || {};
var prevDelta = session.prevDelta || {};
var prevInput = session.prevInput || {};
if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {
prevDelta = session.prevDelta = {
x: prevInput.deltaX || 0,
y: prevInput.deltaY || 0
};
offset = session.offsetDelta = {
x: center.x,
y: center.y
};
}
input.deltaX = prevDelta.x + (center.x - offset.x);
input.deltaY = prevDelta.y + (center.y - offset.y);
}
/**
* @private
* calculate the velocity between two points. unit is in px per ms.
* @param {Number} deltaTime
* @param {Number} x
* @param {Number} y
* @return {Object} velocity `x` and `y`
*/
function getVelocity(deltaTime, x, y) {
return {
x: x / deltaTime || 0,
y: y / deltaTime || 0
};
}
/**
* @private
* calculate the scale factor between two pointersets
* no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
* @param {Array} start array of pointers
* @param {Array} end array of pointers
* @return {Number} scale
*/
function getScale(start, end) {
return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
}
/**
* @private
* calculate the rotation degrees between two pointersets
* @param {Array} start array of pointers
* @param {Array} end array of pointers
* @return {Number} rotation
*/
function getRotation(start, end) {
return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0], PROPS_CLIENT_XY);
}
/**
* @private
* velocity is calculated every x ms
* @param {Object} session
* @param {Object} input
*/
function computeIntervalInputData(session, input) {
var last = session.lastInterval || input;
var deltaTime = input.timeStamp - last.timeStamp;
var velocity;
var velocityX;
var velocityY;
var direction;
if (input.eventType !== INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {
var deltaX = input.deltaX - last.deltaX;
var deltaY = input.deltaY - last.deltaY;
var v = getVelocity(deltaTime, deltaX, deltaY);
velocityX = v.x;
velocityY = v.y;
velocity = abs(v.x) > abs(v.y) ? v.x : v.y;
direction = getDirection(deltaX, deltaY);
session.lastInterval = input;
} else {
// use latest velocity info if it doesn't overtake a minimum period
velocity = last.velocity;
velocityX = last.velocityX;
velocityY = last.velocityY;
direction = last.direction;
}
input.velocity = velocity;
input.velocityX = velocityX;
input.velocityY = velocityY;
input.direction = direction;
}
/**
* @private
* extend the data with some usable properties like scale, rotate, velocity etc
* @param {Object} manager
* @param {Object} input
*/
function computeInputData(manager, input) {
var session = manager.session;
var pointers = input.pointers;
var pointersLength = pointers.length; // store the first input to calculate the distance and direction
if (!session.firstInput) {
session.firstInput = simpleCloneInputData(input);
} // to compute scale and rotation we need to store the multiple touches
if (pointersLength > 1 && !session.firstMultiple) {
session.firstMultiple = simpleCloneInputData(input);
} else if (pointersLength === 1) {
session.firstMultiple = false;
}
var firstInput = session.firstInput,
firstMultiple = session.firstMultiple;
var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;
var center = input.center = getCenter(pointers);
input.timeStamp = now();
input.deltaTime = input.timeStamp - firstInput.timeStamp;
input.angle = getAngle(offsetCenter, center);
input.distance = getDistance(offsetCenter, center);
computeDeltaXY(session, input);
input.offsetDirection = getDirection(input.deltaX, input.deltaY);
var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY);
input.overallVelocityX = overallVelocity.x;
input.overallVelocityY = overallVelocity.y;
input.overallVelocity = abs(overallVelocity.x) > abs(overallVelocity.y) ? overallVelocity.x : overallVelocity.y;
input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;
input.maxPointers = !session.prevInput ? input.pointers.length : input.pointers.length > session.prevInput.maxPointers ? input.pointers.length : session.prevInput.maxPointers;
computeIntervalInputData(session, input); // find the correct target
var target = manager.element;
if (hasParent(input.srcEvent.target, target)) {
target = input.srcEvent.target;
}
input.target = target;
}
/**
* @private
* handle input events
* @param {Manager} manager
* @param {String} eventType
* @param {Object} input
*/
function inputHandler(manager, eventType, input) {
var pointersLen = input.pointers.length;
var changedPointersLen = input.changedPointers.length;
var isFirst = eventType & INPUT_START && pointersLen - changedPointersLen === 0;
var isFinal = eventType & (INPUT_END | INPUT_CANCEL) && pointersLen - changedPointersLen === 0;
input.isFirst = !!isFirst;
input.isFinal = !!isFinal;
if (isFirst) {
manager.session = {};
} // source event is the normalized value of the domEvents
// like 'touchstart, mouseup, pointerdown'
input.eventType = eventType; // compute scale, rotation etc
computeInputData(manager, input); // emit secret event
manager.emit('hammer.input', input);
manager.recognize(input);
manager.session.prevInput = input;
}
/**
* @private
* split string on whitespace
* @param {String} str
* @returns {Array} words
*/
function splitStr(str) {
return str.trim().split(/\s+/g);
}
/**
* @private
* addEventListener with multiple events at once
* @param {EventTarget} target
* @param {String} types
* @param {Function} handler
*/
function addEventListeners(target, types, handler) {
each(splitStr(types), function (type) {
target.addEventListener(type, handler, false);
});
}
/**
* @private
* removeEventListener with multiple events at once
* @param {EventTarget} target
* @param {String} types
* @param {Function} handler
*/
function removeEventListeners(target, types, handler) {
each(splitStr(types), function (type) {
target.removeEventListener(type, handler, false);
});
}
/**
* @private
* get the window object of an element
* @param {HTMLElement} element
* @returns {DocumentView|Window}
*/
function getWindowForElement(element) {
var doc = element.ownerDocument || element;
return doc.defaultView || doc.parentWindow || window;
}
/**
* @private
* create new input type manager
* @param {Manager} manager
* @param {Function} callback
* @returns {Input}
* @constructor
*/
var Input =
/*#__PURE__*/
function () {
function Input(manager, callback) {
var self = this;
this.manager = manager;
this.callback = callback;
this.element = manager.element;
this.target = manager.options.inputTarget; // smaller wrapper around the handler, for the scope and the enabled state of the manager,
// so when disabled the input events are completely bypassed.
this.domHandler = function (ev) {
if (boolOrFn(manager.options.enable, [manager])) {
self.handler(ev);
}
};
this.init();
}
/**
* @private
* should handle the inputEvent data and trigger the callback
* @virtual
*/
var _proto = Input.prototype;
_proto.handler = function handler() {};
/**
* @private
* bind the events
*/
_proto.init = function init() {
this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);
this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);
this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
};
/**
* @private
* unbind the events
*/
_proto.destroy = function destroy() {
this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);
this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);
this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
};
return Input;
}();
/**
* @private
* find if a array contains the object using indexOf or a simple polyFill
* @param {Array} src
* @param {String} find
* @param {String} [findByKey]
* @return {Boolean|Number} false when not found, or the index
*/
function inArray(src, find, findByKey) {
if (src.indexOf && !findByKey) {
return src.indexOf(find);
} else {
var i = 0;
while (i < src.length) {
if (findByKey && src[i][findByKey] == find || !findByKey && src[i] === find) {
// do not use === here, test fails
return i;
}
i++;
}
return -1;
}
}
var POINTER_INPUT_MAP = {
pointerdown: INPUT_START,
pointermove: INPUT_MOVE,
pointerup: INPUT_END,
pointercancel: INPUT_CANCEL,
pointerout: INPUT_CANCEL
}; // in IE10 the pointer types is defined as an enum
var IE10_POINTER_TYPE_ENUM = {
2: INPUT_TYPE_TOUCH,
3: INPUT_TYPE_PEN,
4: INPUT_TYPE_MOUSE,
5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816
};
var POINTER_ELEMENT_EVENTS = 'pointerdown';
var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel'; // IE10 has prefixed support, and case-sensitive
if (win.MSPointerEvent && !win.PointerEvent) {
POINTER_ELEMENT_EVENTS = 'MSPointerDown';
POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel';
}
/**
* @private
* Pointer events input
* @constructor
* @extends Input
*/
var PointerEventInput =
/*#__PURE__*/
function (_Input) {
_inheritsLoose(PointerEventInput, _Input);
function PointerEventInput() {
var _this;
var proto = PointerEventInput.prototype;
proto.evEl = POINTER_ELEMENT_EVENTS;
proto.evWin = POINTER_WINDOW_EVENTS;
_this = _Input.apply(this, arguments) || this;
_this.store = _this.manager.session.pointerEvents = [];
return _this;
}
/**
* @private
* handle mouse events
* @param {Object} ev
*/
var _proto = PointerEventInput.prototype;
_proto.handler = function handler(ev) {
var store = this.store;
var removePointer = false;
var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;
var isTouch = pointerType === INPUT_TYPE_TOUCH; // get index of the event in the store
var storeIndex = inArray(store, ev.pointerId, 'pointerId'); // start and mouse must be down
if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
if (storeIndex < 0) {
store.push(ev);
storeIndex = store.length - 1;
}
} else if (eventType & (INPUT_END | INPUT_CANCEL)) {
removePointer = true;
} // it not found, so the pointer hasn't been down (so it's probably a hover)
if (storeIndex < 0) {
return;
} // update the event in the store
store[storeIndex] = ev;
this.callback(this.manager, eventType, {
pointers: store,
changedPointers: [ev],
pointerType: pointerType,
srcEvent: ev
});
if (removePointer) {
// remove from the store
store.splice(storeIndex, 1);
}
};
return PointerEventInput;
}(Input);
/**
* @private
* convert array-like objects to real arrays
* @param {Object} obj
* @returns {Array}
*/
function toArray(obj) {
return Array.prototype.slice.call(obj, 0);
}
/**
* @private
* unique array with objects based on a key (like 'id') or just by the array's value
* @param {Array} src [{id:1},{id:2},{id:1}]
* @param {String} [key]
* @param {Boolean} [sort=False]
* @returns {Array} [{id:1},{id:2}]
*/
function uniqueArray(src, key, sort) {
var results = [];
var values = [];
var i = 0;
while (i < src.length) {
var val = key ? src[i][key] : src[i];
if (inArray(values, val) < 0) {
results.push(src[i]);
}
values[i] = val;
i++;
}
if (sort) {
if (!key) {
results = results.sort();
} else {
results = results.sort(function (a, b) {
return a[key] > b[key];
});
}
}
return results;
}
var TOUCH_INPUT_MAP = {
touchstart: INPUT_START,
touchmove: INPUT_MOVE,
touchend: INPUT_END,
touchcancel: INPUT_CANCEL
};
var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel';
/**
* @private
* Multi-user touch events input
* @constructor
* @extends Input
*/
var TouchInput =
/*#__PURE__*/
function (_Input) {
_inheritsLoose(TouchInput, _Input);
function TouchInput() {
var _this;
TouchInput.prototype.evTarget = TOUCH_TARGET_EVENTS;
_this = _Input.apply(this, arguments) || this;
_this.targetIds = {}; // this.evTarget = TOUCH_TARGET_EVENTS;
return _this;
}
var _proto = TouchInput.prototype;
_proto.handler = function handler(ev) {
var type = TOUCH_INPUT_MAP[ev.type];
var touches = getTouches.call(this, ev, type);
if (!touches) {
return;
}
this.callback(this.manager, type, {
pointers: touches[0],
changedPointers: touches[1],
pointerType: INPUT_TYPE_TOUCH,
srcEvent: ev
});
};
return TouchInput;
}(Input);
function getTouches(ev, type) {
var allTouches = toArray(ev.touches);
var targetIds = this.targetIds; // when there is only one touch, the process can be simplified
if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
targetIds[allTouches[0].identifier] = true;
return [allTouches, allTouches];
}
var i;
var targetTouches;
var changedTouches = toArray(ev.changedTouches);
var changedTargetTouches = [];
var target = this.target; // get target touches from touches
targetTouches = allTouches.filter(function (touch) {
return hasParent(touch.target, target);
}); // collect touches
if (type === INPUT_START) {
i = 0;
while (i < targetTouches.length) {
targetIds[targetTouches[i].identifier] = true;
i++;
}
} // filter changed touches to only contain touches that exist in the collected target ids
i = 0;
while (i < changedTouches.length) {
if (targetIds[changedTouches[i].identifier]) {
changedTargetTouches.push(changedTouches[i]);
} // cleanup removed touches
if (type & (INPUT_END | INPUT_CANCEL)) {
delete targetIds[changedTouches[i].identifier];
}
i++;
}
if (!changedTargetTouches.length) {
return;
}
return [// merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true), changedTargetTouches];
}
var MOUSE_INPUT_MAP = {
mousedown: INPUT_START,
mousemove: INPUT_MOVE,
mouseup: INPUT_END
};
var MOUSE_ELEMENT_EVENTS = 'mousedown';
var MOUSE_WINDOW_EVENTS = 'mousemove mouseup';
/**
* @private
* Mouse events input
* @constructor
* @extends Input
*/
var MouseInput =
/*#__PURE__*/
function (_Input) {
_inheritsLoose(MouseInput, _Input);
function MouseInput() {
var _this;
var proto = MouseInput.prototype;
proto.evEl = MOUSE_ELEMENT_EVENTS;
proto.evWin = MOUSE_WINDOW_EVENTS;
_this = _Input.apply(this, arguments) || this;
_this.pressed = false; // mousedown state
return _this;
}
/**
* @private
* handle mouse events
* @param {Object} ev
*/
var _proto = MouseInput.prototype;
_proto.handler = function handler(ev) {
var eventType = MOUSE_INPUT_MAP[ev.type]; // on start we want to have the left mouse button down
if (eventType & INPUT_START && ev.button === 0) {
this.pressed = true;
}
if (eventType & INPUT_MOVE && ev.which !== 1) {
eventType = INPUT_END;
} // mouse must be down
if (!this.pressed) {
return;
}
if (eventType & INPUT_END) {
this.pressed = false;
}
this.callback(this.manager, eventType, {
pointers: [ev],
changedPointers: [ev],
pointerType: INPUT_TYPE_MOUSE,
srcEvent: ev
});
};
return MouseInput;
}(Input);
/**
* @private
* Combined touch and mouse input
*
* Touch has a higher priority then mouse, and while touching no mouse events are allowed.
* This because touch devices also emit mouse events while doing a touch.
*
* @constructor
* @extends Input
*/
var DEDUP_TIMEOUT = 2500;
var DEDUP_DISTANCE = 25;
function setLastTouch(eventData) {
var _eventData$changedPoi = eventData.changedPointers,
touch = _eventData$changedPoi[0];
if (touch.identifier === this.primaryTouch) {
var lastTouch = {
x: touch.clientX,
y: touch.clientY
};
var lts = this.lastTouches;
this.lastTouches.push(lastTouch);
var removeLastTouch = function removeLastTouch() {
var i = lts.indexOf(lastTouch);
if (i > -1) {
lts.splice(i, 1);
}
};
setTimeout(removeLastTouch, DEDUP_TIMEOUT);
}
}
function recordTouches(eventType, eventData) {
if (eventType & INPUT_START) {
this.primaryTouch = eventData.changedPointers[0].identifier;
setLastTouch.call(this, eventData);
} else if (eventType & (INPUT_END | INPUT_CANCEL)) {
setLastTouch.call(this, eventData);
}
}
function isSyntheticEvent(eventData) {
var x = eventData.srcEvent.clientX;
var y = eventData.srcEvent.clientY;
for (var i = 0; i < this.lastTouches.length; i++) {
var t = this.lastTouches[i];
var dx = Math.abs(x - t.x);
var dy = Math.abs(y - t.y);
if (dx <= DEDUP_DISTANCE && dy <= DEDUP_DISTANCE) {
return true;
}
}
return false;
}
var TouchMouseInput =
/*#__PURE__*/
function () {
var TouchMouseInput =
/*#__PURE__*/
function (_Input) {
_inheritsLoose(TouchMouseInput, _Input);
function TouchMouseInput(_manager, callback) {
var _this;
_this = _Input.call(this, _manager, callback) || this;
_this.handler = function (manager, inputEvent, inputData) {
var isTouch = inputData.pointerType === INPUT_TYPE_TOUCH;
var isMouse = inputData.pointerType === INPUT_TYPE_MOUSE;
if (isMouse && inputData.sourceCapabilities && inputData.sourceCapabilities.firesTouchEvents) {
return;
} // when we're in a touch event, record touches to de-dupe synthetic mouse event
if (isTouch) {
recordTouches.call(_assertThisInitialized(_assertThisInitialized(_this)), inputEvent, inputData);
} else if (isMouse && isSyntheticEvent.call(_assertThisInitialized(_assertThisInitialized(_this)), inputData)) {
return;
}
_this.callback(manager, inputEvent, inputData);
};
_this.touch = new TouchInput(_this.manager, _this.handler);
_this.mouse = new MouseInput(_this.manager, _this.handler);
_this.primaryTouch = null;
_this.lastTouches = [];
return _this;
}
/**
* @private
* handle mouse and touch events
* @param {Hammer} manager
* @param {String} inputEvent
* @param {Object} inputData
*/
var _proto = TouchMouseInput.prototype;
/**
* @private
* remove the event listeners
*/
_proto.destroy = function destroy() {
this.touch.destroy();
this.mouse.destroy();
};
return TouchMouseInput;
}(Input);
return TouchMouseInput;
}();
/**
* @private
* create new input type manager
* called by the Manager constructor
* @param {Hammer} manager
* @returns {Input}
*/
function createInputInstance(manager) {
var Type; // let inputClass = manager.options.inputClass;
var inputClass = manager.options.inputClass;
if (inputClass) {
Type = inputClass;
} else if (SUPPORT_POINTER_EVENTS) {
Type = PointerEventInput;
} else if (SUPPORT_ONLY_TOUCH) {
Type = TouchInput;
} else if (!SUPPORT_TOUCH) {
Type = MouseInput;
} else {
Type = TouchMouseInput;
}
return new Type(manager, inputHandler);
}
/**
* @private
* if the argument is an array, we want to execute the fn on each entry
* if it aint an array we don't want to do a thing.
* this is used by all the methods that accept a single and array argument.
* @param {*|Array} arg
* @param {String} fn
* @param {Object} [context]
* @returns {Boolean}
*/
function invokeArrayArg(arg, fn, context) {
if (Array.isArray(arg)) {
each(arg, context[fn], context);
return true;
}
return false;
}
var STATE_POSSIBLE = 1;
var STATE_BEGAN = 2;
var STATE_CHANGED = 4;
var STATE_ENDED = 8;
var STATE_RECOGNIZED = STATE_ENDED;
var STATE_CANCELLED = 16;
var STATE_FAILED = 32;
/**
* @private
* get a unique id
* @returns {number} uniqueId
*/
var _uniqueId = 1;
function uniqueId() {
return _uniqueId++;
}
/**
* @private
* get a recognizer by name if it is bound to a manager
* @param {Recognizer|String} otherRecognizer
* @param {Recognizer} recognizer
* @returns {Recognizer}
*/
function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
var manager = recognizer.manager;
if (manager) {
return manager.get(otherRecognizer);
}
return otherRecognizer;
}
/**
* @private
* get a usable string, used as event postfix
* @param {constant} state
* @returns {String} state
*/
function stateStr(state) {
if (state & STATE_CANCELLED) {
return 'cancel';
} else if (state & STATE_ENDED) {
return 'end';
} else if (state & STATE_CHANGED) {
return 'move';
} else if (state & STATE_BEGAN) {
return 'start';
}
return '';
}
/**
* @private
* Recognizer flow explained; *
* All recognizers have the initial state of POSSIBLE when a input session starts.
* The definition of a input session is from the first input until the last input, with all it's movement in it. *
* Example session for mouse-input: mousedown -> mousemove -> mouseup
*
* On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
* which determines with state it should be.
*
* If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
* POSSIBLE to give it another change on the next cycle.
*
* Possible
* |
* +-----+---------------+
* | |
* +-----+-----+ |
* | | |
* Failed Cancelled |
* +-------+------+
* | |
* Recognized Began
* |
* Changed
* |
* Ended/Recognized
*/
/**
* @private
* Recognizer
* Every recognizer needs to extend from this class.
* @constructor
* @param {Object} options
*/
var Recognizer =
/*#__PURE__*/
function () {
function Recognizer(options) {
if (options === void 0) {
options = {};
}
this.options = _extends({
enable: true
}, options);
this.id = uniqueId();
this.manager = null; // default is enable true
this.state = STATE_POSSIBLE;
this.simultaneous = {};
this.requireFail = [];
}
/**
* @private
* set options
* @param {Object} options
* @return {Recognizer}
*/
var _proto = Recognizer.prototype;
_proto.set = function set(options) {
assign$1(this.options, options); // also update the touchAction, in case something changed about the directions/enabled state
this.manager && this.manager.touchAction.update();
return this;
};
/**
* @private
* recognize simultaneous with an other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
_proto.recognizeWith = function recognizeWith(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
return this;
}
var simultaneous = this.simultaneous;
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
if (!simultaneous[otherRecognizer.id]) {
simultaneous[otherRecognizer.id] = otherRecognizer;
otherRecognizer.recognizeWith(this);
}
return this;
};
/**
* @private
* drop the simultaneous link. it doesnt remove the link on the other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
_proto.dropRecognizeWith = function dropRecognizeWith(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {
return this;
}
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
delete this.simultaneous[otherRecognizer.id];
return this;
};
/**
* @private
* recognizer can only run when an other is failing
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
_proto.requireFailure = function requireFailure(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {
return this;
}
var requireFail = this.requireFail;
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
if (inArray(requireFail, otherRecognizer) === -1) {
requireFail.push(otherRecognizer);
otherRecognizer.requireFailure(this);
}
return this;
};
/**
* @private
* drop the requireFailure link. it does not remove the link on the other recognizer.
* @param {Recognizer} otherRecognizer
* @returns {Recognizer} this
*/
_proto.dropRequireFailure = function dropRequireFailure(otherRecognizer) {
if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {
return this;
}
otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
var index = inArray(this.requireFail, otherRecognizer);
if (index > -1) {
this.requireFail.splice(index, 1);
}
return this;
};
/**
* @private
* has require failures boolean
* @returns {boolean}
*/
_proto.hasRequireFailures = function hasRequireFailures() {
return this.requireFail.length > 0;
};
/**
* @private
* if the recognizer can recognize simultaneous with an other recognizer
* @param {Recognizer} otherRecognizer
* @returns {Boolean}
*/
_proto.canRecognizeWith = function canRecognizeWith(otherRecognizer) {
return !!this.simultaneous[otherRecognizer.id];
};
/**
* @private
* You should use `tryEmit` instead of `emit` directly to check
* that all the needed recognizers has failed before emitting.
* @param {Object} input
*/
_proto.emit = function emit(input) {
var self = this;
var state = this.state;
function emit(event) {
self.manager.emit(event, input);
} // 'panstart' and 'panmove'
if (state < STATE_ENDED) {
emit(self.options.event + stateStr(state));
}
emit(self.options.event); // simple 'eventName' events
if (input.additionalEvent) {
// additional event(panleft, panright, pinchin, pinchout...)
emit(input.additionalEvent);
} // panend and pancancel
if (state >= STATE_ENDED) {
emit(self.options.event + stateStr(state));
}
};
/**
* @private
* Check that all the require failure recognizers has failed,
* if true, it emits a gesture event,
* otherwise, setup the state to FAILED.
* @param {Object} input
*/
_proto.tryEmit = function tryEmit(input) {
if (this.canEmit()) {
return this.emit(input);
} // it's failing anyway
this.state = STATE_FAILED;
};
/**
* @private
* can we emit?
* @returns {boolean}
*/
_proto.canEmit = function canEmit() {
var i = 0;
while (i < this.requireFail.length) {
if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
return false;
}
i++;
}
return true;
};
/**
* @private
* update the recognizer
* @param {Object} inputData
*/
_proto.recognize = function recognize(inputData) {
// make a new copy of the inputData
// so we can change the inputData without messing up the other recognizers
var inputDataClone = assign$1({}, inputData); // is is enabled and allow recognizing?
if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
this.reset();
this.state = STATE_FAILED;
return;
} // reset when we've reached the end
if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
this.state = STATE_POSSIBLE;
}
this.state = this.process(inputDataClone); // the recognizer has recognized a gesture
// so trigger an event
if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
this.tryEmit(inputDataClone);
}
};
/**
* @private
* return the state of the recognizer
* the actual recognizing happens in this method
* @virtual
* @param {Object} inputData
* @returns {constant} STATE
*/
/* jshint ignore:start */
_proto.process = function process(inputData) {};
/* jshint ignore:end */
/**
* @private
* return the preferred touch-action
* @virtual
* @returns {Array}
*/
_proto.getTouchAction = function getTouchAction() {};
/**
* @private
* called when the gesture isn't allowed to recognize
* like when another is being recognized or it is disabled
* @virtual
*/
_proto.reset = function reset() {};
return Recognizer;
}();
var defaults = {
/**
* @private
* set if DOM events are being triggered.
* But this is slower and unused by simple implementations, so disabled by default.
* @type {Boolean}
* @default false
*/
domEvents: false,
/**
* @private
* The value for the touchAction property/fallback.
* When set to `compute` it will magically set the correct value based on the added recognizers.
* @type {String}
* @default compute
*/
touchAction: TOUCH_ACTION_COMPUTE,
/**
* @private
* @type {Boolean}
* @default true
*/
enable: true,
/**
* @private
* EXPERIMENTAL FEATURE -- can be removed/changed
* Change the parent input target element.
* If Null, then it is being set the to main element.
* @type {Null|EventTarget}
* @default null
*/
inputTarget: null,
/**
* @private
* force an input class
* @type {Null|Function}
* @default null
*/
inputClass: null,
/**
* @private
* Default recognizer setup when calling `Hammer()`
* When creating a new Manager these will be skipped.
* @type {Array}
*/
preset: [],
/**
* @private
* Some CSS properties can be used to improve the working of Hammer.
* Add them to this method and they will be set when creating a new Manager.
* @namespace
*/
cssProps: {
/**
* @private
* Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
* @type {String}
* @default 'none'
*/
userSelect: "none",
/**
* @private
* Disable the Windows Phone grippers when pressing an element.
* @type {String}
* @default 'none'
*/
touchSelect: "none",
/**
* @private
* Disables the default callout shown when you touch and hold a touch target.
* On iOS, when you touch and hold a touch target such as a link, Safari displays
* a callout containing information about the link. This property allows you to disable that callout.
* @type {String}
* @default 'none'
*/
touchCallout: "none",
/**
* @private
* Specifies whether zooming is enabled. Used by IE10>
* @type {String}
* @default 'none'
*/
contentZooming: "none",
/**
* @private
* Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
* @type {String}
* @default 'none'
*/
userDrag: "none",
/**
* @private
* Overrides the highlight color shown when the user taps a link or a JavaScript
* clickable element in iOS. This property obeys the alpha value, if specified.
* @type {String}
* @default 'rgba(0,0,0,0)'
*/
tapHighlightColor: "rgba(0,0,0,0)"
}
};
var STOP = 1;
var FORCED_STOP = 2;
/**
* @private
* add/remove the css properties as defined in manager.options.cssProps
* @param {Manager} manager
* @param {Boolean} add
*/
function toggleCssProps(manager, add) {
var element = manager.element;
if (!element.style) {
return;
}
var prop;
each(manager.options.cssProps, function (value, name) {
prop = prefixed(element.style, name);
if (add) {
manager.oldCssProps[prop] = element.style[prop];
element.style[prop] = value;
} else {
element.style[prop] = manager.oldCssProps[prop] || "";
}
});
if (!add) {
manager.oldCssProps = {};
}
}
/**
* @private
* trigger dom event
* @param {String} event
* @param {Object} data
*/
function triggerDomEvent(event, data) {
var gestureEvent = document.createEvent("Event");
gestureEvent.initEvent(event, true, true);
gestureEvent.gesture = data;
data.target.dispatchEvent(gestureEvent);
}
/**
* @private
* Manager
* @param {HTMLElement} element
* @param {Object} [options]
* @constructor
*/
var Manager =
/*#__PURE__*/
function () {
function Manager(element, options) {
var _this = this;
this.options = assign$1({}, defaults, options || {});
this.options.inputTarget = this.options.inputTarget || element;
this.handlers = {};
this.session = {};
this.recognizers = [];
this.oldCssProps = {};
this.element = element;
this.input = createInputInstance(this);
this.touchAction = new TouchAction(this, this.options.touchAction);
toggleCssProps(this, true);
each(this.options.recognizers, function (item) {
var recognizer = _this.add(new item[0](item[1]));
item[2] && recognizer.recognizeWith(item[2]);
item[3] && recognizer.requireFailure(item[3]);
}, this);
}
/**
* @private
* set options
* @param {Object} options
* @returns {Manager}
*/
var _proto = Manager.prototype;
_proto.set = function set(options) {
assign$1(this.options, options); // Options that need a little more setup
if (options.touchAction) {
this.touchAction.update();
}
if (options.inputTarget) {
// Clean up existing event listeners and reinitialize
this.input.destroy();
this.input.target = options.inputTarget;
this.input.init();
}
return this;
};
/**
* @private
* stop recognizing for this session.
* This session will be discarded, when a new [input]start event is fired.
* When forced, the recognizer cycle is stopped immediately.
* @param {Boolean} [force]
*/
_proto.stop = function stop(force) {
this.session.stopped = force ? FORCED_STOP : STOP;
};
/**
* @private
* run the recognizers!
* called by the inputHandler function on every movement of the pointers (touches)
* it walks through all the recognizers and tries to detect the gesture that is being made
* @param {Object} inputData
*/
_proto.recognize = function recognize(inputData) {
var session = this.session;
if (session.stopped) {
return;
} // run the touch-action polyfill
this.touchAction.preventDefaults(inputData);
var recognizer;
var recognizers = this.recognizers; // this holds the recognizer that is being recognized.
// so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
// if no recognizer is detecting a thing, it is set to `null`
var curRecognizer = session.curRecognizer; // reset when the last recognizer is recognized
// or when we're in a new session
if (!curRecognizer || curRecognizer && curRecognizer.state & STATE_RECOGNIZED) {
session.curRecognizer = null;
curRecognizer = null;
}
var i = 0;
while (i < recognizers.length) {
recognizer = recognizers[i]; // find out if we are allowed try to recognize the input for this one.
// 1. allow if the session is NOT forced stopped (see the .stop() method)
// 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
// that is being recognized.
// 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
// this can be setup with the `recognizeWith()` method on the recognizer.
if (session.stopped !== FORCED_STOP && ( // 1
!curRecognizer || recognizer === curRecognizer || // 2
recognizer.canRecognizeWith(curRecognizer))) {
// 3
recognizer.recognize(inputData);
} else {
recognizer.reset();
} // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
// current active recognizer. but only if we don't already have an active recognizer
if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {
session.curRecognizer = recognizer;
curRecognizer = recognizer;
}
i++;
}
};
/**
* @private
* get a recognizer by its event name.
* @param {Recognizer|String} recognizer
* @returns {Recognizer|Null}
*/
_proto.get = function get(recognizer) {
if (recognizer instanceof Recognizer) {
return recognizer;
}
var recognizers = this.recognizers;
for (var i = 0; i < recognizers.length; i++) {
if (recognizers[i].options.event === recognizer) {
return recognizers[i];
}
}
return null;
};
/**
* @private add a recognizer to the manager
* existing recognizers with the same event name will be removed
* @param {Recognizer} recognizer
* @returns {Recognizer|Manager}
*/
_proto.add = function add(recognizer) {
if (invokeArrayArg(recognizer, "add", this)) {
return this;
} // remove existing
var existing = this.get(recognizer.options.event);
if (existing) {
this.remove(existing);
}
this.recognizers.push(recognizer);
recognizer.manager = this;
this.touchAction.update();
return recognizer;
};
/**
* @private
* remove a recognizer by name or instance
* @param {Recognizer|String} recognizer
* @returns {Manager}
*/
_proto.remove = function remove(recognizer) {
if (invokeArrayArg(recognizer, "remove", this)) {
return this;
}
var targetRecognizer = this.get(recognizer); // let's make sure this recognizer exists
if (recognizer) {
var recognizers = this.recognizers;
var index = inArray(recognizers, targetRecognizer);
if (index !== -1) {
recognizers.splice(index, 1);
this.touchAction.update();
}
}
return this;
};
/**
* @private
* bind event
* @param {String} events
* @param {Function} handler
* @returns {EventEmitter} this
*/
_proto.on = function on(events, handler) {
if (events === undefined || handler === undefined) {
return this;
}
var handlers = this.handlers;
each(splitStr(events), function (event) {
handlers[event] = handlers[event] || [];
handlers[event].push(handler);
});
return this;
};
/**
* @private unbind event, leave emit blank to remove all handlers
* @param {String} events
* @param {Function} [handler]
* @returns {EventEmitter} this
*/
_proto.off = function off(events, handler) {
if (events === undefined) {
return this;
}
var handlers = this.handlers;
each(splitStr(events), function (event) {
if (!handler) {
delete handlers[event];
} else {
handlers[event] && handlers[event].splice(inArray(handlers[event], handler), 1);
}
});
return this;
};
/**
* @private emit event to the listeners
* @param {String} event
* @param {Object} data
*/
_proto.emit = function emit(event, data) {
// we also want to trigger dom events
if (this.options.domEvents) {
triggerDomEvent(event, data);
} // no handlers, so skip it all
var handlers = this.handlers[event] && this.handlers[event].slice();
if (!handlers || !handlers.length) {
return;
}
data.type = event;
data.preventDefault = function () {
data.srcEvent.preventDefault();
};
var i = 0;
while (i < handlers.length) {
handlers[i](data);
i++;
}
};
/**
* @private
* destroy the manager and unbinds all events
* it doesn't unbind dom events, that is the user own responsibility
*/
_proto.destroy = function destroy() {
this.element && toggleCssProps(this, false);
this.handlers = {};
this.session = {};
this.input.destroy();
this.element = null;
};
return Manager;
}();
/**
* @private
* This recognizer is just used as a base for the simple attribute recognizers.
* @constructor
* @extends Recognizer
*/
var AttrRecognizer =
/*#__PURE__*/
function (_Recognizer) {
_inheritsLoose(AttrRecognizer, _Recognizer);
function AttrRecognizer(options) {
if (options === void 0) {
options = {};
}
return _Recognizer.call(this, _extends({
pointers: 1
}, options)) || this;
}
/**
* @private
* Used to check if it the recognizer receives valid input, like input.distance > 10.
* @memberof AttrRecognizer
* @param {Object} input
* @returns {Boolean} recognized
*/
var _proto = AttrRecognizer.prototype;
_proto.attrTest = function attrTest(input) {
var optionPointers = this.options.pointers;
return optionPointers === 0 || input.pointers.length === optionPointers;
};
/**
* @private
* Process the input and return the state for the recognizer
* @memberof AttrRecognizer
* @param {Object} input
* @returns {*} State
*/
_proto.process = function process(input) {
var state = this.state;
var eventType = input.eventType;
var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
var isValid = this.attrTest(input); // on cancel input and we've recognized before, return STATE_CANCELLED
if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {
return state | STATE_CANCELLED;
} else if (isRecognized || isValid) {
if (eventType & INPUT_END) {
return state | STATE_ENDED;
} else if (!(state & STATE_BEGAN)) {
return STATE_BEGAN;
}
return state | STATE_CHANGED;
}
return STATE_FAILED;
};
return AttrRecognizer;
}(Recognizer);
/**
* @private
* direction cons to string
* @param {constant} direction
* @returns {String}
*/
function directionStr(direction) {
if (direction === DIRECTION_DOWN) {
return 'down';
} else if (direction === DIRECTION_UP) {
return 'up';
} else if (direction === DIRECTION_LEFT) {
return 'left';
} else if (direction === DIRECTION_RIGHT) {
return 'right';
}
return '';
}
/**
* @private
* Pan
* Recognized when the pointer is down and moved in the allowed direction.
* @constructor
* @extends AttrRecognizer
*/
var PanRecognizer =
/*#__PURE__*/
function (_AttrRecognizer) {
_inheritsLoose(PanRecognizer, _AttrRecognizer);
function PanRecognizer(options) {
var _this;
if (options === void 0) {
options = {};
}
_this = _AttrRecognizer.call(this, _extends({
event: 'pan',
threshold: 10,
pointers: 1,
direction: DIRECTION_ALL
}, options)) || this;
_this.pX = null;
_this.pY = null;
return _this;
}
var _proto = PanRecognizer.prototype;
_proto.getTouchAction = function getTouchAction() {
var direction = this.options.direction;
var actions = [];
if (direction & DIRECTION_HORIZONTAL) {
actions.push(TOUCH_ACTION_PAN_Y);
}
if (direction & DIRECTION_VERTICAL) {
actions.push(TOUCH_ACTION_PAN_X);
}
return actions;
};
_proto.directionTest = function directionTest(input) {
var options = this.options;
var hasMoved = true;
var distance = input.distance;
var direction = input.direction;
var x = input.deltaX;
var y = input.deltaY; // lock to axis?
if (!(direction & options.direction)) {
if (options.direction & DIRECTION_HORIZONTAL) {
direction = x === 0 ? DIRECTION_NONE : x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
hasMoved = x !== this.pX;
distance = Math.abs(input.deltaX);
} else {
direction = y === 0 ? DIRECTION_NONE : y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
hasMoved = y !== this.pY;
distance = Math.abs(input.deltaY);
}
}
input.direction = direction;
return hasMoved && distance > options.threshold && direction & options.direction;
};
_proto.attrTest = function attrTest(input) {
return AttrRecognizer.prototype.attrTest.call(this, input) && ( // replace with a super call
this.state & STATE_BEGAN || !(this.state & STATE_BEGAN) && this.directionTest(input));
};
_proto.emit = function emit(input) {
this.pX = input.deltaX;
this.pY = input.deltaY;
var direction = directionStr(input.direction);
if (direction) {
input.additionalEvent = this.options.event + direction;
}
_AttrRecognizer.prototype.emit.call(this, input);
};
return PanRecognizer;
}(AttrRecognizer);
/*
Copyright (c) 2017 NAVER Corp.
@egjs/axes project is licensed under the MIT license
@egjs/axes JavaScript library
https://github.com/naver/egjs-axes
@version 2.5.13
*/
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics$1 = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
};
function __extends$1(d, b) {
extendStatics$1(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
/* eslint-disable no-new-func, no-nested-ternary */
var win$1;
if (typeof window === "undefined") {
// window is undefined in node.js
win$1 = {};
} else {
win$1 = window;
} // export const DIRECTION_NONE = 1;
var FIXED_DIGIT = 100000;
var TRANSFORM = function () {
if (typeof document === "undefined") {
return "";
}
var bodyStyle = (document.head || document.getElementsByTagName("head")[0]).style;
var target = ["transform", "webkitTransform", "msTransform", "mozTransform"];
for (var i = 0, len = target.length; i < len; i++) {
if (target[i] in bodyStyle) {
return target[i];
}
}
return "";
}();
function toArray$1(nodes) {
// const el = Array.prototype.slice.call(nodes);
// for IE8
var el = [];
for (var i = 0, len = nodes.length; i < len; i++) {
el.push(nodes[i]);
}
return el;
}
function $(param, multi) {
if (multi === void 0) {
multi = false;
}
var el;
if (typeof param === "string") {
// String (HTML, Selector)
// check if string is HTML tag format
var match = param.match(/^<([a-z]+)\s*([^>]*)>/); // creating element
if (match) {
// HTML
var dummy = document.createElement("div");
dummy.innerHTML = param;
el = toArray$1(dummy.childNodes);
} else {
// Selector
el = toArray$1(document.querySelectorAll(param));
}
if (!multi) {
el = el.length >= 1 ? el[0] : undefined;
}
} else if (param === win$1) {
// window
el = param;
} else if (param.nodeName && (param.nodeType === 1 || param.nodeType === 9)) {
// HTMLElement, Document
el = param;
} else if ("jQuery" in win$1 && param instanceof jQuery || param.constructor.prototype.jquery) {
// jQuery
el = multi ? param.toArray() : param.get(0);
} else if (Array.isArray(param)) {
el = param.map(function (v) {
return $(v);
});
if (!multi) {
el = el.length >= 1 ? el[0] : undefined;
}
}
return el;
}
var raf = win$1.requestAnimationFrame || win$1.webkitRequestAnimationFrame;
var caf = win$1.cancelAnimationFrame || win$1.webkitCancelAnimationFrame;
if (raf && !caf) {
var keyInfo_1 = {};
var oldraf_1 = raf;
raf = function (callback) {
function wrapCallback(timestamp) {
if (keyInfo_1[key]) {
callback(timestamp);
}
}
var key = oldraf_1(wrapCallback);
keyInfo_1[key] = true;
return key;
};
caf = function (key) {
delete keyInfo_1[key];
};
} else if (!(raf && caf)) {
raf = function (callback) {
return win$1.setTimeout(function () {
callback(win$1.performance && win$1.performance.now && win$1.performance.now() || new Date().getTime());
}, 16);
};
caf = win$1.clearTimeout;
}
/**
* A polyfill for the window.requestAnimationFrame() method.
* @see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
* @private
*/
function requestAnimationFrame(fp) {
return raf(fp);
}
/**
* A polyfill for the window.cancelAnimationFrame() method. It cancels an animation executed through a call to the requestAnimationFrame() method.
* @param {Number} key − The ID value returned through a call to the requestAnimationFrame() method. <ko>requestAnimationFrame() 메서드가 반환한 아이디 값</ko>
* @see https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame
* @private
*/
function cancelAnimationFrame(key) {
caf(key);
}
function mapToFixed(obj) {
return map(obj, function (value) {
return toFixed(value);
});
}
function map(obj, callback) {
var tranformed = {};
for (var k in obj) {
k && (tranformed[k] = callback(obj[k], k));
}
return tranformed;
}
function filter(obj, callback) {
var filtered = {};
for (var k in obj) {
k && callback(obj[k], k) && (filtered[k] = obj[k]);
}
return filtered;
}
function every(obj, callback) {
for (var k in obj) {
if (k && !callback(obj[k], k)) {
return false;
}
}
return true;
}
function equal(target, base) {
return every(target, function (v, k) {
return v === base[k];
});
}
function toFixed(num) {
return Math.round(num * FIXED_DIGIT) / FIXED_DIGIT;
}
function getInsidePosition(destPos, range, circular, bounce) {
var toDestPos = destPos;
var targetRange = [circular[0] ? range[0] : bounce ? range[0] - bounce[0] : range[0], circular[1] ? range[1] : bounce ? range[1] + bounce[1] : range[1]];
toDestPos = Math.max(targetRange[0], toDestPos);
toDestPos = Math.min(targetRange[1], toDestPos);
return +toFixed(toDestPos);
} // determine outside
function isOutside(pos, range) {
return pos < range[0] || pos > range[1];
}
function getDuration(distance, deceleration) {
var duration = Math.sqrt(distance / deceleration * 2); // when duration is under 100, then value is zero
return duration < 100 ? 0 : duration;
}
function isCircularable(destPos, range, circular) {
return circular[1] && destPos > range[1] || circular[0] && destPos < range[0];
}
function getCirculatedPos(pos, range, circular, isAccurate) {
var toPos = pos;
var min = range[0];
var max = range[1];
var length = max - min;
if (circular[1] && pos > max) {
// right
toPos = (toPos - max) % length + min;
}
if (circular[0] && pos < min) {
// left
toPos = (toPos - min) % length + max;
}
return isAccurate ? toPos : +toFixed(toPos);
}
function minMax(value, min, max) {
return Math.max(Math.min(value, max), min);
}
var AnimationManager =
/*#__PURE__*/
function () {
function AnimationManager(_a) {
var options = _a.options,
itm = _a.itm,
em = _a.em,
axm = _a.axm;
this.options = options;
this.itm = itm;
this.em = em;
this.axm = axm;
this.animationEnd = this.animationEnd.bind(this);
}
var __proto = AnimationManager.prototype;
__proto.getDuration = function (depaPos, destPos, wishDuration) {
var _this = this;
var duration;
if (typeof wishDuration !== "undefined") {
duration = wishDuration;
} else {
var durations_1 = map(destPos, function (v, k) {
return getDuration(Math.abs(v - depaPos[k]), _this.options.deceleration);
});
duration = Object.keys(durations_1).reduce(function (max, v) {
return Math.max(max, durations_1[v]);
}, -Infinity);
}
return minMax(duration, this.options.minimumDuration, this.options.maximumDuration);
};
__proto.createAnimationParam = function (pos, duration, option) {
var depaPos = this.axm.get();
var destPos = pos;
var inputEvent = option && option.event || null;
return {
depaPos: depaPos,
destPos: destPos,
duration: minMax(duration, this.options.minimumDuration, this.options.maximumDuration),
delta: this.axm.getDelta(depaPos, destPos),
inputEvent: inputEvent,
input: option && option.input || null,
isTrusted: !!inputEvent,
done: this.animationEnd
};
};
__proto.grab = function (axes, option) {
if (this._animateParam && axes.length) {
var orgPos_1 = this.axm.get(axes);
var pos = this.axm.map(orgPos_1, function (v, opt) {
return getCirculatedPos(v, opt.range, opt.circular, false);
});
if (!every(pos, function (v, k) {
return orgPos_1[k] === v;
})) {
this.em.triggerChange(pos, false, orgPos_1, option, !!option);
}
this._animateParam = null;
this._raf && cancelAnimationFrame(this._raf);
this._raf = null;
this.em.triggerAnimationEnd(!!(option && option.event));
}
};
__proto.getEventInfo = function () {
if (this._animateParam && this._animateParam.input && this._animateParam.inputEvent) {
return {
input: this._animateParam.input,
event: this._animateParam.inputEvent
};
} else {
return null;
}
};
__proto.restore = function (option) {
var pos = this.axm.get();
var destPos = this.axm.map(pos, function (v, opt) {
return Math.min(opt.range[1], Math.max(opt.range[0], v));
});
this.animateTo(destPos, this.getDuration(pos, destPos), option);
};
__proto.animationEnd = function () {
var beforeParam = this.getEventInfo();
this._animateParam = null; // for Circular
var circularTargets = this.axm.filter(this.axm.get(), function (v, opt) {
return isCircularable(v, opt.range, opt.circular);
});
Object.keys(circularTargets).length > 0 && this.setTo(this.axm.map(circularTargets, function (v, opt) {
return getCirculatedPos(v, opt.range, opt.circular, false);
}));
this.itm.setInterrupt(false);
this.em.triggerAnimationEnd(!!beforeParam);
if (this.axm.isOutside()) {
this.restore(beforeParam);
} else {
this.finish(!!beforeParam);
}
};
__proto.finish = function (isTrusted) {
this._animateParam = null;
this.itm.setInterrupt(false);
this.em.triggerFinish(isTrusted);
};
__proto.animateLoop = function (param, complete) {
if (param.duration) {
this._animateParam = __assign({}, param);
var info_1 = this._animateParam;
var self_1 = this;
var prevPos_1 = info_1.depaPos;
var prevEasingPer_1 = 0;
var directions_1 = map(prevPos_1, function (value, key) {
return value <= info_1.destPos[key] ? 1 : -1;
});
var prevTime_1 = new Date().getTime();
info_1.startTime = prevTime_1;
(function loop() {
self_1._raf = null;
var currentTime = new Date().getTime();
var easingPer = self_1.easing((currentTime - info_1.startTime) / param.duration);
var toPos = map(prevPos_1, function (pos, key) {
return pos + info_1.delta[key] * (easingPer - prevEasingPer_1);
});
toPos = self_1.axm.map(toPos, function (pos, options, key) {
// fix absolute position to relative position
// fix the bouncing phenomenon by changing the range.
var nextPos = getCirculatedPos(pos, options.range, options.circular, true);
if (pos !== nextPos) {
// circular
param.destPos[key] += -directions_1[key] * (options.range[1] - options.range[0]);
prevPos_1[key] += -directions_1[key] * (options.range[1] - options.range[0]);
}
return nextPos;
});
var isCanceled = !self_1.em.triggerChange(toPos, false, mapToFixed(prevPos_1));
prevPos_1 = toPos;
prevTime_1 = currentTime;
prevEasingPer_1 = easingPer;
if (easingPer >= 1) {
var destPos = param.destPos;
if (!equal(destPos, self_1.axm.get(Object.keys(destPos)))) {
self_1.em.triggerChange(destPos, true, mapToFixed(prevPos_1));
}
complete();
return;
} else if (isCanceled) {
self_1.finish(false);
} else {
// animationEnd
self_1._raf = requestAnimationFrame(loop);
}
})();
} else {
this.em.triggerChange(param.destPos, true);
complete();
}
};
__proto.getUserControll = function (param) {
var userWish = param.setTo();
userWish.destPos = this.axm.get(userWish.destPos);
userWish.duration = minMax(userWish.duration, this.options.minimumDuration, this.options.maximumDuration);
return userWish;
};
__proto.animateTo = function (destPos, duration, option) {
var _this = this;
var param = this.createAnimationParam(destPos, duration, option);
var depaPos = __assign({}, param.depaPos);
var retTrigger = this.em.triggerAnimationStart(param); // to control
var userWish = this.getUserControll(param); // You can't stop the 'animationStart' event when 'circular' is true.
if (!retTrigger && this.axm.every(userWish.destPos, function (v, opt) {
return isCircularable(v, opt.range, opt.circular);
})) {
console.warn("You can't stop the 'animation' event when 'circular' is true.");
}
if (retTrigger && !equal(userWish.destPos, depaPos)) {
var inputEvent = option && option.event || null;
this.animateLoop({
depaPos: depaPos,
destPos: userWish.destPos,
duration: userWish.duration,
delta: this.axm.getDelta(depaPos, userWish.destPos),
isTrusted: !!inputEvent,
inputEvent: inputEvent,
input: option && option.input || null
}, function () {
return _this.animationEnd();
});
}
};
__proto.easing = function (p) {
return p > 1 ? 1 : this.options.easing(p);
};
__proto.setTo = function (pos, duration) {
if (duration === void 0) {
duration = 0;
}
var axes = Object.keys(pos);
this.grab(axes);
var orgPos = this.axm.get(axes);
if (equal(pos, orgPos)) {
return this;
}
this.itm.setInterrupt(true);
var movedPos = filter(pos, function (v, k) {
return orgPos[k] !== v;
});
if (!Object.keys(movedPos).length) {
return this;
}
movedPos = this.axm.map(movedPos, function (v, opt) {
var range = opt.range,
circular = opt.circular;
if (circular && (circular[0] || circular[1])) {
return v;
} else {
return getInsidePosition(v, range, circular);
}
});
if (equal(movedPos, orgPos)) {
return this;
}
if (duration > 0) {
this.animateTo(movedPos, duration);
} else {
this.em.triggerChange(movedPos);
this.finish(false);
}
return this;
};
__proto.setBy = function (pos, duration) {
if (duration === void 0) {
duration = 0;
}
return this.setTo(map(this.axm.get(Object.keys(pos)), function (v, k) {
return v + pos[k];
}), duration);
};
return AnimationManager;
}();
var EventManager =
/*#__PURE__*/
function () {
function EventManager(axes) {
this.axes = axes;
}
/**
* This event is fired when a user holds an element on the screen of the device.
* @ko 사용자가 기기의 화면에 손을 대고 있을 때 발생하는 이벤트
* @name eg.Axes#hold
* @event
* @type {object} The object of data to be sent when the event is fired<ko>이벤트가 발생할 때 전달되는 데이터 객체</ko>
* @property {Object.<string, number>} pos coordinate <ko>좌표 정보</ko>
* @property {Object} input The instance of inputType where the event occurred<ko>이벤트가 발생한 inputType 인스턴스</ko>
* @property {Object} inputEvent The event object received from inputType <ko>inputType으로 부터 받은 이벤트 객체</ko>
* @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko>
*
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* }).on("hold", function(event) {
* // event.pos
* // event.input
* // event.inputEvent
* // isTrusted
* });
*/
var __proto = EventManager.prototype;
__proto.triggerHold = function (pos, option) {
this.axes.trigger("hold", {
pos: pos,
input: option.input || null,
inputEvent: option.event || null,
isTrusted: true
});
};
/**
* Specifies the coordinates to move after the 'change' event. It works when the holding value of the change event is true.
* @ko 'change' 이벤트 이후 이동할 좌표를 지정한다. change이벤트의 holding 값이 true일 경우에 동작한다
* @name set
* @function
* @param {Object.<string, number>} pos The coordinate to move to <ko>이동할 좌표</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* }).on("change", function(event) {
* event.holding && event.set({x: 10});
* });
*/
/** Specifies the animation coordinates to move after the 'release' or 'animationStart' events.
* @ko 'release' 또는 'animationStart' 이벤트 이후 이동할 좌표를 지정한다.
* @name setTo
* @function
* @param {Object.<string, number>} pos The coordinate to move to <ko>이동할 좌표</ko>
* @param {Number} [duration] Duration of the animation (unit: ms) <ko>애니메이션 진행 시간(단위: ms)</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* }).on("animationStart", function(event) {
* event.setTo({x: 10}, 2000);
* });
*/
/**
* This event is fired when a user release an element on the screen of the device.
* @ko 사용자가 기기의 화면에서 손을 뗐을 때 발생하는 이벤트
* @name eg.Axes#release
* @event
* @type {object} The object of data to be sent when the event is fired<ko>이벤트가 발생할 때 전달되는 데이터 객체</ko>
* @property {Object.<string, number>} depaPos The coordinates when releasing an element<ko>손을 뗐을 때의 좌표 </ko>
* @property {Object.<string, number>} destPos The coordinates to move to after releasing an element<ko>손을 뗀 뒤에 이동할 좌표</ko>
* @property {Object.<string, number>} delta The movement variation of coordinate <ko>좌표의 변화량</ko>
* @property {Object} inputEvent The event object received from inputType <ko>inputType으로 부터 받은 이벤트 객체</ko>
* @property {Object} input The instance of inputType where the event occurred<ko>이벤트가 발생한 inputType 인스턴스</ko>
* @property {setTo} setTo Specifies the animation coordinates to move after the event <ko>이벤트 이후 이동할 애니메이션 좌표를 지정한다</ko>
* @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko>
*
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* }).on("release", function(event) {
* // event.depaPos
* // event.destPos
* // event.delta
* // event.input
* // event.inputEvent
* // event.setTo
* // event.isTrusted
*
* // if you want to change the animation coordinates to move after the 'release' event.
* event.setTo({x: 10}, 2000);
* });
*/
__proto.triggerRelease = function (param) {
param.setTo = this.createUserControll(param.destPos, param.duration);
this.axes.trigger("release", param);
};
/**
* This event is fired when coordinate changes.
* @ko 좌표가 변경됐을 때 발생하는 이벤트
* @name eg.Axes#change
* @event
* @type {object} The object of data to be sent when the event is fired <ko>이벤트가 발생할 때 전달되는 데이터 객체</ko>
* @property {Object.<string, number>} pos The coordinate <ko>좌표</ko>
* @property {Object.<string, number>} delta The movement variation of coordinate <ko>좌표의 변화량</ko>
* @property {Boolean} holding Indicates whether a user holds an element on the screen of the device.<ko>사용자가 기기의 화면을 누르고 있는지 여부</ko>
* @property {Object} input The instance of inputType where the event occurred. If the value is changed by animation, it returns 'null'.<ko>이벤트가 발생한 inputType 인스턴스. 애니메이션에 의해 값이 변경될 경우에는 'null'을 반환한다.</ko>
* @property {Object} inputEvent The event object received from inputType. If the value is changed by animation, it returns 'null'.<ko>inputType으로 부터 받은 이벤트 객체. 애니메이션에 의해 값이 변경될 경우에는 'null'을 반환한다.</ko>
* @property {set} set Specifies the coordinates to move after the event. It works when the holding value is true <ko>이벤트 이후 이동할 좌표를 지정한다. holding 값이 true일 경우에 동작한다.</ko>
* @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko>
*
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* }).on("change", function(event) {
* // event.pos
* // event.delta
* // event.input
* // event.inputEvent
* // event.holding
* // event.set
* // event.isTrusted
*
* // if you want to change the coordinates to move after the 'change' event.
* // it works when the holding value of the change event is true.
* event.holding && event.set({x: 10});
* });
*/
__proto.triggerChange = function (pos, isAccurate, depaPos, option, holding) {
if (holding === void 0) {
holding = false;
}
var am = this.am;
var axm = am.axm;
var eventInfo = am.getEventInfo();
var moveTo = axm.moveTo(pos, isAccurate, depaPos);
var inputEvent = option && option.event || eventInfo && eventInfo.event || null;
var param = {
pos: moveTo.pos,
delta: moveTo.delta,
holding: holding,
inputEvent: inputEvent,
isTrusted: !!inputEvent,
input: option && option.input || eventInfo && eventInfo.input || null,
set: inputEvent ? this.createUserControll(moveTo.pos) : function () {}
};
var result = this.axes.trigger("change", param);
inputEvent && axm.set(param.set()["destPos"]);
return result;
};
/**
* This event is fired when animation starts.
* @ko 에니메이션이 시작할 때 발생한다.
* @name eg.Axes#animationStart
* @event
* @type {object} The object of data to be sent when the event is fired<ko>이벤트가 발생할 때 전달되는 데이터 객체</ko>
* @property {Object.<string, number>} depaPos The coordinates when animation starts<ko>애니메이션이 시작 되었을 때의 좌표 </ko>
* @property {Object.<string, number>} destPos The coordinates to move to. If you change this value, you can run the animation<ko>이동할 좌표. 이값을 변경하여 애니메이션을 동작시킬수 있다</ko>
* @property {Object.<string, number>} delta The movement variation of coordinate <ko>좌표의 변화량</ko>
* @property {Number} duration Duration of the animation (unit: ms). If you change this value, you can control the animation duration time.<ko>애니메이션 진행 시간(단위: ms). 이값을 변경하여 애니메이션의 이동시간을 조절할 수 있다.</ko>
* @property {Object} input The instance of inputType where the event occurred. If the value is changed by animation, it returns 'null'.<ko>이벤트가 발생한 inputType 인스턴스. 애니메이션에 의해 값이 변경될 경우에는 'null'을 반환한다.</ko>
* @property {Object} inputEvent The event object received from inputType <ko>inputType으로 부터 받은 이벤트 객체</ko>
* @property {setTo} setTo Specifies the animation coordinates to move after the event <ko>이벤트 이후 이동할 애니메이션 좌표를 지정한다</ko>
* @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko>
*
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* }).on("release", function(event) {
* // event.depaPos
* // event.destPos
* // event.delta
* // event.input
* // event.inputEvent
* // event.setTo
* // event.isTrusted
*
* // if you want to change the animation coordinates to move after the 'animationStart' event.
* event.setTo({x: 10}, 2000);
* });
*/
__proto.triggerAnimationStart = function (param) {
param.setTo = this.createUserControll(param.destPos, param.duration);
return this.axes.trigger("animationStart", param);
};
/**
* This event is fired when animation ends.
* @ko 에니메이션이 끝났을 때 발생한다.
* @name eg.Axes#animationEnd
* @event
* @type {object} The object of data to be sent when the event is fired<ko>이벤트가 발생할 때 전달되는 데이터 객체</ko>
* @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko>
*
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* }).on("animationEnd", function(event) {
* // event.isTrusted
* });
*/
__proto.triggerAnimationEnd = function (isTrusted) {
if (isTrusted === void 0) {
isTrusted = false;
}
this.axes.trigger("animationEnd", {
isTrusted: isTrusted
});
};
/**
* This event is fired when all actions have been completed.
* @ko 에니메이션이 끝났을 때 발생한다.
* @name eg.Axes#finish
* @event
* @type {object} The object of data to be sent when the event is fired<ko>이벤트가 발생할 때 전달되는 데이터 객체</ko>
* @property {Boolean} isTrusted Returns true if an event was generated by the user action, or false if it was caused by a script or API call <ko>사용자의 액션에 의해 이벤트가 발생하였으면 true, 스크립트나 API호출에 의해 발생하였을 경우에는 false를 반환한다.</ko>
*
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* }).on("finish", function(event) {
* // event.isTrusted
* });
*/
__proto.triggerFinish = function (isTrusted) {
if (isTrusted === void 0) {
isTrusted = false;
}
this.axes.trigger("finish", {
isTrusted: isTrusted
});
};
__proto.createUserControll = function (pos, duration) {
if (duration === void 0) {
duration = 0;
} // to controll
var userControl = {
destPos: __assign({}, pos),
duration: duration
};
return function (toPos, userDuration) {
toPos && (userControl.destPos = __assign({}, toPos));
userDuration !== undefined && (userControl.duration = userDuration);
return userControl;
};
};
__proto.setAnimationManager = function (am) {
this.am = am;
};
__proto.destroy = function () {
this.axes.off();
};
return EventManager;
}();
var InterruptManager =
/*#__PURE__*/
function () {
function InterruptManager(options) {
this.options = options;
this._prevented = false; // check whether the animation event was prevented
}
var __proto = InterruptManager.prototype;
__proto.isInterrupting = function () {
// when interruptable is 'true', return value is always 'true'.
return this.options.interruptable || this._prevented;
};
__proto.isInterrupted = function () {
return !this.options.interruptable && this._prevented;
};
__proto.setInterrupt = function (prevented) {
!this.options.interruptable && (this._prevented = prevented);
};
return InterruptManager;
}();
var AxisManager =
/*#__PURE__*/
function () {
function AxisManager(axis, options) {
var _this = this;
this.axis = axis;
this.options = options;
this._complementOptions();
this._pos = Object.keys(this.axis).reduce(function (acc, v) {
acc[v] = _this.axis[v].range[0];
return acc;
}, {});
}
/**
* set up 'css' expression
* @private
*/
var __proto = AxisManager.prototype;
__proto._complementOptions = function () {
var _this = this;
Object.keys(this.axis).forEach(function (axis) {
_this.axis[axis] = __assign({
range: [0, 100],
bounce: [0, 0],
circular: [false, false]
}, _this.axis[axis]);
["bounce", "circular"].forEach(function (v) {
var axisOption = _this.axis;
var key = axisOption[axis][v];
if (/string|number|boolean/.test(typeof key)) {
axisOption[axis][v] = [key, key];
}
});
});
};
__proto.getDelta = function (depaPos, destPos) {
var fullDepaPos = this.get(depaPos);
return map(this.get(destPos), function (v, k) {
return v - fullDepaPos[k];
});
};
__proto.get = function (axes) {
var _this = this;
if (axes && Array.isArray(axes)) {
return axes.reduce(function (acc, v) {
if (v && v in _this._pos) {
acc[v] = _this._pos[v];
}
return acc;
}, {});
} else {
return __assign({}, this._pos, axes || {});
}
};
__proto.moveTo = function (pos, isAccurate, depaPos) {
if (depaPos === void 0) {
depaPos = this._pos;
}
var delta = map(this._pos, function (v, key) {
return key in pos && key in depaPos ? pos[key] - depaPos[key] : 0;
});
this.set(this.map(pos, function (v, opt) {
return opt ? getCirculatedPos(v, opt.range, opt.circular, isAccurate) : 0;
}));
return {
pos: __assign({}, this._pos),
delta: delta
};
};
__proto.set = function (pos) {
for (var k in pos) {
if (k && k in this._pos) {
this._pos[k] = pos[k];
}
}
};
__proto.every = function (pos, callback) {
var axisOptions = this.axis;
return every(pos, function (value, key) {
return callback(value, axisOptions[key], key);
});
};
__proto.filter = function (pos, callback) {
var axisOptions = this.axis;
return filter(pos, function (value, key) {
return callback(value, axisOptions[key], key);
});
};
__proto.map = function (pos, callback) {
var axisOptions = this.axis;
return map(pos, function (value, key) {
return callback(value, axisOptions[key], key);
});
};
__proto.isOutside = function (axes) {
return !this.every(axes ? this.get(axes) : this._pos, function (v, opt) {
return !isOutside(v, opt.range);
});
};
return AxisManager;
}();
var InputObserver =
/*#__PURE__*/
function () {
function InputObserver(_a) {
var options = _a.options,
itm = _a.itm,
em = _a.em,
axm = _a.axm,
am = _a.am;
this.isOutside = false;
this.moveDistance = null;
this.isStopped = false;
this.options = options;
this.itm = itm;
this.em = em;
this.axm = axm;
this.am = am;
} // when move pointer is held in outside
var __proto = InputObserver.prototype;
__proto.atOutside = function (pos) {
var _this = this;
if (this.isOutside) {
return this.axm.map(pos, function (v, opt) {
var tn = opt.range[0] - opt.bounce[0];
var tx = opt.range[1] + opt.bounce[1];
return v > tx ? tx : v < tn ? tn : v;
});
} else {
// when start pointer is held in inside
// get a initialization slope value to prevent smooth animation.
var initSlope_1 = this.am.easing(0.00001) / 0.00001;
return this.axm.map(pos, function (v, opt) {
var min = opt.range[0];
var max = opt.range[1];
var out = opt.bounce;
var circular = opt.circular;
if (circular && (circular[0] || circular[1])) {
return v;
} else if (v < min) {
// left
return min - _this.am.easing((min - v) / (out[0] * initSlope_1)) * out[0];
} else if (v > max) {
// right
return max + _this.am.easing((v - max) / (out[1] * initSlope_1)) * out[1];
}
return v;
});
}
};
__proto.get = function (input) {
return this.axm.get(input.axes);
};
__proto.hold = function (input, event) {
if (this.itm.isInterrupted() || !input.axes.length) {
return;
}
var changeOption = {
input: input,
event: event
};
this.isStopped = false;
this.itm.setInterrupt(true);
this.am.grab(input.axes, changeOption);
!this.moveDistance && this.em.triggerHold(this.axm.get(), changeOption);
this.isOutside = this.axm.isOutside(input.axes);
this.moveDistance = this.axm.get(input.axes);
};
__proto.change = function (input, event, offset) {
if (this.isStopped || !this.itm.isInterrupting() || this.axm.every(offset, function (v) {
return v === 0;
})) {
return;
}
var depaPos = this.moveDistance || this.axm.get(input.axes);
var destPos; // for outside logic
destPos = map(depaPos, function (v, k) {
return v + (offset[k] || 0);
});
this.moveDistance && (this.moveDistance = destPos); // from outside to inside
if (this.isOutside && this.axm.every(depaPos, function (v, opt) {
return !isOutside(v, opt.range);
})) {
this.isOutside = false;
}
depaPos = this.atOutside(depaPos);
destPos = this.atOutside(destPos);
var isCanceled = !this.em.triggerChange(destPos, false, depaPos, {
input: input,
event: event
}, true);
if (isCanceled) {
this.isStopped = true;
this.moveDistance = null;
this.am.finish(false);
}
};
__proto.release = function (input, event, offset, inputDuration) {
if (this.isStopped || !this.itm.isInterrupting() || !this.moveDistance) {
return;
}
var pos = this.axm.get(input.axes);
var depaPos = this.axm.get();
var destPos = this.axm.get(this.axm.map(offset, function (v, opt, k) {
if (opt.circular && (opt.circular[0] || opt.circular[1])) {
return pos[k] + v;
} else {
return getInsidePosition(pos[k] + v, opt.range, opt.circular, opt.bounce);
}
}));
var duration = this.am.getDuration(destPos, pos, inputDuration);
if (duration === 0) {
destPos = __assign({}, depaPos);
} // prepare params
var param = {
depaPos: depaPos,
destPos: destPos,
duration: duration,
delta: this.axm.getDelta(depaPos, destPos),
inputEvent: event,
input: input,
isTrusted: true
};
this.em.triggerRelease(param);
this.moveDistance = null; // to contol
var userWish = this.am.getUserControll(param);
var isEqual = equal(userWish.destPos, depaPos);
var changeOption = {
input: input,
event: event
};
if (isEqual || userWish.duration === 0) {
!isEqual && this.em.triggerChange(userWish.destPos, false, depaPos, changeOption, true);
this.itm.setInterrupt(false);
if (this.axm.isOutside()) {
this.am.restore(changeOption);
} else {
this.em.triggerFinish(true);
}
} else {
this.am.animateTo(userWish.destPos, userWish.duration, changeOption);
}
};
return InputObserver;
}();
/**
* @typedef {Object} AxisOption The Axis information. The key of the axis specifies the name to use as the logical virtual coordinate system.
* @ko 축 정보. 축의 키는 논리적인 가상 좌표계로 사용할 이름을 지정한다.
* @property {Number[]} [range] The coordinate of range <ko>좌표 범위</ko>
* @property {Number} [range.0=0] The coordinate of the minimum <ko>최소 좌표</ko>
* @property {Number} [range.1=0] The coordinate of the maximum <ko>최대 좌표</ko>
* @property {Number[]} [bounce] The size of bouncing area. The coordinates can exceed the coordinate area as much as the bouncing area based on user action. If the coordinates does not exceed the bouncing area when an element is dragged, the coordinates where bouncing effects are applied are retuned back into the coordinate area<ko>바운스 영역의 크기. 사용자의 동작에 따라 좌표가 좌표 영역을 넘어 바운스 영역의 크기만큼 더 이동할 수 있다. 사용자가 끌어다 놓는 동작을 했을 때 좌표가 바운스 영역에 있으면, 바운스 효과가 적용된 좌표가 다시 좌표 영역 안으로 들어온다</ko>
* @property {Number} [bounce.0=0] The size of coordinate of the minimum area <ko>최소 좌표 바운스 영역의 크기</ko>
* @property {Number} [bounce.1=0] The size of coordinate of the maximum area <ko>최대 좌표 바운스 영역의 크기</ko>
* @property {Boolean[]} [circular] Indicates whether a circular element is available. If it is set to "true" and an element is dragged outside the coordinate area, the element will appear on the other side.<ko>순환 여부. 'true'로 설정한 방향의 좌표 영역 밖으로 엘리먼트가 이동하면 반대 방향에서 엘리먼트가 나타난다</ko>
* @property {Boolean} [circular.0=false] Indicates whether to circulate to the coordinate of the minimum <ko>최소 좌표 방향의 순환 여부</ko>
* @property {Boolean} [circular.1=false] Indicates whether to circulate to the coordinate of the maximum <ko>최대 좌표 방향의 순환 여부</ko>
**/
/**
* @typedef {Object} AxesOption The option object of the eg.Axes module
* @ko eg.Axes 모듈의 옵션 객체
* @property {Function} [easing=easing.easeOutCubic] The easing function to apply to an animation <ko>애니메이션에 적용할 easing 함수</ko>
* @property {Number} [maximumDuration=Infinity] Maximum duration of the animation <ko>가속도에 의해 애니메이션이 동작할 때의 최대 좌표 이동 시간</ko>
* @property {Number} [minimumDuration=0] Minimum duration of the animation <ko>가속도에 의해 애니메이션이 동작할 때의 최소 좌표 이동 시간</ko>
* @property {Number} [deceleration=0.0006] Deceleration of the animation where acceleration is manually enabled by user. A higher value indicates shorter running time. <ko>사용자의 동작으로 가속도가 적용된 애니메이션의 감속도. 값이 높을수록 애니메이션 실행 시간이 짧아진다</ko>
* @property {Boolean} [interruptable=true] Indicates whether an animation is interruptible.<br>- true: It can be paused or stopped by user action or the API.<br>- false: It cannot be paused or stopped by user action or the API while it is running.<ko>진행 중인 애니메이션 중지 가능 여부.<br>- true: 사용자의 동작이나 API로 애니메이션을 중지할 수 있다.<br>- false: 애니메이션이 진행 중일 때는 사용자의 동작이나 API가 적용되지 않는다</ko>
**/
/**
* @class eg.Axes
* @classdesc A module used to change the information of user action entered by various input devices such as touch screen or mouse into the logical virtual coordinates. You can easily create a UI that responds to user actions.
* @ko 터치 입력 장치나 마우스와 같은 다양한 입력 장치를 통해 전달 받은 사용자의 동작을 논리적인 가상 좌표로 변경하는 모듈이다. 사용자 동작에 반응하는 UI를 손쉽게 만들수 있다.
* @extends eg.Component
*
* @param {Object.<string, AxisOption>} axis Axis information managed by eg.Axes. The key of the axis specifies the name to use as the logical virtual coordinate system. <ko>eg.Axes가 관리하는 축 정보. 축의 키는 논리적인 가상 좌표계로 사용할 이름을 지정한다.</ko>
* @param {AxesOption} [options] The option object of the eg.Axes module<ko>eg.Axes 모듈의 옵션 객체</ko>
* @param {Object.<string, number>} [startPos] The coordinates to be moved when creating an instance. not triggering change event.<ko>인스턴스 생성시 이동할 좌표, change 이벤트는 발생하지 않음.</ko>
*
* @support {"ie": "10+", "ch" : "latest", "ff" : "latest", "sf" : "latest", "edge" : "latest", "ios" : "7+", "an" : "2.3+ (except 3.x)"}
* @example
*
* // 1. Initialize eg.Axes
* const axes = new eg.Axes({
* something1: {
* range: [0, 150],
* bounce: 50
* },
* something2: {
* range: [0, 200],
* bounce: 100
* },
* somethingN: {
* range: [1, 10],
* }
* }, {
* deceleration : 0.0024
* });
*
* // 2. attach event handler
* axes.on({
* "hold" : function(evt) {
* },
* "release" : function(evt) {
* },
* "animationStart" : function(evt) {
* },
* "animationEnd" : function(evt) {
* },
* "change" : function(evt) {
* }
* });
*
* // 3. Initialize inputTypes
* const panInputArea = new eg.Axes.PanInput("#area", {
* scale: [0.5, 1]
* });
* const panInputHmove = new eg.Axes.PanInput("#hmove");
* const panInputVmove = new eg.Axes.PanInput("#vmove");
* const pinchInputArea = new eg.Axes.PinchInput("#area", {
* scale: 1.5
* });
*
* // 4. Connect eg.Axes and InputTypes
* // [PanInput] When the mouse or touchscreen is down and moved.
* // Connect the 'something2' axis to the mouse or touchscreen x position and
* // connect the 'somethingN' axis to the mouse or touchscreen y position.
* axes.connect(["something2", "somethingN"], panInputArea); // or axes.connect("something2 somethingN", panInputArea);
*
* // Connect only one 'something1' axis to the mouse or touchscreen x position.
* axes.connect(["something1"], panInputHmove); // or axes.connect("something1", panInputHmove);
*
* // Connect only one 'something2' axis to the mouse or touchscreen y position.
* axes.connect(["", "something2"], panInputVmove); // or axes.connect(" something2", panInputVmove);
*
* // [PinchInput] Connect 'something2' axis when two pointers are moving toward (zoom-in) or away from each other (zoom-out).
* axes.connect("something2", pinchInputArea);
*/
var Axes =
/*#__PURE__*/
function (_super) {
__extends$1(Axes, _super);
function Axes(axis, options, startPos) {
if (axis === void 0) {
axis = {};
}
if (options === void 0) {
options = {};
}
var _this = _super.call(this) || this;
_this.axis = axis;
_this._inputs = [];
_this.options = __assign({
easing: function easeOutCubic(x) {
return 1 - Math.pow(1 - x, 3);
},
interruptable: true,
maximumDuration: Infinity,
minimumDuration: 0,
deceleration: 0.0006
}, options);
_this.itm = new InterruptManager(_this.options);
_this.axm = new AxisManager(_this.axis, _this.options);
_this.em = new EventManager(_this);
_this.am = new AnimationManager(_this);
_this.io = new InputObserver(_this);
_this.em.setAnimationManager(_this.am);
startPos && _this.em.triggerChange(startPos);
return _this;
}
/**
* Connect the axis of eg.Axes to the inputType.
* @ko eg.Axes의 축과 inputType을 연결한다
* @method eg.Axes#connect
* @param {(String[]|String)} axes The name of the axis to associate with inputType <ko>inputType과 연결할 축의 이름</ko>
* @param {Object} inputType The inputType instance to associate with the axis of eg.Axes <ko>eg.Axes의 축과 연결할 inputType 인스턴스<ko>
* @return {eg.Axes} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "xOther": {
* range: [-100, 100]
* }
* });
*
* axes.connect("x", new eg.Axes.PanInput("#area1"))
* .connect("x xOther", new eg.Axes.PanInput("#area2"))
* .connect(" xOther", new eg.Axes.PanInput("#area3"))
* .connect(["x"], new eg.Axes.PanInput("#area4"))
* .connect(["xOther", "x"], new eg.Axes.PanInput("#area5"))
* .connect(["", "xOther"], new eg.Axes.PanInput("#area6"));
*/
var __proto = Axes.prototype;
__proto.connect = function (axes, inputType) {
var mapped;
if (typeof axes === "string") {
mapped = axes.split(" ");
} else {
mapped = axes.concat();
} // check same instance
if (~this._inputs.indexOf(inputType)) {
this.disconnect(inputType);
} // check same element in hammer type for share
if ("hammer" in inputType) {
var targets = this._inputs.filter(function (v) {
return v.hammer && v.element === inputType.element;
});
if (targets.length) {
inputType.hammer = targets[0].hammer;
}
}
inputType.mapAxes(mapped);
inputType.connect(this.io);
this._inputs.push(inputType);
return this;
};
/**
* Disconnect the axis of eg.Axes from the inputType.
* @ko eg.Axes의 축과 inputType의 연결을 끊는다.
* @method eg.Axes#disconnect
* @param {Object} [inputType] An inputType instance associated with the axis of eg.Axes <ko>eg.Axes의 축과 연결한 inputType 인스턴스<ko>
* @return {eg.Axes} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "xOther": {
* range: [-100, 100]
* }
* });
*
* const input1 = new eg.Axes.PanInput("#area1");
* const input2 = new eg.Axes.PanInput("#area2");
* const input3 = new eg.Axes.PanInput("#area3");
*
* axes.connect("x", input1);
* .connect("x xOther", input2)
* .connect(["xOther", "x"], input3);
*
* axes.disconnect(input1); // disconnects input1
* axes.disconnect(); // disconnects all of them
*/
__proto.disconnect = function (inputType) {
if (inputType) {
var index = this._inputs.indexOf(inputType);
if (index >= 0) {
this._inputs[index].disconnect();
this._inputs.splice(index, 1);
}
} else {
this._inputs.forEach(function (v) {
return v.disconnect();
});
this._inputs = [];
}
return this;
};
/**
* Returns the current position of the coordinates.
* @ko 좌표의 현재 위치를 반환한다
* @method eg.Axes#get
* @param {Object} [axes] The names of the axis <ko>축 이름들</ko>
* @return {Object.<string, number>} Axis coordinate information <ko>축 좌표 정보</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "xOther": {
* range: [-100, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* });
*
* axes.get(); // {"x": 0, "xOther": -100, "zoom": 50}
* axes.get(["x", "zoom"]); // {"x": 0, "zoom": 50}
*/
__proto.get = function (axes) {
return this.axm.get(axes);
};
/**
* Moves an axis to specific coordinates.
* @ko 좌표를 이동한다.
* @method eg.Axes#setTo
* @param {Object.<string, number>} pos The coordinate to move to <ko>이동할 좌표</ko>
* @param {Number} [duration=0] Duration of the animation (unit: ms) <ko>애니메이션 진행 시간(단위: ms)</ko>
* @return {eg.Axes} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "xOther": {
* range: [-100, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* });
*
* axes.setTo({"x": 30, "zoom": 60});
* axes.get(); // {"x": 30, "xOther": -100, "zoom": 60}
*
* axes.setTo({"x": 100, "xOther": 60}, 1000); // animatation
*
* // after 1000 ms
* axes.get(); // {"x": 100, "xOther": 60, "zoom": 60}
*/
__proto.setTo = function (pos, duration) {
if (duration === void 0) {
duration = 0;
}
this.am.setTo(pos, duration);
return this;
};
/**
* Moves an axis from the current coordinates to specific coordinates.
* @ko 현재 좌표를 기준으로 좌표를 이동한다.
* @method eg.Axes#setBy
* @param {Object.<string, number>} pos The coordinate to move to <ko>이동할 좌표</ko>
* @param {Number} [duration=0] Duration of the animation (unit: ms) <ko>애니메이션 진행 시간(단위: ms)</ko>
* @return {eg.Axes} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "xOther": {
* range: [-100, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* });
*
* axes.setBy({"x": 30, "zoom": 10});
* axes.get(); // {"x": 30, "xOther": -100, "zoom": 60}
*
* axes.setBy({"x": 70, "xOther": 60}, 1000); // animatation
*
* // after 1000 ms
* axes.get(); // {"x": 100, "xOther": -40, "zoom": 60}
*/
__proto.setBy = function (pos, duration) {
if (duration === void 0) {
duration = 0;
}
this.am.setBy(pos, duration);
return this;
};
/**
* Returns whether there is a coordinate in the bounce area of the target axis.
* @ko 대상 축 중 bounce영역에 좌표가 존재하는지를 반환한다
* @method eg.Axes#isBounceArea
* @param {Object} [axes] The names of the axis <ko>축 이름들</ko>
* @return {Boolen} Whether the bounce area exists. <ko>bounce 영역 존재 여부</ko>
* @example
* const axes = new eg.Axes({
* "x": {
* range: [0, 100]
* },
* "xOther": {
* range: [-100, 100]
* },
* "zoom": {
* range: [50, 30]
* }
* });
*
* axes.isBounceArea(["x"]);
* axes.isBounceArea(["x", "zoom"]);
* axes.isBounceArea();
*/
__proto.isBounceArea = function (axes) {
return this.axm.isOutside(axes);
};
/**
* Destroys properties, and events used in a module and disconnect all connections to inputTypes.
* @ko 모듈에 사용한 속성, 이벤트를 해제한다. 모든 inputType과의 연결을 끊는다.
* @method eg.Axes#destroy
*/
__proto.destroy = function () {
this.disconnect();
this.em.destroy();
};
/**
* Version info string
* @ko 버전정보 문자열
* @name VERSION
* @static
* @type {String}
* @example
* eg.Axes.VERSION; // ex) 3.3.3
* @memberof eg.Axes
*/
Axes.VERSION = "2.5.13";
/**
* @name eg.Axes.TRANSFORM
* @desc Returns the transform attribute with CSS vendor prefixes.
* @ko CSS vendor prefixes를 붙인 transform 속성을 반환한다.
*
* @constant
* @type {String}
* @example
* eg.Axes.TRANSFORM; // "transform" or "webkitTransform"
*/
Axes.TRANSFORM = TRANSFORM;
/**
* @name eg.Axes.DIRECTION_NONE
* @constant
* @type {Number}
*/
Axes.DIRECTION_NONE = DIRECTION_NONE;
/**
* @name eg.Axes.DIRECTION_LEFT
* @constant
* @type {Number}
*/
Axes.DIRECTION_LEFT = DIRECTION_LEFT;
/**
* @name eg.Axes.DIRECTION_RIGHT
* @constant
* @type {Number}
*/
Axes.DIRECTION_RIGHT = DIRECTION_RIGHT;
/**
* @name eg.Axes.DIRECTION_UP
* @constant
* @type {Number}
*/
Axes.DIRECTION_UP = DIRECTION_UP;
/**
* @name eg.Axes.DIRECTION_DOWN
* @constant
* @type {Number}
*/
Axes.DIRECTION_DOWN = DIRECTION_DOWN;
/**
* @name eg.Axes.DIRECTION_HORIZONTAL
* @constant
* @type {Number}
*/
Axes.DIRECTION_HORIZONTAL = DIRECTION_HORIZONTAL;
/**
* @name eg.Axes.DIRECTION_VERTICAL
* @constant
* @type {Number}
*/
Axes.DIRECTION_VERTICAL = DIRECTION_VERTICAL;
/**
* @name eg.Axes.DIRECTION_ALL
* @constant
* @type {Number}
*/
Axes.DIRECTION_ALL = DIRECTION_ALL;
return Axes;
}(Component);
var SUPPORT_POINTER_EVENTS$1 = "PointerEvent" in win$1 || "MSPointerEvent" in win$1;
var SUPPORT_TOUCH$1 = "ontouchstart" in win$1;
var UNIQUEKEY = "_EGJS_AXES_INPUTTYPE_";
function toAxis(source, offset) {
return offset.reduce(function (acc, v, i) {
if (source[i]) {
acc[source[i]] = v;
}
return acc;
}, {});
}
function createHammer(element, options) {
try {
// create Hammer
return new Manager(element, __assign({}, options));
} catch (e) {
return null;
}
}
function convertInputType(inputType) {
if (inputType === void 0) {
inputType = [];
}
var hasTouch = false;
var hasMouse = false;
var hasPointer = false;
inputType.forEach(function (v) {
switch (v) {
case "mouse":
hasMouse = true;
break;
case "touch":
hasTouch = SUPPORT_TOUCH$1;
break;
case "pointer":
hasPointer = SUPPORT_POINTER_EVENTS$1;
// no default
}
});
if (hasPointer) {
return PointerEventInput;
} else if (hasTouch && hasMouse) {
return TouchMouseInput;
} else if (hasTouch) {
return TouchInput;
} else if (hasMouse) {
return MouseInput;
}
return null;
}
function getDirectionByAngle(angle, thresholdAngle) {
if (thresholdAngle < 0 || thresholdAngle > 90) {
return DIRECTION_NONE;
}
var toAngle = Math.abs(angle);
return toAngle > thresholdAngle && toAngle < 180 - thresholdAngle ? DIRECTION_VERTICAL : DIRECTION_HORIZONTAL;
}
function getNextOffset(speeds, deceleration) {
var normalSpeed = Math.sqrt(speeds[0] * speeds[0] + speeds[1] * speeds[1]);
var duration = Math.abs(normalSpeed / -deceleration);
return [speeds[0] / 2 * duration, speeds[1] / 2 * duration];
}
function useDirection(checkType, direction, userDirection) {
if (userDirection) {
return !!(direction === DIRECTION_ALL || direction & checkType && userDirection & checkType);
} else {
return !!(direction & checkType);
}
}
/**
* @typedef {Object} PanInputOption The option object of the eg.Axes.PanInput module.
* @ko eg.Axes.PanInput 모듈의 옵션 객체
* @property {String[]} [inputType=["touch","mouse", "pointer"]] Types of input devices.<br>- touch: Touch screen<br>- mouse: Mouse <ko>입력 장치 종류.<br>- touch: 터치 입력 장치<br>- mouse: 마우스</ko>
* @property {Number[]} [scale] Coordinate scale that a user can move<ko>사용자의 동작으로 이동하는 좌표의 배율</ko>
* @property {Number} [scale.0=1] horizontal axis scale <ko>수평축 배율</ko>
* @property {Number} [scale.1=1] vertical axis scale <ko>수직축 배율</ko>
* @property {Number} [thresholdAngle=45] The threshold value that determines whether user action is horizontal or vertical (0~90) <ko>사용자의 동작이 가로 방향인지 세로 방향인지 판단하는 기준 각도(0~90)</ko>
* @property {Number} [threshold=0] Minimal pan distance required before recognizing <ko>사용자의 Pan 동작을 인식하기 위해산 최소한의 거리</ko>
* @property {Object} [hammerManagerOptions={cssProps: {userSelect: "none",touchSelect: "none",touchCallout: "none",userDrag: "none"}] Options of Hammer.Manager <ko>Hammer.Manager의 옵션</ko>
**/
/**
* @class eg.Axes.PanInput
* @classdesc A module that passes the amount of change to eg.Axes when the mouse or touchscreen is down and moved. use less than two axes.
* @ko 마우스나 터치 스크린을 누르고 움직일때의 변화량을 eg.Axes에 전달하는 모듈. 두개 이하의 축을 사용한다.
*
* @example
* const pan = new eg.Axes.PanInput("#area", {
* inputType: ["touch"],
* scale: [1, 1.3],
* });
*
* // Connect the 'something2' axis to the mouse or touchscreen x position when the mouse or touchscreen is down and moved.
* // Connect the 'somethingN' axis to the mouse or touchscreen y position when the mouse or touchscreen is down and moved.
* axes.connect(["something2", "somethingN"], pan); // or axes.connect("something2 somethingN", pan);
*
* // Connect only one 'something1' axis to the mouse or touchscreen x position when the mouse or touchscreen is down and moved.
* axes.connect(["something1"], pan); // or axes.connect("something1", pan);
*
* // Connect only one 'something2' axis to the mouse or touchscreen y position when the mouse or touchscreen is down and moved.
* axes.connect(["", "something2"], pan); // or axes.connect(" something2", pan);
*
* @param {HTMLElement|String|jQuery} element An element to use the eg.Axes.PanInput module <ko>eg.Axes.PanInput 모듈을 사용할 엘리먼트</ko>
* @param {PanInputOption} [options] The option object of the eg.Axes.PanInput module<ko>eg.Axes.PanInput 모듈의 옵션 객체</ko>
*/
var PanInput =
/*#__PURE__*/
function () {
function PanInput(el, options) {
this.axes = [];
this.hammer = null;
this.element = null;
this.panRecognizer = null;
/**
* Hammer helps you add support for touch gestures to your page
*
* @external Hammer
* @see {@link http://hammerjs.github.io|Hammer.JS}
* @see {@link http://hammerjs.github.io/jsdoc/Hammer.html|Hammer.JS API documents}
* @see Hammer.JS applies specific CSS properties by {@link http://hammerjs.github.io/jsdoc/Hammer.defaults.cssProps.html|default} when creating an instance. The eg.Axes module removes all default CSS properties provided by Hammer.JS
*/
if (typeof Manager === "undefined") {
throw new Error("The Hammerjs must be loaded before eg.Axes.PanInput.\nhttp://hammerjs.github.io/");
}
this.element = $(el);
this.options = __assign({
inputType: ["touch", "mouse", "pointer"],
scale: [1, 1],
thresholdAngle: 45,
threshold: 0,
hammerManagerOptions: {
// css properties were removed due to usablility issue
// http://hammerjs.github.io/jsdoc/Hammer.defaults.cssProps.html
cssProps: {
userSelect: "none",
touchSelect: "none",
touchCallout: "none",
userDrag: "none"
}
}
}, options);
this.onHammerInput = this.onHammerInput.bind(this);
this.onPanmove = this.onPanmove.bind(this);
this.onPanend = this.onPanend.bind(this);
}
var __proto = PanInput.prototype;
__proto.mapAxes = function (axes) {
var useHorizontal = !!axes[0];
var useVertical = !!axes[1];
if (useHorizontal && useVertical) {
this._direction = DIRECTION_ALL;
} else if (useHorizontal) {
this._direction = DIRECTION_HORIZONTAL;
} else if (useVertical) {
this._direction = DIRECTION_VERTICAL;
} else {
this._direction = DIRECTION_NONE;
}
this.axes = axes;
};
__proto.connect = function (observer) {
var hammerOption = {
direction: this._direction,
threshold: this.options.threshold
};
if (this.hammer) {
// for sharing hammer instance.
// hammer remove previous PanRecognizer.
this.removeRecognizer();
this.dettachEvent();
} else {
var keyValue = this.element[UNIQUEKEY];
if (!keyValue) {
keyValue = String(Math.round(Math.random() * new Date().getTime()));
}
var inputClass = convertInputType(this.options.inputType);
if (!inputClass) {
throw new Error("Wrong inputType parameter!");
}
this.hammer = createHammer(this.element, __assign({
inputClass: inputClass
}, this.options.hammerManagerOptions));
this.element[UNIQUEKEY] = keyValue;
}
this.panRecognizer = new PanRecognizer(hammerOption);
this.hammer.add(this.panRecognizer);
this.attachEvent(observer);
return this;
};
__proto.disconnect = function () {
this.removeRecognizer();
if (this.hammer) {
this.dettachEvent();
}
this._direction = DIRECTION_NONE;
return this;
};
/**
* Destroys elements, properties, and events used in a module.
* @ko 모듈에 사용한 엘리먼트와 속성, 이벤트를 해제한다.
* @method eg.Axes.PanInput#destroy
*/
__proto.destroy = function () {
this.disconnect();
if (this.hammer && this.hammer.recognizers.length === 0) {
this.hammer.destroy();
}
delete this.element[UNIQUEKEY];
this.element = null;
this.hammer = null;
};
/**
* Enables input devices
* @ko 입력 장치를 사용할 수 있게 한다
* @method eg.Axes.PanInput#enable
* @return {eg.Axes.PanInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
*/
__proto.enable = function () {
this.hammer && (this.hammer.get("pan").options.enable = true);
return this;
};
/**
* Disables input devices
* @ko 입력 장치를 사용할 수 없게 한다.
* @method eg.Axes.PanInput#disable
* @return {eg.Axes.PanInput} An instance of a module itself <ko>모듈 자신의 인스턴스</ko>
*/
__proto.disable = function () {
this.hammer && (this.hammer.get("pan").options.enable = false);
return this;
};
/**
* Returns whether to use an input device
* @ko 입력 장치를 사용 여부를 반환한다.
* @method eg.Axes.PanInput#isEnable
* @return {Boolean} Whether to use an input device <ko>입력장치 사용여부</ko>
*/
__proto.isEnable = function () {
return !!(this.hammer && this.hammer.get("pan").options.enable);
};
__proto.removeRecognizer = function () {
if (this.hammer && this.panRecognizer) {
this.hammer.remove(this.panRecognizer);
this.panRecognizer = null;
}
};
__proto.onHammerInput = function (event) {
if (this.isEnable()) {
if (event.isFirst) {
this.observer.hold(this, event);
} else if (event.isFinal) {
this.onPanend(event);
}
}
};
__proto.onPanmove = function (event) {
var userDirection = getDirectionByAngle(event.angle, this.options.thresholdAngle); // not support offset properties in Hammerjs - start
var prevInput = this.hammer.session.prevInput;
/* eslint-disable no-param-reassign */
if (prevInput) {
event.offsetX = event.deltaX - prevInput.deltaX;
event.offsetY = event.deltaY - prevInput.deltaY;
} else {
event.offsetX = 0;
event.offsetY = 0;
}
var offset = this.getOffset([event.offsetX, event.offsetY], [useDirection(DIRECTION_HORIZONTAL, this._direction, userDirection), useDirection(DIRECTION_VERTICAL, this._direction, userDirection)]);
var prevent = offset.some(function (v) {
return v !== 0;
});
if (prevent) {
event.srcEvent.preventDefault();
event.srcEvent.stopPropagation();
}
event.preventSystemEvent = prevent;
prevent && this.observer.change(this, event, toAxis(this.axes, offset));
};
__proto.onPanend = function (event) {
var offset = this.getOffset([Math.abs(event.velocityX) * (event.deltaX < 0 ? -1 : 1), Math.abs(event.velocityY) * (event.deltaY < 0 ? -1 : 1)], [useDirection(DIRECTION_HORIZONTAL, this._direction), useDirection(DIRECTION_VERTICAL, this._direction)]);
offset = getNextOffset(offset, this.observer.options.deceleration);
this.observer.release(this, event, toAxis(this.axes, offset));
};
__proto.attachEvent = function (observer) {
this.observer = observer;
this.hammer.on("hammer.input", this.onHammerInput).on("panstart panmove", this.onPanmove);
};
__proto.dettachEvent = function () {
this.hammer.off("hammer.input", this.onHammerInput).off("panstart panmove", this.onPanmove);
this.observer = null;
};
__proto.getOffset = function (properties, direction) {
var offset = [0, 0];
var scale = this.options.scale;
if (direction[0]) {
offset[0] = properties[0] * scale[0];
}
if (direction[1]) {
offset[1] = properties[1] * scale[1];
}
return offset;
};
return PanInput;
}();
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var MOVE_TYPE = {
SNAP: "snap",
FREE_SCROLL: "freeScroll"
};
var DEFAULT_MOVE_TYPE_OPTIONS = {
snap: {
type: "snap",
count: 1
},
freeScroll: {
type: "freeScroll"
}
};
var isBrowser = typeof document !== "undefined";
/**
* Default options for creating Flicking.
* @ko 플리킹을 만들 때 사용하는 기본 옵션들
* @private
* @memberof eg.Flicking
*/
var DEFAULT_OPTIONS = {
classPrefix: "eg-flick",
deceleration: 0.0075,
horizontal: true,
circular: false,
infinite: false,
infiniteThreshold: 0,
lastIndex: Infinity,
threshold: 40,
duration: 100,
panelEffect: function (x) {
return 1 - Math.pow(1 - x, 3);
},
defaultIndex: 0,
inputType: ["touch", "mouse"],
thresholdAngle: 45,
bounce: 10,
autoResize: false,
adaptive: false,
zIndex: 2000,
bound: false,
overflow: false,
hanger: "50%",
anchor: "50%",
gap: 0,
moveType: DEFAULT_MOVE_TYPE_OPTIONS.snap,
useOffset: false,
isEqualSize: false,
isConstantSize: false,
renderOnlyVisible: false,
renderExternal: false,
collectStatistics: true
};
var DEFAULT_VIEWPORT_CSS = {
position: "relative",
zIndex: DEFAULT_OPTIONS.zIndex,
overflow: "hidden"
};
var DEFAULT_CAMERA_CSS = {
width: "100%",
height: "100%",
willChange: "transform"
};
var DEFAULT_PANEL_CSS = {
position: "absolute"
};
var EVENTS = {
HOLD_START: "holdStart",
HOLD_END: "holdEnd",
MOVE_START: "moveStart",
MOVE: "move",
MOVE_END: "moveEnd",
CHANGE: "change",
RESTORE: "restore",
SELECT: "select",
NEED_PANEL: "needPanel",
VISIBLE_CHANGE: "visibleChange"
};
var AXES_EVENTS = {
HOLD: "hold",
CHANGE: "change",
RELEASE: "release",
ANIMATION_END: "animationEnd",
FINISH: "finish"
};
var STATE_TYPE = {
IDLE: 0,
HOLDING: 1,
DRAGGING: 2,
ANIMATING: 3,
DISABLED: 4
};
var DIRECTION = {
PREV: "PREV",
NEXT: "NEXT"
};
var FLICKING_METHODS = {
prev: true,
next: true,
moveTo: true,
getIndex: true,
getAllPanels: true,
getCurrentPanel: true,
getElement: true,
getPanel: true,
getPanelCount: true,
getStatus: true,
getVisiblePanels: true,
enableInput: true,
disableInput: true,
destroy: true,
resize: true,
setStatus: true,
isPlaying: true
}; // Check whether browser supports transform: translate3d
// https://stackoverflow.com/questions/5661671/detecting-transform-translate3d-support
var checkTranslateSupport = function () {
var transforms = {
webkitTransform: "-webkit-transform",
msTransform: "-ms-transform",
MozTransform: "-moz-transform",
OTransform: "-o-transform",
transform: "transform"
};
if (!isBrowser) {
return {
name: transforms.transform,
has3d: true
};
}
var supportedStyle = document.documentElement.style;
var transformName = "";
for (var prefixedTransform in transforms) {
if (prefixedTransform in supportedStyle) {
transformName = prefixedTransform;
}
}
if (!transformName) {
throw new Error("Browser doesn't support CSS3 2D Transforms.");
}
var el = document.createElement("div");
document.documentElement.insertBefore(el, null);
el.style[transformName] = "translate3d(1px, 1px, 1px)";
var styleVal = window.getComputedStyle(el).getPropertyValue(transforms[transformName]);
el.parentElement.removeChild(el);
var transformInfo = {
name: transformName,
has3d: styleVal.length > 0 && styleVal !== "none"
};
checkTranslateSupport = function () {
return transformInfo;
};
return transformInfo;
};
var TRANSFORM$1 = checkTranslateSupport();
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
function merge(target) {
var srcs = [];
for (var _i = 1; _i < arguments.length; _i++) {
srcs[_i - 1] = arguments[_i];
}
srcs.forEach(function (source) {
Object.keys(source).forEach(function (key) {
var value = source[key];
target[key] = value;
});
});
return target;
}
function parseElement(element) {
if (!Array.isArray(element)) {
element = [element];
}
var elements = [];
element.forEach(function (el) {
if (isString(el)) {
var tempDiv = document.createElement("div");
tempDiv.innerHTML = el;
elements.push.apply(elements, toArray$2(tempDiv.children));
while (tempDiv.firstChild) {
tempDiv.removeChild(tempDiv.firstChild);
}
} else {
elements.push(el);
}
});
return elements;
}
function isString(value) {
return typeof value === "string";
} // Get class list of element as string array
function addClass(element, className) {
if (element.classList) {
element.classList.add(className);
} else {
if (!hasClass(element, className)) {
element.className = (element.className + " " + className).replace(/\s{2,}/g, " ");
}
}
}
function hasClass(element, className) {
if (element.classList) {
return element.classList.contains(className);
} else {
return element.className.split(" ").indexOf(className) >= 0;
}
}
function applyCSS(element, cssObj) {
Object.keys(cssObj).forEach(function (property) {
element.style[property] = cssObj[property];
});
}
function clamp(val, min, max) {
return Math.max(Math.min(val, max), min);
} // Min: inclusive, Max: exclusive
function isBetween(val, min, max) {
return val >= min && val <= max;
}
function toArray$2(iterable) {
return [].slice.call(iterable);
}
function isArray(arr) {
return arr && arr.constructor === Array;
}
function parseArithmeticExpression(cssValue, base, defaultVal) {
// Set base / 2 to default value, if it's undefined
var defaultValue = defaultVal != null ? defaultVal : base / 2;
var cssRegex = /(?:(\+|\-)\s*)?(\d+(?:\.\d+)?(%|px)?)/g;
if (typeof cssValue === "number") {
return clamp(cssValue, 0, base);
}
var idx = 0;
var calculatedValue = 0;
var matchResult = cssRegex.exec(cssValue);
while (matchResult != null) {
var sign = matchResult[1];
var value = matchResult[2];
var unit = matchResult[3];
var parsedValue = parseFloat(value);
if (idx <= 0) {
sign = sign || "+";
} // Return default value for values not in good form
if (!sign) {
return defaultValue;
}
if (unit === "%") {
parsedValue = parsedValue / 100 * base;
}
calculatedValue += sign === "+" ? parsedValue : -parsedValue; // Match next occurrence
++idx;
matchResult = cssRegex.exec(cssValue);
} // None-matched
if (idx === 0) {
return defaultValue;
} // Clamp between 0 ~ base
return clamp(calculatedValue, 0, base);
}
function getProgress(pos, range) {
// start, anchor, end
// -1 , 0 , 1
var min = range[0],
center = range[1],
max = range[2];
if (pos > center && max - center) {
// 0 ~ 1
return (pos - center) / (max - center);
} else if (pos < center && center - min) {
// -1 ~ 0
return (pos - center) / (center - min);
} else if (pos !== center && max - min) {
return (pos - min) / (max - min);
}
return 0;
}
function findIndex(iterable, callback) {
for (var i = 0; i < iterable.length; i += 1) {
var element = iterable[i];
if (element && callback(element)) {
return i;
}
}
return -1;
} // return [0, 1, ...., max - 1]
function counter(max) {
var counterArray = [];
for (var i = 0; i < max; i += 1) {
counterArray[i] = i;
}
return counterArray;
} // Circulate number between range [min, max]
/*
* "indexed" means min and max is not same, so if it's true "min - 1" should be max
* While if it's false, "min - 1" should be "max - 1"
* use `indexed: true` when it should be used for circulating integers like index
* or `indexed: false` when it should be used for something like positions.
*/
function circulate(value, min, max, indexed) {
var size = indexed ? max - min + 1 : max - min;
if (value < min) {
var offset = indexed ? (min - value - 1) % size : (min - value) % size;
value = max - offset;
} else if (value > max) {
var offset = indexed ? (value - max - 1) % size : (value - max) % size;
value = min + offset;
}
return value;
}
function restoreStyle(element, originalStyle) {
originalStyle.className ? element.setAttribute("class", originalStyle.className) : element.removeAttribute("class");
originalStyle.style ? element.setAttribute("style", originalStyle.style) : element.removeAttribute("style");
}
/**
* Decorator that makes the method of flicking available in the framework.
* @ko 프레임워크에서 플리킹의 메소드를 사용할 수 있게 하는 데코레이터.
* @memberof eg.Flicking
* @private
* @example
* ```js
* import Flicking, { withFlickingMethods } from "@egjs/flicking";
*
* class Flicking extends React.Component<Partial<FlickingProps & FlickingOptions>> {
* @withFlickingMethods
* private flicking: Flicking;
* }
* ```
*/
function withFlickingMethods(prototype, flickingName) {
Object.keys(FLICKING_METHODS).forEach(function (name) {
if (prototype[name]) {
return;
}
prototype[name] = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var result = (_a = this[flickingName])[name].apply(_a, args); // fix `this` type to return your own `flicking` instance to the instance using the decorator.
if (result === this[flickingName]) {
return this;
} else {
return result;
}
var _a;
};
});
}
function getBbox(element, useOffset) {
var bbox;
if (useOffset) {
bbox = {
x: 0,
y: 0,
width: element.offsetWidth,
height: element.offsetHeight
};
} else {
var clientRect = element.getBoundingClientRect();
bbox = {
x: clientRect.left,
y: clientRect.top,
width: clientRect.width,
height: clientRect.height
};
}
return bbox;
}
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var Panel =
/*#__PURE__*/
function () {
function Panel(element, index, viewport) {
this.viewport = viewport;
this.prevSibling = null;
this.nextSibling = null;
this.clonedPanels = [];
this.state = {
index: index,
position: 0,
relativeAnchorPosition: 0,
size: 0,
isClone: false,
isVirtual: false,
cloneIndex: -1,
originalStyle: {
className: "",
style: ""
},
cachedBbox: null
};
this.setElement(element);
}
var __proto = Panel.prototype;
__proto.resize = function (givenBbox) {
var state = this.state;
var options = this.viewport.options;
var bbox = givenBbox ? givenBbox : this.getBbox();
this.state.cachedBbox = bbox;
var prevSize = state.size;
state.size = options.horizontal ? bbox.width : bbox.height;
if (prevSize !== state.size) {
state.relativeAnchorPosition = parseArithmeticExpression(options.anchor, state.size);
}
if (!state.isClone) {
this.clonedPanels.forEach(function (panel) {
var cloneState = panel.state;
cloneState.size = state.size;
cloneState.cachedBbox = state.cachedBbox;
cloneState.relativeAnchorPosition = state.relativeAnchorPosition;
});
}
};
__proto.unCacheBbox = function () {
this.state.cachedBbox = null;
};
__proto.getProgress = function () {
var viewport = this.viewport;
var options = viewport.options;
var panelCount = viewport.panelManager.getPanelCount();
var scrollAreaSize = viewport.getScrollAreaSize();
var relativeIndex = (options.circular ? Math.floor(this.getPosition() / scrollAreaSize) * panelCount : 0) + this.getIndex();
var progress = relativeIndex - viewport.getCurrentProgress();
return progress;
};
__proto.getOutsetProgress = function () {
var viewport = this.viewport;
var outsetRange = [-this.getSize(), viewport.getRelativeHangerPosition() - this.getRelativeAnchorPosition(), viewport.getSize()];
var relativePanelPosition = this.getPosition() - viewport.getCameraPosition();
var outsetProgress = getProgress(relativePanelPosition, outsetRange);
return outsetProgress;
};
__proto.getVisibleRatio = function () {
var viewport = this.viewport;
var panelSize = this.getSize();
var relativePanelPosition = this.getPosition() - viewport.getCameraPosition();
var rightRelativePanelPosition = relativePanelPosition + panelSize;
var visibleSize = Math.min(viewport.getSize(), rightRelativePanelPosition) - Math.max(relativePanelPosition, 0);
var visibleRatio = visibleSize >= 0 ? visibleSize / panelSize : 0;
return visibleRatio;
};
__proto.focus = function (duration) {
var viewport = this.viewport;
var currentPanel = viewport.getCurrentPanel();
var hangerPosition = viewport.getHangerPosition();
var anchorPosition = this.getAnchorPosition();
if (hangerPosition === anchorPosition || !currentPanel) {
return;
}
var currentPosition = currentPanel.getPosition();
var eventType = currentPosition === this.getPosition() ? "" : EVENTS.CHANGE;
viewport.moveTo(this, viewport.findEstimatedPosition(this), eventType, null, duration);
};
__proto.update = function (updateFunction, shouldResize) {
if (updateFunction === void 0) {
updateFunction = null;
}
if (shouldResize === void 0) {
shouldResize = true;
}
var identicalPanels = this.getIdenticalPanels();
if (updateFunction) {
identicalPanels.forEach(function (eachPanel) {
updateFunction(eachPanel.getElement());
});
}
if (shouldResize) {
identicalPanels.forEach(function (eachPanel) {
eachPanel.unCacheBbox();
});
this.viewport.addVisiblePanel(this);
this.viewport.resize();
}
};
__proto.prev = function () {
var viewport = this.viewport;
var options = viewport.options;
var prevSibling = this.prevSibling;
if (!prevSibling) {
return null;
}
var currentIndex = this.getIndex();
var currentPosition = this.getPosition();
var prevPanelIndex = prevSibling.getIndex();
var prevPanelPosition = prevSibling.getPosition();
var prevPanelSize = prevSibling.getSize();
var hasEmptyPanelBetween = currentIndex - prevPanelIndex > 1;
var notYetMinPanel = options.infinite && currentIndex > 0 && prevPanelIndex > currentIndex;
if (hasEmptyPanelBetween || notYetMinPanel) {
// Empty panel exists between
return null;
}
var newPosition = currentPosition - prevPanelSize - options.gap;
var prevPanel = prevSibling;
if (prevPanelPosition !== newPosition) {
prevPanel = prevSibling.clone(prevSibling.getCloneIndex(), true);
prevPanel.setPosition(newPosition);
}
return prevPanel;
};
__proto.next = function () {
var viewport = this.viewport;
var options = viewport.options;
var nextSibling = this.nextSibling;
var lastIndex = viewport.panelManager.getLastIndex();
if (!nextSibling) {
return null;
}
var currentIndex = this.getIndex();
var currentPosition = this.getPosition();
var nextPanelIndex = nextSibling.getIndex();
var nextPanelPosition = nextSibling.getPosition();
var hasEmptyPanelBetween = nextPanelIndex - currentIndex > 1;
var notYetMaxPanel = options.infinite && currentIndex < lastIndex && nextPanelIndex < currentIndex;
if (hasEmptyPanelBetween || notYetMaxPanel) {
return null;
}
var newPosition = currentPosition + this.getSize() + options.gap;
var nextPanel = nextSibling;
if (nextPanelPosition !== newPosition) {
nextPanel = nextSibling.clone(nextSibling.getCloneIndex(), true);
nextPanel.setPosition(newPosition);
}
return nextPanel;
};
__proto.insertBefore = function (element) {
var viewport = this.viewport;
var parsedElements = parseElement(element);
var firstPanel = viewport.panelManager.firstPanel();
var prevSibling = this.prevSibling; // Finding correct inserting index
// While it should insert removing empty spaces,
// It also should have to be bigger than prevSibling' s index
var targetIndex = prevSibling && firstPanel.getIndex() !== this.getIndex() ? Math.max(prevSibling.getIndex() + 1, this.getIndex() - parsedElements.length) : Math.max(this.getIndex() - parsedElements.length, 0);
return viewport.insert(targetIndex, parsedElements);
};
__proto.insertAfter = function (element) {
return this.viewport.insert(this.getIndex() + 1, element);
};
__proto.remove = function () {
this.viewport.remove(this.getIndex());
return this;
};
__proto.destroy = function (option) {
if (!option.preserveUI) {
var originalStyle = this.state.originalStyle;
restoreStyle(this.element, originalStyle);
} // release resources
for (var x in this) {
this[x] = null;
}
};
__proto.getElement = function () {
return this.element;
};
__proto.getAnchorPosition = function () {
return this.state.position + this.state.relativeAnchorPosition;
};
__proto.getRelativeAnchorPosition = function () {
return this.state.relativeAnchorPosition;
};
__proto.getIndex = function () {
return this.state.index;
};
__proto.getPosition = function () {
return this.state.position;
};
__proto.getSize = function () {
return this.state.size;
};
__proto.getBbox = function () {
var state = this.state;
var viewport = this.viewport;
var element = this.element;
var options = viewport.options;
if (!element) {
state.cachedBbox = {
x: 0,
y: 0,
width: 0,
height: 0
};
} else if (!state.cachedBbox) {
var wasVisible = Boolean(element.parentNode);
var cameraElement = viewport.getCameraElement();
if (!wasVisible) {
cameraElement.appendChild(element);
viewport.addVisiblePanel(this);
}
state.cachedBbox = getBbox(element, options.useOffset);
if (!wasVisible && viewport.options.renderExternal) {
cameraElement.removeChild(element);
}
}
return state.cachedBbox;
};
__proto.isClone = function () {
return this.state.isClone;
};
__proto.getOverlappedClass = function (classes) {
var element = this.element;
for (var _i = 0, classes_1 = classes; _i < classes_1.length; _i++) {
var className = classes_1[_i];
if (hasClass(element, className)) {
return className;
}
}
};
__proto.getCloneIndex = function () {
return this.state.cloneIndex;
};
__proto.getClonedPanels = function () {
var state = this.state;
return state.isClone ? this.original.getClonedPanels() : this.clonedPanels;
};
__proto.getIdenticalPanels = function () {
var state = this.state;
return state.isClone ? this.original.getIdenticalPanels() : [this].concat(this.clonedPanels);
};
__proto.getOriginalPanel = function () {
return this.state.isClone ? this.original : this;
};
__proto.setIndex = function (index) {
var state = this.state;
state.index = index;
this.clonedPanels.forEach(function (panel) {
return panel.state.index = index;
});
};
__proto.setPosition = function (pos) {
this.state.position = pos;
return this;
};
__proto.setPositionCSS = function (offset) {
if (offset === void 0) {
offset = 0;
}
if (!this.element) {
return;
}
var state = this.state;
var pos = state.position;
var options = this.viewport.options;
var elementStyle = this.element.style;
var currentElementStyle = options.horizontal ? elementStyle.left : elementStyle.top;
var styleToApply = pos - offset + "px";
if (!state.isVirtual && currentElementStyle !== styleToApply) {
options.horizontal ? elementStyle.left = styleToApply : elementStyle.top = styleToApply;
}
};
__proto.clone = function (cloneIndex, isVirtual, element) {
if (isVirtual === void 0) {
isVirtual = false;
}
var state = this.state;
var viewport = this.viewport;
var cloneElement = element;
if (!cloneElement && this.element) {
cloneElement = isVirtual ? this.element : this.element.cloneNode(true);
}
var clonedPanel = new Panel(cloneElement, state.index, viewport);
var clonedState = clonedPanel.state;
clonedPanel.original = state.isClone ? this.original : this;
clonedState.isClone = true;
clonedState.isVirtual = isVirtual;
clonedState.cloneIndex = cloneIndex; // Inherit some state values
clonedState.size = state.size;
clonedState.relativeAnchorPosition = state.relativeAnchorPosition;
clonedState.originalStyle = state.originalStyle;
clonedState.cachedBbox = state.cachedBbox;
if (!isVirtual) {
this.clonedPanels.push(clonedPanel);
} else {
clonedPanel.prevSibling = this.prevSibling;
clonedPanel.nextSibling = this.nextSibling;
}
return clonedPanel;
};
__proto.removeElement = function () {
if (!this.viewport.options.renderExternal) {
var element = this.element;
element.parentNode.removeChild(element);
} // Do the same thing for clones
if (!this.state.isClone) {
this.removeClonedPanelsAfter(0);
}
};
__proto.removeClonedPanelsAfter = function (start) {
var options = this.viewport.options;
var removingPanels = this.clonedPanels.splice(start);
if (!options.renderExternal && !options.renderOnlyVisible) {
removingPanels.forEach(function (panel) {
panel.removeElement();
});
}
};
__proto.setElement = function (element) {
if (!element) {
return;
}
var currentElement = this.element;
if (element !== currentElement) {
var options = this.viewport.options;
if (currentElement) {
if (options.horizontal) {
element.style.left = currentElement.style.left;
} else {
element.style.top = currentElement.style.top;
}
} else {
var originalStyle = this.state.originalStyle;
originalStyle.className = element.getAttribute("class");
originalStyle.style = element.getAttribute("style");
}
this.element = element;
if (options.classPrefix) {
addClass(element, options.classPrefix + "-panel");
} // Update size info after applying panel css
applyCSS(this.element, DEFAULT_PANEL_CSS);
}
};
return Panel;
}();
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var PanelManager =
/*#__PURE__*/
function () {
function PanelManager(cameraElement, options) {
this.cameraElement = cameraElement;
this.panels = [];
this.clones = [];
this.range = {
min: -1,
max: -1
};
this.length = 0;
this.cloneCount = 0;
this.options = options;
this.lastIndex = options.lastIndex;
}
var __proto = PanelManager.prototype;
__proto.firstPanel = function () {
return this.panels[this.range.min];
};
__proto.lastPanel = function () {
return this.panels[this.range.max];
};
__proto.allPanels = function () {
return this.panels.concat(this.clones.reduce(function (allClones, clones) {
return allClones.concat(clones);
}, []));
};
__proto.originalPanels = function () {
return this.panels;
};
__proto.clonedPanels = function () {
return this.clones;
};
__proto.replacePanels = function (newPanels, newClones) {
this.panels = newPanels;
this.clones = newClones;
this.range = {
min: findIndex(newPanels, function (panel) {
return Boolean(panel);
}),
max: newPanels.length - 1
};
this.length = newPanels.filter(function (panel) {
return Boolean(panel);
}).length;
};
__proto.has = function (index) {
return !!this.panels[index];
};
__proto.get = function (index) {
return this.panels[index];
};
__proto.getPanelCount = function () {
return this.length;
};
__proto.getLastIndex = function () {
return this.lastIndex;
};
__proto.getRange = function () {
return this.range;
};
__proto.getCloneCount = function () {
return this.cloneCount;
};
__proto.setLastIndex = function (lastIndex) {
this.lastIndex = lastIndex;
var firstPanel = this.firstPanel();
var lastPanel = this.lastPanel();
if (!firstPanel || !lastPanel) {
return; // no meaning of updating range & length
} // Remove panels above new last index
var range = this.range;
if (lastPanel.getIndex() > lastIndex) {
var removingPanels = this.panels.splice(lastIndex + 1);
this.length -= removingPanels.length;
var firstRemovedPanel = removingPanels.filter(function (panel) {
return !!panel;
})[0];
var possibleLastPanel = firstRemovedPanel.prevSibling;
if (possibleLastPanel) {
range.max = possibleLastPanel.getIndex();
} else {
range.min = -1;
range.max = -1;
}
if (this.shouldRender()) {
removingPanels.forEach(function (panel) {
return panel.removeElement();
});
}
}
};
__proto.setCloneCount = function (cloneCount) {
this.cloneCount = cloneCount;
}; // Insert at index
// Returns pushed elements from index, inserting at 'empty' position doesn't push elements behind it
__proto.insert = function (index, newPanels) {
var panels = this.panels;
var range = this.range;
var isCircular = this.options.circular;
var lastIndex = this.lastIndex; // Find first panel that index is greater than inserting index
var nextSibling = this.findFirstPanelFrom(index); // if it's null, element will be inserted at last position
// https://developer.mozilla.org/ko/docs/Web/API/Node/insertBefore#Syntax
var firstPanel = this.firstPanel();
var siblingElement = nextSibling ? nextSibling.getElement() : isCircular && firstPanel ? firstPanel.getClonedPanels()[0].getElement() : null; // Insert panels before sibling element
this.insertNewPanels(newPanels, siblingElement);
var pushedIndex = newPanels.length; // Like when setting index 50 while visible panels are 0, 1, 2
if (index > range.max) {
newPanels.forEach(function (panel, offset) {
panels[index + offset] = panel;
});
} else {
var panelsAfterIndex = panels.slice(index, index + newPanels.length); // Find empty from beginning
var emptyPanelCount = findIndex(panelsAfterIndex, function (panel) {
return !!panel;
});
if (emptyPanelCount < 0) {
// All empty
emptyPanelCount = panelsAfterIndex.length;
}
pushedIndex = newPanels.length - emptyPanelCount; // Insert removing empty panels
panels.splice.apply(panels, [index, emptyPanelCount].concat(newPanels)); // Remove panels after last index
if (panels.length > lastIndex + 1) {
var removedPanels = panels.splice(lastIndex + 1).filter(function (panel) {
return Boolean(panel);
});
this.length -= removedPanels.length; // Find first
var newLastIndex = lastIndex - findIndex(this.panels.concat().reverse(), function (panel) {
return !!panel;
}); // Can be filled with empty after newLastIndex
this.panels.splice(newLastIndex + 1);
this.range.max = newLastIndex;
if (this.shouldRender()) {
removedPanels.forEach(function (panel) {
return panel.removeElement();
});
}
}
} // Update index of previous panels
if (pushedIndex > 0) {
panels.slice(index + newPanels.length).forEach(function (panel) {
panel.setIndex(panel.getIndex() + pushedIndex);
});
} // Update state
this.length += newPanels.length;
this.updateIndex(index);
if (isCircular) {
this.addNewClones(index, newPanels, newPanels.length - pushedIndex, nextSibling);
var clones = this.clones;
var panelCount_1 = this.panels.length;
if (clones[0] && clones[0].length > lastIndex + 1) {
clones.forEach(function (cloneSet) {
cloneSet.splice(panelCount_1);
});
}
}
return pushedIndex;
};
__proto.replace = function (index, newPanels) {
var panels = this.panels;
var range = this.range;
var options = this.options;
var isCircular = options.circular; // Find first panel that index is greater than inserting index
var nextSibling = this.findFirstPanelFrom(index + newPanels.length); // if it's null, element will be inserted at last position
// https://developer.mozilla.org/ko/docs/Web/API/Node/insertBefore#Syntax
var firstPanel = this.firstPanel();
var siblingElement = nextSibling ? nextSibling.getElement() : isCircular && firstPanel ? firstPanel.getClonedPanels()[0].getElement() : null; // Insert panels before sibling element
this.insertNewPanels(newPanels, siblingElement);
if (index > range.max) {
// Temporarily insert null at index to use splice()
panels[index] = null;
}
var replacedPanels = panels.splice.apply(panels, [index, newPanels.length].concat(newPanels));
var wasNonEmptyCount = replacedPanels.filter(function (panel) {
return Boolean(panel);
}).length; // Suppose inserting [1, 2, 3] at 0 position when there were [empty, 1]
// So length should be increased by 3(inserting panels) - 1(non-empty panels)
this.length += newPanels.length - wasNonEmptyCount;
this.updateIndex(index);
if (isCircular) {
this.addNewClones(index, newPanels, newPanels.length, nextSibling);
}
if (this.shouldRender()) {
replacedPanels.forEach(function (panel) {
return panel && panel.removeElement();
});
}
return replacedPanels;
};
__proto.remove = function (index, deleteCount) {
if (deleteCount === void 0) {
deleteCount = 1;
}
var isCircular = this.options.circular;
var panels = this.panels;
var clones = this.clones; // Delete count should be equal or larger than 0
deleteCount = Math.max(deleteCount, 0);
var deletedPanels = panels.splice(index, deleteCount).filter(function (panel) {
return !!panel;
});
if (this.shouldRender()) {
deletedPanels.forEach(function (panel) {
return panel.removeElement();
});
}
if (isCircular) {
clones.forEach(function (cloneSet) {
cloneSet.splice(index, deleteCount);
});
} // Update indexes
panels.slice(index).forEach(function (panel) {
panel.setIndex(panel.getIndex() - deleteCount);
}); // Check last panel is empty
var lastIndex = panels.length - 1;
if (!panels[lastIndex]) {
var reversedPanels = panels.concat().reverse();
var nonEmptyIndexFromLast = findIndex(reversedPanels, function (panel) {
return !!panel;
});
lastIndex = nonEmptyIndexFromLast < 0 ? -1 // All empty
: lastIndex - nonEmptyIndexFromLast; // Remove all empty panels from last
panels.splice(lastIndex + 1);
if (isCircular) {
clones.forEach(function (cloneSet) {
cloneSet.splice(lastIndex + 1);
});
}
} // Update range & length
this.range = {
min: findIndex(panels, function (panel) {
return !!panel;
}),
max: lastIndex
};
this.length -= deletedPanels.length;
if (this.length <= 0) {
// Reset clones
this.clones = [];
this.cloneCount = 0;
}
return deletedPanels;
};
__proto.chainAllPanels = function () {
var allPanels = this.allPanels().filter(function (panel) {
return !!panel;
});
var allPanelsCount = allPanels.length;
if (allPanelsCount <= 1) {
return;
}
allPanels.slice(1, allPanels.length - 1).forEach(function (panel, idx) {
var prevPanel = allPanels[idx];
var nextPanel = allPanels[idx + 2];
panel.prevSibling = prevPanel;
panel.nextSibling = nextPanel;
});
var firstPanel = allPanels[0];
var lastPanel = allPanels[allPanelsCount - 1];
firstPanel.prevSibling = null;
firstPanel.nextSibling = allPanels[1];
lastPanel.prevSibling = allPanels[allPanelsCount - 2];
lastPanel.nextSibling = null;
if (this.options.circular) {
firstPanel.prevSibling = lastPanel;
lastPanel.nextSibling = firstPanel;
}
};
__proto.insertClones = function (cloneIndex, index, clonedPanels, deleteCount) {
if (deleteCount === void 0) {
deleteCount = 0;
}
var clones = this.clones;
var lastIndex = this.lastIndex;
if (!clones[cloneIndex]) {
var newClones_1 = [];
clonedPanels.forEach(function (panel, offset) {
newClones_1[index + offset] = panel;
});
clones[cloneIndex] = newClones_1;
} else {
var insertTarget_1 = clones[cloneIndex];
if (index >= insertTarget_1.length) {
clonedPanels.forEach(function (panel, offset) {
insertTarget_1[index + offset] = panel;
});
} else {
insertTarget_1.splice.apply(insertTarget_1, [index, deleteCount].concat(clonedPanels)); // Remove panels after last index
if (clonedPanels.length > lastIndex + 1) {
clonedPanels.splice(lastIndex + 1);
}
}
}
}; // clones are operating in set
__proto.removeClonesAfter = function (cloneIndex) {
var panels = this.panels;
panels.forEach(function (panel) {
panel.removeClonedPanelsAfter(cloneIndex);
});
this.clones.splice(cloneIndex);
};
__proto.findPanelOf = function (element) {
var allPanels = this.allPanels();
for (var _i = 0, allPanels_1 = allPanels; _i < allPanels_1.length; _i++) {
var panel = allPanels_1[_i];
if (!panel) {
continue;
}
var panelElement = panel.getElement();
if (panelElement.contains(element)) {
return panel;
}
}
};
__proto.findFirstPanelFrom = function (index) {
for (var _i = 0, _a = this.panels.slice(index); _i < _a.length; _i++) {
var panel = _a[_i];
if (panel && panel.getIndex() >= index && panel.getElement().parentNode) {
return panel;
}
}
};
__proto.addNewClones = function (index, originalPanels, deleteCount, nextSibling) {
var _this = this;
var cameraElement = this.cameraElement;
var cloneCount = this.getCloneCount();
var lastPanel = this.lastPanel();
var lastPanelClones = lastPanel ? lastPanel.getClonedPanels() : [];
var nextSiblingClones = nextSibling ? nextSibling.getClonedPanels() : [];
var _loop_1 = function (cloneIndex) {
var cloneNextSibling = nextSiblingClones[cloneIndex];
var lastPanelSibling = lastPanelClones[cloneIndex];
var cloneSiblingElement = cloneNextSibling ? cloneNextSibling.getElement() : lastPanelSibling ? lastPanelSibling.getElement().nextElementSibling : null;
var newClones = originalPanels.map(function (panel) {
var clone = panel.clone(cloneIndex);
if (_this.shouldRender()) {
cameraElement.insertBefore(clone.getElement(), cloneSiblingElement);
}
return clone;
});
this_1.insertClones(cloneIndex, index, newClones, deleteCount);
};
var this_1 = this;
for (var _i = 0, _a = counter(cloneCount); _i < _a.length; _i++) {
var cloneIndex = _a[_i];
_loop_1(cloneIndex);
}
};
__proto.updateIndex = function (insertingIndex) {
var panels = this.panels;
var range = this.range;
var newLastIndex = panels.length - 1;
if (newLastIndex > range.max) {
range.max = newLastIndex;
}
if (insertingIndex < range.min || range.min < 0) {
range.min = insertingIndex;
}
};
__proto.insertNewPanels = function (newPanels, siblingElement) {
if (this.shouldRender()) {
var fragment_1 = document.createDocumentFragment();
newPanels.forEach(function (panel) {
return fragment_1.appendChild(panel.getElement());
});
this.cameraElement.insertBefore(fragment_1, siblingElement);
}
};
__proto.shouldRender = function () {
var options = this.options;
return !options.renderExternal && !options.renderOnlyVisible;
};
return PanelManager;
}();
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var State =
/*#__PURE__*/
function () {
function State() {
this.delta = 0;
this.direction = null;
this.targetPanel = null;
this.lastPosition = 0;
}
var __proto = State.prototype;
__proto.onEnter = function (prevState) {
this.delta = prevState.delta;
this.direction = prevState.direction;
this.targetPanel = prevState.targetPanel;
this.lastPosition = prevState.lastPosition;
};
__proto.onExit = function (nextState) {// DO NOTHING
};
__proto.onHold = function (e, context) {// DO NOTHING
};
__proto.onChange = function (e, context) {// DO NOTHING
};
__proto.onRelease = function (e, context) {// DO NOTHING
};
__proto.onAnimationEnd = function (e, context) {// DO NOTHING
};
__proto.onFinish = function (e, context) {// DO NOTHING
};
return State;
}();
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var IdleState =
/*#__PURE__*/
function (_super) {
__extends(IdleState, _super);
function IdleState() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.type = STATE_TYPE.IDLE;
_this.holding = false;
_this.playing = false;
return _this;
}
var __proto = IdleState.prototype;
__proto.onEnter = function () {
this.direction = null;
this.targetPanel = null;
this.delta = 0;
this.lastPosition = 0;
};
__proto.onHold = function (e, _a) {
var flicking = _a.flicking,
viewport = _a.viewport,
triggerEvent = _a.triggerEvent,
transitTo = _a.transitTo; // Shouldn't do any action until any panels on flicking area
if (flicking.getPanelCount() <= 0) {
if (viewport.options.infinite) {
viewport.moveCamera(viewport.getCameraPosition(), e);
}
transitTo(STATE_TYPE.DISABLED);
return;
}
this.lastPosition = viewport.getCameraPosition();
triggerEvent(EVENTS.HOLD_START, e, true).onSuccess(function () {
transitTo(STATE_TYPE.HOLDING);
}).onStopped(function () {
transitTo(STATE_TYPE.DISABLED);
});
}; // By methods call
__proto.onChange = function (e, context) {
var triggerEvent = context.triggerEvent,
transitTo = context.transitTo;
triggerEvent(EVENTS.MOVE_START, e, false).onSuccess(function () {
// Trigger AnimatingState's onChange, to trigger "move" event immediately
transitTo(STATE_TYPE.ANIMATING).onChange(e, context);
}).onStopped(function () {
transitTo(STATE_TYPE.DISABLED);
});
};
return IdleState;
}(State);
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var HoldingState =
/*#__PURE__*/
function (_super) {
__extends(HoldingState, _super);
function HoldingState() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.type = STATE_TYPE.HOLDING;
_this.holding = true;
_this.playing = true;
_this.releaseEvent = null;
return _this;
}
var __proto = HoldingState.prototype;
__proto.onChange = function (e, context) {
var flicking = context.flicking,
triggerEvent = context.triggerEvent,
transitTo = context.transitTo;
var offset = flicking.options.horizontal ? e.inputEvent.offsetX : e.inputEvent.offsetY;
this.direction = offset < 0 ? DIRECTION.NEXT : DIRECTION.PREV;
triggerEvent(EVENTS.MOVE_START, e, true).onSuccess(function () {
// Trigger DraggingState's onChange, to trigger "move" event immediately
transitTo(STATE_TYPE.DRAGGING).onChange(e, context);
}).onStopped(function () {
transitTo(STATE_TYPE.DISABLED);
});
};
__proto.onRelease = function (e, context) {
var viewport = context.viewport,
triggerEvent = context.triggerEvent,
transitTo = context.transitTo;
triggerEvent(EVENTS.HOLD_END, e, true);
if (e.delta.flick !== 0) {
// Sometimes "release" event on axes triggered before "change" event
// Especially if user flicked panel fast in really short amount of time
// if delta is not zero, that means above case happened.
// Event flow should be HOLD_START -> MOVE_START -> MOVE -> HOLD_END
// At least one move event should be included between holdStart and holdEnd
e.setTo({
flick: viewport.getCameraPosition()
}, 0);
transitTo(STATE_TYPE.IDLE);
return;
} // Can't handle select event here,
// As "finish" axes event happens
this.releaseEvent = e;
};
__proto.onFinish = function (e, _a) {
var viewport = _a.viewport,
triggerEvent = _a.triggerEvent,
transitTo = _a.transitTo; // Should transite to IDLE state before select event
// As user expects hold is already finished
transitTo(STATE_TYPE.IDLE);
if (!this.releaseEvent) {
return;
} // Handle release event here
// To prevent finish event called twice
var releaseEvent = this.releaseEvent; // Static click
var srcEvent = releaseEvent.inputEvent.srcEvent;
var clickedElement;
if (srcEvent.type === "touchend") {
var touchEvent = srcEvent;
var touch = touchEvent.changedTouches[0];
clickedElement = document.elementFromPoint(touch.clientX, touch.clientY);
} else {
clickedElement = srcEvent.target;
}
var clickedPanel = viewport.panelManager.findPanelOf(clickedElement);
var cameraPosition = viewport.getCameraPosition();
if (clickedPanel) {
var clickedPanelPosition = clickedPanel.getPosition();
var direction = clickedPanelPosition > cameraPosition ? DIRECTION.NEXT : clickedPanelPosition < cameraPosition ? DIRECTION.PREV : null; // Don't provide axes event, to use axes instance instead
triggerEvent(EVENTS.SELECT, null, true, {
direction: direction,
index: clickedPanel.getIndex(),
panel: clickedPanel
});
}
};
return HoldingState;
}(State);
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var DraggingState =
/*#__PURE__*/
function (_super) {
__extends(DraggingState, _super);
function DraggingState() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.type = STATE_TYPE.DRAGGING;
_this.holding = true;
_this.playing = true;
return _this;
}
var __proto = DraggingState.prototype;
__proto.onChange = function (e, _a) {
var moveCamera = _a.moveCamera,
transitTo = _a.transitTo;
if (!e.delta.flick) {
return;
}
moveCamera(e).onStopped(function () {
transitTo(STATE_TYPE.DISABLED);
});
};
__proto.onRelease = function (e, context) {
var flicking = context.flicking,
viewport = context.viewport,
triggerEvent = context.triggerEvent,
transitTo = context.transitTo,
stopCamera = context.stopCamera;
var delta = this.delta;
var absDelta = Math.abs(delta);
var options = flicking.options;
var horizontal = options.horizontal;
var moveType = viewport.moveType;
var inputEvent = e.inputEvent;
var velocity = horizontal ? inputEvent.velocityX : inputEvent.velocityY;
var inputDelta = horizontal ? inputEvent.deltaX : inputEvent.deltaY;
var isNextDirection = Math.abs(velocity) > 1 ? velocity < 0 : absDelta > 0 ? delta > 0 : inputDelta < 0;
var swipeDistance = viewport.options.bound ? Math.max(absDelta, Math.abs(inputDelta)) : absDelta;
var swipeAngle = inputEvent.deltaX ? Math.abs(180 * Math.atan(inputEvent.deltaY / inputEvent.deltaX) / Math.PI) : 90;
var belowAngleThreshold = horizontal ? swipeAngle <= options.thresholdAngle : swipeAngle > options.thresholdAngle;
var overThreshold = swipeDistance >= options.threshold && belowAngleThreshold;
var moveTypeContext = {
viewport: viewport,
axesEvent: e,
state: this,
swipeDistance: swipeDistance,
isNextDirection: isNextDirection
}; // Update last position to cope with Axes's animating behavior
// Axes uses start position when animation start
triggerEvent(EVENTS.HOLD_END, e, true);
var targetPanel = this.targetPanel;
if (!overThreshold && targetPanel) {
// Interrupted while animating
var interruptDestInfo = moveType.findPanelWhenInterrupted(moveTypeContext);
viewport.moveTo(interruptDestInfo.panel, interruptDestInfo.destPos, interruptDestInfo.eventType, e, interruptDestInfo.duration);
transitTo(STATE_TYPE.ANIMATING);
return;
}
var currentPanel = viewport.getCurrentPanel();
var nearestPanel = viewport.getNearestPanel();
if (!currentPanel || !nearestPanel) {
// There're no panels
e.stop();
transitTo(STATE_TYPE.IDLE);
return;
}
var destInfo = overThreshold ? moveType.findTargetPanel(moveTypeContext) : moveType.findRestorePanel(moveTypeContext);
viewport.moveTo(destInfo.panel, destInfo.destPos, destInfo.eventType, e, destInfo.duration).onSuccess(function () {
transitTo(STATE_TYPE.ANIMATING);
}).onStopped(function () {
transitTo(STATE_TYPE.DISABLED);
stopCamera(e);
});
};
return DraggingState;
}(State);
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var AnimatingState =
/*#__PURE__*/
function (_super) {
__extends(AnimatingState, _super);
function AnimatingState() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.type = STATE_TYPE.ANIMATING;
_this.holding = false;
_this.playing = true;
return _this;
}
var __proto = AnimatingState.prototype;
__proto.onHold = function (e, _a) {
var viewport = _a.viewport,
triggerEvent = _a.triggerEvent,
transitTo = _a.transitTo;
var options = viewport.options;
var scrollArea = viewport.getScrollArea();
var scrollAreaSize = viewport.getScrollAreaSize();
var loopCount = Math.floor((this.lastPosition + this.delta - scrollArea.prev) / scrollAreaSize);
var targetPanel = this.targetPanel;
if (options.circular && loopCount !== 0 && targetPanel) {
var cloneCount = viewport.panelManager.getCloneCount();
var originalTargetPosition = targetPanel.getPosition(); // cloneIndex is from -1 to cloneCount - 1
var newCloneIndex = circulate(targetPanel.getCloneIndex() - loopCount, -1, cloneCount - 1, true);
var newTargetPosition = originalTargetPosition - loopCount * scrollAreaSize;
var newTargetPanel = targetPanel.getIdenticalPanels()[newCloneIndex + 1].clone(newCloneIndex, true); // Set new target panel considering looped count
newTargetPanel.setPosition(newTargetPosition);
this.targetPanel = newTargetPanel;
} // Reset last position and delta
this.delta = 0;
this.lastPosition = viewport.getCameraPosition(); // Update current panel as current nearest panel
viewport.setCurrentPanel(viewport.getNearestPanel());
triggerEvent(EVENTS.HOLD_START, e, true).onSuccess(function () {
transitTo(STATE_TYPE.DRAGGING);
}).onStopped(function () {
transitTo(STATE_TYPE.DISABLED);
});
};
__proto.onChange = function (e, _a) {
var moveCamera = _a.moveCamera,
transitTo = _a.transitTo;
if (!e.delta.flick) {
return;
}
moveCamera(e).onStopped(function () {
transitTo(STATE_TYPE.DISABLED);
});
};
__proto.onFinish = function (e, _a) {
var flicking = _a.flicking,
viewport = _a.viewport,
triggerEvent = _a.triggerEvent,
transitTo = _a.transitTo;
var isTrusted = e && e.isTrusted;
viewport.options.bound ? viewport.setCurrentPanel(this.targetPanel) : viewport.setCurrentPanel(viewport.getNearestPanel());
if (flicking.options.adaptive) {
viewport.updateAdaptiveSize();
}
transitTo(STATE_TYPE.IDLE);
triggerEvent(EVENTS.MOVE_END, e, isTrusted, {
direction: this.direction
});
};
return AnimatingState;
}(State);
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var DisabledState =
/*#__PURE__*/
function (_super) {
__extends(DisabledState, _super);
function DisabledState() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.type = STATE_TYPE.DISABLED;
_this.holding = false;
_this.playing = true;
return _this;
}
var __proto = DisabledState.prototype;
__proto.onAnimationEnd = function (e, _a) {
var transitTo = _a.transitTo;
transitTo(STATE_TYPE.IDLE);
};
__proto.onChange = function (e, _a) {
var viewport = _a.viewport,
transitTo = _a.transitTo; // Can stop Axes's change event
e.stop(); // Should update axes position as it's already changed at this moment
viewport.updateAxesPosition(viewport.getCameraPosition());
transitTo(STATE_TYPE.IDLE);
};
__proto.onRelease = function (e, _a) {
var transitTo = _a.transitTo; // This is needed when stopped hold start event
if (e.delta.flick === 0) {
transitTo(STATE_TYPE.IDLE);
}
};
return DisabledState;
}(State);
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var StateMachine =
/*#__PURE__*/
function () {
function StateMachine() {
var _this = this;
this.state = new IdleState();
this.transitTo = function (nextStateType) {
var currentState = _this.state;
if (currentState.type !== nextStateType) {
var nextState = void 0;
switch (nextStateType) {
case STATE_TYPE.IDLE:
nextState = new IdleState();
break;
case STATE_TYPE.HOLDING:
nextState = new HoldingState();
break;
case STATE_TYPE.DRAGGING:
nextState = new DraggingState();
break;
case STATE_TYPE.ANIMATING:
nextState = new AnimatingState();
break;
case STATE_TYPE.DISABLED:
nextState = new DisabledState();
break;
}
currentState.onExit(nextState);
nextState.onEnter(currentState);
_this.state = nextState;
}
return _this.state;
};
}
var __proto = StateMachine.prototype;
__proto.fire = function (eventType, e, context) {
var currentState = this.state;
switch (eventType) {
case AXES_EVENTS.HOLD:
currentState.onHold(e, context);
break;
case AXES_EVENTS.CHANGE:
currentState.onChange(e, context);
break;
case AXES_EVENTS.RELEASE:
currentState.onRelease(e, context);
break;
case AXES_EVENTS.ANIMATION_END:
currentState.onAnimationEnd(e, context);
break;
case AXES_EVENTS.FINISH:
currentState.onFinish(e, context);
break;
}
};
__proto.getState = function () {
return this.state;
};
return StateMachine;
}();
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var MoveType =
/*#__PURE__*/
function () {
function MoveType() {}
var __proto = MoveType.prototype;
__proto.is = function (type) {
return type === this.type;
};
__proto.findRestorePanel = function (ctx) {
var viewport = ctx.viewport;
var options = viewport.options;
var panel = options.circular ? this.findRestorePanelInCircularMode(ctx) : viewport.getCurrentPanel();
return {
panel: panel,
destPos: viewport.findEstimatedPosition(panel),
duration: options.duration,
eventType: EVENTS.RESTORE
};
};
__proto.findPanelWhenInterrupted = function (ctx) {
var state = ctx.state,
viewport = ctx.viewport;
var targetPanel = state.targetPanel;
return {
panel: targetPanel,
destPos: viewport.findEstimatedPosition(targetPanel),
duration: viewport.options.duration,
eventType: ""
};
}; // Calculate minimum distance to "change" panel
__proto.calcBrinkOfChange = function (ctx) {
var viewport = ctx.viewport,
isNextDirection = ctx.isNextDirection;
var options = viewport.options;
var currentPanel = viewport.getCurrentPanel();
var halfGap = options.gap / 2;
var relativeAnchorPosition = currentPanel.getRelativeAnchorPosition(); // Minimum distance needed to decide prev/next panel as nearest
/*
* | Prev | Next |
* |--------|--------------|
* [][ |<-Anchor ][] <- Panel + Half-Gap
*/
var minimumDistanceToChange = isNextDirection ? currentPanel.getSize() - relativeAnchorPosition + halfGap : relativeAnchorPosition + halfGap;
minimumDistanceToChange = Math.max(minimumDistanceToChange, options.threshold);
return minimumDistanceToChange;
};
__proto.findRestorePanelInCircularMode = function (ctx) {
var viewport = ctx.viewport;
var originalPanel = viewport.getCurrentPanel().getOriginalPanel();
var hangerPosition = viewport.getHangerPosition();
var firstClonedPanel = originalPanel.getIdenticalPanels()[1];
var lapped = Math.abs(originalPanel.getAnchorPosition() - hangerPosition) > Math.abs(firstClonedPanel.getAnchorPosition() - hangerPosition);
return !ctx.isNextDirection && lapped ? firstClonedPanel : originalPanel;
};
return MoveType;
}();
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var Snap =
/*#__PURE__*/
function (_super) {
__extends(Snap, _super);
function Snap(count) {
var _this = _super.call(this) || this;
_this.type = MOVE_TYPE.SNAP;
_this.count = count;
return _this;
}
var __proto = Snap.prototype;
__proto.findTargetPanel = function (ctx) {
var viewport = ctx.viewport,
axesEvent = ctx.axesEvent,
swipeDistance = ctx.swipeDistance;
var snapCount = this.count;
var eventDelta = Math.abs(axesEvent.delta.flick);
var currentPanel = viewport.getCurrentPanel();
var nearestPanel = viewport.getNearestPanel();
var minimumDistanceToChange = this.calcBrinkOfChange(ctx);
var nearestIsCurrent = nearestPanel.getIndex() === currentPanel.getIndex(); // This can happen when bounce is 0
var shouldMoveWhenBounceIs0 = viewport.canSetBoundMode() && nearestIsCurrent;
var shouldMoveToAdjacent = !viewport.isOutOfBound() && (swipeDistance <= minimumDistanceToChange || shouldMoveWhenBounceIs0);
if (snapCount > 1 && eventDelta > minimumDistanceToChange) {
return this.findSnappedPanel(ctx);
} else if (shouldMoveToAdjacent) {
return this.findAdjacentPanel(ctx);
} else {
return {
panel: nearestPanel,
duration: viewport.options.duration,
destPos: viewport.findEstimatedPosition(nearestPanel),
// As swipeDistance holds mouse/touch position change regardless of bounce option value
// swipDistance > minimumDistanceToChange can happen in bounce area
// Second condition is for handling that.
eventType: swipeDistance <= minimumDistanceToChange || viewport.isOutOfBound() && nearestIsCurrent ? EVENTS.RESTORE : EVENTS.CHANGE
};
}
};
__proto.findSnappedPanel = function (ctx) {
var axesEvent = ctx.axesEvent,
viewport = ctx.viewport,
state = ctx.state,
isNextDirection = ctx.isNextDirection;
var eventDelta = Math.abs(axesEvent.delta.flick);
var minimumDistanceToChange = this.calcBrinkOfChange(ctx);
var snapCount = this.count;
var options = viewport.options;
var scrollAreaSize = viewport.getScrollAreaSize();
var halfGap = options.gap / 2;
var estimatedHangerPos = axesEvent.destPos.flick + viewport.getRelativeHangerPosition();
var panelToMove = viewport.getNearestPanel();
var cycleIndex = panelToMove.getCloneIndex() + 1; // 0(original) or 1(clone)
var passedPanelCount = 0;
while (passedPanelCount < snapCount) {
// Since panelToMove holds also cloned panels, we should use original panel's position
var originalPanel = panelToMove.getOriginalPanel();
var panelPosition = originalPanel.getPosition() + cycleIndex * scrollAreaSize;
var panelSize = originalPanel.getSize();
var panelNextPosition = panelPosition + panelSize + halfGap;
var panelPrevPosition = panelPosition - halfGap; // Current panelToMove contains destPos
if (isNextDirection && panelNextPosition > estimatedHangerPos || !isNextDirection && panelPrevPosition < estimatedHangerPos) {
break;
}
var siblingPanel = isNextDirection ? panelToMove.nextSibling : panelToMove.prevSibling;
if (!siblingPanel) {
break;
}
var panelIndex = panelToMove.getIndex();
var siblingIndex = siblingPanel.getIndex();
if (isNextDirection && siblingIndex <= panelIndex || !isNextDirection && siblingIndex >= panelIndex) {
cycleIndex = isNextDirection ? cycleIndex + 1 : cycleIndex - 1;
}
panelToMove = siblingPanel;
passedPanelCount += 1;
}
var originalPosition = panelToMove.getOriginalPanel().getPosition();
if (cycleIndex !== 0) {
panelToMove = panelToMove.clone(panelToMove.getCloneIndex(), true);
panelToMove.setPosition(originalPosition + cycleIndex * scrollAreaSize);
}
var defaultDuration = viewport.options.duration;
var duration = clamp(axesEvent.duration, defaultDuration, defaultDuration * passedPanelCount);
return {
panel: panelToMove,
destPos: viewport.findEstimatedPosition(panelToMove),
duration: duration,
eventType: Math.max(eventDelta, state.delta) > minimumDistanceToChange ? EVENTS.CHANGE : EVENTS.RESTORE
};
};
__proto.findAdjacentPanel = function (ctx) {
var viewport = ctx.viewport,
isNextDirection = ctx.isNextDirection;
var options = viewport.options;
var currentIndex = viewport.getCurrentIndex();
var currentPanel = viewport.panelManager.get(currentIndex);
var hangerPosition = viewport.getHangerPosition();
var scrollArea = viewport.getScrollArea();
var firstClonedPanel = currentPanel.getIdenticalPanels()[1];
var lapped = options.circular && Math.abs(currentPanel.getAnchorPosition() - hangerPosition) > Math.abs(firstClonedPanel.getAnchorPosition() - hangerPosition); // If lapped in circular mode, use first cloned panel as base panel
var basePanel = lapped ? firstClonedPanel : currentPanel;
var basePosition = basePanel.getPosition();
var adjacentPanel = isNextDirection ? basePanel.nextSibling : basePanel.prevSibling;
var eventType = adjacentPanel ? EVENTS.CHANGE : EVENTS.RESTORE;
var panelToMove = adjacentPanel ? adjacentPanel : basePanel;
var targetRelativeAnchorPosition = panelToMove.getRelativeAnchorPosition();
var estimatedPanelPosition = options.circular ? isNextDirection ? basePosition + basePanel.getSize() + targetRelativeAnchorPosition + options.gap : basePosition - (panelToMove.getSize() - targetRelativeAnchorPosition) - options.gap : panelToMove.getAnchorPosition();
var estimatedPosition = estimatedPanelPosition - viewport.getRelativeHangerPosition();
var destPos = viewport.canSetBoundMode() ? clamp(estimatedPosition, scrollArea.prev, scrollArea.next) : estimatedPosition;
return {
panel: panelToMove,
destPos: destPos,
duration: options.duration,
eventType: eventType
};
};
return Snap;
}(MoveType);
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var FreeScroll =
/*#__PURE__*/
function (_super) {
__extends(FreeScroll, _super);
function FreeScroll() {
var _this = // Set snap count to Infinity
_super.call(this, Infinity) || this;
_this.type = MOVE_TYPE.FREE_SCROLL;
return _this;
}
var __proto = FreeScroll.prototype;
__proto.findTargetPanel = function (ctx) {
var axesEvent = ctx.axesEvent,
state = ctx.state,
viewport = ctx.viewport;
var destPos = axesEvent.destPos.flick;
var minimumDistanceToChange = this.calcBrinkOfChange(ctx);
var scrollArea = viewport.getScrollArea();
var currentPanel = viewport.getCurrentPanel();
var options = viewport.options;
var delta = Math.abs(axesEvent.delta.flick + state.delta);
if (delta > minimumDistanceToChange) {
var destInfo = _super.prototype.findSnappedPanel.call(this, ctx);
destInfo.duration = axesEvent.duration;
destInfo.destPos = destPos;
destInfo.eventType = !options.circular && destInfo.panel === currentPanel ? "" : EVENTS.CHANGE;
return destInfo;
} else {
var estimatedPosition = options.circular ? circulate(destPos, scrollArea.prev, scrollArea.next, false) : destPos;
estimatedPosition = clamp(estimatedPosition, scrollArea.prev, scrollArea.next);
estimatedPosition += viewport.getRelativeHangerPosition();
var estimatedPanel = viewport.findNearestPanelAt(estimatedPosition);
return {
panel: estimatedPanel,
destPos: destPos,
duration: axesEvent.duration,
eventType: ""
};
}
};
__proto.findRestorePanel = function (ctx) {
return this.findTargetPanel(ctx);
};
__proto.findPanelWhenInterrupted = function (ctx) {
var viewport = ctx.viewport;
return {
panel: viewport.getNearestPanel(),
destPos: viewport.getCameraPosition(),
duration: 0,
eventType: ""
};
};
__proto.calcBrinkOfChange = function (ctx) {
var viewport = ctx.viewport,
isNextDirection = ctx.isNextDirection;
var options = viewport.options;
var currentPanel = viewport.getCurrentPanel();
var halfGap = options.gap / 2;
var lastPosition = viewport.stateMachine.getState().lastPosition;
var currentPanelPosition = currentPanel.getPosition(); // As camera can stop anywhere in free scroll mode,
// minimumDistanceToChange should be calculated differently.
// Ref #191(https://github.com/naver/egjs-flicking/issues/191)
var lastHangerPosition = lastPosition + viewport.getRelativeHangerPosition();
var scrollAreaSize = viewport.getScrollAreaSize();
var minimumDistanceToChange = isNextDirection ? currentPanelPosition + currentPanel.getSize() - lastHangerPosition + halfGap : lastHangerPosition - currentPanelPosition + halfGap;
minimumDistanceToChange = Math.abs(minimumDistanceToChange % scrollAreaSize);
return Math.min(minimumDistanceToChange, scrollAreaSize - minimumDistanceToChange);
};
return FreeScroll;
}(Snap);
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
var Viewport =
/*#__PURE__*/
function () {
function Viewport(flicking, options, triggerEvent) {
var _this = this;
this.plugins = [];
this.stopCamera = function (axesEvent) {
if (axesEvent && axesEvent.setTo) {
axesEvent.setTo({
flick: _this.state.position
}, 0);
}
_this.stateMachine.transitTo(STATE_TYPE.IDLE);
};
this.flicking = flicking;
this.triggerEvent = triggerEvent;
this.state = {
size: 0,
position: 0,
panelMaintainRatio: 0,
relativeHangerPosition: 0,
positionOffset: 0,
scrollArea: {
prev: 0,
next: 0
},
visibleIndex: {
min: NaN,
max: NaN
},
translate: TRANSFORM$1,
infiniteThreshold: 0,
checkedIndexes: [],
isAdaptiveCached: false,
isViewportGiven: false,
isCameraGiven: false,
originalViewportStyle: {
className: null,
style: null
},
originalCameraStyle: {
className: null,
style: null
},
cachedBbox: null
};
this.options = options;
this.stateMachine = new StateMachine();
this.visiblePanels = [];
this.panelBboxes = {};
this.build();
}
var __proto = Viewport.prototype;
__proto.moveTo = function (panel, destPos, eventType, axesEvent, duration) {
var _this = this;
if (duration === void 0) {
duration = this.options.duration;
}
var state = this.state;
var currentState = this.stateMachine.getState();
var currentPosition = state.position;
var isTrusted = axesEvent ? axesEvent.isTrusted : false;
var direction = destPos === currentPosition ? null : destPos > currentPosition ? DIRECTION.NEXT : DIRECTION.PREV;
var eventResult;
if (eventType === EVENTS.CHANGE) {
eventResult = this.triggerEvent(EVENTS.CHANGE, axesEvent, isTrusted, {
index: panel.getIndex(),
panel: panel,
direction: direction
});
} else if (eventType === EVENTS.RESTORE) {
eventResult = this.triggerEvent(EVENTS.RESTORE, axesEvent, isTrusted);
} else {
eventResult = {
onSuccess: function (callback) {
callback();
return this;
},
onStopped: function () {
return this;
}
};
}
eventResult.onSuccess(function () {
currentState.delta = 0;
currentState.lastPosition = _this.getCameraPosition();
currentState.targetPanel = panel;
currentState.direction = destPos === currentPosition ? null : destPos > currentPosition ? DIRECTION.NEXT : DIRECTION.PREV;
if (destPos === currentPosition) {
// no move
_this.nearestPanel = panel;
_this.currentPanel = panel;
}
if (axesEvent && axesEvent.setTo) {
// freeScroll only occurs in release events
axesEvent.setTo({
flick: destPos
}, duration);
} else {
_this.axes.setTo({
flick: destPos
}, duration);
}
});
return eventResult;
};
__proto.moveCamera = function (pos, axesEvent) {
var state = this.state;
var options = this.options;
var transform = state.translate.name;
var scrollArea = state.scrollArea; // Update position & nearestPanel
if (options.circular && !isBetween(pos, scrollArea.prev, scrollArea.next)) {
pos = circulate(pos, scrollArea.prev, scrollArea.next, false);
}
state.position = pos;
this.nearestPanel = this.findNearestPanel();
var nearestPanel = this.nearestPanel;
var originalNearestPosition = nearestPanel ? nearestPanel.getPosition() : 0; // From 0(panel position) to 1(panel position + panel size)
// When it's on gap area value will be (val > 1 || val < 0)
if (nearestPanel) {
var hangerPosition = this.getHangerPosition();
var panelPosition = nearestPanel.getPosition();
var panelSize = nearestPanel.getSize();
var halfGap = options.gap / 2; // As panel's range is from panel position - half gap ~ panel pos + panel size + half gap
state.panelMaintainRatio = (hangerPosition - panelPosition + halfGap) / (panelSize + 2 * halfGap);
} else {
state.panelMaintainRatio = 0;
}
this.checkNeedPanel(axesEvent); // Possibly modified after need panel, if it's looped
var modifiedNearestPosition = nearestPanel ? nearestPanel.getPosition() : 0;
pos += modifiedNearestPosition - originalNearestPosition;
state.position = pos;
this.updateVisiblePanels(); // Offset is needed to fix camera layer size in visible-only rendering mode
var posOffset = options.renderOnlyVisible ? state.positionOffset : 0;
var moveVector = options.horizontal ? [-(pos - posOffset), 0] : [0, -(pos - posOffset)];
var moveCoord = moveVector.map(function (coord) {
return Math.round(coord) + "px";
}).join(", ");
this.cameraElement.style[transform] = state.translate.has3d ? "translate3d(" + moveCoord + ", 0px)" : "translate(" + moveCoord + ")";
};
__proto.unCacheBbox = function () {
var state = this.state;
var options = this.options;
state.cachedBbox = null;
state.visibleIndex = {
min: NaN,
max: NaN
};
var viewportElement = this.viewportElement;
if (!options.horizontal) {
// Don't preserve previous width for adaptive resizing
viewportElement.style.width = "";
} else {
viewportElement.style.height = "";
}
state.isAdaptiveCached = false;
this.panelBboxes = {};
};
__proto.resize = function () {
this.updateSize();
this.updateOriginalPanelPositions();
this.updateAdaptiveSize();
this.updateScrollArea();
this.updateClonePanels();
this.updateCameraPosition();
this.updatePlugins();
}; // Find nearest anchor from current hanger position
__proto.findNearestPanel = function () {
var state = this.state;
var panelManager = this.panelManager;
var hangerPosition = this.getHangerPosition();
if (this.isOutOfBound()) {
var position = state.position;
return position <= state.scrollArea.prev ? panelManager.firstPanel() : panelManager.lastPanel();
}
return this.findNearestPanelAt(hangerPosition);
};
__proto.findNearestPanelAt = function (position) {
var panelManager = this.panelManager;
var allPanels = panelManager.allPanels();
var minimumDistance = Infinity;
var nearestPanel;
for (var _i = 0, allPanels_1 = allPanels; _i < allPanels_1.length; _i++) {
var panel = allPanels_1[_i];
if (!panel) {
continue;
}
var prevPosition = panel.getPosition();
var nextPosition = prevPosition + panel.getSize(); // Use shortest distance from panel's range
var distance = isBetween(position, prevPosition, nextPosition) ? 0 : Math.min(Math.abs(prevPosition - position), Math.abs(nextPosition - position));
if (distance > minimumDistance) {
break;
} else if (distance === minimumDistance) {
var minimumAnchorDistance = Math.abs(position - nearestPanel.getAnchorPosition());
var anchorDistance = Math.abs(position - panel.getAnchorPosition());
if (anchorDistance > minimumAnchorDistance) {
break;
}
}
minimumDistance = distance;
nearestPanel = panel;
}
return nearestPanel;
};
__proto.findNearestIdenticalPanel = function (panel) {
var nearest = panel;
var shortestDistance = Infinity;
var hangerPosition = this.getHangerPosition();
var identicals = panel.getIdenticalPanels();
identicals.forEach(function (identical) {
var anchorPosition = identical.getAnchorPosition();
var distance = Math.abs(anchorPosition - hangerPosition);
if (distance < shortestDistance) {
nearest = identical;
shortestDistance = distance;
}
});
return nearest;
}; // Find shortest camera position that distance is minimum
__proto.findShortestPositionToPanel = function (panel) {
var state = this.state;
var options = this.options;
var anchorPosition = panel.getAnchorPosition();
var hangerPosition = this.getHangerPosition();
var distance = Math.abs(hangerPosition - anchorPosition);
var scrollAreaSize = state.scrollArea.next - state.scrollArea.prev;
if (!options.circular) {
var position = anchorPosition - state.relativeHangerPosition;
return this.canSetBoundMode() ? clamp(position, state.scrollArea.prev, state.scrollArea.next) : position;
} else {
// If going out of viewport border is more efficient way of moving, choose that position
return distance <= scrollAreaSize - distance ? anchorPosition - state.relativeHangerPosition : anchorPosition > hangerPosition // PREV TO NEXT
? anchorPosition - state.relativeHangerPosition - scrollAreaSize // NEXT TO PREV
: anchorPosition - state.relativeHangerPosition + scrollAreaSize;
}
};
__proto.findEstimatedPosition = function (panel) {
var scrollArea = this.getScrollArea();
var estimatedPosition = panel.getAnchorPosition() - this.getRelativeHangerPosition();
estimatedPosition = this.canSetBoundMode() ? clamp(estimatedPosition, scrollArea.prev, scrollArea.next) : estimatedPosition;
return estimatedPosition;
};
__proto.addVisiblePanel = function (panel) {
if (this.getVisibleIndexOf(panel) < 0) {
this.visiblePanels.push(panel);
}
};
__proto.enable = function () {
this.panInput.enable();
};
__proto.disable = function () {
this.panInput.disable();
};
__proto.insert = function (index, element) {
var _this = this;
var lastIndex = this.panelManager.getLastIndex(); // Index should not below 0
if (index < 0 || index > lastIndex) {
return [];
}
var state = this.state;
var options = this.options;
var parsedElements = parseElement(element);
var panels = parsedElements.map(function (el, idx) {
return new Panel(el, index + idx, _this);
}).slice(0, lastIndex - index + 1);
if (panels.length <= 0) {
return [];
}
var pushedIndex = this.panelManager.insert(index, panels); // ...then calc bbox for all panels
this.resizePanels(panels);
if (!this.currentPanel) {
this.currentPanel = panels[0];
this.nearestPanel = panels[0];
var newCenterPanel = panels[0];
var newPanelPosition = this.findEstimatedPosition(newCenterPanel);
state.position = newPanelPosition;
this.updateAxesPosition(newPanelPosition);
state.panelMaintainRatio = (newCenterPanel.getRelativeAnchorPosition() + options.gap / 2) / (newCenterPanel.getSize() + options.gap);
} // Update checked indexes in infinite mode
this.updateCheckedIndexes({
min: index,
max: index
});
state.checkedIndexes.forEach(function (indexes, idx) {
var min = indexes[0],
max = indexes[1];
if (index < min) {
// Push checked index
state.checkedIndexes.splice(idx, 1, [min + pushedIndex, max + pushedIndex]);
}
}); // Uncache visible index to refresh panels
state.visibleIndex = {
min: NaN,
max: NaN
};
this.resize();
return panels;
};
__proto.replace = function (index, element) {
var _this = this;
var state = this.state;
var options = this.options;
var panelManager = this.panelManager;
var lastIndex = panelManager.getLastIndex(); // Index should not below 0
if (index < 0 || index > lastIndex) {
return [];
}
var parsedElements = parseElement(element);
var panels = parsedElements.map(function (el, idx) {
return new Panel(el, index + idx, _this);
}).slice(0, lastIndex - index + 1);
if (panels.length <= 0) {
return [];
}
var replacedPanels = panelManager.replace(index, panels);
replacedPanels.forEach(function (panel) {
var visibleIndex = _this.getVisibleIndexOf(panel);
if (visibleIndex > -1) {
_this.visiblePanels.splice(visibleIndex, 1);
}
}); // ...then calc bbox for all panels
this.resizePanels(panels);
var currentPanel = this.currentPanel;
var wasEmpty = !currentPanel;
if (wasEmpty) {
this.currentPanel = panels[0];
this.nearestPanel = panels[0];
var newCenterPanel = panels[0];
var newPanelPosition = this.findEstimatedPosition(newCenterPanel);
state.position = newPanelPosition;
this.updateAxesPosition(newPanelPosition);
state.panelMaintainRatio = (newCenterPanel.getRelativeAnchorPosition() + options.gap / 2) / (newCenterPanel.getSize() + options.gap);
} else if (isBetween(currentPanel.getIndex(), index, index + panels.length - 1)) {
// Current panel is replaced
this.currentPanel = panelManager.get(currentPanel.getIndex());
} // Update checked indexes in infinite mode
this.updateCheckedIndexes({
min: index,
max: index + panels.length - 1
}); // Uncache visible index to refresh panels
state.visibleIndex = {
min: NaN,
max: NaN
};
this.resize();
return panels;
};
__proto.remove = function (index, deleteCount) {
if (deleteCount === void 0) {
deleteCount = 1;
}
var state = this.state; // Index should not below 0
index = Math.max(index, 0);
var panelManager = this.panelManager;
var currentIndex = this.getCurrentIndex();
var removedPanels = panelManager.remove(index, deleteCount);
if (isBetween(currentIndex, index, index + deleteCount - 1)) {
// Current panel is removed
// Use panel at removing index - 1 as new current panel if it exists
var newCurrentIndex = Math.max(index - 1, panelManager.getRange().min);
this.currentPanel = panelManager.get(newCurrentIndex);
} // Update checked indexes in infinite mode
if (deleteCount > 0) {
// Check whether removing index will affect checked indexes
// Suppose index 0 is empty and removed index 1, then checked index 0 should be deleted and vice versa.
this.updateCheckedIndexes({
min: index - 1,
max: index + deleteCount
}); // Uncache visible index to refresh panels
state.visibleIndex = {
min: NaN,
max: NaN
};
}
if (panelManager.getPanelCount() <= 0) {
this.currentPanel = undefined;
this.nearestPanel = undefined;
}
this.resize();
var scrollArea = state.scrollArea;
if (state.position < scrollArea.prev || state.position > scrollArea.next) {
var newPosition = circulate(state.position, scrollArea.prev, scrollArea.next, false);
this.moveCamera(newPosition);
this.updateAxesPosition(newPosition);
}
return removedPanels;
};
__proto.updateAdaptiveSize = function () {
var state = this.state;
var options = this.options;
var horizontal = options.horizontal;
var currentPanel = this.getCurrentPanel();
if (!currentPanel) {
return;
}
var shouldApplyAdaptive = options.adaptive || !state.isAdaptiveCached;
var viewportStyle = this.viewportElement.style;
if (shouldApplyAdaptive) {
var sizeToApply = void 0;
if (options.adaptive) {
var panelBbox = currentPanel.getBbox();
sizeToApply = horizontal ? panelBbox.height : panelBbox.width;
} else {
// Find minimum height of panels to maximum panel size
var maximumPanelSize = this.panelManager.originalPanels().reduce(function (maximum, panel) {
var panelBbox = panel.getBbox();
return Math.max(maximum, horizontal ? panelBbox.height : panelBbox.width);
}, 0);
sizeToApply = maximumPanelSize;
}
var viewportBbox = this.updateBbox();
sizeToApply = Math.max(sizeToApply, horizontal ? viewportBbox.height : viewportBbox.width);
state.isAdaptiveCached = true;
var viewportSize = sizeToApply + "px";
if (horizontal) {
viewportStyle.height = viewportSize;
state.cachedBbox.height = sizeToApply;
} else {
viewportStyle.width = viewportSize;
state.cachedBbox.width = sizeToApply;
}
}
};
__proto.updateBbox = function () {
var state = this.state;
var options = this.options;
var viewportElement = this.viewportElement;
if (!state.cachedBbox) {
state.cachedBbox = getBbox(viewportElement, options.useOffset);
}
return state.cachedBbox;
};
__proto.updatePlugins = function () {
var _this = this; // update for resize
this.plugins.forEach(function (plugin) {
plugin.update && plugin.update(_this.flicking);
});
};
__proto.destroy = function (option) {
var state = this.state;
var wrapper = this.flicking.getElement();
var viewportElement = this.viewportElement;
var cameraElement = this.cameraElement;
var originalPanels = this.panelManager.originalPanels();
this.removePlugins(this.plugins);
if (!option.preserveUI) {
restoreStyle(viewportElement, state.originalViewportStyle);
restoreStyle(cameraElement, state.originalCameraStyle);
if (!state.isCameraGiven && !this.options.renderExternal) {
var topmostElement_1 = state.isViewportGiven ? viewportElement : wrapper;
var deletingElement = state.isViewportGiven ? cameraElement : viewportElement;
originalPanels.forEach(function (panel) {
topmostElement_1.appendChild(panel.getElement());
});
topmostElement_1.removeChild(deletingElement);
}
}
this.axes.destroy();
this.panInput.destroy();
originalPanels.forEach(function (panel) {
panel.destroy(option);
}); // release resources
for (var x in this) {
this[x] = null;
}
};
__proto.restore = function (status) {
var panels = status.panels;
var defaultIndex = this.options.defaultIndex;
var cameraElement = this.cameraElement;
var panelManager = this.panelManager; // Restore index
cameraElement.innerHTML = panels.map(function (panel) {
return panel.html;
}).join(""); // Create panels first
this.refreshPanels();
var createdPanels = panelManager.originalPanels(); // ...then order it by its index
var orderedPanels = [];
panels.forEach(function (panel, idx) {
var createdPanel = createdPanels[idx];
createdPanel.setIndex(panel.index);
orderedPanels[panel.index] = createdPanel;
});
panelManager.replacePanels(orderedPanels, []);
panelManager.setCloneCount(0); // No clones at this point
var panelCount = panelManager.getPanelCount();
if (panelCount > 0) {
this.currentPanel = panelManager.get(status.index) || panelManager.get(defaultIndex) || panelManager.firstPanel();
this.nearestPanel = this.currentPanel;
} else {
this.currentPanel = undefined;
this.nearestPanel = undefined;
}
this.visiblePanels = orderedPanels.filter(function (panel) {
return Boolean(panel);
});
this.resize();
this.axes.setTo({
flick: status.position
}, 0);
this.moveCamera(status.position);
};
__proto.calcVisiblePanels = function () {
var allPanels = this.panelManager.allPanels();
if (this.options.renderOnlyVisible) {
var _a = this.state.visibleIndex,
min = _a.min,
max = _a.max;
var visiblePanels = min >= 0 ? allPanels.slice(min, max + 1) : allPanels.slice(0, max + 1).concat(allPanels.slice(min));
return visiblePanels.filter(function (panel) {
return panel;
});
} else {
return allPanels.filter(function (panel) {
var outsetProgress = panel.getOutsetProgress();
return outsetProgress > -1 && outsetProgress < 1;
});
}
};
__proto.getCurrentPanel = function () {
return this.currentPanel;
};
__proto.getCurrentIndex = function () {
var currentPanel = this.currentPanel;
return currentPanel ? currentPanel.getIndex() : -1;
};
__proto.getNearestPanel = function () {
return this.nearestPanel;
}; // Get progress from nearest panel
__proto.getCurrentProgress = function () {
var currentState = this.stateMachine.getState();
var nearestPanel = currentState.playing || currentState.holding ? this.nearestPanel : this.currentPanel;
var panelManager = this.panelManager;
if (!nearestPanel) {
// There're no panels
return NaN;
}
var _a = this.getScrollArea(),
prevRange = _a.prev,
nextRange = _a.next;
var cameraPosition = this.getCameraPosition();
var isOutOfBound = this.isOutOfBound();
var prevPanel = nearestPanel.prevSibling;
var nextPanel = nearestPanel.nextSibling;
var hangerPosition = this.getHangerPosition();
var nearestAnchorPos = nearestPanel.getAnchorPosition();
if (isOutOfBound && prevPanel && nextPanel && cameraPosition < nextRange // On the basis of anchor, prevPanel is nearestPanel.
&& hangerPosition - prevPanel.getAnchorPosition() < nearestAnchorPos - hangerPosition) {
nearestPanel = prevPanel;
nextPanel = nearestPanel.nextSibling;
prevPanel = nearestPanel.prevSibling;
nearestAnchorPos = nearestPanel.getAnchorPosition();
}
var nearestIndex = nearestPanel.getIndex() + (nearestPanel.getCloneIndex() + 1) * panelManager.getPanelCount();
var nearestSize = nearestPanel.getSize();
if (isOutOfBound) {
var relativeHangerPosition = this.getRelativeHangerPosition();
if (nearestAnchorPos > nextRange + relativeHangerPosition) {
// next bounce area: hangerPosition - relativeHangerPosition - nextRange
hangerPosition = nearestAnchorPos + hangerPosition - relativeHangerPosition - nextRange;
} else if (nearestAnchorPos < prevRange + relativeHangerPosition) {
// prev bounce area: hangerPosition - relativeHangerPosition - prevRange
hangerPosition = nearestAnchorPos + hangerPosition - relativeHangerPosition - prevRange;
}
}
var hangerIsNextToNearestPanel = hangerPosition >= nearestAnchorPos;
var gap = this.options.gap;
var basePosition = nearestAnchorPos;
var targetPosition = nearestAnchorPos;
if (hangerIsNextToNearestPanel) {
targetPosition = nextPanel ? nextPanel.getAnchorPosition() : nearestAnchorPos + nearestSize + gap;
} else {
basePosition = prevPanel ? prevPanel.getAnchorPosition() : nearestAnchorPos - nearestSize - gap;
}
var progressBetween = (hangerPosition - basePosition) / (targetPosition - basePosition);
var startIndex = hangerIsNextToNearestPanel ? nearestIndex : prevPanel ? prevPanel.getIndex() : nearestIndex - 1;
return startIndex + progressBetween;
}; // Update axes flick position without triggering event
__proto.updateAxesPosition = function (position) {
var axes = this.axes;
axes.off();
axes.setTo({
flick: position
}, 0);
axes.on(this.axesHandlers);
};
__proto.getSize = function () {
return this.state.size;
};
__proto.getScrollArea = function () {
return this.state.scrollArea;
};
__proto.isOutOfBound = function () {
var state = this.state;
var options = this.options;
var scrollArea = state.scrollArea;
return !options.circular && options.bound && (state.position <= scrollArea.prev || state.position >= scrollArea.next);
};
__proto.canSetBoundMode = function () {
var options = this.options;
return options.bound && !options.circular;
};
__proto.getViewportElement = function () {
return this.viewportElement;
};
__proto.getCameraElement = function () {
return this.cameraElement;
};
__proto.getScrollAreaSize = function () {
var scrollArea = this.state.scrollArea;
return scrollArea.next - scrollArea.prev;
};
__proto.getRelativeHangerPosition = function () {
return this.state.relativeHangerPosition;
};
__proto.getHangerPosition = function () {
return this.state.position + this.state.relativeHangerPosition;
};
__proto.getCameraPosition = function () {
return this.state.position;
};
__proto.getPositionOffset = function () {
return this.state.positionOffset;
};
__proto.getCheckedIndexes = function () {
return this.state.checkedIndexes;
};
__proto.getVisibleIndex = function () {
return this.state.visibleIndex;
};
__proto.getVisiblePanels = function () {
return this.visiblePanels;
};
__proto.setCurrentPanel = function (panel) {
this.currentPanel = panel;
};
__proto.setLastIndex = function (index) {
var currentPanel = this.currentPanel;
var panelManager = this.panelManager;
panelManager.setLastIndex(index);
if (currentPanel && currentPanel.getIndex() > index) {
this.currentPanel = panelManager.lastPanel();
}
this.resize();
};
__proto.setVisiblePanels = function (panels) {
this.visiblePanels = panels;
};
__proto.connectAxesHandler = function (handlers) {
var axes = this.axes;
this.axesHandlers = handlers;
axes.on(handlers);
};
__proto.addPlugins = function (plugins) {
var _this = this;
var newPlugins = [].concat(plugins);
newPlugins.forEach(function (plugin) {
plugin.init(_this.flicking);
});
this.plugins = this.plugins.concat(newPlugins);
return this;
};
__proto.removePlugins = function (plugins) {
var _this = this;
var currentPlugins = this.plugins;
var removedPlugins = [].concat(plugins);
removedPlugins.forEach(function (plugin) {
var index = currentPlugins.indexOf(plugin);
if (index > -1) {
currentPlugins.splice(index, 1);
}
plugin.destroy(_this.flicking);
});
return this;
};
__proto.updateCheckedIndexes = function (changedRange) {
var state = this.state;
var removed = 0;
state.checkedIndexes.concat().forEach(function (indexes, idx) {
var min = indexes[0],
max = indexes[1]; // Can fill part of indexes in range
if (changedRange.min <= max && changedRange.max >= min) {
// Remove checked index from list
state.checkedIndexes.splice(idx - removed, 1);
removed++;
}
});
};
__proto.resetVisibleIndex = function () {
var visibleIndex = this.state.visibleIndex;
visibleIndex.min = NaN;
visibleIndex.max = NaN;
};
__proto.appendUncachedPanelElements = function (panels) {
var _this = this;
var options = this.options;
var fragment = document.createDocumentFragment();
if (options.isEqualSize) {
var prevVisiblePanels = this.visiblePanels;
var equalSizeClasses_1 = options.isEqualSize; // for readability
var cached_1 = {};
this.visiblePanels = [];
Object.keys(this.panelBboxes).forEach(function (className) {
cached_1[className] = true;
});
panels.forEach(function (panel) {
var overlappedClass = panel.getOverlappedClass(equalSizeClasses_1);
if (overlappedClass && !cached_1[overlappedClass]) {
if (!options.renderExternal) {
fragment.appendChild(panel.getElement());
}
_this.visiblePanels.push(panel);
cached_1[overlappedClass] = true;
} else if (!overlappedClass) {
if (!options.renderExternal) {
fragment.appendChild(panel.getElement());
}
_this.visiblePanels.push(panel);
}
});
prevVisiblePanels.forEach(function (panel) {
_this.addVisiblePanel(panel);
});
} else {
if (!options.renderExternal) {
panels.forEach(function (panel) {
return fragment.appendChild(panel.getElement());
});
}
this.visiblePanels = panels.filter(function (panel) {
return Boolean(panel);
});
}
if (!options.renderExternal) {
this.cameraElement.appendChild(fragment);
}
};
__proto.updateClonePanels = function () {
var panelManager = this.panelManager; // Clone panels in circular mode
if (this.options.circular && panelManager.getPanelCount() > 0) {
this.clonePanels();
this.updateClonedPanelPositions();
}
panelManager.chainAllPanels();
};
__proto.getVisibleIndexOf = function (panel) {
return findIndex(this.visiblePanels, function (visiblePanel) {
return visiblePanel === panel;
});
};
__proto.build = function () {
this.setElements();
this.applyCSSValue();
this.setMoveType();
this.setAxesInstance();
this.refreshPanels();
this.setDefaultPanel();
this.resize();
this.moveToDefaultPanel();
};
__proto.setElements = function () {
var state = this.state;
var options = this.options;
var wrapper = this.flicking.getElement();
var classPrefix = options.classPrefix;
var viewportCandidate = wrapper.children[0];
var hasViewportElement = viewportCandidate && hasClass(viewportCandidate, classPrefix + "-viewport");
var viewportElement = hasViewportElement ? viewportCandidate : document.createElement("div");
var cameraCandidate = hasViewportElement ? viewportElement.children[0] : wrapper.children[0];
var hasCameraElement = cameraCandidate && hasClass(cameraCandidate, classPrefix + "-camera");
var cameraElement = hasCameraElement ? cameraCandidate : document.createElement("div");
if (!hasCameraElement) {
cameraElement.className = classPrefix + "-camera";
var panelElements = hasViewportElement ? viewportElement.children : wrapper.children; // Make all panels to be a child of camera element
// wrapper <- viewport <- camera <- panels[1...n]
toArray$2(panelElements).forEach(function (child) {
cameraElement.appendChild(child);
});
} else {
state.originalCameraStyle = {
className: cameraElement.getAttribute("class"),
style: cameraElement.getAttribute("style")
};
}
if (!hasViewportElement) {
viewportElement.className = classPrefix + "-viewport"; // Add viewport element to wrapper
wrapper.appendChild(viewportElement);
} else {
state.originalViewportStyle = {
className: viewportElement.getAttribute("class"),
style: viewportElement.getAttribute("style")
};
}
if (!hasCameraElement || !hasViewportElement) {
viewportElement.appendChild(cameraElement);
}
this.viewportElement = viewportElement;
this.cameraElement = cameraElement;
state.isViewportGiven = hasViewportElement;
state.isCameraGiven = hasCameraElement;
};
__proto.applyCSSValue = function () {
var options = this.options;
var viewportElement = this.viewportElement;
var cameraElement = this.cameraElement;
var viewportStyle = this.viewportElement.style; // Set default css values for each element
applyCSS(viewportElement, DEFAULT_VIEWPORT_CSS);
applyCSS(cameraElement, DEFAULT_CAMERA_CSS);
viewportElement.style.zIndex = "" + options.zIndex;
if (options.horizontal) {
viewportStyle.minHeight = "100%";
viewportStyle.width = "100%";
} else {
viewportStyle.minWidth = "100%";
viewportStyle.height = "100%";
}
if (options.overflow) {
viewportStyle.overflow = "visible";
}
this.panelManager = new PanelManager(this.cameraElement, options);
};
__proto.setMoveType = function () {
var moveType = this.options.moveType;
switch (moveType.type) {
case MOVE_TYPE.SNAP:
this.moveType = new Snap(moveType.count);
break;
case MOVE_TYPE.FREE_SCROLL:
this.moveType = new FreeScroll();
break;
default:
throw new Error("moveType is not correct!");
}
};
__proto.setAxesInstance = function () {
var state = this.state;
var options = this.options;
var scrollArea = state.scrollArea;
var horizontal = options.horizontal;
this.axes = new Axes({
flick: {
range: [scrollArea.prev, scrollArea.next],
circular: options.circular,
bounce: [0, 0]
}
}, {
easing: options.panelEffect,
deceleration: options.deceleration,
interruptable: true
});
this.panInput = new PanInput(this.viewportElement, {
inputType: options.inputType,
thresholdAngle: options.thresholdAngle,
scale: options.horizontal ? [-1, 0] : [0, -1]
});
this.axes.connect(horizontal ? ["flick", ""] : ["", "flick"], this.panInput);
};
__proto.refreshPanels = function () {
var _this = this;
var panelManager = this.panelManager; // Panel elements were attached to camera element by Flicking class
var panelElements = this.cameraElement.children; // Initialize panels
var panels = toArray$2(panelElements).map(function (el, idx) {
return new Panel(el, idx, _this);
});
panelManager.replacePanels(panels, []);
this.visiblePanels = panels.filter(function (panel) {
return Boolean(panel);
});
};
__proto.setDefaultPanel = function () {
var options = this.options;
var panelManager = this.panelManager;
var indexRange = this.panelManager.getRange();
var index = clamp(options.defaultIndex, indexRange.min, indexRange.max);
this.currentPanel = panelManager.get(index);
};
__proto.clonePanels = function () {
var state = this.state;
var options = this.options;
var panelManager = this.panelManager;
var gap = options.gap;
var viewportSize = state.size;
var firstPanel = panelManager.firstPanel();
var lastPanel = panelManager.lastPanel(); // There're no panels exist
if (!firstPanel) {
return;
} // For each panels, clone itself while last panel's position + size is below viewport size
var panels = panelManager.originalPanels();
var reversedPanels = panels.concat().reverse();
var sumOriginalPanelSize = lastPanel.getPosition() + lastPanel.getSize() - firstPanel.getPosition() + gap;
var relativeAnchorPosition = firstPanel.getRelativeAnchorPosition();
var relativeHangerPosition = this.getRelativeHangerPosition();
var areaPrev = (relativeHangerPosition - relativeAnchorPosition) % sumOriginalPanelSize;
var sizeSum = 0;
var panelAtLeftBoundary;
for (var _i = 0, reversedPanels_1 = reversedPanels; _i < reversedPanels_1.length; _i++) {
var panel = reversedPanels_1[_i];
if (!panel) {
continue;
}
sizeSum += panel.getSize() + gap;
if (sizeSum >= areaPrev) {
panelAtLeftBoundary = panel;
break;
}
}
var areaNext = (viewportSize - relativeHangerPosition + relativeAnchorPosition) % sumOriginalPanelSize;
sizeSum = 0;
var panelAtRightBoundary;
for (var _a = 0, panels_1 = panels; _a < panels_1.length; _a++) {
var panel = panels_1[_a];
if (!panel) {
continue;
}
sizeSum += panel.getSize() + gap;
if (sizeSum >= areaNext) {
panelAtRightBoundary = panel;
break;
}
} // Need one more set of clones on prev area of original panel 0
var needCloneOnPrev = panelAtLeftBoundary.getIndex() !== 0 && panelAtLeftBoundary.getIndex() <= panelAtRightBoundary.getIndex(); // Visible count of panel 0 on first screen
var panel0OnFirstscreen = Math.ceil((relativeHangerPosition + firstPanel.getSize() - relativeAnchorPosition) / sumOriginalPanelSize) + Math.ceil((viewportSize - relativeHangerPosition + relativeAnchorPosition) / sumOriginalPanelSize) - 1; // duplication
var cloneCount = panel0OnFirstscreen + (needCloneOnPrev ? 1 : 0);
var prevCloneCount = panelManager.getCloneCount();
panelManager.setCloneCount(cloneCount);
if (options.renderExternal) {
return;
}
if (cloneCount > prevCloneCount) {
var _loop_1 = function (cloneIndex) {
var clones = panels.map(function (origPanel) {
return origPanel.clone(cloneIndex);
});
var fragment = document.createDocumentFragment();
clones.forEach(function (panel) {
return fragment.appendChild(panel.getElement());
});
this_1.cameraElement.appendChild(fragment);
(_a = this_1.visiblePanels).push.apply(_a, clones.filter(function (clone) {
return Boolean(clone);
}));
panelManager.insertClones(cloneIndex, 0, clones);
var _a;
};
var this_1 = this; // should clone more
for (var cloneIndex = prevCloneCount; cloneIndex < cloneCount; cloneIndex++) {
_loop_1(cloneIndex);
}
} else if (cloneCount < prevCloneCount) {
// should remove some
panelManager.removeClonesAfter(cloneCount);
}
};
__proto.moveToDefaultPanel = function () {
var state = this.state;
var panelManager = this.panelManager;
var options = this.options;
var indexRange = this.panelManager.getRange();
var defaultIndex = clamp(options.defaultIndex, indexRange.min, indexRange.max);
var defaultPanel = panelManager.get(defaultIndex);
var defaultPosition = 0;
if (defaultPanel) {
defaultPosition = defaultPanel.getAnchorPosition() - state.relativeHangerPosition;
defaultPosition = this.canSetBoundMode() ? clamp(defaultPosition, state.scrollArea.prev, state.scrollArea.next) : defaultPosition;
}
this.moveCamera(defaultPosition);
this.axes.setTo({
flick: defaultPosition
}, 0);
};
__proto.updateSize = function () {
var state = this.state;
var options = this.options;
var panels = this.panelManager.originalPanels().filter(function (panel) {
return Boolean(panel);
});
var bbox = this.updateBbox();
var prevSize = state.size; // Update size & hanger position
state.size = options.horizontal ? bbox.width : bbox.height;
if (prevSize !== state.size) {
state.relativeHangerPosition = parseArithmeticExpression(options.hanger, state.size);
state.infiniteThreshold = parseArithmeticExpression(options.infiniteThreshold, state.size);
}
if (panels.length <= 0) {
return;
}
this.resizePanels(panels);
};
__proto.updateOriginalPanelPositions = function () {
var gap = this.options.gap;
var panelManager = this.panelManager;
var firstPanel = panelManager.firstPanel();
var panels = panelManager.originalPanels();
if (!firstPanel) {
return;
}
var currentPanel = this.currentPanel;
var nearestPanel = this.nearestPanel;
var currentState = this.stateMachine.getState();
var scrollArea = this.state.scrollArea; // Update panel position && fit to wrapper
var nextPanelPos = firstPanel.getPosition();
var maintainingPanel = firstPanel;
if (nearestPanel) {
// We should maintain nearestPanel's position
var looped = !isBetween(currentState.lastPosition + currentState.delta, scrollArea.prev, scrollArea.next);
maintainingPanel = looped ? currentPanel : nearestPanel;
} else if (firstPanel.getIndex() > 0) {
maintainingPanel = currentPanel;
}
var panelsBeforeMaintainPanel = panels.slice(0, maintainingPanel.getIndex() + (maintainingPanel.getCloneIndex() + 1) * panels.length);
var accumulatedSize = panelsBeforeMaintainPanel.reduce(function (total, panel) {
return total + panel.getSize() + gap;
}, 0);
nextPanelPos = maintainingPanel.getPosition() - accumulatedSize;
panels.forEach(function (panel) {
var newPosition = nextPanelPos;
var panelSize = panel.getSize();
panel.setPosition(newPosition);
nextPanelPos += panelSize + gap;
});
if (!this.options.renderOnlyVisible) {
panels.forEach(function (panel) {
return panel.setPositionCSS();
});
}
};
__proto.updateClonedPanelPositions = function () {
var state = this.state;
var options = this.options;
var panelManager = this.panelManager;
var clonedPanels = panelManager.clonedPanels().reduce(function (allClones, clones) {
return allClones.concat(clones);
}, []).filter(function (panel) {
return Boolean(panel);
});
var scrollArea = state.scrollArea;
var firstPanel = panelManager.firstPanel();
var lastPanel = panelManager.lastPanel();
if (!firstPanel) {
return;
}
var sumOriginalPanelSize = lastPanel.getPosition() + lastPanel.getSize() - firstPanel.getPosition() + options.gap; // Locate all cloned panels linearly first
for (var _i = 0, clonedPanels_1 = clonedPanels; _i < clonedPanels_1.length; _i++) {
var panel = clonedPanels_1[_i];
var origPanel = panel.getOriginalPanel();
var cloneIndex = panel.getCloneIndex();
var cloneBasePos = sumOriginalPanelSize * (cloneIndex + 1);
var clonedPanelPos = cloneBasePos + origPanel.getPosition();
panel.setPosition(clonedPanelPos);
}
var lastReplacePosition = firstPanel.getPosition(); // reverse() pollutes original array, so copy it with concat()
for (var _a = 0, _b = clonedPanels.concat().reverse(); _a < _b.length; _a++) {
var panel = _b[_a];
var panelSize = panel.getSize();
var replacePosition = lastReplacePosition - panelSize - options.gap;
if (replacePosition + panelSize <= scrollArea.prev) {
// Replace is not meaningful, as it won't be seen in current scroll area
break;
}
panel.setPosition(replacePosition);
lastReplacePosition = replacePosition;
}
if (!this.options.renderOnlyVisible) {
clonedPanels.forEach(function (panel) {
panel.setPositionCSS();
});
}
};
__proto.updateScrollArea = function () {
var state = this.state;
var panelManager = this.panelManager;
var options = this.options;
var axes = this.axes; // Set viewport scrollable area
var firstPanel = panelManager.firstPanel();
var lastPanel = panelManager.lastPanel();
var relativeHangerPosition = state.relativeHangerPosition;
if (!firstPanel) {
state.scrollArea = {
prev: 0,
next: 0
};
} else if (this.canSetBoundMode()) {
var sumOriginalPanelSize = lastPanel.getPosition() + lastPanel.getSize() - firstPanel.getPosition();
if (sumOriginalPanelSize >= state.size) {
state.scrollArea = {
prev: firstPanel.getPosition(),
next: lastPanel.getPosition() + lastPanel.getSize() - state.size
};
} else {
// Find anchor position of set of the combined panels
var relAnchorPosOfCombined = parseArithmeticExpression(options.anchor, sumOriginalPanelSize);
var anchorPos = firstPanel.getPosition() + clamp(relAnchorPosOfCombined, sumOriginalPanelSize - (state.size - relativeHangerPosition), relativeHangerPosition);
state.scrollArea = {
prev: anchorPos - relativeHangerPosition,
next: anchorPos - relativeHangerPosition
};
}
} else if (options.circular) {
var sumOriginalPanelSize = lastPanel.getPosition() + lastPanel.getSize() - firstPanel.getPosition() + options.gap; // Maximum scroll extends to first clone sequence's first panel
state.scrollArea = {
prev: firstPanel.getAnchorPosition() - relativeHangerPosition,
next: sumOriginalPanelSize + firstPanel.getAnchorPosition() - relativeHangerPosition
};
} else {
state.scrollArea = {
prev: firstPanel.getAnchorPosition() - relativeHangerPosition,
next: lastPanel.getAnchorPosition() - relativeHangerPosition
};
}
var viewportSize = state.size;
var bounce = options.bounce;
var parsedBounce;
if (isArray(bounce)) {
parsedBounce = bounce.map(function (val) {
return parseArithmeticExpression(val, viewportSize, DEFAULT_OPTIONS.bounce);
});
} else {
var parsedVal = parseArithmeticExpression(bounce, viewportSize, DEFAULT_OPTIONS.bounce);
parsedBounce = [parsedVal, parsedVal];
} // Update axes range and bounce
var flick = axes.axis.flick;
flick.range = [state.scrollArea.prev, state.scrollArea.next];
flick.bounce = parsedBounce;
}; // Update camera position after resizing
__proto.updateCameraPosition = function () {
var state = this.state;
var currentPanel = this.getCurrentPanel();
var currentState = this.stateMachine.getState();
var isFreeScroll = this.moveType.is(MOVE_TYPE.FREE_SCROLL);
var relativeHangerPosition = this.getRelativeHangerPosition();
var halfGap = this.options.gap / 2;
if (currentState.holding || currentState.playing) {
this.updateVisiblePanels();
return;
}
var newPosition;
if (isFreeScroll) {
var nearestPanel = this.getNearestPanel();
newPosition = nearestPanel ? nearestPanel.getPosition() - halfGap + (nearestPanel.getSize() + 2 * halfGap) * state.panelMaintainRatio - relativeHangerPosition : this.getCameraPosition();
} else {
newPosition = currentPanel ? currentPanel.getAnchorPosition() - relativeHangerPosition : this.getCameraPosition();
}
if (this.canSetBoundMode()) {
newPosition = clamp(newPosition, state.scrollArea.prev, state.scrollArea.next);
} // Pause & resume axes to prevent axes's "change" event triggered
// This should be done before moveCamera, as moveCamera can trigger needPanel
this.updateAxesPosition(newPosition);
this.moveCamera(newPosition);
};
__proto.checkNeedPanel = function (axesEvent) {
var state = this.state;
var options = this.options;
var panelManager = this.panelManager;
var currentPanel = this.currentPanel;
var nearestPanel = this.nearestPanel;
var currentState = this.stateMachine.getState();
if (!options.infinite) {
return;
}
var gap = options.gap;
var infiniteThreshold = state.infiniteThreshold;
var maxLastIndex = panelManager.getLastIndex();
if (maxLastIndex < 0) {
return;
}
if (!currentPanel || !nearestPanel) {
// There're no panels
this.triggerNeedPanel({
axesEvent: axesEvent,
siblingPanel: null,
direction: null,
indexRange: {
min: 0,
max: maxLastIndex,
length: maxLastIndex + 1
}
});
return;
}
var originalNearestPosition = nearestPanel.getPosition(); // Check next direction
var checkingPanel = !currentState.holding && !currentState.playing ? currentPanel : nearestPanel;
while (checkingPanel) {
var currentIndex = checkingPanel.getIndex();
var nextSibling = checkingPanel.nextSibling;
var lastPanel = panelManager.lastPanel();
var atLastPanel = currentIndex === lastPanel.getIndex();
var nextIndex = !atLastPanel && nextSibling ? nextSibling.getIndex() : maxLastIndex + 1;
var currentNearestPosition = nearestPanel.getPosition();
var panelRight = checkingPanel.getPosition() + checkingPanel.getSize() - (currentNearestPosition - originalNearestPosition);
var cameraNext = state.position + state.size; // There're empty panels between
var emptyPanelExistsBetween = nextIndex - currentIndex > 1; // Expected prev panel's left position is smaller than camera position
var overThreshold = panelRight + gap - infiniteThreshold <= cameraNext;
if (emptyPanelExistsBetween && overThreshold) {
this.triggerNeedPanel({
axesEvent: axesEvent,
siblingPanel: checkingPanel,
direction: DIRECTION.NEXT,
indexRange: {
min: currentIndex + 1,
max: nextIndex - 1,
length: nextIndex - currentIndex - 1
}
});
} // Trigger needPanel in circular & at max panel index
if (options.circular && currentIndex === maxLastIndex && overThreshold) {
var firstPanel = panelManager.firstPanel();
var firstIndex = firstPanel ? firstPanel.getIndex() : -1;
if (firstIndex > 0) {
this.triggerNeedPanel({
axesEvent: axesEvent,
siblingPanel: checkingPanel,
direction: DIRECTION.NEXT,
indexRange: {
min: 0,
max: firstIndex - 1,
length: firstIndex
}
});
}
} // Check whether panels are changed
var lastPanelAfterNeed = panelManager.lastPanel();
var atLastPanelAfterNeed = lastPanelAfterNeed && currentIndex === lastPanelAfterNeed.getIndex();
if (atLastPanelAfterNeed || !overThreshold) {
break;
}
checkingPanel = checkingPanel.nextSibling;
} // Check prev direction
checkingPanel = nearestPanel;
while (checkingPanel) {
var cameraPrev = state.position;
var checkingIndex = checkingPanel.getIndex();
var prevSibling = checkingPanel.prevSibling;
var firstPanel = panelManager.firstPanel();
var atFirstPanel = checkingIndex === firstPanel.getIndex();
var prevIndex = !atFirstPanel && prevSibling ? prevSibling.getIndex() : -1;
var currentNearestPosition = nearestPanel.getPosition();
var panelLeft = checkingPanel.getPosition() - (currentNearestPosition - originalNearestPosition); // There're empty panels between
var emptyPanelExistsBetween = checkingIndex - prevIndex > 1; // Expected prev panel's right position is smaller than camera position
var overThreshold = panelLeft - gap + infiniteThreshold >= cameraPrev;
if (emptyPanelExistsBetween && overThreshold) {
this.triggerNeedPanel({
axesEvent: axesEvent,
siblingPanel: checkingPanel,
direction: DIRECTION.PREV,
indexRange: {
min: prevIndex + 1,
max: checkingIndex - 1,
length: checkingIndex - prevIndex - 1
}
});
} // Trigger needPanel in circular & at panel 0
if (options.circular && checkingIndex === 0 && overThreshold) {
var lastPanel = panelManager.lastPanel();
if (lastPanel && lastPanel.getIndex() < maxLastIndex) {
var lastIndex = lastPanel.getIndex();
this.triggerNeedPanel({
axesEvent: axesEvent,
siblingPanel: checkingPanel,
direction: DIRECTION.PREV,
indexRange: {
min: lastIndex + 1,
max: maxLastIndex,
length: maxLastIndex - lastIndex
}
});
}
} // Check whether panels were changed
var firstPanelAfterNeed = panelManager.firstPanel();
var atFirstPanelAfterNeed = firstPanelAfterNeed && checkingIndex === firstPanelAfterNeed.getIndex(); // Looped in circular mode
if (atFirstPanelAfterNeed || !overThreshold) {
break;
}
checkingPanel = checkingPanel.prevSibling;
}
};
__proto.triggerNeedPanel = function (params) {
var _this = this;
var axesEvent = params.axesEvent,
siblingPanel = params.siblingPanel,
direction = params.direction,
indexRange = params.indexRange;
var options = this.options;
var checkedIndexes = this.state.checkedIndexes;
var alreadyTriggered = checkedIndexes.some(function (_a) {
var min = _a[0],
max = _a[1];
return min === indexRange.min || max === indexRange.max;
});
var hasHandler = this.flicking.hasOn(EVENTS.NEED_PANEL);
if (alreadyTriggered || !hasHandler) {
return;
} // Should done before triggering event, as we can directly add panels by event callback
checkedIndexes.push([indexRange.min, indexRange.max]);
var index = siblingPanel ? siblingPanel.getIndex() : 0;
var isTrusted = axesEvent ? axesEvent.isTrusted : false;
this.triggerEvent(EVENTS.NEED_PANEL, axesEvent, isTrusted, {
index: index,
panel: siblingPanel,
direction: direction,
range: indexRange,
fill: function (element) {
var panelManager = _this.panelManager;
if (!siblingPanel) {
return _this.insert(panelManager.getRange().max + 1, element);
}
var parsedElements = parseElement(element); // Slice elements to fit size equal to empty spaces
var elements = direction === DIRECTION.NEXT ? parsedElements.slice(0, indexRange.length) : parsedElements.slice(-indexRange.length);
if (direction === DIRECTION.NEXT) {
if (options.circular && index === panelManager.getLastIndex()) {
// needPanel event is triggered on last index, insert at index 0
return _this.insert(0, elements);
} else {
return siblingPanel.insertAfter(elements);
}
} else if (direction === DIRECTION.PREV) {
if (options.circular && index === 0) {
// needPanel event is triggered on first index(0), insert at the last index
return _this.insert(indexRange.max - elements.length + 1, elements);
} else {
return siblingPanel.insertBefore(elements);
}
} else {
// direction is null when there're no panels exist
return _this.insert(0, elements);
}
}
});
};
__proto.updateVisiblePanels = function () {
var state = this.state;
var options = this.options;
var cameraElement = this.cameraElement;
var visibleIndex = state.visibleIndex;
var renderExternal = options.renderExternal,
renderOnlyVisible = options.renderOnlyVisible;
if (!renderOnlyVisible) {
return;
}
if (!this.nearestPanel) {
this.resetVisibleIndex();
while (cameraElement.firstChild) {
cameraElement.removeChild(cameraElement.firstChild);
}
return;
}
var newVisibleIndex = this.calcNewVisiblePanelIndex();
if (newVisibleIndex.min !== visibleIndex.min || newVisibleIndex.max !== visibleIndex.max) {
state.visibleIndex = newVisibleIndex;
if (isNaN(newVisibleIndex.min) || isNaN(newVisibleIndex.max)) {
return;
}
var prevVisiblePanels = this.visiblePanels;
var newVisiblePanels = this.calcVisiblePanels();
var _a = this.checkVisiblePanelChange(prevVisiblePanels, newVisiblePanels),
addedPanels = _a.addedPanels,
removedPanels = _a.removedPanels;
if (newVisiblePanels.length > 0) {
var firstVisiblePanelPos = newVisiblePanels[0].getPosition();
state.positionOffset = firstVisiblePanelPos;
}
newVisiblePanels.forEach(function (panel) {
panel.setPositionCSS(state.positionOffset);
});
if (!renderExternal) {
removedPanels.forEach(function (panel) {
var panelElement = panel.getElement();
panelElement.parentNode && cameraElement.removeChild(panelElement);
});
var fragment_1 = document.createDocumentFragment();
addedPanels.forEach(function (panel) {
fragment_1.appendChild(panel.getElement());
});
cameraElement.appendChild(fragment_1);
}
this.visiblePanels = newVisiblePanels;
this.flicking.trigger(EVENTS.VISIBLE_CHANGE, {
type: EVENTS.VISIBLE_CHANGE,
range: {
min: newVisibleIndex.min,
max: newVisibleIndex.max
}
});
} else {
this.visiblePanels.forEach(function (panel) {
return panel.setPositionCSS(state.positionOffset);
});
}
};
__proto.calcNewVisiblePanelIndex = function () {
var cameraPos = this.getCameraPosition();
var viewportSize = this.getSize();
var basePanel = this.nearestPanel;
var panelManager = this.panelManager;
var allPanelCount = panelManager.getRange().max + 1;
var cloneCount = panelManager.getCloneCount();
var checkLastPanel = function (panel, getNextPanel, isOutOfViewport) {
var lastPanel = panel;
while (true) {
var nextPanel = getNextPanel(lastPanel);
if (!nextPanel || isOutOfViewport(nextPanel)) {
break;
}
lastPanel = nextPanel;
}
return lastPanel;
};
var lastPanelOfNextDir = checkLastPanel(basePanel, function (panel) {
var nextPanel = panel.nextSibling;
if (nextPanel && nextPanel.getPosition() >= panel.getPosition()) {
return nextPanel;
} else {
return null;
}
}, function (panel) {
return panel.getPosition() >= cameraPos + viewportSize;
});
var lastPanelOfPrevDir = checkLastPanel(basePanel, function (panel) {
var prevPanel = panel.prevSibling;
if (prevPanel && prevPanel.getPosition() <= panel.getPosition()) {
return prevPanel;
} else {
return null;
}
}, function (panel) {
return panel.getPosition() + panel.getSize() <= cameraPos;
});
var minPanelCloneIndex = lastPanelOfPrevDir.getCloneIndex();
var maxPanelCloneOffset = allPanelCount * (lastPanelOfNextDir.getCloneIndex() + 1);
var minPanelCloneOffset = minPanelCloneIndex > -1 ? allPanelCount * (cloneCount - minPanelCloneIndex) : 0;
var newVisibleIndex = {
// Relative index including clone, can be negative number
min: basePanel.getCloneIndex() > -1 ? lastPanelOfPrevDir.getIndex() + minPanelCloneOffset : lastPanelOfPrevDir.getIndex() - minPanelCloneOffset,
// Relative index including clone
max: lastPanelOfNextDir.getIndex() + maxPanelCloneOffset
}; // Stopped on first cloned first panel
if (lastPanelOfPrevDir.getIndex() === 0 && lastPanelOfPrevDir.getCloneIndex() === 0) {
newVisibleIndex.min = allPanelCount;
}
return newVisibleIndex;
};
__proto.checkVisiblePanelChange = function (prevVisiblePanels, newVisiblePanels) {
var prevRefCount = prevVisiblePanels.map(function () {
return 0;
});
var newRefCount = newVisiblePanels.map(function () {
return 0;
});
prevVisiblePanels.forEach(function (prevPanel, prevIndex) {
newVisiblePanels.forEach(function (newPanel, newIndex) {
if (prevPanel === newPanel) {
prevRefCount[prevIndex]++;
newRefCount[newIndex]++;
}
});
});
var removedPanels = prevRefCount.reduce(function (removed, count, index) {
return count === 0 ? removed.concat([prevVisiblePanels[index]]) : removed;
}, []);
var addedPanels = newRefCount.reduce(function (added, count, index) {
return count === 0 ? added.concat([newVisiblePanels[index]]) : added;
}, []);
return {
removedPanels: removedPanels,
addedPanels: addedPanels
};
};
__proto.resizePanels = function (panels) {
var options = this.options;
var panelBboxes = this.panelBboxes;
if (options.isEqualSize === true) {
if (!panelBboxes.default) {
var defaultPanel = panels[0];
panelBboxes.default = defaultPanel.getBbox();
}
var defaultBbox_1 = panelBboxes.default;
panels.forEach(function (panel) {
panel.resize(defaultBbox_1);
});
return;
} else if (options.isEqualSize) {
var equalSizeClasses_2 = options.isEqualSize;
panels.forEach(function (panel) {
var overlappedClass = panel.getOverlappedClass(equalSizeClasses_2);
if (overlappedClass) {
panel.resize(panelBboxes[overlappedClass]);
panelBboxes[overlappedClass] = panel.getBbox();
} else {
panel.resize();
}
});
return;
}
panels.forEach(function (panel) {
panel.resize();
});
};
return Viewport;
}();
var tid = "UA-70842526-24";
var cid = Math.random() * Math.pow(10, 20) / Math.pow(10, 10);
function sendEvent(category, action, label) {
if (!isBrowser) {
return;
}
try {
var innerWidth = window.innerWidth;
var innerHeight = window.innerHeight;
var screen = window.screen || {
width: innerWidth,
height: innerHeight
};
var collectInfos = ["v=1", "t=event", "dl=" + location.href, "ul=" + (navigator.language || "en-us").toLowerCase(), "de=" + (document.charset || document.inputEncoding || document.characterSet || "utf-8"), "dr=" + document.referrer, "dt=" + document.title, "sr=" + screen.width + "x" + screen.height, "vp=" + innerWidth + "x" + innerHeight, "ec=" + category, "ea=" + action, "el=" + JSON.stringify(label), "cid=" + cid, "tid=" + tid, "cd1=3.4.5", "z=" + Math.floor(Math.random() * 10000000)];
var req = new XMLHttpRequest();
req.open("GET", "https://www.google-analytics.com/collect?" + collectInfos.join("&"));
req.send();
} catch (e) {}
}
/**
* Copyright (c) 2015 NAVER Corp.
* egjs projects are licensed under the MIT license
*/
/**
* @memberof eg
* @extends eg.Component
* @support {"ie": "10+", "ch" : "latest", "ff" : "latest", "sf" : "latest" , "edge" : "latest", "ios" : "7+", "an" : "4.X+"}
* @requires {@link https://github.com/naver/egjs-component|eg.Component}
* @requires {@link https://github.com/naver/egjs-axes|eg.Axes}
* @see Easing Functions Cheat Sheet {@link http://easings.net/} <ko>이징 함수 Cheat Sheet {@link http://easings.net/}</ko>
*/
var Flicking =
/*#__PURE__*/
function (_super) {
__extends(Flicking, _super);
/**
* @param element A base element for the eg.Flicking module. When specifying a value as a `string` type, you must specify a css selector string to select the element.<ko>eg.Flicking 모듈을 사용할 기준 요소. `string`타입으로 값 지정시 요소를 선택하기 위한 css 선택자 문자열을 지정해야 한다.</ko>
* @param options An option object of the eg.Flicking module<ko>eg.Flicking 모듈의 옵션 객체</ko>
* @param {string} [options.classPrefix="eg-flick"] A prefix of class names will be added for the panels, viewport, and camera.<ko>패널들과 뷰포트, 카메라에 추가될 클래스 이름의 접두사.</ko>
* @param {number} [options.deceleration=0.0075] Deceleration value for panel movement animation for animation triggered by manual user input. A higher value means a shorter running time.<ko>사용자의 동작으로 가속도가 적용된 패널 이동 애니메이션의 감속도. 값이 높을수록 애니메이션 실행 시간이 짧아진다.</ko>
* @param {boolean} [options.horizontal=true] The direction of panel movement. (true: horizontal, false: vertical)<ko>패널 이동 방향. (true: 가로방향, false: 세로방향)</ko>
* @param {boolean} [options.circular=false] Enables circular mode, which connects first/last panel for continuous scrolling.<ko>순환 모드를 활성화한다. 순환 모드에서는 양 끝의 패널이 서로 연결되어 끊김없는 스크롤이 가능하다.</ko>
* @param {boolean} [options.infinite=false] Enables infinite mode, which can automatically trigger needPanel until reaching the last panel's index reaches the lastIndex.<ko>무한 모드를 활성화한다. 무한 모드에서는 needPanel 이벤트를 자동으로 트리거한다. 해당 동작은 마지막 패널의 인덱스가 lastIndex와 일치할때까지 일어난다.</ko>
* @param {number} [options.infiniteThreshold=0] A Threshold from viewport edge before triggering `needPanel` event in infinite mode.<ko>무한 모드에서 `needPanel`이벤트가 발생하기 위한 뷰포트 끝으로부터의 최대 거리.</ko>
* @param {number} [options.lastIndex=Infinity] Maximum panel index that Flicking can set. Flicking won't trigger `needPanel` when the event's panel index is greater than it.<br/>Also, if the last panel's index reached a given index, you can't add more panels.<ko>Flicking이 설정 가능한 패널의 최대 인덱스. `needPanel` 이벤트에 지정된 인덱스가 최대 패널의 개수보다 같거나 커야 하는 경우에 이벤트를 트리거하지 않게 한다.<br>또한, 마지막 패널의 인덱스가 주어진 인덱스와 동일할 경우, 새로운 패널을 더 이상 추가할 수 없다.</ko>
* @param {number} [options.threshold=40] Movement threshold to change panel(unit: pixel). It should be dragged above the threshold to change the current panel.<ko>패널 변경을 위한 이동 임계값 (단위: 픽셀). 주어진 값 이상으로 스크롤해야만 패널 변경이 가능하다.</ko>
* @param {number} [options.duration=100] Duration of the panel movement animation. (unit: ms)<ko>패널 이동 애니메이션 진행 시간.(단위: ms)</ko>
* @param {function} [options.panelEffect=x => 1 - Math.pow(1 - x, 3)] An easing function applied to the panel movement animation. Default value is `easeOutCubic`.<ko>패널 이동 애니메이션에 적용할 easing함수. 기본값은 `easeOutCubic`이다.</ko>
* @param {number} [options.defaultIndex=0] Index of the panel to set as default when initializing. A zero-based integer.<ko>초기화시 지정할 디폴트 패널의 인덱스로, 0부터 시작하는 정수.</ko>
* @param {string[]} [options.inputType=["touch,"mouse"]] Types of input devices to enable.({@link https://naver.github.io/egjs-axes/release/latest/doc/global.html#PanInputOption Reference})<ko>활성화할 입력 장치 종류. ({@link https://naver.github.io/egjs-axes/release/latest/doc/global.html#PanInputOption 참고})</ko>
* @param {number} [options.thresholdAngle=45] The threshold angle value(0 ~ 90).<br>If the input angle from click/touched position is above or below this value in horizontal and vertical mode each, scrolling won't happen.<ko>스크롤 동작을 막기 위한 임계각(0 ~ 90).<br>클릭/터치한 지점으로부터 계산된 사용자 입력의 각도가 horizontal/vertical 모드에서 각각 크거나 작으면, 스크롤 동작이 이루어지지 않는다.</ko>
* @param {number|string|number[]|string[]} [options.bounce=[10,10]] The size value of the bounce area. Only can be enabled when `circular=false`.<br>You can set different bounce value for prev/next direction by using array.<br>`number` for px value, and `string` for px, and % value relative to viewport size.(ex - 0, "10px", "20%")<ko>바운스 영역의 크기값. `circular=false`인 경우에만 사용할 수 있다.<br>배열을 통해 prev/next 방향에 대해 서로 다른 바운스 값을 지정 가능하다.<br>`number`를 통해 px값을, `stirng`을 통해 px 혹은 뷰포트 크기 대비 %값을 사용할 수 있다.(ex - 0, "10px", "20%")</ko>
* @param {boolean} [options.autoResize=false] Whether the `resize` method should be called automatically after a window resize event.<ko>window의 `resize` 이벤트 이후 자동으로 resize()메소드를 호출할지의 여부.</ko>
* @param {boolean} [options.adaptive=false] Whether the height(horizontal)/width(vertical) of the viewport element reflects the height/width value of the panel after completing the movement.<ko>목적 패널로 이동한 후 그 패널의 높이(horizontal)/너비(vertical)값을 뷰포트 요소의 높이/너비값에 반영할지 여부.</ko>
* @param {number|""} [options.zIndex=2000] z-index value for viewport element.<ko>뷰포트 엘리먼트의 z-index 값.</ko>
* @param {boolean} [options.bound=false] Prevent the view from going out of the first/last panel. Only can be enabled when `circular=false`.<ko>뷰가 첫번째와 마지막 패널 밖으로 나가는 것을 막아준다. `circular=false`인 경우에만 사용할 수 있다.</ko>
* @param {boolean} [options.overflow=false] Disables CSS property `overflow: hidden` in viewport if `true`.<ko>`true`로 설정시 뷰포트에 `overflow: hidden` 속성을 해제한다.</ko>
* @param {string} [options.hanger="50%"] The reference position of the hanger in the viewport, which hangs panel anchors should be stopped at.<br>It should be provided in px or % value of viewport size.<br>You can combinate those values with plus/minus sign.<br>ex) "50", "100px", "0%", "25% + 100px"<ko>뷰포트 내부의 행어의 위치. 패널의 앵커들이 뷰포트 내에서 멈추는 지점에 해당한다.<br>px값이나, 뷰포트의 크기 대비 %값을 사용할 수 있고, 이를 + 혹은 - 기호로 연계하여 사용할 수도 있다.<br>예) "50", "100px", "0%", "25% + 100px"</ko>
* @param {string} [options.anchor="50%"] The reference position of the anchor in panels, which can be hanged by viewport hanger.<br>It should be provided in px or % value of panel size.<br>You can combinate those values with plus/minus sign.<br>ex) "50", "100px", "0%", "25% + 100px"<ko>패널 내부의 앵커의 위치. 뷰포트의 행어와 연계하여 패널이 화면 내에서 멈추는 지점을 설정할 수 있다.<br>px값이나, 패널의 크기 대비 %값을 사용할 수 있고, 이를 + 혹은 - 기호로 연계하여 사용할 수도 있다.<br>예) "50", "100px", "0%", "25% + 100px"</ko>
* @param {number} [options.gap=0] Space value between panels. Should be given in number.(px)<ko>패널간에 부여할 간격의 크기를 나타내는 숫자.(px)</ko>
* @param {eg.Flicking.MoveTypeOption} [options.moveType="snap"] Movement style by user input. (ex: snap, freeScroll)<ko>사용자 입력에 의한 이동 방식.(ex: snap, freeScroll)</ko>
* @param {boolean} [options.useOffset=false] Whether to use `offsetWidth`/`offsetHeight` instead of `getBoundingClientRect` for panel/viewport size calculation.<br/>You can use this option to calculate the original panel size when CSS transform is applied to viewport or panel.<br/>⚠️ If panel size is not fixed integer value, there can be a 1px gap between panels.<ko>패널과 뷰포트의 크기를 계산할 때 `offsetWidth`/`offsetHeight`를 `getBoundingClientRect` 대신 사용할지 여부.<br/>패널이나 뷰포트에 CSS transform이 설정되어 있을 때 원래 패널 크기를 계산하려면 옵션을 활성화한다.<br/>⚠️ 패널의 크기가 정수로 고정되어있지 않다면 패널 사이에 1px의 공간이 생길 수 있다.</ko>
* @param {boolean} [options.renderOnlyVisible] Whether to render visible panels only. This can dramatically increase performance when there're many panels.<ko>보이는 패널만 렌더링할지 여부를 설정한다. 패널이 많을 경우에 퍼포먼스를 크게 향상시킬 수 있다.</ko>
* @param {boolean|string[]} [options.isEqualSize] This option indicates whether all panels have the same size(true) of first panel, or it can hold a list of class names that determines panel size.<br/>Enabling this option can increase performance while recalculating panel size.<ko>모든 패널의 크기가 동일한지(true), 혹은 패널 크기를 결정하는 패널 클래스들의 리스트.<br/>이 옵션을 설정하면 패널 크기 재설정시에 성능을 높일 수 있다.</ko>
* @param {boolean} [options.isConstantSize] Whether all panels have a constant size that won't be changed after resize. Enabling this option can increase performance while recalculating panel size.<ko>모든 패널의 크기가 불변인지의 여부. 이 옵션을 'true'로 설정하면 패널 크기 재설정시에 성능을 높일 수 있다.</ko>
* @param {boolean} [options.renderExternal] Whether to use external rendering. It will delegate DOM manipulation and can synchronize the rendered state by calling `sync()` method. You can use this option to use in frameworks like React, Vue, Angular, which has its states and rendering methods.<ko>외부 렌더링을 사용할 지의 여부. 이 옵션을 사용시 렌더링을 외부에 위임할 수 있고, `sync()`를 호출하여 그 상태를 동기화할 수 있다. 이 옵션을 사용하여, React, Vue, Angular 등 자체적인 상태와 렌더링 방법을 갖는 프레임워크에 대응할 수 있다.</ko>
* @param {boolean} [options.collectStatistics=true] Whether to collect statistics on how you are using `Flicking`. These statistical data do not contain any personal information and are used only as a basis for the development of a user-friendly product.<ko>어떻게 `Flicking`을 사용하고 있는지에 대한 통계 수집 여부를 나타낸다. 이 통계자료는 개인정보를 포함하고 있지 않으며 오직 사용자 친화적인 제품으로 발전시키기 위한 근거자료로서 활용한다.</ko>
*/
function Flicking(element, options) {
if (options === void 0) {
options = {};
}
var _this = _super.call(this) || this;
_this.isPanelChangedAtBeforeSync = false;
/**
* Update panels to current state.
* @ko 패널들을 현재 상태에 맞춰 갱신한다.
* @method
* @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko>
*/
_this.resize = function () {
var viewport = _this.viewport;
var options = _this.options;
var wrapper = _this.getElement();
var allPanels = viewport.panelManager.allPanels();
if (!options.isConstantSize) {
allPanels.forEach(function (panel) {
return panel.unCacheBbox();
});
}
var shouldResetElements = options.renderOnlyVisible && !options.isConstantSize && options.isEqualSize !== true; // Temporarily set parent's height to prevent scroll (#333)
var parent = wrapper.parentElement;
var origStyle = parent.style.height;
parent.style.height = parent.offsetHeight + "px";
viewport.unCacheBbox(); // This should be done before adding panels, to lower performance issue
viewport.updateBbox();
if (shouldResetElements) {
viewport.appendUncachedPanelElements(allPanels);
}
viewport.resize();
parent.style.height = origStyle;
return _this;
};
_this.triggerEvent = function (eventName, axesEvent, isTrusted, params) {
if (params === void 0) {
params = {};
}
var viewport = _this.viewport;
var canceled = true; // Ignore events before viewport is initialized
if (viewport) {
var state = viewport.stateMachine.getState();
var _a = viewport.getScrollArea(),
prev = _a.prev,
next = _a.next;
var pos = viewport.getCameraPosition();
var progress = getProgress(pos, [prev, prev, next]);
if (_this.options.circular) {
progress %= 1;
}
canceled = !_super.prototype.trigger.call(_this, eventName, merge({
type: eventName,
index: _this.getIndex(),
panel: _this.getCurrentPanel(),
direction: state.direction,
holding: state.holding,
progress: progress,
axesEvent: axesEvent,
isTrusted: isTrusted
}, params));
}
return {
onSuccess: function (callback) {
if (!canceled) {
callback();
}
return this;
},
onStopped: function (callback) {
if (canceled) {
callback();
}
return this;
}
};
}; // Return result of "move" event triggered
_this.moveCamera = function (axesEvent) {
var viewport = _this.viewport;
var state = viewport.stateMachine.getState();
var options = _this.options;
var pos = axesEvent.pos.flick;
var previousPosition = viewport.getCameraPosition();
if (axesEvent.isTrusted && state.holding) {
var inputOffset = options.horizontal ? axesEvent.inputEvent.offsetX : axesEvent.inputEvent.offsetY;
var isNextDirection = inputOffset < 0;
var cameraChange = pos - previousPosition;
var looped = isNextDirection === pos < previousPosition;
if (options.circular && looped) {
// Reached at max/min range of axes
var scrollAreaSize = viewport.getScrollAreaSize();
cameraChange = (cameraChange > 0 ? -1 : 1) * (scrollAreaSize - Math.abs(cameraChange));
}
var currentDirection = cameraChange === 0 ? state.direction : cameraChange > 0 ? DIRECTION.NEXT : DIRECTION.PREV;
state.direction = currentDirection;
}
state.delta += axesEvent.delta.flick;
viewport.moveCamera(pos, axesEvent);
return _this.triggerEvent(EVENTS.MOVE, axesEvent, axesEvent.isTrusted).onStopped(function () {
// Undo camera movement
viewport.moveCamera(previousPosition, axesEvent);
});
}; // Set flicking wrapper user provided
var wrapper;
if (isString(element)) {
wrapper = document.querySelector(element);
if (!wrapper) {
throw new Error("Base element doesn't exist.");
}
} else if (element.nodeName && element.nodeType === 1) {
wrapper = element;
} else {
throw new Error("Element should be provided in string or HTMLElement.");
}
_this.wrapper = wrapper; // Override default options
_this.options = merge({}, DEFAULT_OPTIONS, options); // Override moveType option
var currentOptions = _this.options;
var moveType = currentOptions.moveType;
if (moveType in DEFAULT_MOVE_TYPE_OPTIONS) {
currentOptions.moveType = DEFAULT_MOVE_TYPE_OPTIONS[moveType];
} // Make viewport instance with panel container element
_this.viewport = new Viewport(_this, _this.options, _this.triggerEvent);
_this.listenInput();
_this.listenResize();
if (_this.options.collectStatistics) {
sendEvent("usage", "options", options);
}
return _this;
}
/**
* Move to the previous panel if it exists.
* @ko 이전 패널이 존재시 해당 패널로 이동한다.
* @param [duration=options.duration] Duration of the panel movement animation.(unit: ms)<ko>패널 이동 애니메이션 진행 시간.(단위: ms)</ko>
* @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko>
*/
var __proto = Flicking.prototype;
__proto.prev = function (duration) {
var currentPanel = this.getCurrentPanel();
var currentState = this.viewport.stateMachine.getState();
if (currentPanel && currentState.type === STATE_TYPE.IDLE) {
var prevPanel = currentPanel.prev();
if (prevPanel) {
prevPanel.focus(duration);
}
}
return this;
};
/**
* Move to the next panel if it exists.
* @ko 다음 패널이 존재시 해당 패널로 이동한다.
* @param [duration=options.duration] Duration of the panel movement animation(unit: ms).<ko>패널 이동 애니메이션 진행 시간.(단위: ms)</ko>
* @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko>
*/
__proto.next = function (duration) {
var currentPanel = this.getCurrentPanel();
var currentState = this.viewport.stateMachine.getState();
if (currentPanel && currentState.type === STATE_TYPE.IDLE) {
var nextPanel = currentPanel.next();
if (nextPanel) {
nextPanel.focus(duration);
}
}
return this;
};
/**
* Move to the panel of given index.
* @ko 주어진 인덱스에 해당하는 패널로 이동한다.
* @param index The index number of the panel to move.<ko>이동할 패널의 인덱스 번호.</ko>
* @param duration [duration=options.duration] Duration of the panel movement.(unit: ms)<ko>패널 이동 애니메이션 진행 시간.(단위: ms)</ko>
* @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko>
*/
__proto.moveTo = function (index, duration) {
var viewport = this.viewport;
var panel = viewport.panelManager.get(index);
var state = viewport.stateMachine.getState();
if (!panel || state.type !== STATE_TYPE.IDLE) {
return this;
}
var anchorPosition = panel.getAnchorPosition();
var hangerPosition = viewport.getHangerPosition();
var targetPanel = panel;
if (this.options.circular) {
var scrollAreaSize = viewport.getScrollAreaSize(); // Check all three possible locations, find the nearest position among them.
var possiblePositions = [anchorPosition - scrollAreaSize, anchorPosition, anchorPosition + scrollAreaSize];
var nearestPosition = possiblePositions.reduce(function (nearest, current) {
return Math.abs(current - hangerPosition) < Math.abs(nearest - hangerPosition) ? current : nearest;
}, Infinity) - panel.getRelativeAnchorPosition();
var identicals = panel.getIdenticalPanels();
var offset = nearestPosition - anchorPosition;
if (offset > 0) {
// First cloned panel is nearest
targetPanel = identicals[1];
} else if (offset < 0) {
// Last cloned panel is nearest
targetPanel = identicals[identicals.length - 1];
}
targetPanel = targetPanel.clone(targetPanel.getCloneIndex(), true);
targetPanel.setPosition(nearestPosition);
}
var currentIndex = this.getIndex();
if (hangerPosition === targetPanel.getAnchorPosition() && currentIndex === index) {
return this;
}
var eventType = panel.getIndex() === viewport.getCurrentIndex() ? "" : EVENTS.CHANGE;
viewport.moveTo(targetPanel, viewport.findEstimatedPosition(targetPanel), eventType, null, duration);
return this;
};
/**
* Return index of the current panel. `-1` if no panel exists.
* @ko 현재 패널의 인덱스 번호를 반환한다. 패널이 하나도 없을 경우 `-1`을 반환한다.
* @return Current panel's index, zero-based integer.<ko>현재 패널의 인덱스 번호. 0부터 시작하는 정수.</ko>
*/
__proto.getIndex = function () {
return this.viewport.getCurrentIndex();
};
/**
* Return the wrapper element user provided in constructor.
* @ko 사용자가 생성자에서 제공한 래퍼 엘리먼트를 반환한다.
* @return Wrapper element user provided.<ko>사용자가 제공한 래퍼 엘리먼트.</ko>
*/
__proto.getElement = function () {
return this.wrapper;
};
/**
* Return current panel. `null` if no panel exists.
* @ko 현재 패널을 반환한다. 패널이 하나도 없을 경우 `null`을 반환한다.
* @return Current panel.<ko>현재 패널.</ko>
*/
__proto.getCurrentPanel = function () {
var viewport = this.viewport;
var panel = viewport.getCurrentPanel();
return panel ? panel : null;
};
/**
* Return the panel of given index. `null` if it doesn't exists.
* @ko 주어진 인덱스에 해당하는 패널을 반환한다. 해당 패널이 존재하지 않을 시 `null`이다.
* @return Panel of given index.<ko>주어진 인덱스에 해당하는 패널.</ko>
*/
__proto.getPanel = function (index) {
var viewport = this.viewport;
var panel = viewport.panelManager.get(index);
return panel ? panel : null;
};
/**
* Return all panels.
* @ko 모든 패널들을 반환한다.
* @param - Should include cloned panels or not.<ko>복사된 패널들을 포함할지의 여부.</ko>
* @return All panels.<ko>모든 패널들.</ko>
*/
__proto.getAllPanels = function (includeClone) {
var viewport = this.viewport;
var panelManager = viewport.panelManager;
var panels = includeClone ? panelManager.allPanels() : panelManager.originalPanels();
return panels.filter(function (panel) {
return !!panel;
});
};
/**
* Return the panels currently shown in viewport area.
* @ko 현재 뷰포트 영역에서 보여지고 있는 패널들을 반환한다.
* @return Panels currently shown in viewport area.<ko>현재 뷰포트 영역에 보여지는 패널들</ko>
*/
__proto.getVisiblePanels = function () {
return this.viewport.calcVisiblePanels();
};
/**
* Return length of original panels.
* @ko 원본 패널의 개수를 반환한다.
* @return Length of original panels.<ko>원본 패널의 개수</ko>
*/
__proto.getPanelCount = function () {
return this.viewport.panelManager.getPanelCount();
};
/**
* Return how many groups of clones are created.
* @ko 몇 개의 클론 그룹이 생성되었는지를 반환한다.
* @return Length of cloned panel groups.<ko>클론된 패널 그룹의 개수</ko>
*/
__proto.getCloneCount = function () {
return this.viewport.panelManager.getCloneCount();
};
/**
* Get maximum panel index for `infinite` mode.
* @ko `infinite` 모드에서 적용되는 추가 가능한 패널의 최대 인덱스 값을 반환한다.
* @see {@link eg.Flicking.FlickingOptions}
* @return Maximum index of panel that can be added.<ko>최대 추가 가능한 패널의 인덱스.</ko>
*/
__proto.getLastIndex = function () {
return this.viewport.panelManager.getLastIndex();
};
/**
* Set maximum panel index for `infinite' mode.<br>[needPanel]{@link eg.Flicking#events:needPanel} won't be triggered anymore when last panel's index reaches it.<br>Also, you can't add more panels after it.
* @ko `infinite` 모드에서 적용되는 패널의 최대 인덱스를 설정한다.<br>마지막 패널의 인덱스가 설정한 값에 도달할 경우 더 이상 [needPanel]{@link eg.Flicking#events:needPanel} 이벤트가 발생되지 않는다.<br>또한, 설정한 인덱스 이후로 새로운 패널을 추가할 수 없다.
* @param - Maximum panel index.
* @see {@link eg.Flicking.FlickingOptions}
* @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko>
*/
__proto.setLastIndex = function (index) {
this.viewport.setLastIndex(index);
return this;
};
/**
* Return panel movement animation.
* @ko 현재 패널 이동 애니메이션이 진행 중인지를 반환한다.
* @return Is animating or not.<ko>애니메이션 진행 여부.</ko>
*/
__proto.isPlaying = function () {
return this.viewport.stateMachine.getState().playing;
};
/**
* Unblock input devices.
* @ko 막았던 입력 장치로부터의 입력을 푼다.
* @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko>
*/
__proto.enableInput = function () {
this.viewport.enable();
return this;
};
/**
* Block input devices.
* @ko 입력 장치로부터의 입력을 막는다.
* @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko>
*/
__proto.disableInput = function () {
this.viewport.disable();
return this;
};
/**
* Get current flicking status. You can restore current state by giving returned value to [setStatus()]{@link eg.Flicking#setStatus}.
* @ko 현재 상태 값을 반환한다. 반환받은 값을 [setStatus()]{@link eg.Flicking#setStatus} 메소드의 인자로 지정하면 현재 상태를 복원할 수 있다.
* @return An object with current status value information.<ko>현재 상태값 정보를 가진 객체.</ko>
*/
__proto.getStatus = function () {
var viewport = this.viewport;
var panels = viewport.panelManager.originalPanels().filter(function (panel) {
return !!panel;
}).map(function (panel) {
return {
html: panel.getElement().outerHTML,
index: panel.getIndex()
};
});
return {
index: viewport.getCurrentIndex(),
panels: panels,
position: viewport.getCameraPosition()
};
};
/**
* Restore to the state of the `status`.
* @ko `status`의 상태로 복원한다.
* @param status Status value to be restored. You can specify the return value of the [getStatus()]{@link eg.Flicking#getStatus} method.<ko>복원할 상태 값. [getStatus()]{@link eg.Flicking#getStatus}메서드의 반환값을 지정하면 된다.</ko>
*/
__proto.setStatus = function (status) {
this.viewport.restore(status);
};
/**
* Add plugins that can have different effects on Flicking.
* @ko 플리킹에 다양한 효과를 부여할 수 있는 플러그인을 추가한다.
* @param - The plugin(s) to add.<ko>추가할 플러그인(들).</ko>
* @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko>
*/
__proto.addPlugins = function (plugins) {
this.viewport.addPlugins(plugins);
return this;
};
/**
* Remove plugins from Flicking.
* @ko 플리킹으로부터 플러그인들을 제거한다.
* @param - The plugin(s) to remove.<ko>제거 플러그인(들).</ko>
* @return {eg.Flicking} The instance itself.<ko>인스턴스 자기 자신.</ko>
*/
__proto.removePlugins = function (plugins) {
this.viewport.removePlugins(plugins);
return this;
};
/**
* Return the reference element and all its children to the state they were in before the instance was created. Remove all attached event handlers. Specify `null` for all attributes of the instance (including inherited attributes).
* @ko 기준 요소와 그 하위 패널들을 인스턴스 생성전의 상태로 되돌린다. 부착된 모든 이벤트 핸들러를 탈거한다. 인스턴스의 모든 속성(상속받은 속성포함)에 `null`을 지정한다.
* @example
* const flick = new eg.Flicking("#flick");
* flick.destroy();
* console.log(flick.moveTo); // null
*/
__proto.destroy = function (option) {
if (option === void 0) {
option = {};
}
this.off();
if (this.options.autoResize) {
window.removeEventListener("resize", this.resize);
}
this.viewport.destroy(option); // release resources
for (var x in this) {
this[x] = null;
}
};
/**
* Add new panels at the beginning of panels.
* @ko 제일 앞에 새로운 패널을 추가한다.
* @param element - Either HTMLElement, HTML string, or array of them.<br>It can be also HTML string of multiple elements with same depth.<ko>HTMLElement 혹은 HTML 문자열, 혹은 그것들의 배열도 가능하다.<br>또한, 같은 depth의 여러 개의 엘리먼트에 해당하는 HTML 문자열도 가능하다.</ko>
* @return Array of appended panels.<ko>추가된 패널들의 배열</ko>
* @example
* // Suppose there were no panels at initialization
* const flicking = new eg.Flicking("#flick");
* flicking.replace(3, document.createElement("div")); // Add new panel at index 3
* flicking.prepend("\<div\>Panel\</div\>"); // Prepended at index 2
* flicking.prepend(["\<div\>Panel\</div\>", document.createElement("div")]); // Prepended at index 0, 1
* flicking.prepend("\<div\>Panel\</div\>"); // Prepended at index 0, pushing every panels behind it.
*/
__proto.prepend = function (element) {
var viewport = this.viewport;
var parsedElements = parseElement(element);
var insertingIndex = Math.max(viewport.panelManager.getRange().min - parsedElements.length, 0);
return viewport.insert(insertingIndex, parsedElements);
};
/**
* Add new panels at the end of panels.
* @ko 제일 끝에 새로운 패널을 추가한다.
* @param element - Either HTMLElement, HTML string, or array of them.<br>It can be also HTML string of multiple elements with same depth.<ko>HTMLElement 혹은 HTML 문자열, 혹은 그것들의 배열도 가능하다.<br>또한, 같은 depth의 여러 개의 엘리먼트에 해당하는 HTML 문자열도 가능하다.</ko>
* @return Array of appended panels.<ko>추가된 패널들의 배열</ko>
* @example
* // Suppose there were no panels at initialization
* const flicking = new eg.Flicking("#flick");
* flicking.append(document.createElement("div")); // Appended at index 0
* flicking.append("\<div\>Panel\</div\>"); // Appended at index 1
* flicking.append(["\<div\>Panel\</div\>", document.createElement("div")]); // Appended at index 2, 3
* // Even this is possible
* flicking.append("\<div\>Panel 1\</div\>\<div\>Panel 2\</div\>"); // Appended at index 4, 5
*/
__proto.append = function (element) {
var viewport = this.viewport;
return viewport.insert(viewport.panelManager.getRange().max + 1, element);
};
/**
* Replace existing panels with new panels from given index. If target index is empty, add new panel at target index.
* @ko 주어진 인덱스로부터의 패널들을 새로운 패널들로 교체한다. 인덱스에 해당하는 자리가 비어있다면, 새로운 패널을 해당 자리에 집어넣는다.
* @param index - Start index to replace new panels.<ko>새로운 패널들로 교체할 시작 인덱스</ko>
* @param element - Either HTMLElement, HTML string, or array of them.<br>It can be also HTML string of multiple elements with same depth.<ko>HTMLElement 혹은 HTML 문자열, 혹은 그것들의 배열도 가능하다.<br>또한, 같은 depth의 여러 개의 엘리먼트에 해당하는 HTML 문자열도 가능하다.</ko>
* @return Array of created panels by replace.<ko>교체되어 새롭게 추가된 패널들의 배열</ko>
* @example
* // Suppose there were no panels at initialization
* const flicking = new eg.Flicking("#flick");
*
* // This will add new panel at index 3,
* // Index 0, 1, 2 is empty at this moment.
* // [empty, empty, empty, PANEL]
* flicking.replace(3, document.createElement("div"));
*
* // As index 2 was empty, this will also add new panel at index 2.
* // [empty, empty, PANEL, PANEL]
* flicking.replace(2, "\<div\>Panel\</div\>");
*
* // Index 3 was not empty, so it will replace previous one.
* // It will also add new panels at index 4 and 5.
* // before - [empty, empty, PANEL, PANEL]
* // after - [empty, empty, PANEL, NEW_PANEL, NEW_PANEL, NEW_PANEL]
* flicking.replace(3, ["\<div\>Panel\</div\>", "\<div\>Panel\</div\>", "\<div\>Panel\</div\>"])
*/
__proto.replace = function (index, element) {
return this.viewport.replace(index, element);
};
/**
* Remove panel at target index. This will decrease index of panels behind it.
* @ko `index`에 해당하는 자리의 패널을 제거한다. 수행시 `index` 이후의 패널들의 인덱스가 감소된다.
* @param index - Index of panel to remove.<ko>제거할 패널의 인덱스</ko>
* @param {number} [deleteCount=1] - Number of panels to remove from index.<ko>`index` 이후로 제거할 패널의 개수.</ko>
* @return Array of removed panels<ko>제거된 패널들의 배열</ko>
*/
__proto.remove = function (index, deleteCount) {
if (deleteCount === void 0) {
deleteCount = 1;
}
return this.viewport.remove(index, deleteCount);
};
/**
* Get indexes to render. Should be used with `renderOnlyVisible` option.
* @private
* @ko 렌더링이 필요한 인덱스들을 반환한다. `renderOnlyVisible` 옵션과 함께 사용해야 한다.
* @param - Info object of how panel infos are changed.<ko>패널 정보들의 변경 정보를 담는 오브젝트.</ko>
* @return Array of indexes to render.<ko>렌더링할 인덱스의 배열</ko>
*/
__proto.getRenderingIndexes = function (diffResult) {
var viewport = this.viewport;
var _a = viewport.getVisibleIndex(),
min = _a.min,
max = _a.max;
var maintained = diffResult.maintained.reduce(function (values, _a) {
var before = _a[0],
after = _a[1];
values[before] = after;
return values;
}, {});
var prevPanelCount = diffResult.prevList.length;
var panelCount = diffResult.list.length;
var added = diffResult.added;
var list = counter(prevPanelCount * (this.getCloneCount() + 1));
var visibles = min >= 0 ? list.slice(min, max + 1) : list.slice(0, max + 1).concat(list.slice(min));
visibles = visibles.filter(function (val) {
return maintained[val % prevPanelCount] != null;
}).map(function (val) {
var cloneIndex = Math.floor(val / prevPanelCount);
var changedIndex = maintained[val % prevPanelCount];
return changedIndex + panelCount * cloneIndex;
});
var renderingPanels = visibles.concat(added);
var allPanels = viewport.panelManager.allPanels();
viewport.setVisiblePanels(renderingPanels.map(function (index) {
return allPanels[index];
}));
return renderingPanels;
};
/**
* Synchronize info of panels instance with info given by external rendering.
* @ko 외부 렌더링 방식에 의해 입력받은 패널의 정보와 현재 플리킹이 갖는 패널 정보를 동기화한다.
* @private
* @param - Info object of how panel infos are changed.<ko>패널 정보들의 변경 정보를 담는 오브젝트.</ko>
* @param - Whether called from sync method <ko> sync 메소드로부터 호출됐는지 여부 </ko>
*/
__proto.beforeSync = function (diffInfo) {
var _this = this;
var maintained = diffInfo.maintained,
added = diffInfo.added,
changed = diffInfo.changed,
removed = diffInfo.removed;
var viewport = this.viewport;
var panelManager = viewport.panelManager;
var isCircular = this.options.circular;
var cloneCount = panelManager.getCloneCount();
var prevClonedPanels = panelManager.clonedPanels(); // Update visible panels
var newVisiblePanels = viewport.getVisiblePanels().filter(function (panel) {
return findIndex(removed, function (index) {
return index === panel.getIndex();
}) < 0;
});
viewport.setVisiblePanels(newVisiblePanels); // Did not changed at all
if (added.length <= 0 && removed.length <= 0 && changed.length <= 0 && cloneCount === prevClonedPanels.length) {
return this;
}
var prevOriginalPanels = panelManager.originalPanels();
var newPanels = [];
var newClones = counter(cloneCount).map(function () {
return [];
});
maintained.forEach(function (_a) {
var beforeIdx = _a[0],
afterIdx = _a[1];
newPanels[afterIdx] = prevOriginalPanels[beforeIdx];
newPanels[afterIdx].setIndex(afterIdx);
});
added.forEach(function (addIndex) {
newPanels[addIndex] = new Panel(null, addIndex, _this.viewport);
});
if (isCircular) {
counter(cloneCount).forEach(function (groupIndex) {
var prevCloneGroup = prevClonedPanels[groupIndex];
var newCloneGroup = newClones[groupIndex];
maintained.forEach(function (_a) {
var beforeIdx = _a[0],
afterIdx = _a[1];
newCloneGroup[afterIdx] = prevCloneGroup ? prevCloneGroup[beforeIdx] : newPanels[afterIdx].clone(groupIndex, false);
newCloneGroup[afterIdx].setIndex(afterIdx);
});
added.forEach(function (addIndex) {
var newPanel = newPanels[addIndex];
newCloneGroup[addIndex] = newPanel.clone(groupIndex, false);
});
});
}
added.forEach(function (index) {
viewport.updateCheckedIndexes({
min: index,
max: index
});
});
removed.forEach(function (index) {
viewport.updateCheckedIndexes({
min: index - 1,
max: index + 1
});
});
var checkedIndexes = viewport.getCheckedIndexes();
checkedIndexes.forEach(function (_a, idx) {
var min = _a[0],
max = _a[1]; // Push checked indexes backward
var pushedIndex = added.filter(function (index) {
return index < min && panelManager.has(index);
}).length - removed.filter(function (index) {
return index < min;
}).length;
checkedIndexes.splice(idx, 1, [min + pushedIndex, max + pushedIndex]);
}); // Only effective only when there are least one panel which have changed its index
if (changed.length > 0) {
// Removed checked index by changed ones after pushing
maintained.forEach(function (_a) {
var next = _a[1];
viewport.updateCheckedIndexes({
min: next,
max: next
});
});
}
panelManager.replacePanels(newPanels, newClones);
this.isPanelChangedAtBeforeSync = true;
};
/**
* Synchronize info of panels with DOM info given by external rendering.
* @ko 외부 렌더링 방식에 의해 입력받은 DOM의 정보와 현재 플리킹이 갖는 패널 정보를 동기화 한다.
* @private
* @param - Info object of how panel elements are changed.<ko>패널의 DOM 요소들의 변경 정보를 담는 오브젝트.</ko>
*/
__proto.sync = function (diffInfo) {
var list = diffInfo.list,
maintained = diffInfo.maintained,
added = diffInfo.added,
changed = diffInfo.changed,
removed = diffInfo.removed; // Did not changed at all
if (added.length <= 0 && removed.length <= 0 && changed.length <= 0) {
return this;
}
var viewport = this.viewport;
var _a = this.options,
renderOnlyVisible = _a.renderOnlyVisible,
circular = _a.circular;
var panelManager = viewport.panelManager;
if (!renderOnlyVisible) {
var indexRange = panelManager.getRange();
var beforeDiffInfo = diffInfo;
if (circular) {
var prevOriginalPanelCount_1 = indexRange.max;
var originalPanelCount_1 = list.length / (panelManager.getCloneCount() + 1) >> 0;
var originalAdded = added.filter(function (index) {
return index < originalPanelCount_1;
});
var originalRemoved = removed.filter(function (index) {
return index <= prevOriginalPanelCount_1;
});
var originalMaintained = maintained.filter(function (_a) {
var beforeIdx = _a[0];
return beforeIdx <= prevOriginalPanelCount_1;
});
var originalChanged = changed.filter(function (_a) {
var beforeIdx = _a[0];
return beforeIdx <= prevOriginalPanelCount_1;
});
beforeDiffInfo = {
added: originalAdded,
maintained: originalMaintained,
removed: originalRemoved,
changed: originalChanged
};
}
this.beforeSync(beforeDiffInfo);
}
var visiblePanels = renderOnlyVisible ? viewport.getVisiblePanels() : this.getAllPanels(true);
added.forEach(function (addedIndex) {
var addedElement = list[addedIndex];
var beforePanel = visiblePanels[addedIndex];
beforePanel.setElement(addedElement); // As it can be 0
beforePanel.unCacheBbox();
});
if (this.isPanelChangedAtBeforeSync) {
viewport.resetVisibleIndex();
this.isPanelChangedAtBeforeSync = false;
}
viewport.resize();
return this;
};
__proto.listenInput = function () {
var flicking = this;
var viewport = flicking.viewport;
var stateMachine = viewport.stateMachine; // Set event context
flicking.eventContext = {
flicking: flicking,
viewport: flicking.viewport,
transitTo: stateMachine.transitTo,
triggerEvent: flicking.triggerEvent,
moveCamera: flicking.moveCamera,
stopCamera: viewport.stopCamera
};
var handlers = {};
var _loop_1 = function (key) {
var eventType = AXES_EVENTS[key];
handlers[eventType] = function (e) {
return stateMachine.fire(eventType, e, flicking.eventContext);
};
};
for (var key in AXES_EVENTS) {
_loop_1(key);
} // Connect Axes instance with PanInput
flicking.viewport.connectAxesHandler(handlers);
};
__proto.listenResize = function () {
if (this.options.autoResize) {
window.addEventListener("resize", this.resize);
}
};
/**
* Version info string
* @ko 버전정보 문자열
* @example
* eg.Flicking.VERSION; // ex) 3.0.0
* @memberof eg.Flicking
*/
Flicking.VERSION = "3.4.5";
/**
* Direction constant - "PREV" or "NEXT"
* @ko 방향 상수 - "PREV" 또는 "NEXT"
* @type {object}
* @property {"PREV"} PREV - Prev direction from current hanger position.<br/>It's `left(←️)` direction when `horizontal: true`.<br/>Or, `up(↑️)` direction when `horizontal: false`.<ko>현재 행어를 기준으로 이전 방향.<br/>`horizontal: true`일 경우 `왼쪽(←️)` 방향.<br/>`horizontal: false`일 경우 `위쪽(↑️)`방향이다.</ko>
* @property {"NEXT"} NEXT - Next direction from current hanger position.<br/>It's `right(→)` direction when `horizontal: true`.<br/>Or, `down(↓️)` direction when `horizontal: false`.<ko>현재 행어를 기준으로 다음 방향.<br/>`horizontal: true`일 경우 `오른쪽(→)` 방향.<br/>`horizontal: false`일 경우 `아래쪽(↓️)`방향이다.</ko>
* @example
* eg.Flicking.DIRECTION.PREV; // "PREV"
* eg.Flicking.DIRECTION.NEXT; // "NEXT"
*/
Flicking.DIRECTION = DIRECTION;
/**
* Event type object with event name strings.
* @ko 이벤트 이름 문자열들을 담은 객체
* @type {object}
* @property {"holdStart"} HOLD_START - holdStart event<ko>holdStart 이벤트</ko>
* @property {"holdEnd"} HOLD_END - holdEnd event<ko>holdEnd 이벤트</ko>
* @property {"moveStart"} MOVE_START - moveStart event<ko>moveStart 이벤트</ko>
* @property {"move"} MOVE - move event<ko>move 이벤트</ko>
* @property {"moveEnd"} MOVE_END - moveEnd event<ko>moveEnd 이벤트</ko>
* @property {"change"} CHANGE - change event<ko>change 이벤트</ko>
* @property {"restore"} RESTORE - restore event<ko>restore 이벤트</ko>
* @property {"select"} SELECT - select event<ko>select 이벤트</ko>
* @property {"needPanel"} NEED_PANEL - needPanel event<ko>needPanel 이벤트</ko>
* @example
* eg.Flicking.EVENTS.MOVE_START; // "MOVE_START"
*/
Flicking.EVENTS = EVENTS;
return Flicking;
}(Component);
Flicking.withFlickingMethods = withFlickingMethods;
Flicking.DEFAULT_OPTIONS = DEFAULT_OPTIONS;
Flicking.MOVE_TYPE = MOVE_TYPE;
return Flicking;
}));
//# sourceMappingURL=flicking.pkgd.js.map
|
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { deepmerge, elementAcceptingRef } from '@material-ui/utils';
import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled';
import { alpha } from '../styles/colorManipulator';
import experimentalStyled from '../styles/experimentalStyled';
import useThemeProps from '../styles/useThemeProps';
import capitalize from '../utils/capitalize';
import Grow from '../Grow';
import Popper from '../Popper';
import useEventCallback from '../utils/useEventCallback';
import useForkRef from '../utils/useForkRef';
import useId from '../utils/useId';
import useIsFocusVisible from '../utils/useIsFocusVisible';
import useControlled from '../utils/useControlled';
import tooltipClasses, { getTooltipUtilityClass } from './tooltipClasses';
function round(value) {
return Math.round(value * 1e5) / 1e5;
}
const overridesResolver = (props, styles) => {
const {
styleProps
} = props;
return deepmerge(_extends({}, !styleProps.disableInteractive && styles.popperInteractive, styleProps.arrow && styles.popperArrow, {
[`& .${tooltipClasses.tooltip}`]: _extends({}, styles.tooltip, styleProps.touch && styles.touch, styleProps.arrow && styles.tooltipArrow, styles[`tooltipPlacement${capitalize(styleProps.placement.split('-')[0])}`]),
[`& .${tooltipClasses.arrow}`]: styles.arrow
}), styles.popper || {});
};
const useUtilityClasses = styleProps => {
const {
classes,
disableInteractive,
arrow,
touch,
placement
} = styleProps;
const slots = {
popper: ['popper', !disableInteractive && 'popperInteractive', arrow && 'popperArrow'],
tooltip: ['tooltip', arrow && 'tooltipArrow', touch && 'touch', `tooltipPlacement${capitalize(placement.split('-')[0])}`],
arrow: ['arrow']
};
return composeClasses(slots, getTooltipUtilityClass, classes);
};
const TooltipPopper = experimentalStyled(Popper, {}, {
name: 'MuiTooltip',
slot: 'Popper',
overridesResolver
})(({
theme,
styleProps
}) => _extends({
/* Styles applied to the Popper element. */
zIndex: theme.zIndex.tooltip,
pointerEvents: 'none'
}, !styleProps.disableInteractive && {
pointerEvents: 'auto'
}, styleProps.arrow && {
[`&[data-popper-placement*="bottom"] .${tooltipClasses.arrow}`]: {
top: 0,
left: 0,
marginTop: '-0.71em',
'&::before': {
transformOrigin: '0 100%'
}
},
[`&[data-popper-placement*="top"] .${tooltipClasses.arrow}`]: {
bottom: 0,
left: 0,
marginBottom: '-0.71em',
'&::before': {
transformOrigin: '100% 0'
}
},
[`&[data-popper-placement*="right"] .${tooltipClasses.arrow}`]: {
left: 0,
marginLeft: '-0.71em',
height: '1em',
width: '0.71em',
'&::before': {
transformOrigin: '100% 100%'
}
},
[`&[data-popper-placement*="left"] .${tooltipClasses.arrow}`]: {
right: 0,
marginRight: '-0.71em',
height: '1em',
width: '0.71em',
'&::before': {
transformOrigin: '0 0'
}
}
}));
const TooltipTooltip = experimentalStyled('div', {}, {
name: 'MuiTooltip',
slot: 'Tooltip'
})(({
theme,
styleProps
}) => _extends({
/* Styles applied to the tooltip (label wrapper) element. */
backgroundColor: alpha(theme.palette.grey[700], 0.92),
borderRadius: theme.shape.borderRadius,
color: theme.palette.common.white,
fontFamily: theme.typography.fontFamily,
padding: '4px 8px',
fontSize: theme.typography.pxToRem(11),
maxWidth: 300,
margin: 2,
wordWrap: 'break-word',
fontWeight: theme.typography.fontWeightMedium
}, styleProps.arrow && {
position: 'relative',
margin: 0
}, styleProps.touch && {
padding: '8px 16px',
fontSize: theme.typography.pxToRem(14),
lineHeight: `${round(16 / 14)}em`,
fontWeight: theme.typography.fontWeightRegular
}, styleProps.placement.split('-')[0] === 'left' && {
transformOrigin: 'right center',
marginRight: '24px',
[theme.breakpoints.up('sm')]: {
marginRight: '14px'
}
}, styleProps.placement.split('-')[0] === 'right' && {
transformOrigin: 'left center',
marginLeft: '24px',
[theme.breakpoints.up('sm')]: {
marginLeft: '14px'
}
}, styleProps.placement.split('-')[0] === 'top' && {
transformOrigin: 'center bottom',
marginBottom: '24px',
[theme.breakpoints.up('sm')]: {
marginBottom: '14px'
}
}, styleProps.placement.split('-')[0] === 'bottom' && {
transformOrigin: 'center top',
marginTop: '24px',
[theme.breakpoints.up('sm')]: {
marginTop: '14px'
}
}));
const TooltipArrow = experimentalStyled('span', {}, {
name: 'MuiTooltip',
slot: 'Arrow'
})(({
theme
}) => ({
/* Styles applied to the arrow element. */
overflow: 'hidden',
position: 'absolute',
width: '1em',
height: '0.71em'
/* = width / sqrt(2) = (length of the hypotenuse) */
,
boxSizing: 'border-box',
color: alpha(theme.palette.grey[700], 0.9),
'&::before': {
content: '""',
margin: 'auto',
display: 'block',
width: '100%',
height: '100%',
backgroundColor: 'currentColor',
transform: 'rotate(45deg)'
}
}));
let hystersisOpen = false;
let hystersisTimer = null;
export function testReset() {
hystersisOpen = false;
clearTimeout(hystersisTimer);
}
function composeEventHandler(handler, eventHandler) {
return event => {
if (eventHandler) {
eventHandler(event);
}
handler(event);
};
}
const Tooltip = /*#__PURE__*/React.forwardRef(function Tooltip(inProps, ref) {
const _useThemeProps = useThemeProps({
props: inProps,
name: 'MuiTooltip'
}),
{
theme
} = _useThemeProps,
props = _objectWithoutPropertiesLoose(_useThemeProps, ["theme", "isRtl"]);
const {
arrow = false,
children,
describeChild = false,
disableFocusListener = false,
disableHoverListener = false,
disableInteractive: disableInteractiveProp = false,
disableTouchListener = false,
enterDelay = 100,
enterNextDelay = 0,
enterTouchDelay = 700,
followCursor = false,
id: idProp,
leaveDelay = 0,
leaveTouchDelay = 1500,
onClose,
onOpen,
open: openProp,
placement = 'bottom',
PopperComponent = Popper,
PopperProps = {},
title,
TransitionComponent = Grow,
TransitionProps
} = props,
other = _objectWithoutPropertiesLoose(props, ["arrow", "children", "describeChild", "disableFocusListener", "disableHoverListener", "disableInteractive", "disableTouchListener", "enterDelay", "enterNextDelay", "enterTouchDelay", "followCursor", "id", "leaveDelay", "leaveTouchDelay", "onClose", "onOpen", "open", "placement", "PopperComponent", "PopperProps", "title", "TransitionComponent", "TransitionProps"]);
const [childNode, setChildNode] = React.useState();
const [arrowRef, setArrowRef] = React.useState(null);
const ignoreNonTouchEvents = React.useRef(false);
const disableInteractive = disableInteractiveProp || followCursor;
const closeTimer = React.useRef();
const enterTimer = React.useRef();
const leaveTimer = React.useRef();
const touchTimer = React.useRef();
const [openState, setOpenState] = useControlled({
controlled: openProp,
default: false,
name: 'Tooltip',
state: 'open'
});
let open = openState;
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
const {
current: isControlled
} = React.useRef(openProp !== undefined); // eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {
if (childNode && childNode.disabled && !isControlled && title !== '' && childNode.tagName.toLowerCase() === 'button') {
console.error(['Material-UI: You are providing a disabled `button` child to the Tooltip component.', 'A disabled element does not fire events.', "Tooltip needs to listen to the child element's events to display the title.", '', 'Add a simple wrapper element, such as a `span`.'].join('\n'));
}
}, [title, childNode, isControlled]);
}
const id = useId(idProp);
const prevUserSelect = React.useRef();
const stopTouchInteraction = React.useCallback(() => {
if (prevUserSelect.current !== undefined) {
document.body.style.WebkitUserSelect = prevUserSelect.current;
prevUserSelect.current = undefined;
}
clearTimeout(touchTimer.current);
}, []);
React.useEffect(() => {
return () => {
clearTimeout(closeTimer.current);
clearTimeout(enterTimer.current);
clearTimeout(leaveTimer.current);
stopTouchInteraction();
};
}, [stopTouchInteraction]);
const handleOpen = event => {
clearTimeout(hystersisTimer);
hystersisOpen = true; // The mouseover event will trigger for every nested element in the tooltip.
// We can skip rerendering when the tooltip is already open.
// We are using the mouseover event instead of the mouseenter event to fix a hide/show issue.
setOpenState(true);
if (onOpen && !open) {
onOpen(event);
}
};
const handleClose = useEventCallback(
/**
* @param {React.SyntheticEvent | Event} event
*/
event => {
clearTimeout(hystersisTimer);
hystersisTimer = setTimeout(() => {
hystersisOpen = false;
}, 800 + leaveDelay);
setOpenState(false);
if (onClose && open) {
onClose(event);
}
clearTimeout(closeTimer.current);
closeTimer.current = setTimeout(() => {
ignoreNonTouchEvents.current = false;
}, theme.transitions.duration.shortest);
});
const handleEnter = event => {
if (ignoreNonTouchEvents.current && event.type !== 'touchstart') {
return;
} // Remove the title ahead of time.
// We don't want to wait for the next render commit.
// We would risk displaying two tooltips at the same time (native + this one).
if (childNode) {
childNode.removeAttribute('title');
}
clearTimeout(enterTimer.current);
clearTimeout(leaveTimer.current);
if (enterDelay || hystersisOpen && enterNextDelay) {
event.persist();
enterTimer.current = setTimeout(() => {
handleOpen(event);
}, hystersisOpen ? enterNextDelay : enterDelay);
} else {
handleOpen(event);
}
};
const handleLeave = event => {
clearTimeout(enterTimer.current);
clearTimeout(leaveTimer.current);
event.persist();
leaveTimer.current = setTimeout(() => {
handleClose(event);
}, leaveDelay);
};
const {
isFocusVisibleRef,
onBlur: handleBlurVisible,
onFocus: handleFocusVisible,
ref: focusVisibleRef
} = useIsFocusVisible(); // We don't necessarily care about the focusVisible state (which is safe to access via ref anyway).
// We just need to re-render the Tooltip if the focus-visible state changes.
const [, setChildIsFocusVisible] = React.useState(false);
const handleBlur = event => {
handleBlurVisible(event);
if (isFocusVisibleRef.current === false) {
setChildIsFocusVisible(false);
handleLeave(event);
}
};
const handleFocus = event => {
// Workaround for https://github.com/facebook/react/issues/7769
// The autoFocus of React might trigger the event before the componentDidMount.
// We need to account for this eventuality.
if (!childNode) {
setChildNode(event.currentTarget);
}
handleFocusVisible(event);
if (isFocusVisibleRef.current === true) {
setChildIsFocusVisible(true);
handleEnter(event);
}
};
const detectTouchStart = event => {
ignoreNonTouchEvents.current = true;
const childrenProps = children.props;
if (childrenProps.onTouchStart) {
childrenProps.onTouchStart(event);
}
};
const handleMouseOver = handleEnter;
const handleMouseLeave = handleLeave;
const handleTouchStart = event => {
detectTouchStart(event);
clearTimeout(leaveTimer.current);
clearTimeout(closeTimer.current);
stopTouchInteraction();
event.persist();
prevUserSelect.current = document.body.style.WebkitUserSelect; // Prevent iOS text selection on long-tap.
document.body.style.WebkitUserSelect = 'none';
touchTimer.current = setTimeout(() => {
document.body.style.WebkitUserSelect = prevUserSelect.current;
handleEnter(event);
}, enterTouchDelay);
};
const handleTouchEnd = event => {
if (children.props.onTouchEnd) {
children.props.onTouchEnd(event);
}
clearTimeout(touchTimer.current);
clearTimeout(leaveTimer.current);
event.persist();
leaveTimer.current = setTimeout(() => {
handleClose(event);
}, leaveTouchDelay);
};
React.useEffect(() => {
if (!open) {
return undefined;
}
/**
* @param {KeyboardEvent} nativeEvent
*/
function handleKeyDown(nativeEvent) {
// IE11, Edge (prior to using Bink?) use 'Esc'
if (nativeEvent.key === 'Escape' || nativeEvent.key === 'Esc') {
handleClose(nativeEvent);
}
}
document.addEventListener('keydown', handleKeyDown);
return () => {
document.removeEventListener('keydown', handleKeyDown);
};
}, [handleClose, open]);
const handleUseRef = useForkRef(setChildNode, ref);
const handleFocusRef = useForkRef(focusVisibleRef, handleUseRef);
const handleRef = useForkRef(children.ref, handleFocusRef); // There is no point in displaying an empty tooltip.
if (title === '') {
open = false;
}
const positionRef = React.useRef({
x: 0,
y: 0
});
const popperRef = React.useRef();
const handleMouseMove = event => {
const childrenProps = children.props;
if (childrenProps.onMouseMove) {
childrenProps.onMouseMove(event);
}
positionRef.current = {
x: event.clientX,
y: event.clientY
};
if (popperRef.current) {
popperRef.current.update();
}
};
const nameOrDescProps = {};
const titleIsString = typeof title === 'string';
if (describeChild) {
nameOrDescProps.title = !open && titleIsString && !disableHoverListener ? title : null;
nameOrDescProps['aria-describedby'] = open ? id : null;
} else {
nameOrDescProps['aria-label'] = titleIsString ? title : null;
nameOrDescProps['aria-labelledby'] = open && !titleIsString ? id : null;
}
const childrenProps = _extends({}, nameOrDescProps, other, children.props, {
className: clsx(other.className, children.props.className),
onTouchStart: detectTouchStart,
ref: handleRef
}, followCursor ? {
onMouseMove: handleMouseMove
} : {});
if (process.env.NODE_ENV !== 'production') {
childrenProps['data-mui-internal-clone-element'] = true; // eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {
if (childNode && !childNode.getAttribute('data-mui-internal-clone-element')) {
console.error(['Material-UI: The `children` component of the Tooltip is not forwarding its props correctly.', 'Please make sure that props are spread on the same element that the ref is applied to.'].join('\n'));
}
}, [childNode]);
}
const interactiveWrapperListeners = {};
if (!disableTouchListener) {
childrenProps.onTouchStart = handleTouchStart;
childrenProps.onTouchEnd = handleTouchEnd;
}
if (!disableHoverListener) {
childrenProps.onMouseOver = composeEventHandler(handleMouseOver, childrenProps.onMouseOver);
childrenProps.onMouseLeave = composeEventHandler(handleMouseLeave, childrenProps.onMouseLeave);
if (!disableInteractive) {
interactiveWrapperListeners.onMouseOver = handleMouseOver;
interactiveWrapperListeners.onMouseLeave = handleMouseLeave;
}
}
if (!disableFocusListener) {
childrenProps.onFocus = composeEventHandler(handleFocus, childrenProps.onFocus);
childrenProps.onBlur = composeEventHandler(handleBlur, childrenProps.onBlur);
if (!disableInteractive) {
interactiveWrapperListeners.onFocus = handleFocus;
interactiveWrapperListeners.onBlur = handleBlur;
}
}
if (process.env.NODE_ENV !== 'production') {
if (children.props.title) {
console.error(['Material-UI: You have provided a `title` prop to the child of <Tooltip />.', `Remove this title prop \`${children.props.title}\` or the Tooltip component.`].join('\n'));
}
}
const popperOptions = React.useMemo(() => {
var _PopperProps$popperOp;
let tooltipModifiers = [{
name: 'arrow',
enabled: Boolean(arrowRef),
options: {
element: arrowRef,
padding: 4
}
}];
if ((_PopperProps$popperOp = PopperProps.popperOptions) !== null && _PopperProps$popperOp !== void 0 && _PopperProps$popperOp.modifiers) {
tooltipModifiers = tooltipModifiers.concat(PopperProps.popperOptions.modifiers);
}
return _extends({}, PopperProps.popperOptions, {
modifiers: tooltipModifiers
});
}, [arrowRef, PopperProps]);
const styleProps = _extends({}, props, {
arrow,
disableInteractive,
placement,
PopperComponent,
touch: ignoreNonTouchEvents.current
});
const classes = useUtilityClasses(styleProps);
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.cloneElement(children, childrenProps), /*#__PURE__*/React.createElement(TooltipPopper, _extends({
as: PopperComponent,
className: classes.popper,
placement: placement,
anchorEl: followCursor ? {
getBoundingClientRect: () => ({
top: positionRef.current.y,
left: positionRef.current.x,
right: positionRef.current.x,
bottom: positionRef.current.y,
width: 0,
height: 0
})
} : childNode,
popperRef: popperRef,
open: childNode ? open : false,
id: id,
transition: true
}, interactiveWrapperListeners, PopperProps, {
popperOptions: popperOptions,
styleProps: styleProps
}), ({
TransitionProps: TransitionPropsInner
}) => /*#__PURE__*/React.createElement(TransitionComponent, _extends({
timeout: theme.transitions.duration.shorter
}, TransitionPropsInner, TransitionProps), /*#__PURE__*/React.createElement(TooltipTooltip, {
className: classes.tooltip,
styleProps: styleProps
}, title, arrow ? /*#__PURE__*/React.createElement(TooltipArrow, {
className: classes.arrow,
ref: setArrowRef,
styleProps: styleProps
}) : null))));
});
process.env.NODE_ENV !== "production" ? Tooltip.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* If `true`, adds an arrow to the tooltip.
* @default false
*/
arrow: PropTypes.bool,
/**
* Tooltip reference element.
*/
children: elementAcceptingRef.isRequired,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* Set to `true` if the `title` acts as an accessible description.
* By default the `title` acts as an accessible label for the child.
* @default false
*/
describeChild: PropTypes.bool,
/**
* Do not respond to focus events.
* @default false
*/
disableFocusListener: PropTypes.bool,
/**
* Do not respond to hover events.
* @default false
*/
disableHoverListener: PropTypes.bool,
/**
* Makes a tooltip not interactive, i.e. it will close when the user
* hovers over the tooltip before the `leaveDelay` is expired.
* @default false
*/
disableInteractive: PropTypes.bool,
/**
* Do not respond to long press touch events.
* @default false
*/
disableTouchListener: PropTypes.bool,
/**
* The number of milliseconds to wait before showing the tooltip.
* This prop won't impact the enter touch delay (`enterTouchDelay`).
* @default 100
*/
enterDelay: PropTypes.number,
/**
* The number of milliseconds to wait before showing the tooltip when one was already recently opened.
* @default 0
*/
enterNextDelay: PropTypes.number,
/**
* The number of milliseconds a user must touch the element before showing the tooltip.
* @default 700
*/
enterTouchDelay: PropTypes.number,
/**
* If `true`, the tooltip follow the cursor over the wrapped element.
* @default false
*/
followCursor: PropTypes.bool,
/**
* This prop is used to help implement the accessibility logic.
* If you don't provide this prop. It falls back to a randomly generated id.
*/
id: PropTypes.string,
/**
* The number of milliseconds to wait before hiding the tooltip.
* This prop won't impact the leave touch delay (`leaveTouchDelay`).
* @default 0
*/
leaveDelay: PropTypes.number,
/**
* The number of milliseconds after the user stops touching an element before hiding the tooltip.
* @default 1500
*/
leaveTouchDelay: PropTypes.number,
/**
* Callback fired when the component requests to be closed.
*
* @param {object} event The event source of the callback.
*/
onClose: PropTypes.func,
/**
* Callback fired when the component requests to be open.
*
* @param {object} event The event source of the callback.
*/
onOpen: PropTypes.func,
/**
* If `true`, the component is shown.
*/
open: PropTypes.bool,
/**
* Tooltip placement.
* @default 'bottom'
*/
placement: PropTypes.oneOf(['bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']),
/**
* The component used for the popper.
* @default Popper
*/
PopperComponent: PropTypes.elementType,
/**
* Props applied to the [`Popper`](/api/popper/) element.
* @default {}
*/
PopperProps: PropTypes.object,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.object,
/**
* Tooltip title. Zero-length titles string are never displayed.
*/
title: PropTypes
/* @typescript-to-proptypes-ignore */
.node.isRequired,
/**
* The component used for the transition.
* [Follow this guide](/components/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.
* @default Grow
*/
TransitionComponent: PropTypes.elementType,
/**
* Props applied to the transition element.
* By default, the element is based on this [`Transition`](http://reactcommunity.org/react-transition-group/transition) component.
*/
TransitionProps: PropTypes.object
} : void 0;
export default Tooltip; |
import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["tabIndex", "placeholder", "children", "align", "getRootRef", "multiline", "disabled", "onClick", "sizeX", "sizeY"];
import { createScopedElement } from "../../lib/jsxRuntime";
import { classNames } from "../../lib/classNames";
import { DropdownIcon } from "../DropdownIcon/DropdownIcon";
import { FormField } from "../FormField/FormField";
import { withAdaptivity, SizeType } from "../../hoc/withAdaptivity";
import { usePlatform } from "../../hooks/usePlatform";
import { getClassName } from "../../helpers/getClassName";
import Headline from "../Typography/Headline/Headline";
import Text from "../Typography/Text/Text";
import { VKCOM } from "../../lib/platform";
import "../Select/Select.css";
var SelectMimicry = function SelectMimicry(_ref) {
var _classNames;
var tabIndex = _ref.tabIndex,
placeholder = _ref.placeholder,
children = _ref.children,
align = _ref.align,
getRootRef = _ref.getRootRef,
multiline = _ref.multiline,
disabled = _ref.disabled,
onClick = _ref.onClick,
sizeX = _ref.sizeX,
sizeY = _ref.sizeY,
restProps = _objectWithoutProperties(_ref, _excluded);
var platform = usePlatform();
var TypographyComponent = platform === VKCOM || sizeY === SizeType.COMPACT ? Text : Headline;
return createScopedElement(FormField, _extends({}, restProps, {
tabIndex: disabled ? null : tabIndex,
vkuiClass: classNames(getClassName("Select", platform), "Select--mimicry", (_classNames = {
"Select--not-selected": !children,
"Select--multiline": multiline
}, _defineProperty(_classNames, "Select--align-".concat(align), !!align), _defineProperty(_classNames, "Select--sizeX--".concat(sizeX), !!sizeX), _defineProperty(_classNames, "Select--sizeY--".concat(sizeY), !!sizeY), _classNames)),
getRootRef: getRootRef,
onClick: disabled ? null : onClick,
disabled: disabled,
after: createScopedElement(DropdownIcon, null)
}), createScopedElement(TypographyComponent, {
Component: "div",
weight: "regular",
vkuiClass: "Select__container"
}, createScopedElement("span", {
vkuiClass: "Select__title"
}, children || placeholder)));
};
SelectMimicry.defaultProps = {
tabIndex: 0
};
export default withAdaptivity(SelectMimicry, {
sizeX: true,
sizeY: true
});
//# sourceMappingURL=SelectMimicry.js.map |
/**
* @license Highstock JS v10.0.0 (2022-03-07)
*
* Indicator series type for Highcharts Stock
*
* (c) 2010-2021 Sebastian Bochan
*
* License: www.highcharts.com/license
*/
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/indicators/momentum', ['highcharts', 'highcharts/modules/stock'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
'use strict';
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
if (typeof CustomEvent === 'function') {
window.dispatchEvent(
new CustomEvent(
'HighchartsModuleLoaded',
{ detail: { path: path, module: obj[path] }
})
);
}
}
}
_registerModule(_modules, 'Stock/Indicators/Momentum/MomentumIndicator.js', [_modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (SeriesRegistry, U) {
/* *
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var SMAIndicator = SeriesRegistry.seriesTypes.sma;
var extend = U.extend,
isArray = U.isArray,
merge = U.merge;
/* eslint-disable require-jsdoc */
function populateAverage(xVal, yVal, i, period, index) {
var mmY = yVal[i - 1][index] - yVal[i - period - 1][index],
mmX = xVal[i - 1];
return [mmX, mmY];
}
/* eslint-enable require-jsdoc */
/**
* The Momentum series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.momentum
*
* @augments Highcharts.Series
*/
var MomentumIndicator = /** @class */ (function (_super) {
__extends(MomentumIndicator, _super);
function MomentumIndicator() {
var _this = _super !== null && _super.apply(this,
arguments) || this;
_this.data = void 0;
_this.options = void 0;
_this.points = void 0;
return _this;
}
MomentumIndicator.prototype.getValues = function (series, params) {
var period = params.period,
index = params.index,
xVal = series.xData,
yVal = series.yData,
yValLen = yVal ? yVal.length : 0,
yValue = yVal[0],
MM = [],
xData = [],
yData = [],
i,
MMPoint;
if (xVal.length <= period) {
return;
}
// Switch index for OHLC / Candlestick / Arearange
if (isArray(yVal[0])) {
yValue = yVal[0][index];
}
else {
return;
}
// Calculate value one-by-one for each period in visible data
for (i = (period + 1); i < yValLen; i++) {
MMPoint = populateAverage(xVal, yVal, i, period, index);
MM.push(MMPoint);
xData.push(MMPoint[0]);
yData.push(MMPoint[1]);
}
MMPoint = populateAverage(xVal, yVal, i, period, index);
MM.push(MMPoint);
xData.push(MMPoint[0]);
yData.push(MMPoint[1]);
return {
values: MM,
xData: xData,
yData: yData
};
};
/**
* Momentum. This series requires `linkedTo` option to be set.
*
* @sample stock/indicators/momentum
* Momentum indicator
*
* @extends plotOptions.sma
* @since 6.0.0
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/momentum
* @optionparent plotOptions.momentum
*/
MomentumIndicator.defaultOptions = merge(SMAIndicator.defaultOptions, {
params: {
index: 3
}
});
return MomentumIndicator;
}(SMAIndicator));
extend(MomentumIndicator.prototype, {
nameBase: 'Momentum'
});
SeriesRegistry.registerSeriesType('momentum', MomentumIndicator);
/* *
*
* Default Export
*
* */
/**
* A `Momentum` series. If the [type](#series.momentum.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.momentum
* @since 6.0.0
* @excluding dataParser, dataURL
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/momentum
* @apioption series.momentum
*/
''; // to include the above in the js output
return MomentumIndicator;
});
_registerModule(_modules, 'masters/indicators/momentum.src.js', [], function () {
});
})); |
/*
* big.js v6.0.1
* A small, fast, easy-to-use library for arbitrary-precision decimal arithmetic.
* Copyright (c) 2020 Michael Mclaughlin
* https://github.com/MikeMcl/big.js/LICENCE.md
*/
;(function (GLOBAL) {
'use strict';
var Big,
/************************************** EDITABLE DEFAULTS *****************************************/
// The default values below must be integers within the stated ranges.
/*
* The maximum number of decimal places (DP) of the results of operations involving division:
* div and sqrt, and pow with negative exponents.
*/
DP = 20, // 0 to MAX_DP
/*
* The rounding mode (RM) used when rounding to the above decimal places.
*
* 0 Towards zero (i.e. truncate, no rounding). (ROUND_DOWN)
* 1 To nearest neighbour. If equidistant, round up. (ROUND_HALF_UP)
* 2 To nearest neighbour. If equidistant, to even. (ROUND_HALF_EVEN)
* 3 Away from zero. (ROUND_UP)
*/
RM = 1, // 0, 1, 2 or 3
// The maximum value of DP and Big.DP.
MAX_DP = 1E6, // 0 to 1000000
// The maximum magnitude of the exponent argument to the pow method.
MAX_POWER = 1E6, // 1 to 1000000
/*
* The negative exponent (NE) at and beneath which toString returns exponential notation.
* (JavaScript numbers: -7)
* -1000000 is the minimum recommended exponent value of a Big.
*/
NE = -7, // 0 to -1000000
/*
* The positive exponent (PE) at and above which toString returns exponential notation.
* (JavaScript numbers: 21)
* 1000000 is the maximum recommended exponent value of a Big, but this limit is not enforced.
*/
PE = 21, // 0 to 1000000
/*
* When true, an error will be thrown if a primitive number is passed to the Big constructor,
* or if valueOf is called, or if toNumber is called on a Big which cannot be converted to a
* primitive number without a loss of precision.
*/
STRICT = false, // true or false
/**************************************************************************************************/
// Error messages.
NAME = '[big.js] ',
INVALID = NAME + 'Invalid ',
INVALID_DP = INVALID + 'decimal places',
INVALID_RM = INVALID + 'rounding mode',
DIV_BY_ZERO = NAME + 'Division by zero',
// The shared prototype object.
P = {},
UNDEFINED = void 0,
NUMERIC = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;
/*
* Create and return a Big constructor.
*/
function _Big_() {
/*
* The Big constructor and exported function.
* Create and return a new instance of a Big number object.
*
* n {number|string|Big} A numeric value.
*/
function Big(n) {
var x = this;
// Enable constructor usage without new.
if (!(x instanceof Big)) return n === UNDEFINED ? _Big_() : new Big(n);
// Duplicate.
if (n instanceof Big) {
x.s = n.s;
x.e = n.e;
x.c = n.c.slice();
} else {
if (typeof n !== 'string') {
if (Big.strict === true) {
throw TypeError(INVALID + 'number');
}
// Minus zero?
n = n === 0 && 1 / n < 0 ? '-0' : String(n);
}
parse(x, n);
}
// Retain a reference to this Big constructor.
// Shadow Big.prototype.constructor which points to Object.
x.constructor = Big;
}
Big.prototype = P;
Big.DP = DP;
Big.RM = RM;
Big.NE = NE;
Big.PE = PE;
Big.strict = STRICT;
return Big;
}
/*
* Parse the number or string value passed to a Big constructor.
*
* x {Big} A Big number instance.
* n {number|string} A numeric value.
*/
function parse(x, n) {
var e, i, nl;
if (!NUMERIC.test(n)) {
throw Error(INVALID + 'number');
}
// Determine sign.
x.s = n.charAt(0) == '-' ? (n = n.slice(1), -1) : 1;
// Decimal point?
if ((e = n.indexOf('.')) > -1) n = n.replace('.', '');
// Exponential form?
if ((i = n.search(/e/i)) > 0) {
// Determine exponent.
if (e < 0) e = i;
e += +n.slice(i + 1);
n = n.substring(0, i);
} else if (e < 0) {
// Integer.
e = n.length;
}
nl = n.length;
// Determine leading zeros.
for (i = 0; i < nl && n.charAt(i) == '0';) ++i;
if (i == nl) {
// Zero.
x.c = [x.e = 0];
} else {
// Determine trailing zeros.
for (; nl > 0 && n.charAt(--nl) == '0';);
x.e = e - i - 1;
x.c = [];
// Convert string to array of digits without leading/trailing zeros.
for (e = 0; i <= nl;) x.c[e++] = +n.charAt(i++);
}
return x;
}
/*
* Round Big x to a maximum of sd significant digits using rounding mode rm.
*
* x {Big} The Big to round.
* sd {number} Significant digits: integer, 0 to MAX_DP inclusive.
* rm {number} Rounding mode: 0 (down), 1 (half-up), 2 (half-even) or 3 (up).
* [more] {boolean} Whether the result of division was truncated.
*/
function round(x, sd, rm, more) {
var xc = x.c;
if (rm === UNDEFINED) rm = Big.RM;
if (rm !== 0 && rm !== 1 && rm !== 2 && rm !== 3) {
throw Error(INVALID_RM);
}
if (sd < 1) {
more =
rm === 3 && (more || !!xc[0]) || sd === 0 && (
rm === 1 && xc[0] >= 5 ||
rm === 2 && (xc[0] > 5 || xc[0] === 5 && (more || xc[1] !== UNDEFINED))
);
xc.length = 1;
if (more) {
// 1, 0.1, 0.01, 0.001, 0.0001 etc.
x.e = x.e - sd + 1;
xc[0] = 1;
} else {
// Zero.
xc[0] = x.e = 0;
}
} else if (sd < xc.length) {
// xc[sd] is the digit after the digit that may be rounded up.
more =
rm === 1 && xc[sd] >= 5 ||
rm === 2 && (xc[sd] > 5 || xc[sd] === 5 &&
(more || xc[sd + 1] !== UNDEFINED || xc[sd - 1] & 1)) ||
rm === 3 && (more || !!xc[0]);
// Remove any digits after the required precision.
xc.length = sd--;
// Round up?
if (more) {
// Rounding up may mean the previous digit has to be rounded up.
for (; ++xc[sd] > 9;) {
xc[sd] = 0;
if (!sd--) {
++x.e;
xc.unshift(1);
}
}
}
// Remove trailing zeros.
for (sd = xc.length; !xc[--sd];) xc.pop();
}
return x;
}
/*
* Return a string representing the value of Big x in normal or exponential notation.
* Handles P.toExponential, P.toFixed, P.toJSON, P.toPrecision, P.toString and P.valueOf.
*/
function stringify(x, doExponential, isNonzero) {
var e = x.e,
s = x.c.join(''),
n = s.length;
// Exponential notation?
if (doExponential) {
s = s.charAt(0) + (n > 1 ? '.' + s.slice(1) : '') + (e < 0 ? 'e' : 'e+') + e;
// Normal notation.
} else if (e < 0) {
for (; ++e;) s = '0' + s;
s = '0.' + s;
} else if (e > 0) {
if (++e > n) {
for (e -= n; e--;) s += '0';
} else if (e < n) {
s = s.slice(0, e) + '.' + s.slice(e);
}
} else if (n > 1) {
s = s.charAt(0) + '.' + s.slice(1);
}
return x.s < 0 && isNonzero ? '-' + s : s;
}
// Prototype/instance methods
/*
* Return a new Big whose value is the absolute value of this Big.
*/
P.abs = function () {
var x = new this.constructor(this);
x.s = 1;
return x;
};
/*
* Return 1 if the value of this Big is greater than the value of Big y,
* -1 if the value of this Big is less than the value of Big y, or
* 0 if they have the same value.
*/
P.cmp = function (y) {
var isneg,
x = this,
xc = x.c,
yc = (y = new x.constructor(y)).c,
i = x.s,
j = y.s,
k = x.e,
l = y.e;
// Either zero?
if (!xc[0] || !yc[0]) return !xc[0] ? !yc[0] ? 0 : -j : i;
// Signs differ?
if (i != j) return i;
isneg = i < 0;
// Compare exponents.
if (k != l) return k > l ^ isneg ? 1 : -1;
j = (k = xc.length) < (l = yc.length) ? k : l;
// Compare digit by digit.
for (i = -1; ++i < j;) {
if (xc[i] != yc[i]) return xc[i] > yc[i] ^ isneg ? 1 : -1;
}
// Compare lengths.
return k == l ? 0 : k > l ^ isneg ? 1 : -1;
};
/*
* Return a new Big whose value is the value of this Big divided by the value of Big y, rounded,
* if necessary, to a maximum of Big.DP decimal places using rounding mode Big.RM.
*/
P.div = function (y) {
var x = this,
Big = x.constructor,
a = x.c, // dividend
b = (y = new Big(y)).c, // divisor
k = x.s == y.s ? 1 : -1,
dp = Big.DP;
if (dp !== ~~dp || dp < 0 || dp > MAX_DP) {
throw Error(INVALID_DP);
}
// Divisor is zero?
if (!b[0]) {
throw Error(DIV_BY_ZERO);
}
// Dividend is 0? Return +-0.
if (!a[0]) return new Big(k * 0);
var bl, bt, n, cmp, ri,
bz = b.slice(),
ai = bl = b.length,
al = a.length,
r = a.slice(0, bl), // remainder
rl = r.length,
q = y, // quotient
qc = q.c = [],
qi = 0,
p = dp + (q.e = x.e - y.e) + 1; // precision of the result
q.s = k;
k = p < 0 ? 0 : p;
// Create version of divisor with leading zero.
bz.unshift(0);
// Add zeros to make remainder as long as divisor.
for (; rl++ < bl;) r.push(0);
do {
// n is how many times the divisor goes into current remainder.
for (n = 0; n < 10; n++) {
// Compare divisor and remainder.
if (bl != (rl = r.length)) {
cmp = bl > rl ? 1 : -1;
} else {
for (ri = -1, cmp = 0; ++ri < bl;) {
if (b[ri] != r[ri]) {
cmp = b[ri] > r[ri] ? 1 : -1;
break;
}
}
}
// If divisor < remainder, subtract divisor from remainder.
if (cmp < 0) {
// Remainder can't be more than 1 digit longer than divisor.
// Equalise lengths using divisor with extra leading zero?
for (bt = rl == bl ? b : bz; rl;) {
if (r[--rl] < bt[rl]) {
ri = rl;
for (; ri && !r[--ri];) r[ri] = 9;
--r[ri];
r[rl] += 10;
}
r[rl] -= bt[rl];
}
for (; !r[0];) r.shift();
} else {
break;
}
}
// Add the digit n to the result array.
qc[qi++] = cmp ? n : ++n;
// Update the remainder.
if (r[0] && cmp) r[rl] = a[ai] || 0;
else r = [a[ai]];
} while ((ai++ < al || r[0] !== UNDEFINED) && k--);
// Leading zero? Do not remove if result is simply zero (qi == 1).
if (!qc[0] && qi != 1) {
// There can't be more than one zero.
qc.shift();
q.e--;
p--;
}
// Round?
if (qi > p) round(q, p, Big.RM, r[0] !== UNDEFINED);
return q;
};
/*
* Return true if the value of this Big is equal to the value of Big y, otherwise return false.
*/
P.eq = function (y) {
return this.cmp(y) === 0;
};
/*
* Return true if the value of this Big is greater than the value of Big y, otherwise return
* false.
*/
P.gt = function (y) {
return this.cmp(y) > 0;
};
/*
* Return true if the value of this Big is greater than or equal to the value of Big y, otherwise
* return false.
*/
P.gte = function (y) {
return this.cmp(y) > -1;
};
/*
* Return true if the value of this Big is less than the value of Big y, otherwise return false.
*/
P.lt = function (y) {
return this.cmp(y) < 0;
};
/*
* Return true if the value of this Big is less than or equal to the value of Big y, otherwise
* return false.
*/
P.lte = function (y) {
return this.cmp(y) < 1;
};
/*
* Return a new Big whose value is the value of this Big minus the value of Big y.
*/
P.minus = P.sub = function (y) {
var i, j, t, xlty,
x = this,
Big = x.constructor,
a = x.s,
b = (y = new Big(y)).s;
// Signs differ?
if (a != b) {
y.s = -b;
return x.plus(y);
}
var xc = x.c.slice(),
xe = x.e,
yc = y.c,
ye = y.e;
// Either zero?
if (!xc[0] || !yc[0]) {
// y is non-zero? x is non-zero? Or both are zero.
return yc[0] ? (y.s = -b, y) : new Big(xc[0] ? x : 0);
}
// Determine which is the bigger number. Prepend zeros to equalise exponents.
if (a = xe - ye) {
if (xlty = a < 0) {
a = -a;
t = xc;
} else {
ye = xe;
t = yc;
}
t.reverse();
for (b = a; b--;) t.push(0);
t.reverse();
} else {
// Exponents equal. Check digit by digit.
j = ((xlty = xc.length < yc.length) ? xc : yc).length;
for (a = b = 0; b < j; b++) {
if (xc[b] != yc[b]) {
xlty = xc[b] < yc[b];
break;
}
}
}
// x < y? Point xc to the array of the bigger number.
if (xlty) {
t = xc;
xc = yc;
yc = t;
y.s = -y.s;
}
/*
* Append zeros to xc if shorter. No need to add zeros to yc if shorter as subtraction only
* needs to start at yc.length.
*/
if ((b = (j = yc.length) - (i = xc.length)) > 0) for (; b--;) xc[i++] = 0;
// Subtract yc from xc.
for (b = i; j > a;) {
if (xc[--j] < yc[j]) {
for (i = j; i && !xc[--i];) xc[i] = 9;
--xc[i];
xc[j] += 10;
}
xc[j] -= yc[j];
}
// Remove trailing zeros.
for (; xc[--b] === 0;) xc.pop();
// Remove leading zeros and adjust exponent accordingly.
for (; xc[0] === 0;) {
xc.shift();
--ye;
}
if (!xc[0]) {
// n - n = +0
y.s = 1;
// Result must be zero.
xc = [ye = 0];
}
y.c = xc;
y.e = ye;
return y;
};
/*
* Return a new Big whose value is the value of this Big modulo the value of Big y.
*/
P.mod = function (y) {
var ygtx,
x = this,
Big = x.constructor,
a = x.s,
b = (y = new Big(y)).s;
if (!y.c[0]) {
throw Error(DIV_BY_ZERO);
}
x.s = y.s = 1;
ygtx = y.cmp(x) == 1;
x.s = a;
y.s = b;
if (ygtx) return new Big(x);
a = Big.DP;
b = Big.RM;
Big.DP = Big.RM = 0;
x = x.div(y);
Big.DP = a;
Big.RM = b;
return this.minus(x.times(y));
};
/*
* Return a new Big whose value is the value of this Big plus the value of Big y.
*/
P.plus = P.add = function (y) {
var t,
x = this,
Big = x.constructor,
a = x.s,
b = (y = new Big(y)).s;
// Signs differ?
if (a != b) {
y.s = -b;
return x.minus(y);
}
var xe = x.e,
xc = x.c,
ye = y.e,
yc = y.c;
// Either zero? y is non-zero? x is non-zero? Or both are zero.
if (!xc[0] || !yc[0]) return yc[0] ? y : new Big(xc[0] ? x : a * 0);
xc = xc.slice();
// Prepend zeros to equalise exponents.
// Note: reverse faster than unshifts.
if (a = xe - ye) {
if (a > 0) {
ye = xe;
t = yc;
} else {
a = -a;
t = xc;
}
t.reverse();
for (; a--;) t.push(0);
t.reverse();
}
// Point xc to the longer array.
if (xc.length - yc.length < 0) {
t = yc;
yc = xc;
xc = t;
}
a = yc.length;
// Only start adding at yc.length - 1 as the further digits of xc can be left as they are.
for (b = 0; a; xc[a] %= 10) b = (xc[--a] = xc[a] + yc[a] + b) / 10 | 0;
// No need to check for zero, as +x + +y != 0 && -x + -y != 0
if (b) {
xc.unshift(b);
++ye;
}
// Remove trailing zeros.
for (a = xc.length; xc[--a] === 0;) xc.pop();
y.c = xc;
y.e = ye;
return y;
};
/*
* Return a Big whose value is the value of this Big raised to the power n.
* If n is negative, round to a maximum of Big.DP decimal places using rounding
* mode Big.RM.
*
* n {number} Integer, -MAX_POWER to MAX_POWER inclusive.
*/
P.pow = function (n) {
var x = this,
one = new x.constructor(1),
y = one,
isneg = n < 0;
if (n !== ~~n || n < -MAX_POWER || n > MAX_POWER) {
throw Error(INVALID + 'exponent');
}
if (isneg) n = -n;
for (;;) {
if (n & 1) y = y.times(x);
n >>= 1;
if (!n) break;
x = x.times(x);
}
return isneg ? one.div(y) : y;
};
/*
* Return a new Big whose value is the value of this Big rounded to a maximum precision of sd
* significant digits using rounding mode rm, or Big.RM if rm is not specified.
*
* sd {number} Significant digits: integer, 1 to MAX_DP inclusive.
* rm? {number} Rounding mode: 0 (down), 1 (half-up), 2 (half-even) or 3 (up).
*/
P.prec = function (sd, rm) {
if (sd !== ~~sd || sd < 1 || sd > MAX_DP) {
throw Error(INVALID + 'precision');
}
return round(new this.constructor(this), sd, rm);
};
/*
* Return a new Big whose value is the value of this Big rounded to a maximum of dp decimal places
* using rounding mode rm, or Big.RM if rm is not specified.
* If dp is negative, round to an integer which is a multiple of 10**-dp.
* If dp is not specified, round to 0 decimal places.
*
* dp? {number} Integer, -MAX_DP to MAX_DP inclusive.
* rm? {number} Rounding mode: 0 (down), 1 (half-up), 2 (half-even) or 3 (up).
*/
P.round = function (dp, rm) {
if (dp === UNDEFINED) dp = 0;
else if (dp !== ~~dp || dp < -MAX_DP || dp > MAX_DP) {
throw Error(INVALID_DP);
}
return round(new this.constructor(this), dp + this.e + 1, rm);
};
/*
* Return a new Big whose value is the square root of the value of this Big, rounded, if
* necessary, to a maximum of Big.DP decimal places using rounding mode Big.RM.
*/
P.sqrt = function () {
var r, c, t,
x = this,
Big = x.constructor,
s = x.s,
e = x.e,
half = new Big(0.5);
// Zero?
if (!x.c[0]) return new Big(x);
// Negative?
if (s < 0) {
throw Error(NAME + 'No square root');
}
// Estimate.
s = Math.sqrt(x + '');
// Math.sqrt underflow/overflow?
// Re-estimate: pass x coefficient to Math.sqrt as integer, then adjust the result exponent.
if (s === 0 || s === 1 / 0) {
c = x.c.join('');
if (!(c.length + e & 1)) c += '0';
s = Math.sqrt(c);
e = ((e + 1) / 2 | 0) - (e < 0 || e & 1);
r = new Big((s == 1 / 0 ? '5e' : (s = s.toExponential()).slice(0, s.indexOf('e') + 1)) + e);
} else {
r = new Big(s);
}
e = r.e + (Big.DP += 4);
// Newton-Raphson iteration.
do {
t = r;
r = half.times(t.plus(x.div(t)));
} while (t.c.slice(0, e).join('') !== r.c.slice(0, e).join(''));
return round(r, (Big.DP -= 4) + r.e + 1, Big.RM);
};
/*
* Return a new Big whose value is the value of this Big times the value of Big y.
*/
P.times = P.mul = function (y) {
var c,
x = this,
Big = x.constructor,
xc = x.c,
yc = (y = new Big(y)).c,
a = xc.length,
b = yc.length,
i = x.e,
j = y.e;
// Determine sign of result.
y.s = x.s == y.s ? 1 : -1;
// Return signed 0 if either 0.
if (!xc[0] || !yc[0]) return new Big(y.s * 0);
// Initialise exponent of result as x.e + y.e.
y.e = i + j;
// If array xc has fewer digits than yc, swap xc and yc, and lengths.
if (a < b) {
c = xc;
xc = yc;
yc = c;
j = a;
a = b;
b = j;
}
// Initialise coefficient array of result with zeros.
for (c = new Array(j = a + b); j--;) c[j] = 0;
// Multiply.
// i is initially xc.length.
for (i = b; i--;) {
b = 0;
// a is yc.length.
for (j = a + i; j > i;) {
// Current sum of products at this digit position, plus carry.
b = c[j] + yc[i] * xc[j - i - 1] + b;
c[j--] = b % 10;
// carry
b = b / 10 | 0;
}
c[j] = b;
}
// Increment result exponent if there is a final carry, otherwise remove leading zero.
if (b) ++y.e;
else c.shift();
// Remove trailing zeros.
for (i = c.length; !c[--i];) c.pop();
y.c = c;
return y;
};
/*
* Return a string representing the value of this Big in exponential notation rounded to dp fixed
* decimal places using rounding mode rm, or Big.RM if rm is not specified.
*
* dp? {number} Decimal places: integer, 0 to MAX_DP inclusive.
* rm? {number} Rounding mode: 0 (down), 1 (half-up), 2 (half-even) or 3 (up).
*/
P.toExponential = function (dp, rm) {
var x = this,
n = x.c[0];
if (dp !== UNDEFINED) {
if (dp !== ~~dp || dp < 0 || dp > MAX_DP) {
throw Error(INVALID_DP);
}
x = round(new x.constructor(x), ++dp, rm);
for (; x.c.length < dp;) x.c.push(0);
}
return stringify(x, true, !!n);
};
/*
* Return a string representing the value of this Big in normal notation rounded to dp fixed
* decimal places using rounding mode rm, or Big.RM if rm is not specified.
*
* dp? {number} Decimal places: integer, 0 to MAX_DP inclusive.
* rm? {number} Rounding mode: 0 (down), 1 (half-up), 2 (half-even) or 3 (up).
*
* (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.
* (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
*/
P.toFixed = function (dp, rm) {
var x = this,
n = x.c[0];
if (dp !== UNDEFINED) {
if (dp !== ~~dp || dp < 0 || dp > MAX_DP) {
throw Error(INVALID_DP);
}
x = round(new x.constructor(x), dp + x.e + 1, rm);
// x.e may have changed if the value is rounded up.
for (dp = dp + x.e + 1; x.c.length < dp;) x.c.push(0);
}
return stringify(x, false, !!n);
};
/*
* Return a string representing the value of this Big.
* Return exponential notation if this Big has a positive exponent equal to or greater than
* Big.PE, or a negative exponent equal to or less than Big.NE.
* Omit the sign for negative zero.
*/
P.toJSON = P.toString = function () {
var x = this,
Big = x.constructor;
return stringify(x, x.e <= Big.NE || x.e >= Big.PE, !!x.c[0]);
};
/*
* Return the value of this Big as a primitve number.
*/
P.toNumber = function () {
var n = Number(stringify(this, true, true));
if (this.constructor.strict === true && !this.eq(n.toString())) {
throw Error(NAME + 'Imprecise conversion');
}
return n;
};
/*
* Return a string representing the value of this Big rounded to sd significant digits using
* rounding mode rm, or Big.RM if rm is not specified.
* Use exponential notation if sd is less than the number of digits necessary to represent
* the integer part of the value in normal notation.
*
* sd {number} Significant digits: integer, 1 to MAX_DP inclusive.
* rm? {number} Rounding mode: 0 (down), 1 (half-up), 2 (half-even) or 3 (up).
*/
P.toPrecision = function (sd, rm) {
var x = this,
Big = x.constructor,
n = x.c[0];
if (sd !== UNDEFINED) {
if (sd !== ~~sd || sd < 1 || sd > MAX_DP) {
throw Error(INVALID + 'precision');
}
x = round(new Big(x), sd, rm);
for (; x.c.length < sd;) x.c.push(0);
}
return stringify(x, sd <= x.e || x.e <= Big.NE || x.e >= Big.PE, !!n);
};
/*
* Return a string representing the value of this Big.
* Return exponential notation if this Big has a positive exponent equal to or greater than
* Big.PE, or a negative exponent equal to or less than Big.NE.
* Include the sign for negative zero.
*/
P.valueOf = function () {
var x = this,
Big = x.constructor;
if (Big.strict === true) {
throw Error(NAME + 'valueOf disallowed');
}
return stringify(x, x.e <= Big.NE || x.e >= Big.PE, true);
};
// Export
Big = _Big_();
Big['default'] = Big.Big = Big;
//AMD.
if (typeof define === 'function' && define.amd) {
define(function () { return Big; });
// Node and other CommonJS-like environments that support module.exports.
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = Big;
//Browser.
} else {
GLOBAL.Big = Big;
}
})(this);
|
/**
* Tom Select v1.7.7
* Licensed under the Apache License, Version 2.0 (the "License");
*/
import TomSelect from '../../tom-select.js';
/**
* Converts a scalar to its best string representation
* for hash keys and HTML attribute values.
*
* Transformations:
* 'str' -> 'str'
* null -> ''
* undefined -> ''
* true -> '1'
* false -> '0'
* 0 -> '0'
* 1 -> '1'
*
*/
const hash_key = value => {
if (typeof value === 'undefined' || value === null) return null;
return get_hash(value);
};
const get_hash = value => {
if (typeof value === 'boolean') return value ? '1' : '0';
return value + '';
};
/**
* Prevent default
*
*/
const preventDefault = (evt, stop = false) => {
if (evt) {
evt.preventDefault();
if (stop) {
evt.stopPropagation();
}
}
};
/**
* Return a dom element from either a dom query string, jQuery object, a dom element or html string
* https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518
*
* param query should be {}
*/
const getDom = query => {
if (query.jquery) {
return query[0];
}
if (query instanceof HTMLElement) {
return query;
}
if (query.indexOf('<') > -1) {
let div = document.createElement('div');
div.innerHTML = query.trim(); // Never return a text node of whitespace as the result
return div.firstChild;
}
return document.querySelector(query);
};
/**
* Plugin: "restore_on_backspace" (Tom Select)
* Copyright (c) contributors
*
* 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.
*
*/
TomSelect.define('checkbox_options', function () {
var self = this;
var orig_onOptionSelect = self.onOptionSelect;
self.settings.hideSelected = false; // update the checkbox for an option
var UpdateCheckbox = function UpdateCheckbox(option) {
setTimeout(() => {
var checkbox = option.querySelector('input');
if (option.classList.contains('selected')) {
checkbox.checked = true;
} else {
checkbox.checked = false;
}
}, 1);
}; // add checkbox to option template
self.hook('after', 'setupTemplates', () => {
var orig_render_option = self.settings.render.option;
self.settings.render.option = (data, escape_html) => {
var rendered = getDom(orig_render_option.call(self, data, escape_html));
var checkbox = document.createElement('input');
checkbox.addEventListener('click', function (evt) {
preventDefault(evt);
});
checkbox.type = 'checkbox';
const hashed = hash_key(data[self.settings.valueField]);
if (hashed && self.items.indexOf(hashed) > -1) {
checkbox.checked = true;
}
rendered.prepend(checkbox);
return rendered;
};
}); // uncheck when item removed
self.on('item_remove', value => {
var option = self.getOption(value);
if (option) {
// if dropdown hasn't been opened yet, the option won't exist
option.classList.remove('selected'); // selected class won't be removed yet
UpdateCheckbox(option);
}
}); // remove items when selected option is clicked
self.hook('instead', 'onOptionSelect', (evt, option) => {
if (option.classList.contains('selected')) {
option.classList.remove('selected');
self.removeItem(option.dataset.value);
self.refreshOptions();
preventDefault(evt, true);
return;
}
orig_onOptionSelect.call(self, evt, option);
UpdateCheckbox(option);
});
});
//# sourceMappingURL=plugin.js.map
|
var dbm = require('db-migrate');
var type = dbm.dataType;
exports.up = function(db, callback) {
db.createTable('ripple_addresses', {
id: { type: 'int', primaryKey: true, autoIncrement: true },
managed: { type: 'boolean', default: false, notNull: true},
address: { type: 'string', notNull: true },
type: { type: 'string', notNull: true },
user_id: { type: 'int' },
tag: { type: 'int' },
secret: { type: 'string' },
previous_transaction_hash: { type: 'string' },
createdAt: { type: 'datetime' },
updatedAt: { type: 'datetime' }
}, callback);
};
exports.down = function(db, callback) {
db.dropTable('ripple_addresses', callback);
};
|
{
"name": "aggregate.js",
"url": "https://github.com/jdarling/aggregate.js.git"
}
|
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var React = require('react');
var StylePropable = require('../mixins/style-propable');
var DefaultRawTheme = require('../styles/raw-themes/light-raw-theme');
var ThemeManager = require('../styles/theme-manager');
var LinkMenuItem = React.createClass({
displayName: 'LinkMenuItem',
mixins: [StylePropable],
contextTypes: {
muiTheme: React.PropTypes.object
},
propTypes: {
index: React.PropTypes.number.isRequired,
payload: React.PropTypes.string.isRequired,
text: React.PropTypes.string.isRequired,
target: React.PropTypes.string,
active: React.PropTypes.bool,
disabled: React.PropTypes.bool,
className: React.PropTypes.string,
style: React.PropTypes.object
},
getDefaultProps: function getDefaultProps() {
return {
active: false,
disabled: false
};
},
//for passing default theme context to children
childContextTypes: {
muiTheme: React.PropTypes.object
},
getChildContext: function getChildContext() {
return {
muiTheme: this.state.muiTheme
};
},
getInitialState: function getInitialState() {
return {
muiTheme: this.context.muiTheme ? this.context.muiTheme : ThemeManager.getMuiTheme(DefaultRawTheme),
hovered: false
};
},
//to update theme inside state whenever a new theme is passed down
//from the parent / owner using context
componentWillReceiveProps: function componentWillReceiveProps(nextProps, nextContext) {
var newMuiTheme = nextContext.muiTheme ? nextContext.muiTheme : this.state.muiTheme;
this.setState({ muiTheme: newMuiTheme });
},
getTheme: function getTheme() {
return this.state.muiTheme.menuItem;
},
getStyles: function getStyles() {
var style = {
root: {
userSelect: 'none',
cursor: 'pointer',
display: 'block',
lineHeight: this.getTheme().height + 'px',
paddingLeft: this.getTheme().padding,
paddingRight: this.getTheme().padding
},
rootWhenHovered: {
backgroundColor: this.getTheme().hoverColor
},
rootWhenSelected: {
color: this.getTheme().selectedTextColor
},
rootWhenDisabled: {
cursor: 'default',
color: this.state.muiTheme.rawTheme.palette.disabledColor
}
};
return style;
},
render: function render() {
var onClickHandler = this.props.disabled ? this._stopLink : undefined;
// Prevent context menu 'Open In New Tab/Window'
var linkAttribute = this.props.disabled ? 'data-href' : 'href';
var link = {};
link[linkAttribute] = this.props.payload;
var styles = this.getStyles();
var linkStyles = this.prepareStyles(styles.root, this.props.selected && styles.rootWhenSelected, this.props.selected && styles.rootWhenSelected, this.props.active && !this.props.disabled && styles.rootWhenHovered, this.props.style, this.props.disabled && styles.rootWhenDisabled);
return React.createElement(
'a',
_extends({
key: this.props.index,
target: this.props.target,
style: linkStyles }, link, {
className: this.props.className,
onClick: onClickHandler,
onMouseEnter: this._handleMouseEnter,
onMouseLeave: this._handleMouseLeave }),
this.props.text
);
},
_stopLink: function _stopLink(event) {
event.preventDefault();
},
_handleMouseEnter: function _handleMouseEnter(e) {
this.setState({ hovered: true });
if (!this.props.disabled && this.props.onMouseEnter) this.props.onMouseEnter(e);
},
_handleMouseLeave: function _handleMouseLeave(e) {
this.setState({ hovered: false });
if (!this.props.disabled && this.props.onMouseLeave) this.props.onMouseLeave(e);
}
});
module.exports = LinkMenuItem; |
/* Magic Mirror Test config default calendar with auth by default
*
* By Rodrigo Ramírez Norambuena https://rodrigoramirez.com
* MIT Licensed.
*/
let config = {
timeFormat: 12,
modules: [
{
module: "calendar",
position: "bottom_bar",
config: {
calendars: [
{
maximumNumberOfDays: 10000,
url: "http://localhost:8010/tests/configs/data/calendar_test.ics",
auth: {
user: "MagicMirror",
pass: "CallMeADog"
}
}
]
}
}
]
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {
module.exports = config;
}
|
/**
* Module dependencies.
*/
var Package = require('./Package');
var debug = require('debug')('component');
var mkdir = require('mkdirp');
var utils = require('./utils');
var fs = require('fs');
var path = require('path');
var join = path.join;
var resolve = path.resolve;
var exists = fs.existsSync;
var request = require('superagent');
/**
* Remote.
*/
var remote = 'http://50.116.26.197/components'; // TODO: settings
/**
* Expose utils.
*/
exports.utils = utils;
/**
* Lookup `pkg` within `paths`.
*
* @param {String} pkg
* @param {String} paths
* @return {String} path
* @api private
*/
exports.lookup = function(pkg, paths){
pkg = pkg.toLowerCase();
debug('lookup %s', pkg);
for (var i = 0; i < paths.length; ++i) {
var path = join(paths[i], pkg);
debug('check %s', join(path, 'component.json'));
if (exists(join(path, 'component.json'))) {
debug('found %s', path);
return path;
}
}
};
/**
* Return the dependencies of local `pkg`,
* as one or more objects in an array,
* since `pkg` may reference other local
* packages as dependencies.
*
* @param {String} pkg
* @param {Array} [paths]
* @return {Array}
* @api private
*/
exports.dependenciesOf = function(pkg, paths, parent){
paths = paths || [];
var path = exports.lookup(pkg, paths);
if (!path && parent) throw new Error('failed to lookup "' + parent + '"\'s dep "' + pkg + '"');
if (!path) throw new Error('failed to lookup "' + pkg + '"');
var conf = require(resolve(path, 'component.json'));
var deps = [conf.dependencies || {}];
if (conf.local) {
var localPaths = (conf.paths || []).map(function(depPath){
return resolve(path, depPath);
});
conf.local.forEach(function(dep){
deps = deps.concat(exports.dependenciesOf(dep, paths.concat(localPaths), pkg));
});
}
return deps;
};
/**
* Install the given `pkg` at `version`.
*
* @param {String} pkg
* @param {String} version
* @param {Object} options
* @return {Package}
* @api public
*/
exports.install = function(pkg, version, options){
return new Package(pkg, version, options);
};
/**
* Fetch info for the given `pkg` at `version`.
*
* @param {String} pkg
* @param {String} version
* @return {Package}
* @api public
*/
exports.info = function(pkg, version, fn){
pkg = new Package(pkg, version);
pkg.getJSON(fn);
};
/**
* Check if component `name` exists in ./components.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
exports.exists = function(name){
name = name.replace('/', '-');
var file = path.join('components', name);
return exists(file);
};
/**
* Search with the given `query` and callback `fn(err, components)`.
*
* @param {String} query
* @param {Function} fn
* @api public
*/
exports.search = function(query, fn){
var url = query
? remote + '/search/' + encodeURIComponent(query)
: remote + '/all';
request
.get(url)
.set('Accept-Encoding', 'gzip')
.end(function(err, res){
if (err) return fn(err);
fn(null, res.body);
});
};
/**
* Register `username` and `project`.
*
* @param {String} username
* @param {String} project
* @param {Object} json config
* @param {Function} fn
* @api public
*/
exports.register = function(username, project, conf, fn){
var url = remote + '/component/' + username + '/' + project;
request
.post(url)
.send(conf)
.end(function(err, res){
if (err) return fn(err);
if (!res.ok) return fn(new Error('got ' + res.status + ' response ' + res.text));
fn();
});
};
/**
* Fetch `pkg` changelog.
*
* @param {String} pkg
* @param {Function} fn
* @api public
*/
exports.changes = function(pkg, fn){
// TODO: check changelog etc...
exports.file(pkg, 'History.md', fn);
};
/**
* Fetch `pkg`'s `file` contents.
*
* @param {String} pkg
* @param {String} file
* @param {Function} fn
* @api public
*/
exports.file = function(pkg, file, fn){
var url = 'https://api.github.com/repos/' + pkg + '/contents/' + file;
request
.get(url)
.end(function(err, res){
if (err) return fn(err);
if (!res.ok) return fn();
fn(null, res.body);
});
};
|
/**
* @ngdoc service
* @name languages
*
* @description Provides access to the list of languages for available translations.
*
* The list of languages is initialized from the session state
* and can then later be updated using the add() method.
*/
'use strict';
var eventsa = require('./events');
// @ngInject
function votes(settings, session, $rootScope, $http) {
$rootScope.$on(eventsa.SESSION_RELOADED, function (event, languageName) {
if (languageName == "") {
$rootScope.allVotes = {};
$rootScope.updateUserList(0);
}
});
function addVote(username, languageId, score) {
var pageUri = $rootScope.pageUri;
var groupPubid = $rootScope.groupPubid;
var response = $http({
method: 'POST',
url: settings.serviceUrl + 'votes/' + username + '/' + groupPubid + '/' + languageId + '/' + pageUri + '/' + score + '/' + 'addVote',
});
session.reload("");
return response;
};
function showVote(author, score) {
//console.log(session.state.votes);
};
return {
addVote: addVote,
showVote: showVote,
};
};
module.exports = votes; |
define(function(require, exports, module) {
window.jQuery = window.$ = jQuery = require('$');
require('bootstrap');
exports.load_script = function(module, options) {
require.async('./controller/' + module, function(module) {
$(document).ready(function() {
if ($.isFunction(module.run)) {
module.run(options);
}
});
});
};
window.app.load = exports.load_script;
if (window.app.script) {
exports.load_script(window.app.script);
window.app.script = null;
}
var Widget = require('arale.widget');
Widget.autoRenderAll();
require('bootstrap.modal.hack');
window.setTimeout(function() {
$('.ag-error-show').slideUp('slow', function() {
$(this).find('button').click();
});
}, 2000);
$('[data-toggle="tooltip"]').tooltip(); // bootstrap tooltip
}); |
'use strict';
var TimeUnit = require('../TimeUnit');
var zurvan = require('../zurvan');
var assert = require('assert');
describe('zurvan', function() {
describe('under special configuration', function() {
it('runs at arbitrary time since process startup', function() {
return zurvan
.interceptTimers({ timeSinceStartup: 4 })
.then(function() {
assert.equal(4, process.uptime());
assert.deepEqual([4, 0], process.hrtime());
return zurvan.releaseTimers();
})
.then(function() {
return zurvan.interceptTimers({ timeSinceStartup: [100, 132587951] });
})
.then(function() {
assert(Math.abs(100.132587951 - process.uptime()) < 1e-12);
assert.deepEqual([100, 132587951], process.hrtime());
return zurvan.releaseTimers();
})
.then(function() {
return zurvan.interceptTimers({
timeSinceStartup: TimeUnit.microseconds(12e8 + 100)
});
})
.then(function() {
assert(Math.abs(1200.0001 - process.uptime()) < 1e-12);
assert.deepEqual([1200, 100000], process.hrtime());
return zurvan.releaseTimers();
})
.then(function() {
return zurvan.interceptTimers({ timeSinceStartup: [0, 1e10] });
})
.then(function() {
assert.equal(10, process.uptime());
assert.deepEqual([10, 0], process.hrtime());
return zurvan.releaseTimers();
});
});
it('runs at any required system time', function() {
return zurvan
.interceptTimers({ systemTime: Date.UTC(2015, 0, 5) })
.then(function() {
var nowDate = new Date();
assert.equal(nowDate.toISOString(), '2015-01-05T00:00:00.000Z');
assert.equal(0, process.uptime());
return zurvan.releaseTimers();
})
.then(function() {
return zurvan.interceptTimers({
systemTime: new Date(Date.UTC(2010, 5, 6))
});
})
.then(function() {
var nowDate = new Date();
assert.equal(nowDate.toISOString(), '2010-06-06T00:00:00.000Z');
assert.equal(0, process.uptime());
return zurvan.releaseTimers();
})
.then(function() {
return zurvan.interceptTimers({
systemTime: new Date(Date.UTC(1999, 9, 8, 15)).toString(),
timeSinceStartup: TimeUnit.seconds(45)
});
})
.then(function() {
var nowDate = new Date();
assert(nowDate.toISOString(), '1999-10-08T15:00:00.000Z');
assert.equal(45, process.uptime());
return zurvan.releaseTimers();
});
});
it('throws on invalid clearTimeout/clearInterval request', function() {
return zurvan
.interceptTimers({ throwOnInvalidClearTimer: true })
.then(function() {
assert.throws(function() {
clearTimeout(undefined);
}, /undefined/);
assert.throws(function() {
clearInterval(3);
}, /3/);
assert.throws(function() {
clearInterval({});
}, /{}/);
assert.throws(function() {
clearInterval(function() {
var t;
});
}, /var t;/);
assert.throws(function() {
clearTimeout({ uid: 3 });
});
var trickyRef = {
uid: 1
};
trickyRef.ref = trickyRef;
assert.throws(function() {
clearTimeout(trickyRef);
}, /not easily serializable/);
return zurvan.releaseTimers();
});
});
it('throws on invalid clearTimeout from setInterval and vice versa', function() {
return zurvan
.interceptTimers({ throwOnInvalidClearTimer: true })
.then(function() {
var timeoutId = setTimeout(function() {}, 100);
assert.throws(function() {
clearInterval(timeoutId);
}, /was not issued/);
clearTimeout(timeoutId);
var intervalId = setInterval(function() {}, 100);
assert.throws(function() {
clearTimeout(intervalId);
}, /was not issued/);
clearInterval(intervalId);
return zurvan.releaseTimers();
});
});
});
});
|
angular.module('DemoApp', ['angularTouchWidgets']).
controller('demoController', function($scope) {
$scope.driversList = [
{
Driver: {
givenName: 'Sebastian',
familyName: 'Vettel'
},
points: 322,
nationality: "German",
Constructors: [
{name: "Red Bull"}
]
},
{
Driver: {
givenName: 'Fernando',
familyName: 'Alonso'
},
points: 207,
nationality: "Spanish",
Constructors: [
{name: "Ferrari"}
]
}
];
});
|
define([
'jquery',
'backbone',
'marionette',
'App',
'backbone.caching-fetcher' // should be last item in required list. Plugin doesn't return any object
],function ($, Backbone, Marionette, App) {
'use strict';
var redirectToLoginIfNotAuthorized = function(response) {
console.log(response, '401')
//if (response.status === 401){
// window.location = '/login';
//}
};
var showLoader = function() {
$('.navbar .loading').removeClass('loaded');
};
var hideLoader = function() {
$('.navbar .loading').addClass('loaded');
};
return new window.Backbone.CachingFetcher({
onFetchStart: showLoader,
onSuccess: hideLoader,
onSingleFail: redirectToLoginIfNotAuthorized,
onFail: function(data) {
if (!data.fail) {
App.execute('console:error', 'An error occured during resource fetching');
}
}
});
});
|
/**
* Creates map, draws paths, binds events.
* @constructor
* @param {Object} params Parameters to initialize map with.
* @param {String} params.map Name of the map in the format <code>territory_proj_lang</code> where <code>territory</code> is a unique code or name of the territory which the map represents (ISO 3166 standard is used where possible), <code>proj</code> is a name of projection used to generate representation of the map on the plane (projections are named according to the conventions of proj4 utility) and <code>lang</code> is a code of the language, used for the names of regions.
* @param {String} params.backgroundColor Background color of the map in CSS format.
* @param {Boolean} params.zoomOnScroll When set to true map could be zoomed using mouse scroll. Default value is <code>true</code>.
* @param {Boolean} params.zoomOnScrollSpeed Mouse scroll speed. Number from 1 to 10. Default value is <code>3</code>.
* @param {Boolean} params.panOnDrag When set to true, the map pans when being dragged. Default value is <code>true</code>.
* @param {Number} params.zoomMax Indicates the maximum zoom ratio which could be reached zooming the map. Default value is <code>8</code>.
* @param {Number} params.zoomMin Indicates the minimum zoom ratio which could be reached zooming the map. Default value is <code>1</code>.
* @param {Number} params.zoomStep Indicates the multiplier used to zoom map with +/- buttons. Default value is <code>1.6</code>.
* @param {Boolean} params.zoomAnimate Indicates whether or not to animate changing of map zoom with zoom buttons.
* @param {Boolean} params.regionsSelectable When set to true regions of the map could be selected. Default value is <code>false</code>.
* @param {Boolean} params.regionsSelectableOne Allow only one region to be selected at the moment. Default value is <code>false</code>.
* @param {Boolean} params.markersSelectable When set to true markers on the map could be selected. Default value is <code>false</code>.
* @param {Boolean} params.markersSelectableOne Allow only one marker to be selected at the moment. Default value is <code>false</code>.
* @param {Object} params.regionStyle Set the styles for the map's regions. Each region or marker has four states: <code>initial</code> (default state), <code>hover</code> (when the mouse cursor is over the region or marker), <code>selected</code> (when region or marker is selected), <code>selectedHover</code> (when the mouse cursor is over the region or marker and it's selected simultaneously). Styles could be set for each of this states. Default value for that parameter is:
<pre>{
initial: {
fill: 'white',
"fill-opacity": 1,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 1
},
hover: {
"fill-opacity": 0.8,
cursor: 'pointer'
},
selected: {
fill: 'yellow'
},
selectedHover: {
}
}</pre>
* @param {Object} params.regionLabelStyle Set the styles for the regions' labels. Each region or marker has four states: <code>initial</code> (default state), <code>hover</code> (when the mouse cursor is over the region or marker), <code>selected</code> (when region or marker is selected), <code>selectedHover</code> (when the mouse cursor is over the region or marker and it's selected simultaneously). Styles could be set for each of this states. Default value for that parameter is:
<pre>{
initial: {
'font-family': 'Verdana',
'font-size': '12',
'font-weight': 'bold',
cursor: 'default',
fill: 'black'
},
hover: {
cursor: 'pointer'
}
}</pre>
* @param {Object} params.markerStyle Set the styles for the map's markers. Any parameter suitable for <code>regionStyle</code> could be used as well as numeric parameter <code>r</code> to set the marker's radius. Default value for that parameter is:
<pre>{
initial: {
fill: 'grey',
stroke: '#505050',
"fill-opacity": 1,
"stroke-width": 1,
"stroke-opacity": 1,
r: 5
},
hover: {
stroke: 'black',
"stroke-width": 2,
cursor: 'pointer'
},
selected: {
fill: 'blue'
},
selectedHover: {
}
}</pre>
* @param {Object} params.markerLabelStyle Set the styles for the markers' labels. Default value for that parameter is:
<pre>{
initial: {
'font-family': 'Verdana',
'font-size': '12',
'font-weight': 'bold',
cursor: 'default',
fill: 'black'
},
hover: {
cursor: 'pointer'
}
}</pre>
* @param {Object|Array} params.markers Set of markers to add to the map during initialization. In case of array is provided, codes of markers will be set as string representations of array indexes. Each marker is represented by <code>latLng</code> (array of two numeric values), <code>name</code> (string which will be show on marker's tip) and any marker styles.
* @param {Object} params.series Object with two keys: <code>markers</code> and <code>regions</code>. Each of which is an array of series configs to be applied to the respective map elements. See <a href="jvm.DataSeries.html">DataSeries</a> description for a list of parameters available.
* @param {Object|String} params.focusOn This parameter sets the initial position and scale of the map viewport. See <code>setFocus</code> docuemntation for possible parameters.
* @param {Object} params.labels Defines parameters for rendering static labels. Object could contain two keys: <code>regions</code> and <code>markers</code>. Each key value defines configuration object with the following possible options:
<ul>
<li><code>render {Function}</code> - defines method for converting region code or marker index to actual label value.</li>
<li><code>offsets {Object|Function}</code> - provides method or object which could be used to define label offset by region code or marker index.</li>
</ul>
<b>Plase note: static labels feature is not supported in Internet Explorer 8 and below.</b>
* @param {Array|Object|String} params.selectedRegions Set initially selected regions.
* @param {Array|Object|String} params.selectedMarkers Set initially selected markers.
* @param {Function} params.onRegionTipShow <code>(Event e, Object tip, String code)</code> Will be called right before the region tip is going to be shown.
* @param {Function} params.onRegionOver <code>(Event e, String code)</code> Will be called on region mouse over event.
* @param {Function} params.onRegionOut <code>(Event e, String code)</code> Will be called on region mouse out event.
* @param {Function} params.onRegionClick <code>(Event e, String code)</code> Will be called on region click event.
* @param {Function} params.onRegionSelected <code>(Event e, String code, Boolean isSelected, Array selectedRegions)</code> Will be called when region is (de)selected. <code>isSelected</code> parameter of the callback indicates whether region is selected or not. <code>selectedRegions</code> contains codes of all currently selected regions.
* @param {Function} params.onMarkerTipShow <code>(Event e, Object tip, String code)</code> Will be called right before the marker tip is going to be shown.
* @param {Function} params.onMarkerOver <code>(Event e, String code)</code> Will be called on marker mouse over event.
* @param {Function} params.onMarkerOut <code>(Event e, String code)</code> Will be called on marker mouse out event.
* @param {Function} params.onMarkerClick <code>(Event e, String code)</code> Will be called on marker click event.
* @param {Function} params.onMarkerSelected <code>(Event e, String code, Boolean isSelected, Array selectedMarkers)</code> Will be called when marker is (de)selected. <code>isSelected</code> parameter of the callback indicates whether marker is selected or not. <code>selectedMarkers</code> contains codes of all currently selected markers.
* @param {Function} params.onViewportChange <code>(Event e, Number scale)</code> Triggered when the map's viewport is changed (map was panned or zoomed).
*/
jvm.Map = function(params) {
var map = this,
e;
this.params = jvm.$.extend(true, {}, jvm.Map.defaultParams, params);
if (!jvm.Map.maps[this.params.map]) {
throw new Error('Attempt to use map which was not loaded: '+this.params.map);
}
this.mapData = jvm.Map.maps[this.params.map];
this.markers = {};
this.regions = {};
this.regionsColors = {};
this.regionsData = {};
this.container = jvm.$('<div>').addClass('jvectormap-container');
if (this.params.container) {
this.params.container.append( this.container );
}
this.container.data('mapObject', this);
this.defaultWidth = this.mapData.width;
this.defaultHeight = this.mapData.height;
this.setBackgroundColor(this.params.backgroundColor);
this.onResize = function(){
map.updateSize();
}
jvm.$(window).resize(this.onResize);
for (e in jvm.Map.apiEvents) {
if (this.params[e]) {
this.container.bind(jvm.Map.apiEvents[e]+'.jvectormap', this.params[e]);
}
}
this.canvas = new jvm.VectorCanvas(this.container[0], this.width, this.height);
if (this.params.bindTouchEvents) {
if (('ontouchstart' in window) || (window.DocumentTouch && document instanceof DocumentTouch)) {
this.bindContainerTouchEvents();
} else if (window.MSGesture) {
this.bindContainerPointerEvents();
}
}
this.bindContainerEvents();
this.bindElementEvents();
this.createTip();
if (this.params.zoomButtons) {
this.bindZoomButtons();
}
this.createRegions();
this.createMarkers(this.params.markers || {});
this.updateSize();
if (this.params.focusOn) {
if (typeof this.params.focusOn === 'string') {
this.params.focusOn = {region: this.params.focusOn};
} else if (jvm.$.isArray(this.params.focusOn)) {
this.params.focusOn = {regions: this.params.focusOn};
}
this.setFocus(this.params.focusOn);
}
if (this.params.selectedRegions) {
this.setSelectedRegions(this.params.selectedRegions);
}
if (this.params.selectedMarkers) {
this.setSelectedMarkers(this.params.selectedMarkers);
}
this.legendCntHorizontal = jvm.$('<div/>').addClass('jvectormap-legend-cnt jvectormap-legend-cnt-h');
this.legendCntVertical = jvm.$('<div/>').addClass('jvectormap-legend-cnt jvectormap-legend-cnt-v');
this.container.append(this.legendCntHorizontal);
this.container.append(this.legendCntVertical);
if (this.params.series) {
this.createSeries();
}
};
jvm.Map.prototype = {
transX: 0,
transY: 0,
scale: 1,
baseTransX: 0,
baseTransY: 0,
baseScale: 1,
width: 0,
height: 0,
/**
* Set background color of the map.
* @param {String} backgroundColor Background color in CSS format.
*/
setBackgroundColor: function(backgroundColor) {
this.container.css('background-color', backgroundColor);
},
resize: function() {
var curBaseScale = this.baseScale;
if (this.width / this.height > this.defaultWidth / this.defaultHeight) {
this.baseScale = this.height / this.defaultHeight;
this.baseTransX = Math.abs(this.width - this.defaultWidth * this.baseScale) / (2 * this.baseScale);
} else {
this.baseScale = this.width / this.defaultWidth;
this.baseTransY = Math.abs(this.height - this.defaultHeight * this.baseScale) / (2 * this.baseScale);
}
this.scale *= this.baseScale / curBaseScale;
this.transX *= this.baseScale / curBaseScale;
this.transY *= this.baseScale / curBaseScale;
},
/**
* Synchronize the size of the map with the size of the container. Suitable in situations where the size of the container is changed programmatically or container is shown after it became visible.
*/
updateSize: function(){
this.width = this.container.width();
this.height = this.container.height();
this.resize();
this.canvas.setSize(this.width, this.height);
this.applyTransform();
},
/**
* Reset all the series and show the map with the initial zoom.
*/
reset: function() {
var key,
i;
for (key in this.series) {
for (i = 0; i < this.series[key].length; i++) {
this.series[key][i].clear();
}
}
this.scale = this.baseScale;
this.transX = this.baseTransX;
this.transY = this.baseTransY;
this.applyTransform();
},
applyTransform: function() {
var maxTransX,
maxTransY,
minTransX,
minTransY;
if (this.defaultWidth * this.scale <= this.width) {
maxTransX = (this.width - this.defaultWidth * this.scale) / (2 * this.scale);
minTransX = (this.width - this.defaultWidth * this.scale) / (2 * this.scale);
} else {
maxTransX = 0;
minTransX = (this.width - this.defaultWidth * this.scale) / this.scale;
}
if (this.defaultHeight * this.scale <= this.height) {
maxTransY = (this.height - this.defaultHeight * this.scale) / (2 * this.scale);
minTransY = (this.height - this.defaultHeight * this.scale) / (2 * this.scale);
} else {
maxTransY = 0;
minTransY = (this.height - this.defaultHeight * this.scale) / this.scale;
}
if (this.transY > maxTransY) {
this.transY = maxTransY;
} else if (this.transY < minTransY) {
this.transY = minTransY;
}
if (this.transX > maxTransX) {
this.transX = maxTransX;
} else if (this.transX < minTransX) {
this.transX = minTransX;
}
this.canvas.applyTransformParams(this.scale, this.transX, this.transY);
if (this.markers) {
this.repositionMarkers();
}
this.repositionLabels();
this.container.trigger('viewportChange', [this.scale/this.baseScale, this.transX, this.transY]);
},
bindContainerEvents: function(){
var mouseDown = false,
oldPageX,
oldPageY,
map = this;
if (this.params.panOnDrag) {
this.container.mousemove(function(e){
if (mouseDown) {
map.transX -= (oldPageX - e.pageX) / map.scale;
map.transY -= (oldPageY - e.pageY) / map.scale;
map.applyTransform();
oldPageX = e.pageX;
oldPageY = e.pageY;
}
return false;
}).mousedown(function(e){
mouseDown = true;
oldPageX = e.pageX;
oldPageY = e.pageY;
return false;
});
this.onContainerMouseUp = function(){
mouseDown = false;
};
jvm.$('body').mouseup(this.onContainerMouseUp);
}
if (this.params.zoomOnScroll) {
this.container.mousewheel(function(event, delta, deltaX, deltaY) {
var offset = jvm.$(map.container).offset(),
centerX = event.pageX - offset.left,
centerY = event.pageY - offset.top,
zoomStep = Math.pow(1 + map.params.zoomOnScrollSpeed / 1000, event.deltaFactor * event.deltaY);
map.tip.hide();
map.setScale(map.scale * zoomStep, centerX, centerY);
event.preventDefault();
});
}
},
bindContainerTouchEvents: function(){
var touchStartScale,
touchStartDistance,
map = this,
touchX,
touchY,
centerTouchX,
centerTouchY,
lastTouchesLength,
handleTouchEvent = function(e){
var touches = e.originalEvent.touches,
offset,
scale,
transXOld,
transYOld;
if (e.type == 'touchstart') {
lastTouchesLength = 0;
}
if (touches.length == 1) {
if (lastTouchesLength == 1) {
transXOld = map.transX;
transYOld = map.transY;
map.transX -= (touchX - touches[0].pageX) / map.scale;
map.transY -= (touchY - touches[0].pageY) / map.scale;
map.applyTransform();
map.tip.hide();
if (transXOld != map.transX || transYOld != map.transY) {
e.preventDefault();
}
}
touchX = touches[0].pageX;
touchY = touches[0].pageY;
} else if (touches.length == 2) {
if (lastTouchesLength == 2) {
scale = Math.sqrt(
Math.pow(touches[0].pageX - touches[1].pageX, 2) +
Math.pow(touches[0].pageY - touches[1].pageY, 2)
) / touchStartDistance;
map.setScale(
touchStartScale * scale,
centerTouchX,
centerTouchY
)
map.tip.hide();
e.preventDefault();
} else {
offset = jvm.$(map.container).offset();
if (touches[0].pageX > touches[1].pageX) {
centerTouchX = touches[1].pageX + (touches[0].pageX - touches[1].pageX) / 2;
} else {
centerTouchX = touches[0].pageX + (touches[1].pageX - touches[0].pageX) / 2;
}
if (touches[0].pageY > touches[1].pageY) {
centerTouchY = touches[1].pageY + (touches[0].pageY - touches[1].pageY) / 2;
} else {
centerTouchY = touches[0].pageY + (touches[1].pageY - touches[0].pageY) / 2;
}
centerTouchX -= offset.left;
centerTouchY -= offset.top;
touchStartScale = map.scale;
touchStartDistance = Math.sqrt(
Math.pow(touches[0].pageX - touches[1].pageX, 2) +
Math.pow(touches[0].pageY - touches[1].pageY, 2)
);
}
}
lastTouchesLength = touches.length;
};
jvm.$(this.container).bind('touchstart', handleTouchEvent);
jvm.$(this.container).bind('touchmove', handleTouchEvent);
},
bindContainerPointerEvents: function(){
var map = this,
gesture = new MSGesture(),
element = this.container[0],
handlePointerDownEvent = function(e){
gesture.addPointer(e.pointerId);
},
handleGestureEvent = function(e){
var offset,
scale,
transXOld,
transYOld;
if (e.translationX != 0 || e.translationY != 0) {
transXOld = map.transX;
transYOld = map.transY;
map.transX += e.translationX / map.scale;
map.transY += e.translationY / map.scale;
map.applyTransform();
map.tip.hide();
if (transXOld != map.transX || transYOld != map.transY) {
e.preventDefault();
}
}
if (e.scale != 1) {
map.setScale(
map.scale * e.scale,
e.offsetX,
e.offsetY
)
map.tip.hide();
e.preventDefault();
}
};
gesture.target = element;
element.addEventListener("MSGestureChange", handleGestureEvent, false);
element.addEventListener("pointerdown", handlePointerDownEvent, false);
},
bindElementEvents: function(){
var map = this,
pageX,
pageY,
mouseMoved;
this.container.mousemove(function(e){
if (Math.abs(pageX - e.pageX) + Math.abs(pageY - e.pageY) > 2) {
mouseMoved = true;
}
});
/* Can not use common class selectors here because of the bug in jQuery
SVG handling, use with caution. */
this.container.delegate("[class~='jvectormap-element']", 'mouseover mouseout', function(e){
var baseVal = jvm.$(this).attr('class').baseVal || jvm.$(this).attr('class'),
type = baseVal.indexOf('jvectormap-region') === -1 ? 'marker' : 'region',
code = type == 'region' ? jvm.$(this).attr('data-code') : jvm.$(this).attr('data-index'),
element = type == 'region' ? map.regions[code].element : map.markers[code].element,
tipText = type == 'region' ? map.mapData.paths[code].name : (map.markers[code].config.name || ''),
tipShowEvent = jvm.$.Event(type+'TipShow.jvectormap'),
overEvent = jvm.$.Event(type+'Over.jvectormap');
if (e.type == 'mouseover') {
map.container.trigger(overEvent, [code]);
if (!overEvent.isDefaultPrevented()) {
element.setHovered(true);
}
map.tip.text(tipText);
map.container.trigger(tipShowEvent, [map.tip, code]);
if (!tipShowEvent.isDefaultPrevented()) {
map.tip.show();
map.tipWidth = map.tip.width();
map.tipHeight = map.tip.height();
}
} else {
element.setHovered(false);
map.tip.hide();
map.container.trigger(type+'Out.jvectormap', [code]);
}
});
/* Can not use common class selectors here because of the bug in jQuery
SVG handling, use with caution. */
this.container.delegate("[class~='jvectormap-element']", 'mousedown', function(e){
pageX = e.pageX;
pageY = e.pageY;
mouseMoved = false;
});
/* Can not use common class selectors here because of the bug in jQuery
SVG handling, use with caution. */
this.container.delegate("[class~='jvectormap-element']", 'mouseup', function(){
var baseVal = jvm.$(this).attr('class').baseVal ? jvm.$(this).attr('class').baseVal : jvm.$(this).attr('class'),
type = baseVal.indexOf('jvectormap-region') === -1 ? 'marker' : 'region',
code = type == 'region' ? jvm.$(this).attr('data-code') : jvm.$(this).attr('data-index'),
clickEvent = jvm.$.Event(type+'Click.jvectormap'),
element = type == 'region' ? map.regions[code].element : map.markers[code].element;
if (!mouseMoved) {
map.container.trigger(clickEvent, [code]);
if ((type === 'region' && map.params.regionsSelectable) || (type === 'marker' && map.params.markersSelectable)) {
if (!clickEvent.isDefaultPrevented()) {
if (map.params[type+'sSelectableOne']) {
map.clearSelected(type+'s');
}
element.setSelected(!element.isSelected);
}
}
}
});
},
bindZoomButtons: function() {
// var map = this;
// jvm.$('<div/>').addClass('jvectormap-zoomin').text('+').appendTo(this.container);
// jvm.$('<div/>').addClass('jvectormap-zoomout').html('−').appendTo(this.container);
// this.container.find('.jvectormap-zoomin').click(function(){
// map.setScale(map.scale * map.params.zoomStep, map.width / 2, map.height / 2, false, map.params.zoomAnimate);
// });
// this.container.find('.jvectormap-zoomout').click(function(){
// map.setScale(map.scale / map.params.zoomStep, map.width / 2, map.height / 2, false, map.params.zoomAnimate);
// });
},
createTip: function(){
var map = this;
this.tip = jvm.$('<div/>').addClass('jvectormap-tip').appendTo(jvm.$('body'));
this.container.mousemove(function(e){
var left = e.pageX-15-map.tipWidth,
top = e.pageY-15-map.tipHeight;
if (left < 5) {
left = e.pageX + 15;
}
if (top < 5) {
top = e.pageY + 15;
}
map.tip.css({
left: left,
top: top
});
});
},
setScale: function(scale, anchorX, anchorY, isCentered, animate) {
var viewportChangeEvent = jvm.$.Event('zoom.jvectormap'),
interval,
that = this,
i = 0,
count = Math.abs(Math.round((scale - this.scale) * 60 / Math.max(scale, this.scale))),
scaleStart,
scaleDiff,
transXStart,
transXDiff,
transYStart,
transYDiff,
transX,
transY,
deferred = new jvm.$.Deferred();
if (scale > this.params.zoomMax * this.baseScale) {
scale = this.params.zoomMax * this.baseScale;
} else if (scale < this.params.zoomMin * this.baseScale) {
scale = this.params.zoomMin * this.baseScale;
}
if (typeof anchorX != 'undefined' && typeof anchorY != 'undefined') {
zoomStep = scale / this.scale;
if (isCentered) {
transX = anchorX + this.defaultWidth * (this.width / (this.defaultWidth * scale)) / 2;
transY = anchorY + this.defaultHeight * (this.height / (this.defaultHeight * scale)) / 2;
} else {
transX = this.transX - (zoomStep - 1) / scale * anchorX;
transY = this.transY - (zoomStep - 1) / scale * anchorY;
}
}
if (animate && count > 0) {
scaleStart = this.scale;
scaleDiff = (scale - scaleStart) / count;
transXStart = this.transX * this.scale;
transYStart = this.transY * this.scale;
transXDiff = (transX * scale - transXStart) / count;
transYDiff = (transY * scale - transYStart) / count;
interval = setInterval(function(){
i += 1;
that.scale = scaleStart + scaleDiff * i;
that.transX = (transXStart + transXDiff * i) / that.scale;
that.transY = (transYStart + transYDiff * i) / that.scale;
that.applyTransform();
if (i == count) {
clearInterval(interval);
that.container.trigger(viewportChangeEvent, [scale/that.baseScale]);
deferred.resolve();
}
}, 10);
} else {
this.transX = transX;
this.transY = transY;
this.scale = scale;
this.applyTransform();
this.container.trigger(viewportChangeEvent, [scale/this.baseScale]);
deferred.resolve();
}
return deferred;
},
/**
* Set the map's viewport to the specific point and set zoom of the map to the specific level. Point and zoom level could be defined in two ways: using the code of some region to focus on or a central point and zoom level as numbers.
* @param This method takes a configuration object as the single argument. The options passed to it are the following:
* @param {Array} params.regions Array of region codes to zoom to.
* @param {String} params.region Region code to zoom to.
* @param {Number} params.scale Map scale to set.
* @param {Number} params.lat Latitude to set viewport to.
* @param {Number} params.lng Longitude to set viewport to.
* @param {Number} params.x Number from 0 to 1 specifying the horizontal coordinate of the central point of the viewport.
* @param {Number} params.y Number from 0 to 1 specifying the vertical coordinate of the central point of the viewport.
* @param {Boolean} params.animate Indicates whether or not to animate the scale change and transition.
*/
setFocus: function(config){
var bbox,
itemBbox,
newBbox,
codes,
i,
point;
config = config || {};
if (config.region) {
codes = [config.region];
} else if (config.regions) {
codes = config.regions;
}
if (codes) {
for (i = 0; i < codes.length; i++) {
if (this.regions[codes[i]]) {
itemBbox = this.regions[codes[i]].element.shape.getBBox();
if (itemBbox) {
if (typeof bbox == 'undefined') {
bbox = itemBbox;
} else {
newBbox = {
x: Math.min(bbox.x, itemBbox.x),
y: Math.min(bbox.y, itemBbox.y),
width: Math.max(bbox.x + bbox.width, itemBbox.x + itemBbox.width) - Math.min(bbox.x, itemBbox.x),
height: Math.max(bbox.y + bbox.height, itemBbox.y + itemBbox.height) - Math.min(bbox.y, itemBbox.y)
}
bbox = newBbox;
}
}
}
}
return this.setScale(
Math.min(this.width / bbox.width, this.height / bbox.height),
- (bbox.x + bbox.width / 2),
- (bbox.y + bbox.height / 2),
true,
config.animate
);
} else {
if (config.lat && config.lng) {
point = this.latLngToPoint(config.lat, config.lng);
config.x = this.transX - point.x / this.scale;
config.y = this.transY - point.y / this.scale;
} else if (config.x && config.y) {
config.x *= -this.defaultWidth;
config.y *= -this.defaultHeight;
}
return this.setScale(config.scale * this.baseScale, config.x, config.y, true, config.animate);
}
},
getSelected: function(type){
var key,
selected = [];
for (key in this[type]) {
if (this[type][key].element.isSelected) {
selected.push(key);
}
}
return selected;
},
/**
* Return the codes of currently selected regions.
* @returns {Array}
*/
getSelectedRegions: function(){
return this.getSelected('regions');
},
/**
* Return the codes of currently selected markers.
* @returns {Array}
*/
getSelectedMarkers: function(){
return this.getSelected('markers');
},
setSelected: function(type, keys){
var i;
if (typeof keys != 'object') {
keys = [keys];
}
if (jvm.$.isArray(keys)) {
for (i = 0; i < keys.length; i++) {
this[type][keys[i]].element.setSelected(true);
}
} else {
for (i in keys) {
this[type][i].element.setSelected(!!keys[i]);
}
}
},
/**
* Set or remove selected state for the regions.
* @param {String|Array|Object} keys If <code>String</code> or <code>Array</code> the region(s) with the corresponding code(s) will be selected. If <code>Object</code> was provided its keys are codes of regions, state of which should be changed. Selected state will be set if value is true, removed otherwise.
*/
setSelectedRegions: function(keys){
this.setSelected('regions', keys);
},
/**
* Set or remove selected state for the markers.
* @param {String|Array|Object} keys If <code>String</code> or <code>Array</code> the marker(s) with the corresponding code(s) will be selected. If <code>Object</code> was provided its keys are codes of markers, state of which should be changed. Selected state will be set if value is true, removed otherwise.
*/
setSelectedMarkers: function(keys){
this.setSelected('markers', keys);
},
clearSelected: function(type){
var select = {},
selected = this.getSelected(type),
i;
for (i = 0; i < selected.length; i++) {
select[selected[i]] = false;
};
this.setSelected(type, select);
},
/**
* Remove the selected state from all the currently selected regions.
*/
clearSelectedRegions: function(){
this.clearSelected('regions');
},
/**
* Remove the selected state from all the currently selected markers.
*/
clearSelectedMarkers: function(){
this.clearSelected('markers');
},
/**
* Return the instance of Map. Useful when instantiated as a jQuery plug-in.
* @returns {Map}
*/
getMapObject: function(){
return this;
},
/**
* Return the name of the region by region code.
* @returns {String}
*/
getRegionName: function(code){
return this.mapData.paths[code].name;
},
createRegions: function(){
var key,
region,
map = this;
this.regionLabelsGroup = this.regionLabelsGroup || this.canvas.addGroup();
for (key in this.mapData.paths) {
region = new jvm.Region({
map: this,
path: this.mapData.paths[key].path,
code: key,
style: jvm.$.extend(true, {}, this.params.regionStyle),
labelStyle: jvm.$.extend(true, {}, this.params.regionLabelStyle),
canvas: this.canvas,
labelsGroup: this.regionLabelsGroup,
label: this.canvas.mode != 'vml' ? (this.params.labels && this.params.labels.regions) : null
});
jvm.$(region.shape).bind('selected', function(e, isSelected){
map.container.trigger('regionSelected.jvectormap', [jvm.$(this.node).attr('data-code'), isSelected, map.getSelectedRegions()]);
});
this.regions[key] = {
element: region,
config: this.mapData.paths[key]
};
}
},
createMarkers: function(markers) {
var i,
marker,
point,
markerConfig,
markersArray,
map = this;
this.markersGroup = this.markersGroup || this.canvas.addGroup();
this.markerLabelsGroup = this.markerLabelsGroup || this.canvas.addGroup();
if (jvm.$.isArray(markers)) {
markersArray = markers.slice();
markers = {};
for (i = 0; i < markersArray.length; i++) {
markers[i] = markersArray[i];
}
}
for (i in markers) {
markerConfig = markers[i] instanceof Array ? {latLng: markers[i]} : markers[i];
point = this.getMarkerPosition( markerConfig );
if (point !== false) {
marker = new jvm.Marker({
map: this,
style: jvm.$.extend(true, {}, this.params.markerStyle, {initial: markerConfig.style || {}}),
labelStyle: jvm.$.extend(true, {}, this.params.markerLabelStyle),
index: i,
cx: point.x,
cy: point.y,
group: this.markersGroup,
canvas: this.canvas,
labelsGroup: this.markerLabelsGroup,
label: this.canvas.mode != 'vml' ? (this.params.labels && this.params.labels.markers) : null
});
jvm.$(marker.shape).bind('selected', function(e, isSelected){
map.container.trigger('markerSelected.jvectormap', [jvm.$(this.node).attr('data-index'), isSelected, map.getSelectedMarkers()]);
});
if (this.markers[i]) {
this.removeMarkers([i]);
}
this.markers[i] = {element: marker, config: markerConfig};
}
}
},
repositionMarkers: function() {
var i,
point;
for (i in this.markers) {
point = this.getMarkerPosition( this.markers[i].config );
if (point !== false) {
this.markers[i].element.setStyle({cx: point.x, cy: point.y});
}
}
},
repositionLabels: function() {
var key;
for (key in this.regions) {
this.regions[key].element.updateLabelPosition();
}
for (key in this.markers) {
this.markers[key].element.updateLabelPosition();
}
},
getMarkerPosition: function(markerConfig) {
if (jvm.Map.maps[this.params.map].projection) {
return this.latLngToPoint.apply(this, markerConfig.latLng || [0, 0]);
} else {
return {
x: markerConfig.coords[0]*this.scale + this.transX*this.scale,
y: markerConfig.coords[1]*this.scale + this.transY*this.scale
};
}
},
/**
* Add one marker to the map.
* @param {String} key Marker unique code.
* @param {Object} marker Marker configuration parameters.
* @param {Array} seriesData Values to add to the data series.
*/
addMarker: function(key, marker, seriesData){
var markers = {},
data = [],
values,
i,
seriesData = seriesData || [];
markers[key] = marker;
for (i = 0; i < seriesData.length; i++) {
values = {};
if (typeof seriesData[i] !== 'undefined') {
values[key] = seriesData[i];
}
data.push(values);
}
this.addMarkers(markers, data);
},
/**
* Add set of marker to the map.
* @param {Object|Array} markers Markers to add to the map. In case of array is provided, codes of markers will be set as string representations of array indexes.
* @param {Array} seriesData Values to add to the data series.
*/
addMarkers: function(markers, seriesData){
var i;
seriesData = seriesData || [];
this.createMarkers(markers);
for (i = 0; i < seriesData.length; i++) {
this.series.markers[i].setValues(seriesData[i] || {});
};
},
/**
* Remove some markers from the map.
* @param {Array} markers Array of marker codes to be removed.
*/
removeMarkers: function(markers){
var i;
for (i = 0; i < markers.length; i++) {
this.markers[ markers[i] ].element.remove();
delete this.markers[ markers[i] ];
};
},
/**
* Remove all markers from the map.
*/
removeAllMarkers: function(){
var i,
markers = [];
for (i in this.markers) {
markers.push(i);
}
this.removeMarkers(markers)
},
/**
* Converts coordinates expressed as latitude and longitude to the coordinates in pixels on the map.
* @param {Number} lat Latitide of point in degrees.
* @param {Number} lng Longitude of point in degrees.
*/
latLngToPoint: function(lat, lng) {
var point,
proj = jvm.Map.maps[this.params.map].projection,
centralMeridian = proj.centralMeridian,
inset,
bbox;
if (lng < (-180 + centralMeridian)) {
lng += 360;
}
point = jvm.Proj[proj.type](lat, lng, centralMeridian);
inset = this.getInsetForPoint(point.x, point.y);
if (inset) {
bbox = inset.bbox;
point.x = (point.x - bbox[0].x) / (bbox[1].x - bbox[0].x) * inset.width * this.scale;
point.y = (point.y - bbox[0].y) / (bbox[1].y - bbox[0].y) * inset.height * this.scale;
return {
x: point.x + this.transX*this.scale + inset.left*this.scale,
y: point.y + this.transY*this.scale + inset.top*this.scale
};
} else {
return false;
}
},
/**
* Converts cartesian coordinates into coordinates expressed as latitude and longitude.
* @param {Number} x X-axis of point on map in pixels.
* @param {Number} y Y-axis of point on map in pixels.
*/
pointToLatLng: function(x, y) {
var proj = jvm.Map.maps[this.params.map].projection,
centralMeridian = proj.centralMeridian,
insets = jvm.Map.maps[this.params.map].insets,
i,
inset,
bbox,
nx,
ny;
for (i = 0; i < insets.length; i++) {
inset = insets[i];
bbox = inset.bbox;
nx = x - (this.transX*this.scale + inset.left*this.scale);
ny = y - (this.transY*this.scale + inset.top*this.scale);
nx = (nx / (inset.width * this.scale)) * (bbox[1].x - bbox[0].x) + bbox[0].x;
ny = (ny / (inset.height * this.scale)) * (bbox[1].y - bbox[0].y) + bbox[0].y;
if (nx > bbox[0].x && nx < bbox[1].x && ny > bbox[0].y && ny < bbox[1].y) {
return jvm.Proj[proj.type + '_inv'](nx, -ny, centralMeridian);
}
}
return false;
},
getInsetForPoint: function(x, y){
var insets = jvm.Map.maps[this.params.map].insets,
i,
bbox;
for (i = 0; i < insets.length; i++) {
bbox = insets[i].bbox;
if (x > bbox[0].x && x < bbox[1].x && y > bbox[0].y && y < bbox[1].y) {
return insets[i];
}
}
},
createSeries: function(){
var i,
key;
this.series = {
markers: [],
regions: []
};
for (key in this.params.series) {
for (i = 0; i < this.params.series[key].length; i++) {
this.series[key][i] = new jvm.DataSeries(
this.params.series[key][i],
this[key],
this
);
}
}
},
/**
* Gracefully remove the map and and all its accessories, unbind event handlers.
*/
remove: function(){
this.tip.remove();
this.container.remove();
jvm.$(window).unbind('resize', this.onResize);
jvm.$('body').unbind('mouseup', this.onContainerMouseUp);
}
};
jvm.Map.maps = {};
jvm.Map.defaultParams = {
map: 'world_mill_en',
backgroundColor: '#505050',
zoomButtons: true,
zoomOnScroll: true,
zoomOnScrollSpeed: 3,
panOnDrag: true,
zoomMax: 8,
zoomMin: 1,
zoomStep: 1.6,
zoomAnimate: true,
regionsSelectable: false,
markersSelectable: false,
bindTouchEvents: true,
regionStyle: {
initial: {
fill: 'white',
"fill-opacity": 1,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 1
},
hover: {
"fill-opacity": 0.8,
cursor: 'pointer'
},
selected: {
fill: 'yellow'
},
selectedHover: {
}
},
regionLabelStyle: {
initial: {
'font-family': 'Verdana',
'font-size': '12',
'font-weight': 'bold',
cursor: 'default',
fill: 'black'
},
hover: {
cursor: 'pointer'
}
},
markerStyle: {
initial: {
fill: 'grey',
stroke: '#505050',
"fill-opacity": 1,
"stroke-width": 1,
"stroke-opacity": 1,
r: 5
},
hover: {
stroke: 'black',
"stroke-width": 2,
cursor: 'pointer'
},
selected: {
fill: 'blue'
},
selectedHover: {
}
},
markerLabelStyle: {
initial: {
'font-family': 'Verdana',
'font-size': '12',
'font-weight': 'bold',
cursor: 'default',
fill: 'black'
},
hover: {
cursor: 'pointer'
}
}
};
jvm.Map.apiEvents = {
onRegionTipShow: 'regionTipShow',
onRegionOver: 'regionOver',
onRegionOut: 'regionOut',
onRegionClick: 'regionClick',
onRegionSelected: 'regionSelected',
onMarkerTipShow: 'markerTipShow',
onMarkerOver: 'markerOver',
onMarkerOut: 'markerOut',
onMarkerClick: 'markerClick',
onMarkerSelected: 'markerSelected',
onViewportChange: 'viewportChange'
}; |
'use strict';
angular.module('cpZenPlatform').service('auth', function($http, $q) {
var loggedin_user = null;
function topfail( data ) {
console.log(data)
}
return {
login: function(creds,win,fail){
$http({method:'POST', url: '/auth/login', data:creds, cache:false}).
success(win).error(fail||topfail)
},
logout: function(win,fail){
$http({method:'POST', url: '/auth/logout', data:{}, cache:false}).
success(win).error(fail||topfail)
},
instance: function(win,fail){
$http({method:'GET', url: '/auth/instance', cache:false}).
success(win).error(fail||topfail)
},
register: function(details,win,fail){
$http({method:'POST', url: '/api/1.0/users/register', data:details, cache:false}).
success(win).error(fail||topfail)
},
reset: function (creds, win, fail) {
$http({method: 'POST', url: '/api/1.0/users/reset_password', data: creds, cache: false}).
success(win).error(fail||topfail);
},
execute_reset: function(creds,win,fail){
$http({method:'POST', url: '/api/1.0/users/execute_reset', data:creds, cache:false}).
success(win).error(fail||topfail)
},
confirm: function(creds,win,fail){
$http({method:'POST', url: '/auth/confirm', data:creds, cache:false}).
success(win).error(fail||topfail)
},
get_loggedin_user: function (win, fail) {
this.instance(function (data) {
if (!data.user) {
return (fail || topfail)('cannot get logged in user');
}
loggedin_user = data.user;
win(loggedin_user);
});
},
get_loggedin_user_promise: function(){
var deferred = $q.defer();
this.instance(function (data) {
loggedin_user = data.user;
deferred.resolve(loggedin_user);
});
return deferred.promise;
}
};
});
|
// alert('hello');
setTimeout(function() {
$.ajax({
url: '/user.action',
method: 'get',
success: function(data) {
var listStr = data.map(function(ele) {
return '<li>' + ele + '</li>';
}).join('');
$('#root').html(listStr);
},
error: function(error) {
console.log(error);
}
});
$.ajax({
url: '/list.action',
method: 'post',
contentType: 'application/json',
// data:{
// DoctorId:4,
// DoctorName:"胡如根"
// },
data: JSON.stringify([
"DoctorId: 4",
"DoctorName: 胡如根"
]),
success: function(data) {
// var listStr = JSON.parse(data).map(function(ele) {
var listStr = data.map(function(ele) {
return '<li>' + ele + '</li>';
}).join('');
$('#shop').html(listStr);
},
error: function(error) {
console.log(error);
}
});
}, 1000); |
var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname);
var roles = [
{
name: 'admin',
description: 'Admin role'
},
{
name: 'user',
description: 'User role'
},
{
name: 'guest',
description: 'Guest Anonymous role'
}
];
var accounts = [
{
username: 'pai',
email: 'foo@bar.com',
password: 'test',
created: new Date(),
lastUpdated: new Date()
},
{
username: 'test',
email: 'baz@qux.com',
password: 'test',
created: new Date(),
lastUpdated: new Date()
}
];
var acls = [
{
accessType: "*",
permission: "DENY",
principalType: "ROLE",
principalId: "$everyone"
},
{
model: "AmUser",
property: "find",
accessType: "READ",
permission: "ALLOW",
principalType: "ROLE",
principalId: "$authenticated"
}
];
var pois = [
{
name: "Hardenbergplatz",
geopoint: "52.506192,13.332400",
type: 0
}, {
name: "apparent media",
geopoint: "52.509203,13.323838",
type: 0
}, {
name: "Blitzer",
geopoint: "52.490830,13.330926",
type: 0
}
];
/*
app.datasources['mysql'].autoupdate([‚RoleMapping','Role', 'AccessToken', 'AmUser', 'ACL', 'location', 'photo', 'poi'], function(err) {
console.log(err);
if (err) {
console.log(err);
} else {
var ACL = app.models.ACL;
acls.forEach(function(acl) {
ACL.create(acl, function(err, record) {
console.log('Record created: ', record);
});
});
var Role = app.models.Role;
roles.forEach(function(role) {
Role.create(role, function(err, record) {
console.log('Record created: ', record);
});
});
var AmUser = app.models.AmUser;
accounts.forEach(function(account) {
console.log('try create user');
AmUser.create(account, function(err, record) {
if (err) return console.log(err);
console.log('user Record created:', record);
});
});
var Poi = app.models.poi;
pois.forEach(function(poi) {
Poi.create(poi, function(err, record) {
if (err) return console.log(err);
console.log('poi Record created:', record);
});
});
}
});
*/
var local_storage = app.datasources['local_storage'];
var container = local_storage.createModel('container');
app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
console.log('Web server listening at: %s', app.get('url'));
});
};
// start the server if `$ node server.js`
if (require.main === module) {
app.start();
}
|
/**
* Created by Andrey Gayvoronsky on 13/04/16.
*/
const locale = {
placeholder: 'Выберите время',
};
export default locale;
|
// @flow
let x = { m() {} };
x.m = () => {}; // error: m is read-only
let x2 : {m() : void } = { m() {} };
x2.m = () => {}; // error: m is read-only
let y = {...x};
y.m = () => {}; // error: m is read-only
let z = { m : () => {}, ...x };
z.m = () => {}; // error: m is read-only
let z2 = { ...x, m : () => {}, };
z2.m = () => {}; // ok, m is a function property
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M18.41 16.59L13.82 12l4.59-4.59L17 6l-6 6 6 6 1.41-1.41zM6 6h2v12H6V6z" />
, 'FirstPageOutlined');
|
'use strict';
var frontMatter = require('front-matter');
module.exports = function (arr) {
var len = arr.length;
var res = [];
while (len--) {
res.push(frontMatter(arr[len]));
}
// console.log(res)
return res;
};
|
/*
* Copyright (c) 2012 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.
*
*/
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, describe, it, xit, expect, beforeEach, afterEach, waitsFor, runs, $, brackets, waitsForDone */
define(function (require, exports, module) {
"use strict";
var CommandManager, // loaded from brackets.test
EditorManager, // loaded from brackets.test
FileIndexManager, // loaded from brackets.test
PerfUtils, // loaded from brackets.test
JSUtils, // loaded from brackets.test
FileUtils = brackets.getModule("file/FileUtils"),
NativeFileSystem = brackets.getModule("file/NativeFileSystem").NativeFileSystem,
SpecRunnerUtils = brackets.getModule("spec/SpecRunnerUtils"),
UnitTestReporter = brackets.getModule("test/UnitTestReporter");
var extensionPath = FileUtils.getNativeModuleDirectoryPath(module),
testPath = extensionPath + "/unittest-files/syntax",
tempPath = SpecRunnerUtils.getTempDirectory(),
testWindow,
initInlineTest;
function rewriteProject(spec) {
var result = new $.Deferred(),
infos = {},
options = {
parseOffsets : true,
infos : infos,
removePrefix : true
};
SpecRunnerUtils.copyPath(testPath, tempPath, options).done(function () {
spec.infos = infos;
result.resolve();
}).fail(function () {
result.reject();
});
return result.promise();
}
/**
* Performs setup for an inline editor test. Parses offsets (saved to Spec.offsets) for all files in
* the test project (testPath) and saves files back to disk without offset markup.
* When finished, open an editor for the specified project relative file path
* then attempts opens an inline editor at the given offset. Installs an after()
* function restore all file content back to original state with offset markup.
*
* @param {!string} openFile Project relative file path to open in a main editor.
* @param {!number} openOffset The offset index location within openFile to open an inline editor.
* @param {?boolean} expectInline Use false to verify that an inline editor should not be opened. Omit otherwise.
*/
var _initInlineTest = function (openFile, openOffset, expectInline, workingSet) {
var allFiles,
inlineOpened = null,
spec = this;
workingSet = workingSet || [];
expectInline = (expectInline !== undefined) ? expectInline : true;
runs(function () {
waitsForDone(rewriteProject(spec), "rewriteProject");
});
SpecRunnerUtils.loadProjectInTestWindow(tempPath);
runs(function () {
workingSet.push(openFile);
waitsForDone(SpecRunnerUtils.openProjectFiles(workingSet), "openProjectFiles");
});
if (openOffset !== undefined) {
runs(function () {
// open inline editor at specified offset index
waitsForDone(SpecRunnerUtils.toggleQuickEditAtOffset(
EditorManager.getCurrentFullEditor(),
spec.infos[openFile].offsets[openOffset]
), "toggleQuickEditAtOffset");
});
}
};
describe("JSQuickEdit", function () {
/*
*
*/
describe("javaScriptFunctionProvider", function () {
beforeEach(function () {
initInlineTest = _initInlineTest.bind(this);
SpecRunnerUtils.createTestWindowAndRun(this, function (w) {
testWindow = w;
EditorManager = testWindow.brackets.test.EditorManager;
CommandManager = testWindow.brackets.test.CommandManager;
FileIndexManager = testWindow.brackets.test.FileIndexManager;
JSUtils = testWindow.brackets.test.JSUtils;
});
this.addMatchers({
toHaveInlineEditorRange: function (range) {
var i = 0,
editor = this.actual,
hidden,
lineCount = editor.lineCount(),
shouldHide = [],
shouldShow = [],
startLine = range.startLine,
endLine = range.endLine,
visibleRangeCheck;
for (i = 0; i < lineCount; i++) {
hidden = editor._codeMirror.getLineHandle(i).hidden || false;
if (i < startLine) {
if (!hidden) {
shouldHide.push(i); // lines above start line should be hidden
}
} else if ((i >= startLine) && (i <= endLine)) {
if (hidden) {
shouldShow.push(i); // lines in the range should be visible
}
} else if (i > endLine) {
if (!hidden) {
shouldHide.push(i); // lines below end line should be hidden
}
}
}
visibleRangeCheck = (editor._visibleRange.startLine === startLine) &&
(editor._visibleRange.endLine === endLine);
this.message = function () {
var msg = "";
if (shouldHide.length > 0) {
msg += "Expected inline editor to hide [" + shouldHide.toString() + "].\n";
}
if (shouldShow.length > 0) {
msg += "Expected inline editor to show [" + shouldShow.toString() + "].\n";
}
if (!visibleRangeCheck) {
msg += "Editor._visibleRange [" +
editor._visibleRange.startLine + "," +
editor._visibleRange.endLine + "] should be [" +
startLine + "," + endLine + "].";
}
return msg;
};
return (shouldHide.length === 0) &&
(shouldShow.length === 0) &&
visibleRangeCheck;
}
});
});
afterEach(function () {
//debug visual confirmation of inline editor
//waits(1000);
// revert files to original content with offset markup
SpecRunnerUtils.closeTestWindow();
});
it("should ignore tokens that are not function calls or references", function () {
var editor,
extensionRequire,
jsQuickEditMain,
tokensFile = "tokens.js",
promise,
offsets;
initInlineTest(tokensFile);
runs(function () {
extensionRequire = testWindow.brackets.getModule("utils/ExtensionLoader").getRequireContextForExtension("JavaScriptQuickEdit");
jsQuickEditMain = extensionRequire("main");
editor = EditorManager.getCurrentFullEditor();
offsets = this.infos[tokensFile];
// regexp token
promise = jsQuickEditMain.javaScriptFunctionProvider(editor, offsets[0]);
expect(promise).toBeNull();
// multi-line comment
promise = jsQuickEditMain.javaScriptFunctionProvider(editor, offsets[1]);
expect(promise).toBeNull();
// single-line comment
promise = jsQuickEditMain.javaScriptFunctionProvider(editor, offsets[2]);
expect(promise).toBeNull();
// string, double quotes
promise = jsQuickEditMain.javaScriptFunctionProvider(editor, offsets[3]);
expect(promise).toBeNull();
// string, single quotes
promise = jsQuickEditMain.javaScriptFunctionProvider(editor, offsets[4]);
expect(promise).toBeNull();
});
});
it("should open a function with form: function functionName()", function () {
initInlineTest("test1main.js", 0);
runs(function () {
var inlineWidget = EditorManager.getCurrentFullEditor().getInlineWidgets()[0];
var inlinePos = inlineWidget.editors[0].getCursorPos();
// verify cursor position in inline editor
expect(inlinePos).toEqual(this.infos["test1inline.js"].offsets[0]);
});
});
it("should open a function with form: functionName = function()", function () {
initInlineTest("test1main.js", 1);
runs(function () {
var inlineWidget = EditorManager.getCurrentFullEditor().getInlineWidgets()[0];
var inlinePos = inlineWidget.editors[0].getCursorPos();
// verify cursor position in inline editor
expect(inlinePos).toEqual(this.infos["test1inline.js"].offsets[1]);
});
});
it("should open a function with form: functionName: function()", function () {
initInlineTest("test1main.js", 2);
runs(function () {
var inlineWidget = EditorManager.getCurrentFullEditor().getInlineWidgets()[0];
var inlinePos = inlineWidget.editors[0].getCursorPos();
// verify cursor position in inline editor
expect(inlinePos).toEqual(this.infos["test1inline.js"].offsets[2]);
});
});
describe("Code hints tests within quick edit window ", function () {
var JSCodeHints;
/*
* Ask provider for hints at current cursor position; expect it to
* return some
*
* @param {Object} provider - a CodeHintProvider object
* @param {string} key - the charCode of a key press that triggers the
* CodeHint provider
* @return {boolean} - whether the provider has hints in the context of
* the test editor
*/
function expectHints(provider, key) {
if (key === undefined) {
key = null;
}
expect(provider.hasHints(EditorManager.getActiveEditor(), key)).toBe(true);
return provider.getHints(null);
}
/*
* Wait for a hint response object to resolve, then apply a callback
* to the result
*
* @param {Object + jQuery.Deferred} hintObj - a hint response object,
* possibly deferred
* @param {Function} callback - the callback to apply to the resolved
* hint response object
*/
function _waitForHints(hintObj, callback) {
var complete = false,
hintList = null;
if (hintObj.hasOwnProperty("hints")) {
complete = true;
hintList = hintObj.hints;
} else {
hintObj.done(function (obj) {
complete = true;
hintList = obj.hints;
});
}
waitsFor(function () {
return complete;
}, "Expected hints did not resolve", 3000);
runs(function () { callback(hintList); });
}
/*
* Expect a given list of hints to be present in a given hint
* response object, and no more.
*
* @param {Object + jQuery.Deferred} hintObj - a hint response object,
* possibly deferred
* @param {Array.<string>} expectedHints - a list of hints that should be
* present in the hint response, and no more.
*/
function hintsPresentExact(hintObj, expectedHints) {
_waitForHints(hintObj, function (hintList) {
expect(hintList).not.toBeNull();
expect(hintList.length).toBe(expectedHints.length);
expectedHints.forEach(function (expectedHint, index) {
expect(hintList[index].data("token").value).toBe(expectedHint);
});
});
}
/**
* Wait for the editor to change positions, such as after a jump to
* definition has been triggered. Will timeout after 3 seconds
*
* @param {{line:number, ch:number}} oldLocation - the original line/col
* @param {Function} callback - the callback to apply once the editor has changed position
*/
function _waitForJump(oldLocation, callback) {
var cursor = null;
waitsFor(function () {
var activeEditor = EditorManager.getActiveEditor();
cursor = activeEditor.getCursorPos();
return (cursor.line !== oldLocation.line) ||
(cursor.ch !== oldLocation.ch);
}, "Expected jump did not occur", 3000);
runs(function () { callback(cursor); });
}
/**
* Trigger a jump to definition, and verify that the editor jumped to
* the expected location.
*
* @param {{line:number, ch:number, file:string}} expectedLocation - the
* line, column, and optionally the new file the editor should jump to. If the
* editor is expected to stay in the same file, then file may be omitted.
*/
function editorJumped(jsCodeHints, testEditor, expectedLocation) {
var oldLocation = testEditor.getCursorPos();
jsCodeHints.handleJumpToDefinition();
_waitForJump(oldLocation, function (newCursor) {
expect(newCursor.line).toBe(expectedLocation.line);
expect(newCursor.ch).toBe(expectedLocation.ch);
if (expectedLocation.file) {
var activeEditor = EditorManager.getActiveEditor();
expect(activeEditor.document.file.name).toBe(expectedLocation.file);
}
});
}
function initJSCodeHints() {
var extensionRequire = testWindow.brackets.getModule("utils/ExtensionLoader").
getRequireContextForExtension("JavaScriptCodeHints");
JSCodeHints = extensionRequire("main");
}
it("should see code hint lists in quick editor", function () {
var start = {line: 13, ch: 11 },
testPos = {line: 5, ch: 29},
testEditor;
initInlineTest("test.html");
initJSCodeHints();
runs(function () {
var openQuickEditor = SpecRunnerUtils.toggleQuickEditAtOffset(EditorManager.getCurrentFullEditor(), start);
waitsForDone(openQuickEditor, "Open quick editor");
});
runs(function () {
testEditor = EditorManager.getActiveEditor();
testEditor.setCursorPos(testPos);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsPresentExact(hintObj, ["getMonthName(mo: number) -> string"]);
});
});
it("should see jump to definition on variable working in quick editor", function () {
var start = {line: 13, ch: 10 },
testPos = {line: 6, ch: 7},
testJumpPos = {line: 6, ch: 5},
jumpPos = {line: 3, ch: 6},
testEditor;
initInlineTest("test.html");
initJSCodeHints();
runs(function () {
var openQuickEditor = SpecRunnerUtils.toggleQuickEditAtOffset(EditorManager.getCurrentFullEditor(), start);
waitsForDone(openQuickEditor, "Open quick editor");
});
runs(function () {
testEditor = EditorManager.getActiveEditor();
testEditor.setCursorPos(testPos);
var hintObj = expectHints(JSCodeHints.jsHintProvider);
hintsPresentExact(hintObj, ["propA"]);
});
runs(function () {
testEditor = EditorManager.getActiveEditor();
testEditor.setCursorPos(testJumpPos);
editorJumped(JSCodeHints, testEditor, jumpPos);
});
});
// FIXME (issue #3951): jump to method inside quick editor doesn't jump
xit("should see jump to definition on method working in quick editor", function () {
var start = {line: 13, ch: 13 },
testPos = {line: 5, ch: 25},
jumpPos = {line: 9, ch: 21},
testEditor;
initInlineTest("test.html");
initJSCodeHints();
runs(function () {
var openQuickEditor = SpecRunnerUtils.toggleQuickEditAtOffset(EditorManager.getCurrentFullEditor(), start);
waitsForDone(openQuickEditor, "Open quick editor");
});
runs(function () {
testEditor = EditorManager.getActiveEditor();
testEditor.setCursorPos(testPos);
editorJumped(jumpPos);
});
});
});
});
describe("Performance suite", function () {
this.category = "performance";
var testPath = extensionPath + "/unittest-files/jquery-ui";
beforeEach(function () {
SpecRunnerUtils.createTestWindowAndRun(this, function (w) {
testWindow = w;
CommandManager = testWindow.brackets.test.CommandManager;
EditorManager = testWindow.brackets.test.EditorManager;
PerfUtils = testWindow.brackets.test.PerfUtils;
});
});
afterEach(function () {
SpecRunnerUtils.closeTestWindow();
});
it("should open inline editors", function () {
SpecRunnerUtils.loadProjectInTestWindow(testPath);
var extensionRequire,
JavaScriptQuickEdit,
i,
perfMeasurements;
runs(function () {
perfMeasurements = [
{
measure: PerfUtils.JAVASCRIPT_INLINE_CREATE,
children: [
{
measure: PerfUtils.FILE_INDEX_MANAGER_SYNC
},
{
measure: PerfUtils.JAVASCRIPT_FIND_FUNCTION,
children: [
{
measure: PerfUtils.JSUTILS_GET_ALL_FUNCTIONS,
children: [
{
measure: PerfUtils.DOCUMENT_MANAGER_GET_DOCUMENT_FOR_PATH,
name: "Document creation during this search",
operation: "sum"
},
{
measure: PerfUtils.JSUTILS_REGEXP,
operation: "sum"
}
]
},
{
measure: PerfUtils.JSUTILS_END_OFFSET,
operation: "sum"
}
]
}
]
}
];
});
runs(function () {
extensionRequire = testWindow.brackets.getModule("utils/ExtensionLoader").getRequireContextForExtension("JavaScriptQuickEdit");
JavaScriptQuickEdit = extensionRequire("main");
waitsForDone(SpecRunnerUtils.openProjectFiles(["ui/jquery.effects.core.js"]), "openProjectFiles");
});
var runCreateInlineEditor = function () {
var editor = EditorManager.getCurrentFullEditor();
// Set the cursor in the middle of a call to "extend" so the JS helper function works correctly.
editor.setCursorPos(271, 20);
waitsForDone(
JavaScriptQuickEdit._createInlineEditor(editor, "extend"),
"createInlineEditor",
5000
);
};
function logPerf() {
var reporter = UnitTestReporter.getActiveReporter();
reporter.logTestWindow(perfMeasurements);
reporter.clearTestWindow();
}
// repeat 5 times
for (i = 0; i < 5; i++) {
runs(runCreateInlineEditor);
runs(logPerf);
}
});
});
});
});
|
describe("SpyRegistry", function() {
describe("#spyOn", function() {
it("checks for the existence of the object", function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry();
expect(function() {
spyRegistry.spyOn(void 0, 'pants');
}).toThrowError(/could not find an object/);
});
it("checks that a method name was passed", function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry(),
subject = {};
expect(function() {
spyRegistry.spyOn(subject);
}).toThrowError(/No method name supplied/);
});
it("checks for the existence of the method", function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry(),
subject = {};
expect(function() {
spyRegistry.spyOn(subject, 'pants');
}).toThrowError(/method does not exist/);
});
it("checks if it has already been spied upon", function() {
var spies = [],
spyRegistry = new jasmineUnderTest.SpyRegistry({currentSpies: function() { return spies; }}),
subject = { spiedFunc: function() {} };
spyRegistry.spyOn(subject, 'spiedFunc');
expect(function() {
spyRegistry.spyOn(subject, 'spiedFunc');
}).toThrowError(/has already been spied upon/);
});
it("checks if it can be spied upon", function() {
// IE 8 doesn't support `definePropery` on non-DOM nodes
if (jasmine.getEnv().ieVersion < 9) { return; }
var scope = {};
function myFunc() {
return 1;
}
Object.defineProperty(scope, 'myFunc', {
get: function() {
return myFunc;
}
});
var spies = [],
spyRegistry = new jasmineUnderTest.SpyRegistry({currentSpies: function() { return spies; }}),
subject = { spiedFunc: scope.myFunc };
expect(function() {
spyRegistry.spyOn(scope, 'myFunc');
}).toThrowError(/is not declared writable or has no setter/);
expect(function() {
spyRegistry.spyOn(subject, 'spiedFunc');
}).not.toThrowError(/is not declared writable or has no setter/);
});
it("overrides the method on the object and returns the spy", function() {
var originalFunctionWasCalled = false,
spyRegistry = new jasmineUnderTest.SpyRegistry(),
subject = { spiedFunc: function() { originalFunctionWasCalled = true; } };
var spy = spyRegistry.spyOn(subject, 'spiedFunc');
expect(subject.spiedFunc).toEqual(spy);
});
});
describe("#spyOnProperty", function() {
// IE 8 doesn't support `definePropery` on non-DOM nodes
if (jasmine.getEnv().ieVersion < 9) { return; }
it("checks for the existence of the object", function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry();
expect(function() {
spyRegistry.spyOnProperty(void 0, 'pants');
}).toThrowError(/could not find an object/);
});
it("checks that a property name was passed", function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry(),
subject = {};
expect(function() {
spyRegistry.spyOnProperty(subject);
}).toThrowError(/No property name supplied/);
});
it("checks for the existence of the method", function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry(),
subject = {};
expect(function() {
spyRegistry.spyOnProperty(subject, 'pants');
}).toThrowError(/property does not exist/);
});
it("checks for the existence of access type", function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry(),
subject = {};
Object.defineProperty(subject, 'pants', {
get: function() { return 1; },
configurable: true
});
expect(function() {
spyRegistry.spyOnProperty(subject, 'pants', 'set');
}).toThrowError(/does not have access type/);
});
it("checks if it has already been spied upon", function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry(),
subject = {};
Object.defineProperty(subject, 'spiedProp', {
get: function() { return 1; },
configurable: true
});
spyRegistry.spyOnProperty(subject, 'spiedProp');
expect(function() {
spyRegistry.spyOnProperty(subject, 'spiedProp');
}).toThrowError(/has already been spied upon/);
});
it("checks if it can be spied upon", function() {
var subject = {};
Object.defineProperty(subject, 'myProp', {
get: function() {}
});
Object.defineProperty(subject, 'spiedProp', {
get: function() {},
configurable: true
});
var spyRegistry = new jasmineUnderTest.SpyRegistry();
expect(function() {
spyRegistry.spyOnProperty(subject, 'myProp');
}).toThrowError(/is not declared configurable/);
expect(function() {
spyRegistry.spyOnProperty(subject, 'spiedProp');
}).not.toThrowError(/is not declared configurable/);
});
it("overrides the property getter on the object and returns the spy", function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry(),
subject = {},
returnValue = 1;
Object.defineProperty(subject, 'spiedProperty', {
get: function() { return returnValue; },
configurable: true
});
expect(subject.spiedProperty).toEqual(returnValue);
var spy = spyRegistry.spyOnProperty(subject, 'spiedProperty');
var getter = Object.getOwnPropertyDescriptor(subject, 'spiedProperty').get;
expect(getter).toEqual(spy);
expect(subject.spiedProperty).toBeUndefined();
});
it("overrides the property setter on the object and returns the spy", function() {
var spyRegistry = new jasmineUnderTest.SpyRegistry(),
subject = {},
returnValue = 1;
Object.defineProperty(subject, 'spiedProperty', {
get: function() { return returnValue; },
set: function() {},
configurable: true
});
var spy = spyRegistry.spyOnProperty(subject, 'spiedProperty', 'set');
var setter = Object.getOwnPropertyDescriptor(subject, 'spiedProperty').set;
expect(subject.spiedProperty).toEqual(returnValue);
expect(setter).toEqual(spy);
});
});
describe("#clearSpies", function() {
it("restores the original functions on the spied-upon objects", function() {
var spies = [],
spyRegistry = new jasmineUnderTest.SpyRegistry({currentSpies: function() { return spies; }}),
originalFunction = function() {},
subject = { spiedFunc: originalFunction };
spyRegistry.spyOn(subject, 'spiedFunc');
spyRegistry.clearSpies();
expect(subject.spiedFunc).toBe(originalFunction);
});
it("restores the original functions, even when that spy has been replace and re-spied upon", function() {
var spies = [],
spyRegistry = new jasmineUnderTest.SpyRegistry({currentSpies: function() { return spies; }}),
originalFunction = function() {},
subject = { spiedFunc: originalFunction };
spyRegistry.spyOn(subject, 'spiedFunc');
// replace the original spy with some other function
subject.spiedFunc = function() {};
// spy on the function in that location again
spyRegistry.spyOn(subject, 'spiedFunc');
spyRegistry.clearSpies();
expect(subject.spiedFunc).toBe(originalFunction);
});
it("does not add a property that the spied-upon object didn't originally have", function() {
// IE 8 doesn't support `Object.create`
if (jasmine.getEnv().ieVersion < 9) { return; }
var spies = [],
spyRegistry = new jasmineUnderTest.SpyRegistry({currentSpies: function() { return spies; }}),
originalFunction = function() {},
subjectParent = {spiedFunc: originalFunction};
var subject = Object.create(subjectParent);
expect(subject.hasOwnProperty('spiedFunc')).toBe(false);
spyRegistry.spyOn(subject, 'spiedFunc');
spyRegistry.clearSpies();
expect(subject.hasOwnProperty('spiedFunc')).toBe(false);
expect(subject.spiedFunc).toBe(originalFunction);
});
it("restores the original function when it\'s inherited and cannot be deleted", function() {
// IE 8 doesn't support `Object.create` or `Object.defineProperty`
if (jasmine.getEnv().ieVersion < 9) { return; }
var spies = [],
spyRegistry = new jasmineUnderTest.SpyRegistry({currentSpies: function() { return spies; }}),
originalFunction = function() {},
subjectParent = {spiedFunc: originalFunction};
var subject = Object.create(subjectParent);
spyRegistry.spyOn(subject, 'spiedFunc');
// simulate a spy that cannot be deleted
Object.defineProperty(subject, 'spiedFunc', {
configurable: false
});
spyRegistry.clearSpies();
expect(jasmineUnderTest.isSpy(subject.spiedFunc)).toBe(false);
});
});
describe('spying on properties', function() {
it("restores the original properties on the spied-upon objects", function() {
// IE 8 doesn't support `definePropery` on non-DOM nodes
if (jasmine.getEnv().ieVersion < 9) { return; }
var spies = [],
spyRegistry = new jasmineUnderTest.SpyRegistry({currentSpies: function() { return spies; }}),
originalReturn = 1,
subject = {};
Object.defineProperty(subject, 'spiedProp', {
get: function() { return originalReturn; },
configurable: true
});
spyRegistry.spyOnProperty(subject, 'spiedProp');
spyRegistry.clearSpies();
expect(subject.spiedProp).toBe(originalReturn);
});
it("does not add a property that the spied-upon object didn't originally have", function() {
// IE 8 doesn't support `Object.create`
if (jasmine.getEnv().ieVersion < 9) { return; }
var spies = [],
spyRegistry = new jasmineUnderTest.SpyRegistry({currentSpies: function() { return spies; }}),
originalReturn = 1,
subjectParent = {};
Object.defineProperty(subjectParent, 'spiedProp', {
get: function() { return originalReturn; },
configurable: true
});
var subject = Object.create(subjectParent);
expect(subject.hasOwnProperty('spiedProp')).toBe(false);
spyRegistry.spyOnProperty(subject, 'spiedProp');
spyRegistry.clearSpies();
expect(subject.hasOwnProperty('spiedProp')).toBe(false);
expect(subject.spiedProp).toBe(originalReturn);
});
});
});
|
var rwhitespace = /(\s|\t|\r\n|\r|\n)/,
rvalueseparator = /\/|,/,
rvalueseek = /"|'|\(/;
function Rule( property, value, position ) {
var self = this;
if ( ! ( self instanceof Rule ) ) {
return new Rule( property, value, position );
}
self.property = ( property || '' ).trim();
self.value = ( value || '' ).trim();
self.position = position;
self.parts = [];
self.breakdown();
}
Rule.prototype = {
breakdown: function(){
var self = this, value = self.value,
parts = [], i = -1, l = value.length, part = '', c, seek;
for ( ; ++i < l; ) {
c = value[ i ];
// Whitespace is a value separator
if ( rwhitespace.exec( c ) ) {
if ( ( part = part.trim() ).length ) {
parts.push( part );
}
part = '';
}
// Value separator
else if ( rvalueseparator.exec( c ) ) {
if ( ( part = part.trim() ).length ) {
parts.push( part );
}
parts.push( c );
part = '';
}
// Read all characters in a seek sequence (url(...), "...", '...', etc)
else if ( rvalueseek.exec( c ) ) {
part += c;
seek = c == '(' ? ')' : c;
// Find end char
for ( ; ++i < l; ) {
c = value[ i ];
part += c;
// End char found, break off and attach part
if ( c == seek ) {
break;
}
// Skip over escaped values
else if ( c == "\\" && value[ i + 1 ] ) {
part += value[ ++i ];
}
}
parts.push( part );
part = '';
}
else {
part += c;
}
}
// Attach final leftover part
if ( part.length ) {
parts.push( part );
}
self.parts = parts;
}
};
global.CSSTree.Rule = Rule;
|
'use strict';
// '/app/common/custom/othercustfields.nl?whence=' |
import './styles.css'
import React from 'react'
import {connect} from 'cerebral/react'
import StatePaths from './StatePaths'
import Renders from './Renders'
export default connect({
map: 'debugger.componentsMap.**',
renders: 'debugger.renders.**'
},
function Components (props) {
return (
<div className='components-wrapper'>
<StatePaths map={props.map} />
<Renders renders={props.renders} />
</div>
)
}
)
|
(function() {
'use strict';
angular
.module('app.commands')
.controller('CommandsController', CommandsController);
// 'isLoggedIn' is passed from the config.route.js
CommandsController.$inject = ['$location', '$localStorage', '$timeout', 'isLoggedIn', 'CommandService', 'UserService', 'notifyService'];
function CommandsController($location, $localStorage, $timeout, isLoggedIn, CommandService, UserService, notifyService) {
var vm = this;
if (!isLoggedIn) {
$location.path('/');
return;
}
vm.commands = '';
vm.username = $localStorage.username;
vm.deleteCommand = deleteCommand;
vm.newCommand = newCommand;
vm.updateCommand = updateCommand;
vm.copyCommand = copyCommand;
vm.new = {
command: '',
os: '',
version: '',
note: ''
};
vm.edit = {
command: '',
os: '',
version: '',
note: ''
};
commands();
////////////////////
function commands() {
var query = CommandService.command($localStorage.token).query();
query.$promise
.then(function(data) {
vm.commands = data;
}).catch(function(error) {
console.log(error);
vm.commands = error;
});
}
function deleteCommand(command) {
var i;
for (i = 0; i < vm.commands.length; i++)
if(vm.commands[i].id === command.id)
break;
var query = CommandService.command($localStorage.token).delete({id: command.id});
query.$promise
.then(function(data) {
vm.commands.splice(i, 1);
}).catch(function(error) {
console.log(error);
});
}
function newCommand() {
// TODO: Error checking must have at least 'command' filled out
if (vm.new.command === '')
return;
var query = CommandService.command($localStorage.token).save({
command: vm.new.command,
os: vm.new.os,
version: vm.new.version,
note: vm.new.note
});
query.$promise
.then(function(data) {
vm.commands.unshift(data);
$('#newCommandModal').modal('hide');
notifyService.display('Added New Command');
$timeout(function() {
notifyService.showMessage = false;
}, 3000);
})
.catch(function(error) {
console.log(error);
});
}
function updateCommand() {
var i;
for(i = 0; i < vm.commands.length; i++)
if (vm.commands[i].id === vm.edit.id)
break;
// No reason to send update request if objects are still the same
if (angular.equals(vm.commands[i], vm.edit))
return;
var query = CommandService.command($localStorage.token).update({id: vm.edit.id}, {
command: vm.edit.command,
os: vm.edit.os,
version: vm.edit.version,
note: vm.edit.note
});
query.$promise
.then(function(response) {
vm.commands[i] = vm.edit;
$('#updateCommandModal').modal('hide');
notifyService.display('Updated Command');
$timeout(function() {
notifyService.showMessage = false;
}, 3000);
})
.catch(function(error) {
console.log(error);
});
}
function copyCommand(command) {
vm.edit = angular.copy(command);
}
}
})();
|
export function rowHasChanged(r1, r2) {
return r1 != r2;
};
export function sectionHeaderHasChanged(s1, s2){
return s1 != s2;
};
export function getSectionData(dataBlob, sectionID) {
return dataBlob[sectionID]
};
export function getRowData(dataBlob, sectionID, rowID){
return dataBlob[`${sectionID}:${rowID}`];
}
export function setRegistrationErrorMsg({ email, password, location, firstName, lastName}){
if (! /@/.test(email)) { return 'Invalid email address'; }
if (! password.length) { return 'Must set a password.'; }
if (! location || typeof location !== "object") { return "Must set a valid location."; }
if (firstName === '') { return 'Must set a first name.' }
if (lastName === '') { return 'Must set a last name.' }
return '';
}
|
// file: bwipp/databartruncatedcomposite.js
//
// This code was automatically generated from:
// Barcode Writer in Pure PostScript - Version 2015-03-24
//
// Copyright (c) 2011-2015 Mark Warren
// Copyright (c) 2004-2014 Terry Burton
//
// See the LICENSE file in the bwip-js root directory
// for the extended copyright notice.
// BEGIN databartruncatedcomposite
if (!BWIPJS.bwipp["raiseerror"] && BWIPJS.increfs("databartruncatedcomposite", "raiseerror")) {
BWIPJS.load("bwipp/raiseerror.js");
}
if (!BWIPJS.bwipp["databartruncated"] && BWIPJS.increfs("databartruncatedcomposite", "databartruncated")) {
BWIPJS.load("bwipp/databartruncated.js");
}
if (!BWIPJS.bwipp["gs1-cc"] && BWIPJS.increfs("databartruncatedcomposite", "gs1-cc")) {
BWIPJS.load("bwipp/gs1-cc.js");
}
if (!BWIPJS.bwipp["renlinear"] && BWIPJS.increfs("databartruncatedcomposite", "renlinear")) {
BWIPJS.load("bwipp/renlinear.js");
}
if (!BWIPJS.bwipp["renmatrix"] && BWIPJS.increfs("databartruncatedcomposite", "renmatrix")) {
BWIPJS.load("bwipp/renmatrix.js");
}
BWIPJS.bwipp["databartruncatedcomposite"]=function() {
function $f0(){
return -1;
}
function $f1(){
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.ptr--;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f2(){
this.stk[this.ptr++]=true;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f3(){
var a=/^\s*([^\s]+)(\s+.*)?$/.exec(this.stk[this.ptr-1]);
if (a) {
this.stk[this.ptr-1]=BWIPJS.psstring(a[2]===undefined?"":a[2]);
this.stk[this.ptr++]=BWIPJS.psstring(a[1]);
this.stk[this.ptr++]=true;
} else {
this.stk[this.ptr-1]=false;
}
this.stk[this.ptr++]=false;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring)
this.stk[this.ptr-2]=this.stk[this.ptr-2].toString()==this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]==this.stk[this.ptr-1];
this.ptr--;
this.stk[this.ptr++]=$f0;
var t0=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t0.call(this)==-1) return -1;
}
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
this.stk[this.ptr-1]=BWIPJS.psstring(this.stk[this.ptr-1]);
var t=this.stk[this.ptr-2].toString();
this.stk[this.ptr-1].assign(0,t);
this.stk[this.ptr-2]=this.stk[this.ptr-1].subset(0,t.length);
this.ptr--;
this.stk[this.ptr++]=BWIPJS.psstring("=");
var h=this.stk[this.ptr-2];
var t=h.indexOf(this.stk[this.ptr-1]);
if (t==-1) {
this.stk[this.ptr-1]=false;
} else {
this.stk[this.ptr-2]=h.subset(t+this.stk[this.ptr-1].length);
this.stk[this.ptr-1]=h.subset(t,this.stk[this.ptr-1].length);
this.stk[this.ptr++]=h.subset(0,t);
this.stk[this.ptr++]=true;
}
this.stk[this.ptr++]=true;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring)
this.stk[this.ptr-2]=this.stk[this.ptr-2].toString()==this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]==this.stk[this.ptr-1];
this.ptr--;
this.stk[this.ptr++]=$f1;
this.stk[this.ptr++]=$f2;
var t1=this.stk[--this.ptr];
var t2=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t2.call(this)==-1) return -1;
} else {
if (t1.call(this)==-1) return -1;
}
}
function $f4(){
this.stk[this.ptr++]=1;
this.stk[this.ptr-1]={};
this.dict=this.stk[--this.ptr]; this.dstk.push(this.dict);
var t=this.dstk.get("options");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f3;
var t3=this.stk[--this.ptr];
while (true) {
if (t3.call(this)==-1) break;
}
this.stk[this.ptr++]=this.dict;
this.dstk.pop(); this.dict=this.dstk[this.dstk.length-1];
this.stk[this.ptr++]="options";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f5(){
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f6(){
this.stk[this.ptr++]="linear";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.ptr--;
this.stk[this.ptr++]="comp";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
}
function $f7(){
this.ptr--;
}
function $f8(){
this.stk[this.ptr++]=1;
}
function $f9(){
this.stk[this.ptr++]=1;
}
function $f10(){
this.stk[this.ptr++]=0;
}
function $f11(){
var t=this.dstk.get("sep");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("i");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.stk[this.ptr++]=0;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring)
this.stk[this.ptr-2]=this.stk[this.ptr-2].toString()==this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]==this.stk[this.ptr-1];
this.ptr--;
this.stk[this.ptr++]=$f9;
this.stk[this.ptr++]=$f10;
var t10=this.stk[--this.ptr];
var t11=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t11.call(this)==-1) return -1;
} else {
if (t10.call(this)==-1) return -1;
}
}
function $f12(){
var t=this.dstk.get("bot");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("i");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.stk[this.ptr++]=1;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring)
this.stk[this.ptr-2]=this.stk[this.ptr-2].toString()==this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]==this.stk[this.ptr-1];
this.ptr--;
this.stk[this.ptr++]=$f8;
this.stk[this.ptr++]=$f11;
var t12=this.stk[--this.ptr];
var t13=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t13.call(this)==-1) return -1;
} else {
if (t12.call(this)==-1) return -1;
}
}
function $f13(){
this.stk[this.ptr++]=0;
}
function $f14(){
this.stk[this.ptr++]="i";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
var t=this.dstk.get("bot");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("i");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.stk[this.ptr++]=0;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring)
this.stk[this.ptr-2]=this.stk[this.ptr-2].toString()==this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]==this.stk[this.ptr-1];
this.ptr--;
this.stk[this.ptr++]=$f12;
this.stk[this.ptr++]=$f13;
var t14=this.stk[--this.ptr];
var t15=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t15.call(this)==-1) return -1;
} else {
if (t14.call(this)==-1) return -1;
}
var t=this.dstk.get("sep");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
var t=this.dstk.get("i");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
if (this.stk[this.ptr-3] instanceof BWIPJS.psstring || this.stk[this.ptr-3] instanceof BWIPJS.psarray)
this.stk[this.ptr-3].set(this.stk[this.ptr-2], this.stk[this.ptr-1]);
else this.stk[this.ptr-3][this.stk[this.ptr-2].toString()]=this.stk[this.ptr-1];
this.ptr-=3;
}
function $f15(){
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
var t=this.dstk.get("bot");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
var t=this.dstk.get("fp");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
var t=this.dstk.get("f3");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring)
this.stk[this.ptr-2]=this.stk[this.ptr-2].toString()==this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]==this.stk[this.ptr-1];
this.ptr--;
if (typeof(this.stk[this.ptr-1])=="boolean") this.stk[this.ptr-2]=this.stk[this.ptr-2]&&this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]&this.stk[this.ptr-1];
this.ptr--;
}
function $f16(){
var t=this.dstk.get("sep");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("fp");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=BWIPJS.psarray([0,0,0,0,0,0,0,0,0,0,1,0,0]);
this.stk[this.ptr-3].assign(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=3;
}
function $f17(){
this.stk[this.ptr++]="fp";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
var t=this.dstk.get("fp");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=1;
var t=this.dstk.get("fp");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=12;
this.stk[this.ptr-2]=this.stk[this.ptr-2]+this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=$f14;
var t20=this.stk[--this.ptr];
var t18=this.stk[--this.ptr];
var t17=this.stk[--this.ptr];
var t16=this.stk[--this.ptr];
for (var t19=t16; t17<0 ? t19>=t18 : t19<=t18; t19+=t17) {
this.stk[this.ptr++]=t19;
if (t20.call(this)==-1) break;
}
this.stk[this.ptr++]="f3";
this.stk[this.ptr++]=BWIPJS.psarray([1,1,1,1,1,1,1,1,1,0,1,1,1]);
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]=true;
this.stk[this.ptr++]=0;
this.stk[this.ptr++]=1;
this.stk[this.ptr++]=12;
this.stk[this.ptr++]=$f15;
var t25=this.stk[--this.ptr];
var t23=this.stk[--this.ptr];
var t22=this.stk[--this.ptr];
var t21=this.stk[--this.ptr];
for (var t24=t21; t22<0 ? t24>=t23 : t24<=t23; t24+=t22) {
this.stk[this.ptr++]=t24;
if (t25.call(this)==-1) break;
}
this.stk[this.ptr++]=$f16;
var t26=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t26.call(this)==-1) return -1;
}
}
function $f18(){
this.stk[this.ptr++]=0;
}
function $f19(){
this.stk[this.ptr++]=$f18;
}
function $f20(){
this.stk[this.ptr++]=1;
}
function $f21(){
this.stk[this.ptr++]=$f20;
}
function $f22(){
this.stk[this.ptr++]=1;
if (this.stk[this.ptr-1] >= this.ptr) throw "index: underflow";
this.stk[this.ptr-1]=this.stk[this.ptr-2-this.stk[this.ptr-1]];
this.stk[this.ptr++]=1;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring)
this.stk[this.ptr-2]=this.stk[this.ptr-2].toString()==this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]==this.stk[this.ptr-1];
this.ptr--;
this.stk[this.ptr++]=$f19;
this.stk[this.ptr++]=$f21;
var t27=this.stk[--this.ptr];
var t28=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t28.call(this)==-1) return -1;
} else {
if (t27.call(this)==-1) return -1;
}
var t31=this.stk[--this.ptr];
var t29=this.stk[--this.ptr];
for (var t30=0; t30<t29; t30++) {
if (t31.call(this)==-1) break;
}
}
function $f23(){
this.stk[this.ptr++]=1;
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
}
this.stk[this.ptr++]=20;
this.stk[this.ptr-1]={};
this.dict=this.stk[--this.ptr]; this.dstk.push(this.dict);
this.stk[this.ptr++]="options";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="barcode";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]="dontdraw";
this.stk[this.ptr++]=false;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
var t=this.dstk.get("options");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr-1]=BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr++]="stringtype";
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring)
this.stk[this.ptr-2]=this.stk[this.ptr-2].toString()==this.stk[this.ptr-1];
else this.stk[this.ptr-2]=this.stk[this.ptr-2]==this.stk[this.ptr-1];
this.ptr--;
this.stk[this.ptr++]=$f4;
var t4=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t4.call(this)==-1) return -1;
}
var t=this.dstk.get("options");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f5;
var t7=this.stk[--this.ptr];
var t6=this.stk[--this.ptr];
for (t5 in t6) {
if (t6 instanceof BWIPJS.psstring || t6 instanceof BWIPJS.psarray) {
if (t5.charCodeAt(0) > 57) continue;
this.stk[this.ptr++]=t6.get(t5);
} else {
this.stk[this.ptr++]=t5;
this.stk[this.ptr++]=t6[t5];
}
if (t7.call(this)==-1) break;
}
var t=this.dstk.get("barcode");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=BWIPJS.psstring("|");
var h=this.stk[this.ptr-2];
var t=h.indexOf(this.stk[this.ptr-1]);
if (t==-1) {
this.stk[this.ptr-1]=false;
} else {
this.stk[this.ptr-2]=h.subset(t+this.stk[this.ptr-1].length);
this.stk[this.ptr-1]=h.subset(t,this.stk[this.ptr-1].length);
this.stk[this.ptr++]=h.subset(0,t);
this.stk[this.ptr++]=true;
}
this.stk[this.ptr++]=$f6;
this.stk[this.ptr++]=$f7;
var t8=this.stk[--this.ptr];
var t9=this.stk[--this.ptr];
if (this.stk[--this.ptr]) {
if (t9.call(this)==-1) return -1;
} else {
if (t8.call(this)==-1) return -1;
}
this.gsave();
var t=this.dstk.get("options");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=BWIPJS.psstring("lintype");
this.stk[this.ptr++]=BWIPJS.psstring("databartruncated");
if (this.stk[this.ptr-3] instanceof BWIPJS.psstring || this.stk[this.ptr-3] instanceof BWIPJS.psarray)
this.stk[this.ptr-3].set(this.stk[this.ptr-2], this.stk[this.ptr-1]);
else this.stk[this.ptr-3][this.stk[this.ptr-2].toString()]=this.stk[this.ptr-1];
this.ptr-=3;
var t=this.dstk.get("options");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=BWIPJS.psstring("linkage");
this.stk[this.ptr++]=true;
if (this.stk[this.ptr-3] instanceof BWIPJS.psstring || this.stk[this.ptr-3] instanceof BWIPJS.psarray)
this.stk[this.ptr-3].set(this.stk[this.ptr-2], this.stk[this.ptr-1]);
else this.stk[this.ptr-3][this.stk[this.ptr-2].toString()]=this.stk[this.ptr-1];
this.ptr-=3;
var t=this.dstk.get("options");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=BWIPJS.psstring("inkspread");
this.stk[this.ptr++]=BWIPJS.psstring("0");
if (this.stk[this.ptr-3] instanceof BWIPJS.psstring || this.stk[this.ptr-3] instanceof BWIPJS.psarray)
this.stk[this.ptr-3].set(this.stk[this.ptr-2], this.stk[this.ptr-1]);
else this.stk[this.ptr-3][this.stk[this.ptr-2].toString()]=this.stk[this.ptr-1];
this.ptr-=3;
var t=this.dstk.get("options");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=BWIPJS.psstring("dontdraw");
this.stk[this.ptr++]=true;
if (this.stk[this.ptr-3] instanceof BWIPJS.psstring || this.stk[this.ptr-3] instanceof BWIPJS.psarray)
this.stk[this.ptr-3].set(this.stk[this.ptr-2], this.stk[this.ptr-1]);
else this.stk[this.ptr-3][this.stk[this.ptr-2].toString()]=this.stk[this.ptr-1];
this.ptr-=3;
var t=this.dstk.get("linear");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("options");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("databartruncated");
this.stk[this.ptr++]=t;
var t=this.stk[--this.ptr];
if (t instanceof Function) t.call(this); else this.eval(t);
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
this.stk[this.ptr++]=BWIPJS.psstring("sbs");
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.stk[this.ptr++]="linsbs";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr]=this.stk[this.ptr-1]; this.ptr++;
this.stk[this.ptr++]=BWIPJS.psstring("bhs");
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.stk[this.ptr++]=0;
if (this.stk[this.ptr-2] instanceof BWIPJS.psstring || this.stk[this.ptr-2] instanceof BWIPJS.psarray)
this.stk[this.ptr-2]=this.stk[this.ptr-2].get(this.stk[this.ptr-1]);
else this.stk[this.ptr-2]=this.stk[this.ptr-2][this.stk[this.ptr-1].toString()];
this.ptr--;
this.stk[this.ptr++]=72;
this.stk[this.ptr-2]=this.stk[this.ptr-2]*this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]="linheight";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
var t=this.dstk.get("renlinear");
this.stk[this.ptr++]=t;
var t=this.stk[--this.ptr];
if (t instanceof Function) t.call(this); else this.eval(t);
this.stk[this.ptr++]="sepfinder";
this.stk[this.ptr++]=$f17;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.stk[this.ptr++]=Infinity;
this.stk[this.ptr++]=0;
var t=this.dstk.get("linsbs");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f22;
var t34=this.stk[--this.ptr];
var t33=this.stk[--this.ptr];
for (t32 in t33) {
if (t33 instanceof BWIPJS.psstring || t33 instanceof BWIPJS.psarray) {
if (t32.charCodeAt(0) > 57) continue;
this.stk[this.ptr++]=t33.get(t32);
} else {
this.stk[this.ptr++]=t32;
this.stk[this.ptr++]=t33[t32];
}
if (t34.call(this)==-1) break;
}
for (var i=this.ptr-1; i>=0 && this.stk[i]!==Infinity; i--);
if (i==-1) throw "counttomark: underflow";
this.stk[this.ptr]=this.ptr-i-1;
this.ptr++;
this.stk[this.ptr++]=1;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr-1]=BWIPJS.psarray(this.stk[this.ptr-1]);
var t=this.stk[this.ptr-1];
if (t.length >= this.ptr) throw "astore: underflow";
var a=this.stk.splice(this.ptr-1-t.length,t.length);
t.assign(0,a);
this.ptr-=t.length;
this.stk[this.ptr++]="bot";
var t=this.stk[this.ptr-2]; this.stk[this.ptr-2]=this.stk[this.ptr-1]; this.stk[this.ptr-1]=t;
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
this.ptr--;
this.ptr--;
this.stk[this.ptr++]="sep";
this.stk[this.ptr++]=Infinity;
var t=this.dstk.get("bot");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=$f23;
var t37=this.stk[--this.ptr];
var t36=this.stk[--this.ptr];
for (t35 in t36) {
if (t36 instanceof BWIPJS.psstring || t36 instanceof BWIPJS.psarray) {
if (t35.charCodeAt(0) > 57) continue;
this.stk[this.ptr++]=t36.get(t35);
} else {
this.stk[this.ptr++]=t35;
this.stk[this.ptr++]=t36[t35];
}
if (t37.call(this)==-1) break;
}
for (var i = this.ptr-1; i >= 0 && this.stk[i] !== Infinity; i--) ;
if (i < 0) throw "array: underflow";
var t = this.stk.splice(i+1, this.ptr-1-i);
this.ptr = i;
this.stk[this.ptr++]=BWIPJS.psarray(t);
this.dict[this.stk[this.ptr-2]]=this.stk[this.ptr-1]; this.ptr-=2;
var t=this.dstk.get("sep");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=0;
this.stk[this.ptr++]=BWIPJS.psarray([0,0,0]);
this.stk[this.ptr-3].assign(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=3;
var t=this.dstk.get("sep");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("sep");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
this.stk[this.ptr++]=4;
this.stk[this.ptr-2]=this.stk[this.ptr-2]-this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]=BWIPJS.psarray([0,0,0,0]);
this.stk[this.ptr-3].assign(this.stk[this.ptr-2],this.stk[this.ptr-1]); this.ptr-=3;
this.stk[this.ptr++]=18;
var t=this.dstk.get("sepfinder");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=64;
var t=this.dstk.get("sepfinder");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]=0;
var t=this.dstk.get("linheight");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var y=this.stk[--this.ptr];
this.rmoveto(this.stk[--this.ptr],y);
this.stk[this.ptr++]=Infinity;
this.stk[this.ptr++]="ren";
var t=this.dstk.get("renmatrix");
this.stk[this.ptr++]=t;
this.stk[this.ptr++]="pixs";
var t=this.dstk.get("sep");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
this.stk[this.ptr++]="pixx";
var t=this.dstk.get("sep");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
this.stk[this.ptr++]="pixy";
this.stk[this.ptr++]=1;
this.stk[this.ptr++]="height";
this.stk[this.ptr++]=1;
this.stk[this.ptr++]=72;
this.stk[this.ptr-2]=this.stk[this.ptr-2]/this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]="width";
var t=this.dstk.get("sep");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
if (typeof(this.stk[this.ptr-1].length)!=="number") throw "length: invalid: " + BWIPJS.pstype(this.stk[this.ptr-1]);
this.stk[this.ptr-1]=this.stk[this.ptr-1].length;
this.stk[this.ptr++]=72;
this.stk[this.ptr-2]=this.stk[this.ptr-2]/this.stk[this.ptr-1]; this.ptr--;
this.stk[this.ptr++]="opt";
var t=this.dstk.get("options");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t = {};
for (var i = this.ptr-1; i >= 1 && this.stk[i] !== Infinity; i-=2) {
if (this.stk[i-1] === Infinity) throw "dict: malformed stack";
t[this.stk[i-1]]=this.stk[i];
}
if (i < 0 || this.stk[i]!==Infinity) throw "dict: underflow";
this.ptr = i;
this.stk[this.ptr++]=t;
var t=this.dstk.get("renmatrix");
this.stk[this.ptr++]=t;
var t=this.stk[--this.ptr];
if (t instanceof Function) t.call(this); else this.eval(t);
this.stk[this.ptr++]=-5;
this.stk[this.ptr++]=1;
var y=this.stk[--this.ptr];
this.rmoveto(this.stk[--this.ptr],y);
var t=this.dstk.get("comp");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("options");
if (t instanceof Function) t.call(this); else this.stk[this.ptr++]=t;
var t=this.dstk.get("gs1-cc");
this.stk[this.ptr++]=t;
var t=this.stk[--this.ptr];
if (t instanceof Function) t.call(this); else this.eval(t);
var t=this.dstk.get("renmatrix");
this.stk[this.ptr++]=t;
var t=this.stk[--this.ptr];
if (t instanceof Function) t.call(this); else this.eval(t);
this.grestore();
this.dstk.pop(); this.dict=this.dstk[this.dstk.length-1];
psstptr = this.ptr;
}
BWIPJS.decrefs("databartruncatedcomposite");
// END OF databartruncatedcomposite
|
( function () {
"use strict";
var cssPrefix, allStyles,
defaultCss, defaultTextCss,
hiddenCss,
textDimensionCalculateNodeCss,
inputType2tag, nonInputType2tag,
textSizeMeasureNode,
imageSizeMeasureNode,
supportedInputTypeS,
audioWidth, audioHeight,
INPUT_FILE_WIDTH = 240;
// source: http://davidwalsh.name/vendor-prefix
if ( window.getComputedStyle ) {
cssPrefix = (Array.prototype.slice
.call(window.getComputedStyle(document.body, null))
.join('')
.match(/(-moz-|-webkit-|-ms-)/)
)[1];
} else {
cssPrefix = "-ms-";
}
// source: xicooc (http://stackoverflow.com/a/29837441)
LAY.$isBelowIE9 = (/MSIE\s/.test(navigator.userAgent) &&
parseFloat(navigator.appVersion.split("MSIE")[1]) < 10);
allStyles = document.body.style;
// check for matrix 3d support
// source: https://gist.github.com/webinista/3626934
// http://tiffanybbrown.com/2012/09/04/testing-for-css-3d-transforms-support/
allStyles[ (cssPrefix + "transform" ) ] =
'matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)';
if ( window.getComputedStyle ) {
LAY.$isGpuAccelerated =
Boolean(
window.getComputedStyle(
document.body, null ).getPropertyValue(
( cssPrefix + "transform" ) ) ) &&
!LAY.$isBelowIE9;
} else {
LAY.$isGpuAccelerated = false;
}
allStyles = undefined;
defaultCss = "position:absolute;display:block;visibility:inherit;" +
"margin:0;padding:0;" +
"backface-visibility:hidden;" +
"contain:style;" +
"-webkit-backface-visibility: hidden;" +
"box-sizing:border-box;-moz-box-sizing:border-box;" +
"transform-style:preserve-3d;-webkit-transform-style:preserve-3d;" +
"-webkit-overflow-scrolling:touch;" +
"white-space:nowrap;" +
"outline:none;border:none;";
// Most CSS text(/font) properties
// match the defaults of LAY, however
// for ones which do not match the
// below list contains their default css
defaultTextCss = defaultCss +
"font-size:15px;" +
"font-family:sans-serif;color:black;" +
"text-decoration:none;" +
"text-align:left;direction:ltr;line-height:1.3em;" +
"-webkit-font-smoothing:antialiased;";
hiddenCss = "left:-9999px;top:-9999px;visibility:hidden;";
textDimensionCalculateNodeCss =
defaultTextCss +
hiddenCss +
"height:auto;" +
"border:0px solid transparent;" +
"word-wrap:normal;";
inputType2tag = {
lines: "textarea",
option: "select",
options: "select"
};
nonInputType2tag = {
none: "div",
text: "div",
html: "div",
iframe: "iframe",
canvas: "canvas",
image: "img",
video: "video",
audio: "audio"
};
supportedInputTypeS = [
"line", "lines", "password", "option",
"options", "file", "files" ];
var audioElement = document.createElement("audio");
audioElement.controls = true;
document.body.appendChild(audioElement);
audioWidth = audioElement.offsetWidth;
audioHeight = audioElement.offsetHeight;
document.body.removeChild(audioElement);
audioElement = undefined;
function stringifyPlusPx ( val ) {
return val + "px";
}
function setText ( node, text ) {
if ( LAY.$isBelowIE9 ) {
node.innerText = text;
} else {
node.textContent = text;
}
}
function generateSelectOptionsHTML( optionS ) {
var option, html = "";
for ( var i=0, len=optionS.length; i<len; i++ ) {
option = optionS[i];
html += "<option value='" + option.value + "'" +
( option.selected ? " selected='true'" : "" ) +
( option.disabled ? " disabled='true'" : "" ) +
">" + option.content + "</option>";
}
return html;
}
textSizeMeasureNode = document.createElement("div");
textSizeMeasureNode.style.cssText =
textDimensionCalculateNodeCss;
document.body.appendChild( textSizeMeasureNode );
imageSizeMeasureNode = document.createElement("img");
imageSizeMeasureNode.style.cssText = defaultCss + hiddenCss;
document.body.appendChild( imageSizeMeasureNode );
LAY.Part = function (level) {
this.level = level;
this.node = undefined;
this.type = undefined;
this.inputType = undefined;
this.isText = undefined;
this.isInitiallyRendered = false;
this.normalRenderDirtyAttrValS = [];
this.travelRenderDirtyAttrValS = [];
this.whenEventType2fnMainHandler = {};
this.isImageLoaded = false;
this.isVideoLoaded = false;
// If the element tag is not "div", then
// the link is created by wrapping an "a"
// tag around the element (for instance
// a lson $type "image" or "canvas" )
this.isWrappedLink = false;
// acting node will be the same as this.node
// is this.isWrappedLink is false,
// however in the case of this.isWrappedLink
// being true, actingNode will be the inner node
this.actingNode = undefined;
// for many derived levels
this.formationX = undefined;
this.formationY = undefined;
this.init();
};
function getInputType ( type ) {
return type.startsWith( "input:" ) &&
type.slice( "input:".length );
}
LAY.Part.prototype.init = function () {
var inputTag, parentNode, inputType;
inputType = this.inputType = getInputType(
this.level.lson.$type );
this.type = this.inputType ? "input" :
this.level.lson.$type;
if ( inputType && supportedInputTypeS.indexOf(
inputType ) === -1 ) {
LAY.$error("Unsupported $type: input:" + inputType);
}
if ( this.level.pathName === "/" ) {
this.node = document.body;
} else if ( this.inputType ) {
inputTag = inputType2tag[ this.inputType ];
if ( inputTag ) {
this.node = document.createElement( inputTag );
if ( inputType === "options" ) {
this.node.multiple = true;
}
} else {
this.node = document.createElement( "input" );
this.node.type = this.inputType === "line" ?
"text" : ( this.inputType === "files" ? "file" : this.inputType );
if ( inputType === "password" ) {
// we wil treat password as a line
// for logic purposes, as we we will
// not alter the input[type] during
// runtime
this.inputType = "line";
} else if ( inputType === "files" ) {
this.node.multiple = true;
}
}
} else {
var tag = nonInputType2tag[this.type];
if (this.level.lson.states.root.props.link !== undefined ) {
this.node = document.createElement("a");
if (tag !== "div" ) {
this.isWrappedLink = true;
this.actingNode = document.createElement(tag);
this.actingNode.style.cssText = defaultCss;
this.node.appendChild(this.actingNode);
}
} else {
this.node = document.createElement(tag);
}
}
if (!this.isWrappedLink) {
this.actingNode = this.node;
}
this.isText = this.type === "input" ||
this.type === "text" ||
this.type === "html";
if ( this.isText ) {
this.node.style.cssText = defaultTextCss;
} else {
this.node.style.cssText = defaultCss;
}
if ( this.type === "input" && this.inputType === "lines" ) {
this.node.style.whiteSpace = "pre-wrap";
this.node.style.resize = "none";
}
if ( this.type === "image" ) {
var part = this;
LAY.$eventUtils.add( this.actingNode, "load", function() {
part.isImageLoaded = true;
part.updateNaturalWidth();
part.updateNaturalHeight();
LAY.$isNoTransition = true;
LAY.$solve();
});
} else if ( this.type === "video" ) {
var part = this;
LAY.$eventUtils.add( this.actingNode, "loadedmetadata", function() {
part.isVideoLoaded = true;
part.updateNaturalWidth();
part.updateNaturalHeight();
LAY.$isNoTransition = true;
LAY.$solve();
});
}
};
// Precondition: not called on "/" level
LAY.Part.prototype.remove = function () {
if ( this.level.pathName !== "/" ) {
var parentPart = this.level.parentLevel.part;
parentPart.updateNaturalWidth();
parentPart.updateNaturalHeight();
// If the level is inexistent from the start
// then the node will not have been attached
if ( this.node.parentNode === parentPart.node ) {
parentPart.node.removeChild( this.node );
}
LAY.$arrayUtils.remove(
LAY.$naturalWidthDirtyPartS, this );
LAY.$arrayUtils.remove(
LAY.$naturalHeightDirtyPartS, this );
LAY.$arrayUtils.remove(
LAY.$renderDirtyPartS, this );
}
};
LAY.Part.prototype.add = function () {
if ( this.level.pathName !== "/" ) {
var parentPart = this.level.parentLevel.part;
parentPart.updateNaturalWidth();
parentPart.updateNaturalHeight();
this.level.parentLevel.part.node.appendChild( this.node );
}
};
function checkIfLevelIsDisplayed ( level ) {
var attrValDisplay = level.attr2attrVal.display;
return !attrValDisplay || attrValDisplay.calcVal;
}
LAY.Part.prototype.findChildMaxOfAttr =
function ( attr ) {
var
curMaxVal = 0,
childLevel, childLevelAttrVal;
for ( var i = 0,
childLevelS = this.level.childLevelS,
len = childLevelS.length;
i < len; i++ ) {
childLevel = childLevelS[i];
if ( childLevel.isPart && !childLevel.isHelper &&
childLevel.isExist ) {
if ( checkIfLevelIsDisplayed( childLevel ) ) {
childLevelAttrVal = childLevel.attr2attrVal[attr];
if (
( childLevelAttrVal !== undefined ) &&
( childLevelAttrVal.calcVal )
) {
if ( childLevelAttrVal.calcVal > curMaxVal ) {
curMaxVal = childLevelAttrVal.calcVal;
}
}
}
}
}
return curMaxVal;
};
LAY.Part.prototype.getImmidiateReadonlyVal = function ( attr ) {
switch ( attr ) {
case "$naturalWidth":
return this.calculateNaturalWidth();
case "$naturalHeight":
return this.calculateNaturalHeight();
case "$scrolledX":
return this.node.scrollLeft;
case "$scrolledY":
return this.node.scrollTop;
case "$focused":
return this.node === document.activeElement;
case "$hash":
return document.location.hash.substr(1);
case "$pathname":
return document.location.pathname;
case "$href":
return document.location.href;
case "$host":
return document.location.host;
case "$input":
if ( this.inputType.startsWith("option") ) {
var optionS =
this.isInitiallyRendered ?
this.node.options :
( // input might not be calculated
// as yet, thus OR with the empty array
this.level.attr2attrVal.input.calcVal || [] );
var valS = [];
for ( var i = 0, len = optionS.length;
i < len; i++ ) {
if ( optionS[i].selected ) {
valS.push( optionS[i].value )
}
}
// Select the first option if none is selected
// as that will be the default
if ( optionS.length && !valS.length &&
this.inputType === "option" ) {
valS.push(optionS[ 0 ].value );
}
return this.inputType === "option" ?
valS[ 0 ] : valS ;
} else if ( this.inputType.startsWith("file") ) {
return this.inputType === "file" ?
this.node.files[ 0 ] : this.node.files;
} else {
return this.node.value;
}
}
};
LAY.Part.prototype.updateNaturalWidth = function () {
var naturalWidthAttrVal = this.level.$getAttrVal("$naturalWidth");
if ( naturalWidthAttrVal ) {
LAY.$arrayUtils.pushUnique(
LAY.$naturalWidthDirtyPartS,
this );
}
};
LAY.Part.prototype.updateNaturalHeight = function () {
var naturalHeightAttrVal = this.level.$getAttrVal("$naturalHeight");
if ( naturalHeightAttrVal ) {
LAY.$arrayUtils.pushUnique(
LAY.$naturalHeightDirtyPartS,
this );
}
};
LAY.Part.prototype.calculateNaturalWidth = function () {
var attr2attrVal = this.level.attr2attrVal;
if ( this.isText ) {
return this.calculateTextNaturalDimesion( true );
} else if ( this.type === "image" ) {
return this.calculateImageNaturalDimesion( true );
} else if ( this.type === "video" ) {
return this.calculateVideoNaturalDimesion( true );
} else if ( this.type === "audio" ) {
return this.calculateTextNaturalDimesion( true );
} else {
return this.findChildMaxOfAttr( "right" );
}
};
LAY.Part.prototype.calculateNaturalHeight = function () {
var attr2attrVal = this.level.attr2attrVal;
if ( this.isText ) {
return this.calculateTextNaturalDimesion( false );
} else if ( this.type === "image" ) {
return this.calculateImageNaturalDimesion( false );
} else if ( this.type === "video" ) {
return this.calculateVideoNaturalDimesion( false );
} else if ( this.type === "audio" ) {
return this.calculateTextNaturalDimesion( false );
} else {
return this.findChildMaxOfAttr( "bottom" );
}
};
LAY.Part.prototype.calculateImageNaturalDimesion = function ( isWidth ) {
if ( !this.isImageLoaded ) {
return 0;
} else {
imageSizeMeasureNode.src =
this.level.attr2attrVal.image.calcVal;
imageSizeMeasureNode.style.width = "auto";
imageSizeMeasureNode.style.height = "auto";
var otherDim = isWidth ? "height" : "width",
otherDimAttrVal = this.level.attr2attrVal[
otherDim ],
otherDimVal = otherDimAttrVal ?
( otherDimAttrVal.calcVal !== undefined ?
otherDimAttrVal.calcVal : undefined ) : undefined;
if ( isWidth ) {
if ( typeof otherDimVal !== "number" ||
otherDimVal === 0 ) {
return imageSizeMeasureNode.width;
} else {
return imageSizeMeasureNode.width *
( otherDimVal / imageSizeMeasureNode.height );
}
} else {
if ( typeof otherDimVal !== "number" ||
otherDimVal === 0 ) {
return imageSizeMeasureNode.height;
} else {
return imageSizeMeasureNode.height *
( otherDimVal / imageSizeMeasureNode.width );
}
}
}
};
LAY.Part.prototype.calculateVideoNaturalDimesion = function ( isWidth ) {
if ( !this.isVideoLoaded ) {
return 0;
} else {
var node = this.actingNode;
node.style.visibility = "hidden";
var otherDim = isWidth ? "height" : "width",
otherDimAttrVal = this.level.attr2attrVal[
otherDim ],
otherDimVal = otherDimAttrVal ?
( otherDimAttrVal.calcVal !== undefined ?
otherDimAttrVal.calcVal : "auto" ) : "auto";
node.height = "auto";
node.width = "auto";
if ( isWidth ) {
node.height = otherDimVal;
node.style.visibility = "visible";
return node.offsetWidth;
} else {
node.width = otherDimVal;
node.style.visibility = "visible";
return node.videoHeight;
}
}
};
LAY.Part.prototype.calculateAudioNaturalDimesion = function ( isWidth ) {
var isAudioController =
this.level.attr2attrVal.audioController &&
this.level.attr2attrVal.audioController.calcVal;
if ( isWidth ) {
return isAudioController ? audioWidth : 0;
} else {
return isAudioController ? audioHeight : 0;
}
};
/*
* ( Height occupied naturally by text can be estimated
* without creating a DOM node and checking ".offsetHeight"
* if the text does not wrap, or it does wrap however with
* extremely high probability does not span more than 1 line )
* If the height can be estimated without using a DOM node
* then return the estimated height, else return -1;
*/
LAY.Part.prototype.estimateTextNaturalHeight = function ( text ) {
if ( [ "file", "files" ].indexOf( this.type ) !== -1 ||
( this.type === "html" &&
checkIfTextMayHaveHTML ( text ) ) ) {
return -1;
} else {
var heightAttr2default = {
"textSize": 15,
"textWrap": "nowrap",
"textPaddingTop": 0,
"textPaddingBottom": 0,
"borderTopWidth": 0,
"borderBottomWidth": 0,
"textLineHeight": 1.3,
"textLetterSpacing": 1,
"textWordSpacing": 1,
"width": null
};
var heightAttr2val = {};
for ( var heightAttr in heightAttr2default ) {
var attrVal = this.level.attr2attrVal[ heightAttr ];
heightAttr2val[ heightAttr ] = ( attrVal === undefined ||
attrVal.calcVal === undefined ) ?
heightAttr2default[ heightAttr ] : attrVal.calcVal;
}
if (text === "") {
heightAttr2val.textSize = 0;
}
// Do not turn the below statement into a ternary as
// it will end up being unreadable
var isEstimatePossible = false;
if (heightAttr2val.textWrap === "nowrap") {
isEstimatePossible = true;
} else if (
LAY.$isOkayToEstimateWhitespaceHeight &&
( heightAttr2val.textWrap === "normal" ||
text.indexOf( "\\" ) === -1 ) && //escape characters can
// contain whitespace characters such as line breaks and/or tabs
heightAttr2val.textLetterSpacing === 1 &&
heightAttr2val.textWordSpacing === 1 &&
heightAttr2val.width !== null ) {
if (heightAttr2val.textSize === 0 ||
text.length < ( 0.7 *
(heightAttr2val.width/heightAttr2val.textSize))) {
isEstimatePossible = true;
}
}
if ( isEstimatePossible ) {
return ( heightAttr2val.textSize * heightAttr2val.textLineHeight ) +
heightAttr2val.textPaddingTop +
heightAttr2val.textPaddingBottom +
heightAttr2val.borderTopWidth +
heightAttr2val.borderBottomWidth;
} else {
return -1;
}
}
};
function checkIfTextMayHaveHTML( text ) {
return text.indexOf( "<" ) !== -1 && text.indexOf( ">" ) !== -1;
};
LAY.Part.prototype.calculateTextNaturalDimesion = function ( isWidth ) {
var dimensionAlteringAttr2fnStyle = {
textSize: stringifyPxOrString,
textFamily: null,
textWeight: null,
textAlign: null,
textStyle: null,
textDirection: null,
textTransform: null,
textVariant: null,
textLetterSpacing: stringifyPxOrStringOrNormal,
textWordSpacing: stringifyPxOrStringOrNormal,
textLineHeight: stringifyEmOrString,
textOverflow: null,
textIndent: stringifyPlusPx,
textWrap: null,
textWordBreak: null,
textWordWrap: null,
textRendering: null,
textPaddingTop: stringifyPlusPx,
textPaddingRight: stringifyPlusPx,
textPaddingBottom: stringifyPlusPx,
textPaddingLeft: stringifyPlusPx,
borderTopWidth: stringifyPlusPx,
borderRightWidth: stringifyPlusPx,
borderBottomWidth: stringifyPlusPx,
borderLeftWidth: stringifyPlusPx
};
var dimensionAlteringAttr2cssProp = {
textSize: "font-size",
textFamily: "font-family",
textWeight: "font-weight",
textAlign: "text-align",
textStyle: "font-style",
textDirection: "direction",
textTransform: "text-transform",
textVariant: "font-variant",
textLetterSpacing: "letter-spacing",
textWordSpacing: "word-spacing",
textLineHeight: "line-height",
textOverflow: "text-overflow",
textIndent: "text-indent",
textWrap: "white-space",
textWordBreak: "word-break",
textWordWrap: "word-wrap",
textRendering: "text-rendering",
textPaddingTop: "padding-top",
textPaddingRight: "padding-right",
textPaddingBottom: "padding-bottom",
textPaddingLeft: "padding-left",
borderTopWidth: "border-top-width",
borderRightWidth: "border-right-width",
borderBottomWidth: "border-bottom-width",
borderLeftWidth: "border-left-width"
};
var
attr2attrVal = this.level.attr2attrVal,
dimensionAlteringAttr, fnStyle,
textRelatedAttrVal,
content, ret,
cssText = textDimensionCalculateNodeCss,
isTextarea = (this.type === "input" && this.inputType === "lines"),
sizeMeasureNode = textSizeMeasureNode;
if (isTextarea) {
cssText += "white-space:pre-wrap;word-wrap:break-word;";
}
if ( this.type === "input" ) {
if ( this.inputType.startsWith("option") ) {
if ( attr2attrVal.input.isRecalculateRequired ) {
return 0;
}
content = "<select" +
( this.inputType === "multiple" ?
" multiple='true' " : "" ) + ">" +
generateSelectOptionsHTML(
attr2attrVal.input.calcVal
) + "</select>";
} else if ( this.inputType.startsWith("file") ) {
if ( isWidth ) {
return INPUT_FILE_WIDTH;
} else {
content = "<input type='file' " +
( this.inputType === "multiple" ?
" multiple='true' " : "" ) + "/>";
}
} else if (this.inputType === "line") {
// letter "a" is a random letter
// used as a placeholder
content = attr2attrVal.$input ?
( attr2attrVal.$input.calcVal || "a" ) : "a";
} else {
content = attr2attrVal.$input.calcVal;
}
} else if ( this.type === "html" ) {
if ( attr2attrVal.html.isRecalculateRequired ) {
return 0;
}
content = attr2attrVal.html.calcVal;
} else {
if ( attr2attrVal.text.isRecalculateRequired ) {
return 0;
}
content = attr2attrVal.text.calcVal;
}
if ( typeof content !== "string" ) {
content = content.toString();
}
if ( !isWidth && !isTextarea) {
var estimatedHeight = this.estimateTextNaturalHeight(content);
if ( estimatedHeight !== -1 ) {
return estimatedHeight;
}
}
for ( dimensionAlteringAttr in
dimensionAlteringAttr2fnStyle ) {
textRelatedAttrVal = attr2attrVal[
dimensionAlteringAttr ];
if ( textRelatedAttrVal &&
textRelatedAttrVal.calcVal !== undefined ) {
fnStyle = dimensionAlteringAttr2fnStyle[
dimensionAlteringAttr ];
cssText +=
dimensionAlteringAttr2cssProp[
dimensionAlteringAttr ] + ":" +
( (fnStyle === null) ?
textRelatedAttrVal.calcVal :
fnStyle( textRelatedAttrVal.calcVal ) ) + ";";
}
}
if (isTextarea) {
content += "\r\n"
}
if ( isWidth ) {
cssText += "display:inline;width:auto;";
} else {
cssText += "width:" +
( attr2attrVal.width.calcVal || 0 ) + "px;";
}
sizeMeasureNode.style.cssText = cssText;
if ( this.type === "html" ) {
sizeMeasureNode.innerHTML = content;
} else {
setText(textSizeMeasureNode, content);
}
return isWidth ? sizeMeasureNode.offsetWidth :
sizeMeasureNode.offsetHeight;
};
LAY.Part.prototype.addNormalRenderDirtyAttrVal = function ( attrVal ) {
LAY.$arrayUtils.remove( this.travelRenderDirtyAttrValS, attrVal );
LAY.$arrayUtils.pushUnique( this.normalRenderDirtyAttrValS, attrVal );
LAY.$arrayUtils.pushUnique( LAY.$renderDirtyPartS, this );
};
LAY.Part.prototype.addTravelRenderDirtyAttrVal = function ( attrVal ) {
LAY.$arrayUtils.remove( this.normalRenderDirtyAttrValS, attrVal );
LAY.$arrayUtils.pushUnique( this.travelRenderDirtyAttrValS, attrVal );
LAY.$arrayUtils.pushUnique( LAY.$renderDirtyPartS, this );
};
LAY.Part.prototype.updateWhenEventType = function ( eventType ) {
var
numFnHandlersForEventType =
this.level.attr2attrVal[ "$$num.when." + eventType ].val,
fnMainHandler,
thisLevel = this.level,
node = this.node;
if ( LAY.$checkIsWindowEvent( eventType ) &&
this.level.pathName === "/" ) {
node = window;
}
if ( this.whenEventType2fnMainHandler[ eventType ] !== undefined ) {
LAY.$eventUtils.remove(
node, eventType,
this.whenEventType2fnMainHandler[ eventType ] );
}
if ( numFnHandlersForEventType !== 0 ) {
fnMainHandler = function ( e ) {
var i, len, attrValForFnHandler;
for ( i = 0; i < numFnHandlersForEventType; i++ ) {
attrValForFnHandler =
thisLevel.attr2attrVal[ "when." + eventType + "." + ( i + 1 ) ];
if ( attrValForFnHandler !== undefined ) {
attrValForFnHandler.calcVal.call( thisLevel, e );
}
}
};
LAY.$eventUtils.add( node, eventType, fnMainHandler );
this.whenEventType2fnMainHandler[ eventType ] = fnMainHandler;
} else {
this.whenEventType2fnMainHandler[ eventType ] = undefined;
}
};
LAY.Part.prototype.checkIsPropInTransition = function ( prop ) {
return ( this.level.attr2attrVal[ "transition." + prop + ".type" ] !==
undefined ) ||
( this.level.attr2attrVal[ "transition." + prop + ".delay" ] !==
undefined );
};
LAY.Part.prototype.updateTransitionProp = function (transitionProp) {
if (this.isInitiallyRendered && !LAY.$isNoTransition) {
var
attr2attrVal = this.level.attr2attrVal,
attr, attrVal,
transitionPrefix,
transitionType, transitionDuration, transitionDelay, transitionDone,
transitionArgS, transitionArg2val = {},
transitionObj,
i, len,
allAffectedProp, // (eg: when `top` changes but transition
//is provided by `positional`)
affectedPropAttrVal;
// TODO: change the below to a helper function
if ( ( [ "centerX", "right", "centerY", "bottom" ] ).indexOf(
transitionProp ) !== -1 ) {
return;
}
if ( !this.checkIsPropInTransition( transitionProp ) ) {
if ( this.checkIsPropInTransition( "all" ) ) {
allAffectedProp = transitionProp;
transitionProp = "all";
} else {
return;
}
}
transitionPrefix = "transition." + transitionProp + ".";
transitionType =
attr2attrVal[ transitionPrefix + "type" ] ?
attr2attrVal[ transitionPrefix + "type" ].calcVal :
"linear";
transitionDuration =
( attr2attrVal[ transitionPrefix + "duration" ] ?
attr2attrVal[ transitionPrefix + "duration" ].calcVal :
0 );
transitionDelay =
( attr2attrVal[ transitionPrefix + "delay" ] ?
attr2attrVal[ transitionPrefix + "delay" ].calcVal :
0 );
transitionDone =
( attr2attrVal[ transitionPrefix + "done" ] ?
attr2attrVal[ transitionPrefix + "done" ].calcVal :
undefined );
transitionArgS = LAY.$transitionType2args[ transitionType ] ?
LAY.$transitionType2args[ transitionType ] : [];
for ( i=0, len=transitionArgS.length; i<len; i++ ) {
transitionArg2val[ transitionArgS[i] ] = (
attr2attrVal[ transitionPrefix + "args." +
transitionArgS[i] ] ?
attr2attrVal[ transitionPrefix + "args." +
transitionArgS[i] ].calcVal : undefined );
}
if ( !allAffectedProp && ( transitionProp === "all" )) {
for ( attr in attr2attrVal ) {
attrVal = attr2attrVal[attr];
// Only invoke a transition if:
// (1) The prop is renderable (i.e has a render call)
// (2) The prop doesn't have a transition of its
// own. For instance if "left" already has
// a transition then we will not want to override
// its transition with the lower priority "all" transition
if ( attrVal.renderCall &&
!this.checkIsPropInTransition( attrVal.attr ) ) {
this.updateTransitionAttrVal(
attrVal,
transitionType, transitionDelay, transitionDuration,
transitionArg2val, transitionDone
);
}
}
} else {
this.updateTransitionAttrVal(
attr2attrVal[ allAffectedProp || transitionProp ],
transitionType, transitionDelay, transitionDuration,
transitionArg2val, transitionDone
);
}
}
};
LAY.Part.prototype.updateTransitionAttrVal = function ( attrVal,
transitionType, transitionDelay, transitionDuration,
transitionArg2val, transitionDone ) {
if (attrVal === undefined) {
return;
}
// First check if the transition information is complete
if (!attrVal.isDeltaTransitionable &&
(transitionDelay || transitionDone)) {
attrVal.startCalcVal = attrVal.transCalcVal;
attrVal.transition = new LAY.Transition(
"none",
transitionDelay,
0,
{},
transitionDone
);
} else if (
transitionType &&
( transitionDuration !== undefined ) &&
( transitionDelay !== undefined ) &&
( attrVal !== undefined ) &&
( attrVal.isTransitionable )
) {
attrVal.startCalcVal = attrVal.transCalcVal;
attrVal.transition = new LAY.Transition(
transitionType,
transitionDelay,
transitionDuration, transitionArg2val,
transitionDone );
} else if ( attrVal !== undefined ) { // else delete the transition
attrVal.transition = undefined;
}
}
function stringifyPxOrString( val, defaultVal ) {
return ( val === undefined ) ?
defaultVal : ( typeof val === "number" ?
( val + "px" ) : val );
}
function stringifyPxOrStringOrNormal( val, defaultVal ) {
if ( val === 0 ) {
return "normal";
} else {
return stringifyPlusPx( val, defaultVal );
}
}
function stringifyEmOrString( val, defaultVal ) {
return ( val === undefined ) ?
defaultVal : ( typeof val === "number" ?
( val + "em" ) : val );
}
function computePxOrString( attrVal, defaultVal ) {
return stringifyPxOrString(
attrVal && attrVal.transCalcVal,
defaultVal );
}
function computePxOrStringOrNormal( attrVal, defaultVal ) {
return stringifyPxOrStringOrNormal(
attrVal && attrVal.transCalcVal,
defaultVal );
}
function computeEmOrString( attrVal, defaultVal ) {
return stringifyEmOrString(
attrVal && attrVal.transCalcVal,
defaultVal );
}
function computeColorOrString( attrVal, defaultVal ) {
var transCalcVal =
attrVal && attrVal.transCalcVal;
return ( transCalcVal === undefined ) ?
defaultVal : ( transCalcVal instanceof LAY.Color ?
transCalcVal.stringify() : transCalcVal );
}
LAY.Part.prototype.render = function ( renderCall ) {
var
attr2attrVal = this.level.attr2attrVal,
isWrappedLink = this.isWrappedLink,
node = this.actingNode,
wrappedLinkNode = isWrappedLink && this.node,
linkNode = this.node;
switch ( renderCall ) {
case "x":
var x = ( attr2attrVal.left.transCalcVal +
( attr2attrVal.shiftX !== undefined ?
attr2attrVal.shiftX.transCalcVal : 0 ) ) +
"px";
if ( isWrappedLink ) {
wrappedLinkNode.style.left = x;
} else {
node.style.left = x;
}
break;
case "y":
var y = ( attr2attrVal.top.transCalcVal +
( attr2attrVal.shiftY !== undefined ?
attr2attrVal.shiftY.transCalcVal : 0 ) ) +
"px";
if ( isWrappedLink ) {
wrappedLinkNode.style.top = y;
} else {
node.style.top = y;
}
break;
case "positionAndTransform":
var prop = (cssPrefix === "-moz-" ? "" : cssPrefix) +
"transform";
var val = "translate(" +
( ( attr2attrVal.left.transCalcVal +
( attr2attrVal.shiftX !== undefined ?
attr2attrVal.shiftX.transCalcVal : 0 ) ) + "px, " ) +
( ( attr2attrVal.top.transCalcVal +
( attr2attrVal.shiftY !== undefined ?
attr2attrVal.shiftY.transCalcVal : 0 ) ) + "px) " ) +
( attr2attrVal.z !== undefined ?
"translateZ(" + attr2attrVal.z.transCalcVal + "px) " : "" ) +
( attr2attrVal.scaleX !== undefined ?
"scaleX(" + attr2attrVal.scaleX.transCalcVal + ") " : "" ) +
( attr2attrVal.scaleY !== undefined ?
"scaleY(" + attr2attrVal.scaleY.transCalcVal + ") " : "" ) +
( attr2attrVal.scaleZ !== undefined ?
"scaleZ(" + attr2attrVal.scaleZ.transCalcVal + ") " : "" ) +
( attr2attrVal.skewX !== undefined ?
"skewX(" + attr2attrVal.skewX.transCalcVal + "deg) " : "" ) +
( attr2attrVal.skewY !== undefined ?
"skewY(" + attr2attrVal.skewY.transCalcVal + "deg) " : "" ) +
( attr2attrVal.rotateX !== undefined ?
"rotateX(" + attr2attrVal.rotateX.transCalcVal + "deg) " : "" ) +
( attr2attrVal.rotateY !== undefined ?
"rotateY(" + attr2attrVal.rotateY.transCalcVal + "deg) " : "" ) +
( attr2attrVal.rotateZ !== undefined ?
"rotateZ(" + attr2attrVal.rotateZ.transCalcVal + "deg)" : "" );
if ( isWrappedLink ) {
wrappedLinkNode.style[prop] = val;
} else {
node.style[prop] = val;
}
break;
case "transform":
var prop = (cssPrefix === "-moz-" ? "" : cssPrefix) +
"transform";
var val = ( attr2attrVal.scaleX !== undefined ?
"scaleX(" + attr2attrVal.scaleX.transCalcVal + ") " : "" ) +
( attr2attrVal.scaleY !== undefined ?
"scaleY(" + attr2attrVal.scaleY.transCalcVal + ") " : "" ) +
( attr2attrVal.scaleZ !== undefined ?
"scaleZ(" + attr2attrVal.scaleZ.transCalcVal + ") " : "" ) +
( attr2attrVal.skewX !== undefined ?
"skewX(" + attr2attrVal.skewX.transCalcVal + "deg) " : "" ) +
( attr2attrVal.skewY !== undefined ?
"skewY(" + attr2attrVal.skewY.transCalcVal + "deg) " : "" ) +
( attr2attrVal.rotateX !== undefined ?
"rotateX(" + attr2attrVal.rotateX.transCalcVal + "deg) " : "" ) +
( attr2attrVal.rotateY !== undefined ?
"rotateY(" + attr2attrVal.rotateY.transCalcVal + "deg) " : "" ) +
( attr2attrVal.rotateZ !== undefined ?
"rotateZ(" + attr2attrVal.rotateZ.transCalcVal + "deg)" : "" );
if ( isWrappedLink ) {
wrappedLinkNode.style[prop] = val;
} else {
node.style[prop] = val;
}
break;
case "width":
if ( !(this.type === "video" && !this.isVideoLoaded ) ) {
node.style.width =
attr2attrVal.width.transCalcVal + "px";
if (isWrappedLink) {
wrappedLinkNode.style.width =
attr2attrVal.width.transCalcVal + "px";
}
if ( [ "canvas", "video", "image","iframe" ].indexOf(
this.type ) !== -1 ) {
node.width =
attr2attrVal.width.transCalcVal;
}
}
break;
case "height":
if ( !(this.type === "video" && !this.isVideoLoaded ) ) {
node.style.height =
attr2attrVal.height.transCalcVal + "px";
if (isWrappedLink) {
wrappedLinkNode.style.height =
attr2attrVal.height.transCalcVal + "px";
}
if ( [ "canvas", "video", "image","iframe" ].indexOf(
this.type ) !== -1 ) {
node.height =
attr2attrVal.height.transCalcVal;
}
}
break;
case "origin":
var prop = cssPrefix + "transform-origin";
var val = ( ( attr2attrVal.originX !== undefined ?
attr2attrVal.originX.transCalcVal : 0.5 ) * 100 ) + "% " +
( ( attr2attrVal.originY !== undefined ?
attr2attrVal.originY.transCalcVal : 0.5 ) * 100 ) + "% " +
( attr2attrVal.originZ !== undefined ?
attr2attrVal.originZ.transCalcVal : 0 ) + "px";
if (isWrappedLink) {
wrappedLinkNode.style[prop] = val;
} else {
node.style[prop] = val;
}
break;
case "perspective":
if (isWrappedLink) {
wrappedLinkNode.style[ cssPrefix + "perspective" ] =
attr2attrVal.perspective.transCalcVal + "px";
} else {
node.style[ cssPrefix + "perspective" ] =
attr2attrVal.perspective.transCalcVal + "px";
}
break;
case "perspectiveOrigin":
var prop = cssPrefix + "perspective-origin";
var val = ( attr2attrVal.perspectiveOriginX ?
( attr2attrVal.perspectiveOriginX.transCalcVal * 100 )
: 0 ) + "% " +
( attr2attrVal.perspectiveOriginY ?
( attr2attrVal.perspectiveOriginY.transCalcVal * 100 )
: 0 ) + "%";
if (isWrappedLink) {
wrappedLinkNode.style[prop] = val;
} else {
node.style[prop] = val;
}
break;
case "backfaceVisibility":
if (isWrappedLink) {
wrappedLinkNode.style[ cssPrefix + "backface-visibility" ] =
attr2attrVal.backfaceVisibility.transCalcVal;
} else {
node.style[ cssPrefix + "backface-visibility" ] =
attr2attrVal.backfaceVisibility.transCalcVal;
}
break;
case "opacity":
if (isWrappedLink) {
wrappedLinkNode.style.opacity = attr2attrVal.opacity.transCalcVal;
} else {
node.style.opacity = attr2attrVal.opacity.transCalcVal;
}
break;
case "display":
if (isWrappedLink) {
wrappedLinkNode.style.display =
attr2attrVal.display.transCalcVal ? "block" : "none";
} else {
node.style.display =
attr2attrVal.display.transCalcVal ? "block" : "none";
}
break;
case "visible":
if (isWrappedLink) {
wrappedLinkNode.style.visibility =
attr2attrVal.visible.transCalcVal ?
"inherit" : "hidden";
} else {
node.style.visibility =
attr2attrVal.visible.transCalcVal ?
"inherit" : "hidden";
}
break;
case "zIndex":
if (isWrappedLink) {
wrappedLinkNode.style.zIndex =
attr2attrVal.zIndex.transCalcVal || "auto";
} else {
node.style.zIndex =
attr2attrVal.zIndex.transCalcVal || "auto";
}
break;
case "focus":
if ( attr2attrVal.focus.transCalcVal ) {
node.focus();
} else if ( document.activeElement === node ) {
document.body.focus();
}
break;
case "scrollX":
node.scrollLeft =
attr2attrVal.scrollX.transCalcVal;
break;
case "scrollY":
node.scrollTop =
attr2attrVal.scrollY.transCalcVal;
break;
case "scrollElastic":
node["-webkit-overflow-scrolling"] =
attr2attrVal.scrollElastic.transCalcVal ?
"touch" : "auto";
break;
case "overflowX":
node.style.overflowX =
attr2attrVal.overflowX.transCalcVal;
break;
case "overflowY":
node.style.overflowY =
attr2attrVal.overflowY.transCalcVal;
break;
case "cursor":
node.style.cursor = attr2attrVal.
cursor.transCalcVal;
break;
case "userSelect":
if ( this.type !== "input" ) {
node.style[ cssPrefix + "user-select" ] =
attr2attrVal.userSelect.transCalcVal;
}
break;
case "title":
node.title = attr2attrVal.title.transCalcVal;
break;
case "id":
node.id = attr2attrVal.id.transCalcVal;
case "tabindex":
node.tabindex = attr2attrVal.tabindex.transCalcVal;
break;
case "backgroundColor":
node.style.backgroundColor =
attr2attrVal.backgroundColor.transCalcVal.stringify();
break;
case "backgroundImage":
node.style.backgroundImage =
attr2attrVal.backgroundImage.transCalcVal;
break;
case "backgroundAttachment":
node.style.backgroundAttachment =
attr2attrVal.backgroundAttachment.transCalcVal;
break;
case "backgroundRepeat":
node.style.backgroundRepeat =
attr2attrVal.backgroundRepeat.transCalcVal;
break;
case "backgroundSize":
node.style.backgroundSize =
computePxOrString(
attr2attrVal.backgroundSizeX, "auto" ) +
" " +
computePxOrString(
attr2attrVal.backgroundSizeY, "auto" );
break;
case "backgroundPosition":
node.style.backgroundPosition =
computePxOrString(
attr2attrVal.backgroundPositionX, "0px" ) +
" " +
computePxOrString(
attr2attrVal.backgroundPositionX, "0px" );
break;
case "boxShadows":
if ( !LAY.$isBelowIE9 ) {
var s = "";
for ( var i = 1, len = attr2attrVal[ "$$max.boxShadows" ].calcVal;
i <= len; i++ ) {
s +=
( ( attr2attrVal["boxShadows" + i + "Inset" ] !== undefined ?
attr2attrVal["boxShadows" + i + "Inset" ].transCalcVal :
false ) ? "inset " : "" ) +
( attr2attrVal["boxShadows" + i + "X" ].transCalcVal + "px " ) +
( attr2attrVal["boxShadows" + i + "Y" ].transCalcVal + "px " ) +
( ( attr2attrVal["boxShadows" + i + "Blur" ] !== undefined ?
attr2attrVal["boxShadows" + i + "Blur" ].transCalcVal : 0 )
+ "px " ) +
( ( attr2attrVal["boxShadows" + i + "Spread" ] !== undefined ?
attr2attrVal["boxShadows" + i + "Spread" ].transCalcVal : 0 )
+ "px " ) +
( attr2attrVal["boxShadows" + i + "Color" ].
transCalcVal.stringify() );
if ( i !== len ) {
s += ",";
}
}
node.style.boxShadow = s;
}
break;
case "filters":
var s = "";
for ( var i = 1, len = attr2attrVal[ "$$max.filters" ].calcVal;
i <= len; i++ ) {
var filterType = attr2attrVal[ "filters" + i + "Type" ].calcVal;
var filterValue = attr2attrVal[ "filters" + i + "Value" ] &&
attr2attrVal[ "filters" + i + "Value" ].transCalcVal;
switch ( filterType ) {
case "dropShadow":
s += "drop-shadow(" +
( attr2attrVal["filters" + i + "X" ].transCalcVal + "px " ) +
( attr2attrVal["filters" + i + "Y" ].transCalcVal + "px " ) +
( ( attr2attrVal["filters" + i + "Blur" ] ?
attr2attrVal["filters" + i + "Blur" ].transCalcVal : 0 ) +
"px " ) +
// ( ( attr2attrVal["filters" + i + "Spread" ] !== undefined ?
// attr2attrVal[ "filters" + i + "Spread" ].transCalcVal : 0 ) + "px " ) +
( attr2attrVal["filters" + i + "Color" ].
transCalcVal.stringify() ) +
") ";
break;
case "blur":
s += "blur(" + filterValue + "px) ";
break;
case "hueRotate":
s += "hue-rotate(" + filterValue + "deg) ";
break;
case "url":
s += "url(" + filterValue + ") ";
break;
default:
s += filterType + "(" + ( filterValue * 100 ) + "%) ";
}
}
node.style[ cssPrefix + "filter" ] = s;
break;
case "cornerRadiusTopLeft":
node.style.borderTopLeftRadius =
attr2attrVal.cornerRadiusTopLeft.transCalcVal + "px";
break;
case "cornerRadiusTopRight":
node.style.borderTopRightRadius =
attr2attrVal.cornerRadiusTopRight.transCalcVal + "px";
break;
case "cornerRadiusBottomRight":
node.style.borderBottomRightRadius =
attr2attrVal.cornerRadiusBottomRight.transCalcVal + "px";
break;
case "cornerRadiusBottomLeft":
node.style.borderBottomLeftRadius =
attr2attrVal.cornerRadiusBottomLeft.transCalcVal + "px";
break;
case "borderTopStyle":
node.style.borderTopStyle =
attr2attrVal.borderTopStyle.transCalcVal;
break;
case "borderRightStyle":
node.style.borderRightStyle =
attr2attrVal.borderRightStyle.transCalcVal;
break;
case "borderBottomStyle":
node.style.borderBottomStyle =
attr2attrVal.borderBottomStyle.transCalcVal;
break;
case "borderLeftStyle":
node.style.borderLeftStyle =
attr2attrVal.borderLeftStyle.transCalcVal;
break;
case "borderTopColor":
node.style.borderTopColor =
attr2attrVal.borderTopColor.transCalcVal.stringify();
break;
case "borderRightColor":
node.style.borderRightColor =
attr2attrVal.borderRightColor.transCalcVal.stringify();
break;
case "borderBottomColor":
node.style.borderBottomColor =
attr2attrVal.borderBottomColor.transCalcVal.stringify();
break;
case "borderLeftColor":
node.style.borderLeftColor =
attr2attrVal.borderLeftColor.transCalcVal.stringify();
break;
case "borderTopWidth":
node.style.borderTopWidth =
attr2attrVal.borderTopWidth.transCalcVal + "px";
break;
case "borderRightWidth":
node.style.borderRightWidth =
attr2attrVal.borderRightWidth.transCalcVal + "px";
break;
case "borderBottomWidth":
node.style.borderBottomWidth =
attr2attrVal.borderBottomWidth.transCalcVal + "px";
break;
case "borderLeftWidth":
node.style.borderLeftWidth =
attr2attrVal.borderLeftWidth.transCalcVal + "px";
break;
case "html":
node.innerHTML = attr2attrVal.html.transCalcVal;
break;
case "text":
setText( node, attr2attrVal.text.transCalcVal );
break;
case "textSize":
node.style.fontSize =
computePxOrString( attr2attrVal.textSize );
break;
case "textFamily":
node.style.fontFamily =
attr2attrVal.textFamily.transCalcVal;
break;
case "textWeight":
node.style.fontWeight =
attr2attrVal.textWeight.transCalcVal;
break;
case "textColor":
node.style.color =
computeColorOrString(
attr2attrVal.textColor );
break;
case "textVariant":
node.style.fontVariant =
attr2attrVal.textVariant.transCalcVal;
break;
case "textTransform":
node.style.textTransform =
attr2attrVal.textTransform.transCalcVal;
break;
case "textStyle":
node.style.fontStyle =
attr2attrVal.textStyle.transCalcVal;
break;
case "textDecoration":
node.style.textDecoration =
attr2attrVal.textDecoration.transCalcVal;
break;
case "textLetterSpacing":
node.style.letterSpacing = computePxOrStringOrNormal(
attr2attrVal.textLetterSpacing );
break;
case "textWordSpacing":
node.style.wordSpacing = computePxOrStringOrNormal(
attr2attrVal.textWordSpacing );
break;
case "textAlign":
node.style.textAlign = attr2attrVal.textAlign.transCalcVal;
break;
case "textDirection":
node.style.direction = attr2attrVal.textDirection.transCalcVal;
break;
case "textLineHeight":
node.style.lineHeight = computeEmOrString(
attr2attrVal.textLineHeight );
break;
case "textOverflow":
node.style.textOverflow =
attr2attrVal.textOverflow.transCalcVal;
break;
case "textIndent":
node.style.textIndent =
attr2attrVal.textIndent.transCalcVal + "px";
break;
case "textWrap":
node.style.whiteSpace = attr2attrVal.textWrap.transCalcVal;
break;
case "textWordBreak":
node.style.wordBreak = attr2attrVal.textWordBreak.transCalcVal;
break;
case "textWordWrap":
node.style.wordWrap = attr2attrVal.textWordWrap.transCalcVal;
break;
case "textSmoothing":
node.style[ cssPrefix + "font-smoothing" ] =
attr2attrVal.textSmoothing.transCalcVal;
break;
case "textRendering":
node.style.textRendering = attr2attrVal.textRendering.transCalcVal;
break;
case "textPaddingTop":
node.style.paddingTop =
attr2attrVal.textPaddingTop.transCalcVal + "px";
break;
case "textPaddingRight":
node.style.paddingRight =
attr2attrVal.textPaddingRight.transCalcVal + "px";
break;
case "textPaddingBottom":
node.style.paddingBottom =
attr2attrVal.textPaddingBottom.transCalcVal + "px";
break;
case "textPaddingLeft":
node.style.paddingLeft =
attr2attrVal.textPaddingLeft.transCalcVal + "px";
break;
case "textShadows":
var s = "";
for ( var i = 1, len = attr2attrVal[ "$$max.textShadows" ].calcVal;
i <= len; i++ ) {
s +=
( attr2attrVal["textShadows" + i + "Color" ].
transCalcVal.stringify() ) + " " +
( attr2attrVal["textShadows" + i + "X" ].transCalcVal + "px " ) +
( attr2attrVal["textShadows" + i + "Y" ].transCalcVal + "px " ) +
( attr2attrVal["textShadows" + i + "Blur" ].transCalcVal + "px" );
if ( i !== len ) {
s += ",";
}
}
node.style.textShadow = s;
break;
case "input":
var inputVal = attr2attrVal.input.transCalcVal;
if ( this.inputType === "option" || this.inputType === "options" ) {
node.innerHTML = generateSelectOptionsHTML( inputVal );
} else {
node.value = inputVal;
}
break;
case "inputLabel":
node.label = attr2attrVal.inputLabel.transCalcVal;
break;
case "inputAccept":
node.accept = attr2attrVal.inputAccept.transCalcVal;
break;
case "inputPlaceholder":
node.placeholder = attr2attrVal.inputPlaceholder.transCalcVal;
break;
case "inputAutocomplete":
node.autocomplete = attr2attrVal.inputAutocomplete.transCalcVal;
break;
case "inputAutocorrect":
node.autocorrect = attr2attrVal.inputAutocorrect.transCalcVal;
break;
case "inputDisabled":
node.disabled = attr2attrVal.inputDisabled.transCalcVal;
break;
case "link":
linkNode.href = attr2attrVal.link.transCalcVal;
break;
case "linkRel":
linkNode.rel = attr2attrVal.linkRel.transCalcVal;
break;
case "linkDownload":
linkNode.download = attr2attrVal.linkDownload.transCalcVal;
break;
case "linkTarget":
linkNode.target = attr2attrVal.linkTarget.transCalcVal;
break;
case "image":
node.src = attr2attrVal.image.transCalcVal;
break;
case "imageAlt":
node.alt = attr2attrVal.imageAlt.transCalcVal;
break;
case "audio":
node.src = attr2attrVal.audio.transCalcVal;
break;
case "audios":
var
documentFragment = document.createDocumentFragment(),
childNodes = node.childNodes,
childNode;
// first remove the current audio sources
for ( var i = 0, len = childNodes.length; i <= len; i++ ) {
childNode = childNodes[i];
if ( childNode.tagName === "SOURCE" ) {
childNode.parentNode.removeChild( childNode );
}
}
for ( var i = 1, len = attr2attrVal[ "$$max.audios" ].calcVal;
i <= len; i++ ) {
childNode = document.createElement( "source" );
childNode.type =
attr2attrVal[ "audios" + i + "Type" ].transCalcVal;
childNode.src =
attr2attrVal[ "audios" + i + "Src" ].transCalcVal;
documentFragment.appendChild( childNode );
}
node.appendChild( documentFragment );
break;
case "audioTracks":
var
documentFragment = document.createDocumentFragment(),
childNodes = node.childNodes,
childNode;
// first remove the current audio tracks
for ( var i = 0, len = childNodes.length; i <= len; i++ ) {
childNode = childNodes[i];
if ( childNode.tagName === "TRACK" ) {
childNode.parentNode.removeChild( childNode );
}
}
for ( var i = 1, len = attr2attrVal[ "$$max.audioTracks" ].calcVal;
i <= len; i++ ) {
childNode = document.createElement( "track" );
childNode.type =
attr2attrVal[ "audioTracks" + i + "Type" ].transCalcVal;
childNode.src =
attr2attrVal[ "audioTracks" + i + "Src" ].transCalcVal;
documentFragment.appendChild( childNode );
}
node.appendChild( documentFragment );
break;
case "audioVolume":
node.volume = attr2attrVal.audioVolume.transCalcVal;
break;
case "audioController":
node.controls = attr2attrVal.audioController.transCalcVal;
break;
case "audioLoop":
node.loop = attr2attrVal.audioLoop.transCalcVal;
break;
case "audioMuted":
node.muted = attr2attrVal.audioMuted.transCalcVal;
break;
case "audioPreload":
node.preload = attr2attrVal.audioPreload.transCalcVal;
break;
case "video":
node.src = attr2attrVal.video.transCalcVal;
break;
case "videos":
var
documentFragment = document.createDocumentFragment(),
childNodes = node.childNodes,
childNode;
// first remove the current video sources
for ( var i = 0, len = childNodes.length; i <= len; i++ ) {
childNode = childNodes[i];
if ( childNode.tagName === "SOURCE" ) {
childNode.parentNode.removeChild( childNode );
}
}
for ( var i = 1, len = attr2attrVal[ "$$max.videos" ].calcVal;
i <= len; i++ ) {
childNode = document.createElement( "source" );
childNode.type =
attr2attrVal[ "videos" + i + "Type" ].transCalcVal;
childNode.src =
attr2attrVal[ "videos" + i + "Src" ].transCalcVal;
documentFragment.appendChild( childNode );
}
node.appendChild( documentFragment );
break;
case "videoTracks":
var
documentFragment = document.createDocumentFragment(),
childNodes = node.childNodes,
childNode;
// first remove the current video tracks
for ( var i = 0, len = childNodes.length; i <= len; i++ ) {
childNode = childNodes[i];
if ( childNode.tagName === "TRACK" ) {
childNode.parentNode.removeChild( childNode );
}
}
for ( var i = 1, len = attr2attrVal[ "$$max.videoTracks" ].calcVal;
i <= len; i++ ) {
childNode = document.createElement( "track" );
childNode.type =
attr2attrVal[ "videoTracks" + i + "Type" ].transCalcVal;
childNode.src =
attr2attrVal[ "videoTracks" + i + "Src" ].transCalcVal;
documentFragment.appendChild( childNode );
}
node.appendChild( documentFragment );
break;
case "videoAutoplay":
node.autoplay = attr2attrVal.videoAutoplay.transCalcVal;
break;
case "videoController":
node.controls = attr2attrVal.videoController.transCalcVal;
break;
case "videoCrossorigin":
node.crossorigin = attr2attrVal.videoCrossorigin.transCalcVal;
break;
case "videoLoop":
node.loop = attr2attrVal.videoLoop.transCalcVal;
break;
case "videoMuted":
node.muted = attr2attrVal.videoMuted.transCalcVal;
break;
case "videoPreload":
node.preload = attr2attrVal.videoPreload.transCalcVal;
break;
case "videoPoster":
node.poster = attr2attrVal.videoPoster.transCalcVal;
break;
case "iframe":
node.src = attr2attrVal.iframe.transCalcVal;
break;
default:
LAY.$error("Inexistent prop: '" + renderCall + "'");
}
};
})();
|
(function (app) {
'use strict';
app.registerModule('bills');
}(ApplicationConfiguration));
|
var Query = require("./query")
, Utils = require("../../utils")
module.exports = (function() {
var ConnectorManager = function(sequelize, config) {
this.sequelize = sequelize
this.client = null
this.config = config || {}
this.config.port = this.config.port || 5432
this.pooling = (!!this.config.poolCfg && (this.config.poolCfg.maxConnections > 0))
this.pg = this.config.native ? require('pg').native : require('pg')
// set pooling parameters if specified
if (this.pooling) {
this.pg.defaults.poolSize = this.config.poolCfg.maxConnections
this.pg.defaults.poolIdleTimeout = this.config.poolCfg.maxIdleTime
}
this.disconnectTimeoutId = null
this.pendingQueries = 0
this.maxConcurrentQueries = (this.config.maxConcurrentQueries || 50)
}
Utils._.extend(ConnectorManager.prototype, require("../connector-manager").prototype)
var isConnecting = false
var isConnected = false
ConnectorManager.prototype.query = function(sql, callee, options) {
var self = this
if (this.client == null) {
this.connect()
}
var query = new Query(this.client, this.sequelize, callee, options || {})
self.pendingQueries += 1
return query.run(sql)
.success(function() { self.endQuery.call(self) })
.error(function() { self.endQuery.call(self) })
}
ConnectorManager.prototype.endQuery = function() {
var self = this
self.pendingQueries -= 1
if (self.pendingQueries == 0) {
setTimeout(function() {
self.pendingQueries == 0 && self.disconnect.call(self)
}, 100)
}
}
ConnectorManager.prototype.connect = function() {
var self = this
var emitter = new (require('events').EventEmitter)()
// in case database is slow to connect, prevent orphaning the client
if (this.isConnecting) {
return
}
this.isConnecting = true
this.isConnected = false
var uri = this.sequelize.getQueryInterface().QueryGenerator.databaseConnectionUri(this.config)
var connectCallback = function(err, client) {
self.isConnecting = false
if (!!err) {
emitter.emit('error', err)
} else if (client) {
client.query("SET TIME ZONE 'UTC'")
.on('end', function() {
self.isConnected = true
this.client = client
});
} else {
this.client = null
}
}
if (this.pooling) {
// acquire client from pool
this.pg.connect(uri, connectCallback)
} else {
//create one-off client
this.client = new this.pg.Client(uri)
this.client.connect(connectCallback)
}
return emitter
}
ConnectorManager.prototype.disconnect = function() {
var self = this
if (this.client) this.client.end()
this.client = null
this.isConnecting = false
this.isConnected = false
}
return ConnectorManager
})()
|
import DS from 'ember-data';
import BackboneElement from 'ember-fhir/models/backbone-element';
const { attr, belongsTo } = DS;
export default BackboneElement.extend({
actionId: attr('string'),
relationship: attr('string'),
offsetDuration: belongsTo('duration', { async: false }),
offsetRange: belongsTo('range', { async: false })
}); |
angular.module('seoApp').controller('SearchCtrl', ['$scope', '$routeParams', 'SearchService', function($scope, $routeParams, SearchService) {
$scope.term = '';
$scope.matches = SearchService.getEmptyResult();
// Search order
$scope.predicate = 'matches.length';
$scope.reverse = true;
$scope.$watch('term', function(newValue, oldValue, scope) {
if (newValue && newValue !== oldValue && newValue.length > 2) {
$scope.matches = SearchService.search(newValue);
} else {
$scope.matches = SearchService.getEmptyResult();
}
});
}]); |
/*
* Copyright (c) 2012 Massachusetts Institute of Technology, Adobe Systems
* Incorporated, and other contributors. 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.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define */
define(function (require, exports, module) {
function Fsm(desc, initialState) {
this.desc = desc;
this.goto(initialState);
}
Fsm.prototype = {
goto: function (state) {
console.log("[theseus] fsm: -> " + state);
this.trigger("exit");
this.state = state;
this.trigger("enter");
},
trigger: function (eventName) {
var args = Array.prototype.slice.apply(arguments).slice(1);
// console.log("[theseus] fsm: !! " + eventName, args);
if (this.desc[this.state] && (eventName in this.desc[this.state])) {
this.desc[this.state][eventName].apply(this, args);
}
},
};
exports.Fsm = Fsm;
});
|
import {set} from 'cerebral/operators'
import {input, state} from 'cerebral/tags'
import paths from '../paths'
export default function (moduleName) {
const {draftPath, dynamicPaths} = paths(moduleName)
return [
dynamicPaths,
set(state`${draftPath}`, state`${input`itemPath`}`),
// To trigger change on collection list listening for
// draft.key
set(state`${draftPath}.key`, input`key`)
]
}
|
/*
* Crypto-JS v2.5.3
* http://code.google.com/p/crypto-js/
* (c) 2009-2012 by Jeff Mott. All rights reserved.
* http://code.google.com/p/crypto-js/wiki/License
*/
(function(){
// Shortcuts
var C = Crypto,
util = C.util,
charenc = C.charenc,
UTF8 = charenc.UTF8,
Binary = charenc.Binary;
// Public API
var MD5 = C.MD5 = function (message, options) {
var digestbytes = util.wordsToBytes(MD5._md5(message));
return options && options.asBytes ? digestbytes :
options && options.asString ? Binary.bytesToString(digestbytes) :
util.bytesToHex(digestbytes);
};
// The core
MD5._md5 = function (message) {
// Convert to byte array
if (message.constructor == String) message = UTF8.stringToBytes(message);
/* else, assume byte array already */
var m = util.bytesToWords(message),
l = message.length * 8,
a = 1732584193,
b = -271733879,
c = -1732584194,
d = 271733878;
// Swap endian
for (var i = 0; i < m.length; i++) {
m[i] = ((m[i] << 8) | (m[i] >>> 24)) & 0x00FF00FF |
((m[i] << 24) | (m[i] >>> 8)) & 0xFF00FF00;
}
// Padding
m[l >>> 5] |= 0x80 << (l % 32);
m[(((l + 64) >>> 9) << 4) + 14] = l;
// Method shortcuts
var FF = MD5._ff,
GG = MD5._gg,
HH = MD5._hh,
II = MD5._ii;
for (var i = 0; i < m.length; i += 16) {
var aa = a,
bb = b,
cc = c,
dd = d;
a = FF(a, b, c, d, m[i+ 0], 7, -680876936);
d = FF(d, a, b, c, m[i+ 1], 12, -389564586);
c = FF(c, d, a, b, m[i+ 2], 17, 606105819);
b = FF(b, c, d, a, m[i+ 3], 22, -1044525330);
a = FF(a, b, c, d, m[i+ 4], 7, -176418897);
d = FF(d, a, b, c, m[i+ 5], 12, 1200080426);
c = FF(c, d, a, b, m[i+ 6], 17, -1473231341);
b = FF(b, c, d, a, m[i+ 7], 22, -45705983);
a = FF(a, b, c, d, m[i+ 8], 7, 1770035416);
d = FF(d, a, b, c, m[i+ 9], 12, -1958414417);
c = FF(c, d, a, b, m[i+10], 17, -42063);
b = FF(b, c, d, a, m[i+11], 22, -1990404162);
a = FF(a, b, c, d, m[i+12], 7, 1804603682);
d = FF(d, a, b, c, m[i+13], 12, -40341101);
c = FF(c, d, a, b, m[i+14], 17, -1502002290);
b = FF(b, c, d, a, m[i+15], 22, 1236535329);
a = GG(a, b, c, d, m[i+ 1], 5, -165796510);
d = GG(d, a, b, c, m[i+ 6], 9, -1069501632);
c = GG(c, d, a, b, m[i+11], 14, 643717713);
b = GG(b, c, d, a, m[i+ 0], 20, -373897302);
a = GG(a, b, c, d, m[i+ 5], 5, -701558691);
d = GG(d, a, b, c, m[i+10], 9, 38016083);
c = GG(c, d, a, b, m[i+15], 14, -660478335);
b = GG(b, c, d, a, m[i+ 4], 20, -405537848);
a = GG(a, b, c, d, m[i+ 9], 5, 568446438);
d = GG(d, a, b, c, m[i+14], 9, -1019803690);
c = GG(c, d, a, b, m[i+ 3], 14, -187363961);
b = GG(b, c, d, a, m[i+ 8], 20, 1163531501);
a = GG(a, b, c, d, m[i+13], 5, -1444681467);
d = GG(d, a, b, c, m[i+ 2], 9, -51403784);
c = GG(c, d, a, b, m[i+ 7], 14, 1735328473);
b = GG(b, c, d, a, m[i+12], 20, -1926607734);
a = HH(a, b, c, d, m[i+ 5], 4, -378558);
d = HH(d, a, b, c, m[i+ 8], 11, -2022574463);
c = HH(c, d, a, b, m[i+11], 16, 1839030562);
b = HH(b, c, d, a, m[i+14], 23, -35309556);
a = HH(a, b, c, d, m[i+ 1], 4, -1530992060);
d = HH(d, a, b, c, m[i+ 4], 11, 1272893353);
c = HH(c, d, a, b, m[i+ 7], 16, -155497632);
b = HH(b, c, d, a, m[i+10], 23, -1094730640);
a = HH(a, b, c, d, m[i+13], 4, 681279174);
d = HH(d, a, b, c, m[i+ 0], 11, -358537222);
c = HH(c, d, a, b, m[i+ 3], 16, -722521979);
b = HH(b, c, d, a, m[i+ 6], 23, 76029189);
a = HH(a, b, c, d, m[i+ 9], 4, -640364487);
d = HH(d, a, b, c, m[i+12], 11, -421815835);
c = HH(c, d, a, b, m[i+15], 16, 530742520);
b = HH(b, c, d, a, m[i+ 2], 23, -995338651);
a = II(a, b, c, d, m[i+ 0], 6, -198630844);
d = II(d, a, b, c, m[i+ 7], 10, 1126891415);
c = II(c, d, a, b, m[i+14], 15, -1416354905);
b = II(b, c, d, a, m[i+ 5], 21, -57434055);
a = II(a, b, c, d, m[i+12], 6, 1700485571);
d = II(d, a, b, c, m[i+ 3], 10, -1894986606);
c = II(c, d, a, b, m[i+10], 15, -1051523);
b = II(b, c, d, a, m[i+ 1], 21, -2054922799);
a = II(a, b, c, d, m[i+ 8], 6, 1873313359);
d = II(d, a, b, c, m[i+15], 10, -30611744);
c = II(c, d, a, b, m[i+ 6], 15, -1560198380);
b = II(b, c, d, a, m[i+13], 21, 1309151649);
a = II(a, b, c, d, m[i+ 4], 6, -145523070);
d = II(d, a, b, c, m[i+11], 10, -1120210379);
c = II(c, d, a, b, m[i+ 2], 15, 718787259);
b = II(b, c, d, a, m[i+ 9], 21, -343485551);
a = (a + aa) >>> 0;
b = (b + bb) >>> 0;
c = (c + cc) >>> 0;
d = (d + dd) >>> 0;
}
return util.endian([a, b, c, d]);
};
// Auxiliary functions
MD5._ff = function (a, b, c, d, x, s, t) {
var n = a + (b & c | ~b & d) + (x >>> 0) + t;
return ((n << s) | (n >>> (32 - s))) + b;
};
MD5._gg = function (a, b, c, d, x, s, t) {
var n = a + (b & d | c & ~d) + (x >>> 0) + t;
return ((n << s) | (n >>> (32 - s))) + b;
};
MD5._hh = function (a, b, c, d, x, s, t) {
var n = a + (b ^ c ^ d) + (x >>> 0) + t;
return ((n << s) | (n >>> (32 - s))) + b;
};
MD5._ii = function (a, b, c, d, x, s, t) {
var n = a + (c ^ (b | ~d)) + (x >>> 0) + t;
return ((n << s) | (n >>> (32 - s))) + b;
};
// Package private blocksize
MD5._blocksize = 16;
MD5._digestsize = 16;
})();
|
module.exports = {
description: 'makes sure reassignments of double declared variables and their initializers are tracked'
};
|
/* generated by Svelte vX.Y.Z */
import {
SvelteComponent,
create_component,
destroy_component,
init,
mount_component,
noop,
not_equal,
transition_in,
transition_out
} from "svelte/internal";
function create_fragment(ctx) {
let nested;
let current;
nested = new /*Nested*/ ctx[0]({ props: { foo: "bar" } });
return {
c() {
create_component(nested.$$.fragment);
},
m(target, anchor) {
mount_component(nested, target, anchor);
current = true;
},
p: noop,
i(local) {
if (current) return;
transition_in(nested.$$.fragment, local);
current = true;
},
o(local) {
transition_out(nested.$$.fragment, local);
current = false;
},
d(detaching) {
destroy_component(nested, detaching);
}
};
}
function instance($$self) {
const Nested = window.Nested;
return [Nested];
}
class Component extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance, create_fragment, not_equal, {});
}
}
export default Component; |
import { test, describe, before, after, beforeEach } from 'ava-spec'
import { koaApp } from '../helpers/app'
import { createUser, getToken, createTagCat, createTag } from '../helpers/auth'
import { UserSchema } from '../../server/model/user.model'
import { LogsSchema } from '../../server/model/logs.model'
import { TagCategorySchema } from '../../server/model/tag.category.model'
import { TagSchema } from '../../server/model/tag.model'
import config from '../../server/config/env'
let User, Logs, Tag, TagCategory, token, mockTagCatId, mockTagCatName, mockTagId, mockTagName, mockUserId
before(async t => {
const mongoose = require('../../server/connect')
mongoose.Promise = global.Promise
User = mongoose.model('User', UserSchema)
Logs = mongoose.model('Logs', LogsSchema)
Tag = mongoose.model('Tag', TagSchema)
TagCategory = mongoose.model('TagCategory', TagCategorySchema)
const user = await createUser(User, 'admin')
mockUserId = user._id
const tagCat = await createTagCat(TagCategory)
mockTagCatId = tagCat._id
mockTagCatName = tagCat.name
const tag = await createTag(Tag, mockTagCatId)
mockTagId = tag._id
mockTagName = tag.name
token = await getToken(user.email)
})
after(async () => {
await User.findByIdAndRemove(mockUserId)
await Tag.findByIdAndRemove(mockTagId)
await TagCategory.findByIdAndRemove(mockTagCatId)
await Logs.remove()
})
describe('test/api/tags.test.js => post /tags/addTagCat', it => {
it.serial('should when not name return error', async t => {
const res = await koaApp.post('/tags/addTagCat')
.set('Authorization', 'Bearer ' + token)
.send({
desc: '测试标签分类名'
})
t.is(res.status, 422)
})
it.serial('should when second add catName return error', async t => {
const res = await koaApp.post('/tags/addTagCat').set('Authorization', 'Bearer ' + token).send({
name: mockTagCatName,
desc: '测试标签分类名'
})
t.is(res.status, 403)
})
it.serial('should return new tag category', async t => {
const res = await koaApp.post('/tags/addTagCat').set('Authorization', 'Bearer ' + token).send({
name: '标签分类名' + new Date().getTime(),
desc: '测试标签分类名'
})
t.is(res.status, 200)
t.true(res.body.success)
await TagCategory.findByIdAndRemove(res.body.cat_id)
})
})
describe('test/api/tags.test.js => post /tags/addTag', it => {
it.serial('should when not name return error', async t => {
const res = await koaApp.post('/tags/addTag')
.set('Authorization', 'Bearer ' + token)
.send({
cid: mockTagCatId,
is_show: true
})
t.is(res.status, 422)
})
it.serial('should when not cid return error', async t => {
const res = await koaApp.post('/tags/addTag')
.set('Authorization', 'Bearer ' + token)
.send({
name: '标签名称' + new Date().getTime(),
is_show: true
})
t.is(res.status, 422)
})
it.serial('should return new tag', async t => {
const res = await koaApp.post('/tags/addTag')
.set('Authorization', 'Bearer ' + token)
.send({
name: '标签名称' + new Date().getTime(),
cid: mockTagCatId,
is_show: true
})
t.is(res.status, 200)
t.true(res.body.success)
await Tag.findByIdAndRemove(res.body.tag_id)
})
it.serial('should when second add tagName return error', async t => {
const res = await koaApp.post('/tags/addTag')
.set('Authorization', 'Bearer ' + token)
.send({
name: mockTagName,
cid: mockTagCatId,
is_show: true
})
t.is(res.status, 403)
})
})
describe('test/api/tags.test.js => put /tags/:id/updateTagCat', it => {
it.serial('should return update tag category', async t => {
const res = await koaApp.put('/tags/' + mockTagCatId + '/updateTagCat')
.set('Authorization', 'Bearer ' + token)
.send({
_id: mockTagCatId,
name: '新的标签分类名称' + new Date().getTime(),
desc: '新的描述'
})
t.is(res.status, 200)
t.true(res.body.success)
})
})
describe('test/api/tags.test.js => put /tags/:id/updateTag', it => {
it.serial('should return update tag category', async t => {
const res = await koaApp.put('/tags/' + mockTagId + '/updateTag')
.set('Authorization', 'Bearer ' + token)
.send({
_id: mockTagId,
name: '新的分类名称' + new Date().getTime()
})
t.is(res.status, 200)
t.true(res.body.success)
})
})
describe('test/api/tags.test.js => get /tags/getTagCatList', it => {
it.serial('should return tag category list', async t => {
const res = await koaApp.get('/tags/getTagCatList')
.set('Authorization', 'Bearer ' + token)
t.is(res.status, 200)
t.not(res.body.data.length, 0)
})
})
describe('test/api/tags.test.js => get /tags/:id/getTagList', it => {
it.serial('should return tag list in category', async t => {
const res = await koaApp.get('/tags/' + mockTagCatId + '/getTagList')
.set('Authorization', 'Bearer ' + token)
t.is(res.status, 200)
t.not(res.body.data.length, 0)
})
it.serial('should return all tag list', async t => {
const res = await koaApp.get('/tags/0/getTagList')
.set('Authorization', 'Bearer ' + token)
t.is(res.status, 200)
t.not(res.body.data.length, 0)
})
})
describe('test/api/tags.test.js => get /tags/getFrontTagList', it => {
it.serial('should return tag list to frontend', async t => {
const res = await koaApp.get('/tags/getFrontTagList')
t.is(res.status, 200)
t.not(res.body.data.length, 0)
})
})
describe('test/api/tags.test.js => delete /tags/:id', it => {
it.serial('should return error', async t => {
const res = await koaApp.del('/tags/' + mockTagCatId).set('Authorization', 'Bearer ' + token)
t.is(res.status, 403)
})
})
describe('test/api/tags.test.js => delete /tags/:id/deleteTag', it => {
it.serial('should return error', async t => {
const res = await koaApp.del('/tags/dddddd/deleteTag').set('Authorization', 'Bearer ' + token)
t.is(res.status, 500)
})
it.serial('should return success', async t => {
const res = await koaApp.del('/tags/' + mockTagId + '/deleteTag')
.set('Authorization', 'Bearer ' + token)
t.is(res.status, 200)
t.true(res.body.success)
})
})
describe('test/api/tags.test.js => delete /tags/:id', it => {
it.serial('should return error', async t => {
const res = await koaApp.del('/tags/dddddd')
.set('Authorization', 'Bearer ' + token)
t.is(res.status, 500)
})
it.serial('should return success', async t => {
try {
const res = await koaApp.del('/tags/' + mockTagCatId)
.set('Authorization', 'Bearer ' + token)
t.is(res.status, 200)
t.true(res.body.success)
} catch (error) {
t.ifError(error, '错误')
}
})
}) |
function Controller() {
var view = new View();
var box = new Box();
var count = 10;
var initialize = function() {
view.clearScreen();
};
var stopIfDone = function(interval) {
if (count > 1500) {
clearInterval(interval);
}
};
this.partyTime = function() {
initialize();
var cycle = setInterval(function() {
var newBox = box.generate(count);
view.addBox(newBox);
view.scrollDown();
count += 2;
stopIfDone(cycle);
},15);
};
}
|
const convertPathsToTree = files => {
const retVal = {};
files.forEach(file => {
const path = file.path || file.webkitRelativePath || file.name;
// remove leading slash if present, then split into path segments and reduce to object
path
.replace(/^\/+/g, '')
.split('/')
.reduce((r, e, i, sourceArray) => {
if (i === sourceArray.length - 1) {
r[e] = file;
return r[e];
}
r[e] = r[e] ? r[e] : {};
return r[e];
}, retVal);
});
return retVal;
};
export default convertPathsToTree;
|
import * as types from 'constants/ActionTypes';
import api from 'utils/api/attributeSection';
export function handleChanges(data) {
return { type: types.HANDLESEARCHATTRIBUTE, payload: { data } };
}
function _doSearch(data) {
return {
types: [types.HANDLESEARCH, types.HANDLESEARCHSUCCESS, types.HANDLESEARCHFAIL],
payload: {
response: api.searchAttributeSection(data).then(response => response),
data
}
};
}
export function reset() {
return {
type: types.RESETSEARCH
};
}
export function deleteId(id) {
return {
types: [types.HANDLEDELETE, types.HANDLEDELETESUCCESS, types.HANDLEDELETEFAIL],
payload: {
response: api.deleteAttributeSection(id).then(response => response),
id
}
};
}
export function search(data) {
return _doSearch(data);
}
|
// Generated by CoffeeScript 1.9.0
var Account, async, cozydb;
async = require('async');
Account = require('../models/account');
cozydb = require('cozydb');
module.exports.main = function(req, res, next) {
return async.series([
function(cb) {
return cozydb.api.getCozyLocale(cb);
}, function(cb) {
return Account.request('all', cb);
}
], function(err, results) {
var accounts, locale;
if (err != null) {
console.log(err);
return res.render('test.jade', {
imports: "console.log(\"" + err + "\")\nwindow.locale = \"en\";\nwindow.accounts = {};"
});
} else {
locale = results[0], accounts = results[1];
return res.render('test.jade', {
imports: "window.locale = \"" + locale + "\";\nwindow.accounts = " + (JSON.stringify(accounts)) + ";"
});
}
});
};
|
/* eslint no-console: 0 */
'use strict';
const nodemailer = require('../lib/nodemailer');
// Generate SMTP service account from ethereal.email
nodemailer.createTestAccount((err, account) => {
if (err) {
console.error('Failed to create a testing account');
console.error(err);
return process.exit(1);
}
console.log('Credentials obtained, sending message...');
// NB! Store the account object values somewhere if you want
// to re-use the same account for future mail deliveries
// Create a SMTP transporter object
let transporter = nodemailer.createTransport(
{
host: account.smtp.host,
port: account.smtp.port,
secure: account.smtp.secure,
auth: {
type: 'custom',
user: account.user,
pass: account.pass,
method: 'x-login' // force custom method instead of choosing automatically from available methods
},
logger: false,
debug: false, // if true then include SMTP traffic in the logs
customAuth: {
// can create multiple handlers
'x-login': ctx => {
// This custom method implements AUTH LOGIN even though Nodemailer supports it natively.
// AUTH LOGIN mechanism includes multiple steps, so it's great for a demo nevertheless
console.log('Performing custom authentication for %s', ctx.auth.credentials.user);
console.log('Supported extensions: %s', ctx.extensions.join(', '));
console.log('Supported auth methods: %s', ctx.authMethods.join(', '));
if (!ctx.authMethods.includes('LOGIN')) {
console.log('Server does not support AUTH LOGIN');
return ctx.reject(new Error('Can not log in'));
}
console.log('AUTH LOGIN is supported, proceeding with login...');
ctx.sendCommand('AUTH LOGIN', (err, cmd) => {
if (err) {
return ctx.reject(err);
}
if (cmd.status !== 334) {
// expecting '334 VXNlcm5hbWU6'
return ctx.reject('Invalid login sequence while waiting for "334 VXNlcm5hbWU6"');
}
console.log('Sending username: %s', ctx.auth.credentials.user);
ctx.sendCommand(Buffer.from(ctx.auth.credentials.user, 'utf-8').toString('base64'), (err, cmd) => {
if (err) {
return ctx.reject(err);
}
if (cmd.status !== 334) {
// expecting '334 UGFzc3dvcmQ6'
return ctx.reject('Invalid login sequence while waiting for "334 UGFzc3dvcmQ6"');
}
console.log('Sending password: %s', '*'.repeat(ctx.auth.credentials.pass.length));
ctx.sendCommand(Buffer.from(ctx.auth.credentials.pass, 'utf-8').toString('base64'), (err, cmd) => {
if (err) {
return ctx.reject(err);
}
if (cmd.status < 200 || cmd.status >= 300) {
// expecting a 235 response, just in case allow everything in 2xx range
return ctx.reject('User failed to authenticate');
}
console.log('User authenticated! (%s)', cmd.response);
// all checks passed
return ctx.resolve();
});
});
});
}
}
},
{
// default message fields
// sender info
from: 'Pangalink <no-reply@pangalink.net>',
headers: {
'X-Laziness-level': 1000 // just an example header, no need to use this
}
}
);
// Message object
let message = {
// Comma separated list of recipients
to: 'Andris Reinman <andris.reinman@gmail.com>',
// Subject of the message
subject: 'Nodemailer is unicode friendly ✔',
// plaintext body
text: 'Hello to myself!',
// HTML body
html:
'<p><b>Hello</b> to myself <img src="cid:note@example.com"/></p>' +
'<p>Here\'s a nyan cat for you as an embedded attachment:<br/><img src="cid:nyan@example.com"/></p>',
// An array of attachments
attachments: [
// String attachment
{
filename: 'notes.txt',
content: 'Some notes about this e-mail',
contentType: 'text/plain' // optional, would be detected from the filename
},
// Binary Buffer attachment
{
filename: 'image.png',
content: Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD/' +
'//+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4U' +
'g9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC',
'base64'
),
cid: 'note@example.com' // should be as unique as possible
},
// File Stream attachment
{
filename: 'nyan cat ✔.gif',
path: __dirname + '/assets/nyan.gif',
cid: 'nyan@example.com' // should be as unique as possible
}
],
list: {
// List-Help: <mailto:admin@example.com?subject=help>
help: 'admin@example.com?subject=help',
// List-Unsubscribe: <http://example.com> (Comment)
unsubscribe: [
{
url: 'http://example.com/unsubscribe',
comment: 'A short note about this url'
},
'unsubscribe@example.com'
],
// List-ID: "comment" <example.com>
id: {
url: 'mylist.example.com',
comment: 'This is my awesome list'
}
}
};
transporter.sendMail(message, (error, info) => {
if (error) {
console.log('Error occurred');
console.log(error.message);
return process.exit(1);
}
console.log('Message sent successfully!');
console.log(nodemailer.getTestMessageUrl(info));
// only needed when using pooled connections
transporter.close();
});
});
|
// Initialize Firebase
var config = {
apiKey: "AIzaSyA7t-70TsjQO9vvEYC0jrhOtAe8JbgjHmk",
authDomain: "tacl-79682.firebaseapp.com",
databaseURL: "https://tacl-79682.firebaseio.com",
storageBucket: "tacl-79682.appspot.com",
};
firebase.initializeApp(config);
var database = firebase.database();
var data = { season: 4 }
$(function() {
var connectedRef = database.ref(".info/connected");
connectedRef.on("value", function(snap) {
if (snap.val() === true) {
$('#loading').stop(true, false).fadeOut();
} else {
$('#loading').stop(true, false).fadeIn();
}
});
$('#btn_login').bind('click', function(event) {
event.preventDefault();
var login_spinner = $('#login_spinner').show();
firebase.auth().signInWithEmailAndPassword('spycraft@tacl.com', $('#password').val())
.then(function() {
login_spinner.hide();
})
.catch(function(error) {
// Handle Errors here.
$('.login.alert').fadeIn();
$('#login_error_msg').html(error.message);
login_spinner.hide();
})
});
firebase.auth().onAuthStateChanged(function(user) {
if(user) {
$('#loginModal').modal('hide');
} else {
$('#loginModal').modal('show');
}
});
var canvas = $('#canvas')[0];
var ctx = canvas.getContext('2d');
var bgList = [
'http://1920x1080hdwallpapers.com/image/201512/games/3859/starcraft-2-legacy-of-void-spear-of-adun-art.jpg',
'https://images6.alphacoders.com/392/392895.jpg',
'https://images.alphacoders.com/464/464155.jpg',
'http://wallpaperswide.com/download/starcraft_ii_heart_of_the_swarm___zerg_hive-wallpaper-1920x1080.jpg'
];
var bgURL = bgList[Math.floor(Math.random() * bgList.length)];
database.ref('game').on('value', function(result) {
data.season = result.val().season;
});
database.ref('score').on('value', function(result) {
data.score = result.val();
redraw();
});
$('[data-realtime]')
.each(function() {
var input = $(this);
var target = input.data('target');
if(target && target !== '') {
database.ref(target).on('value', function(result) {
input.val(result.val());
if(input.hasClass('selectpicker')) {
input.selectpicker('refresh');
}
});
}
})
.change(function() {
var input = $(this);
var target = input.data('target');
if(target && target !== '') {
database.ref(target).set(input.val());
redraw();
}
})
$('#title').on('input', function(event) {
redraw();
});
function redraw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
var drawbg = bgURL ? drawImage(bgURL, { opacity: 0.4 }) : function(){ return $.when(); };
var drawlogo = drawImage('assets/images/fbpost_overlay.png');
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, 1920, 1080);
drawbg().done(function() {
var centerX = 960;
ctx.save();
ctx.font = "bold 80px 'Times New Roman', '微軟正黑體'";
ctx.fillStyle = 'white';
ctx.textAlign = 'center'
ctx.textBaseline = 'top';
//ctx.fillText('TACL S4 9/20 賽程表', centerX, 50);
textGlow($('#title').val(), centerX, 50, 'white', '#00ccff', 50, 1);
var halfSpace = -70;
var playerSpace = 80;
var halfCenters = [480 - halfSpace, 1440 + halfSpace];
for (var halfId = 0; halfId < 2; halfId++) {
centerX = halfCenters[halfId];
var half = data.score[halfId===0 ? 'first' : 'second'];
ctx.font = "bold 75px 'Times New Roman'";
ctx.textAlign = 'right';
textGlow(half.clan1.name, centerX-80, 200, 'white', '#00ccff', 30, 1);
ctx.textAlign = 'left';
textGlow(half.clan2.name, centerX+80, 200, 'white', '#00ccff', 30, 1);
ctx.textAlign = 'center';
ctx.fillStyle = '#11cfff';
textGlow('vs', centerX, 200, '11ccff', '#00f', 50, 1);
for (var i = 0; i < 4; i++) {
ctx.fillStyle = 'white';
ctx.font = "46px '微軟正黑體'";
ctx.textAlign = 'right';
var player1 = half.clan1.players[i];
textGlow(player1.name, centerX - playerSpace, 320 + i * 150, 'white', '#00ccff', 30, 1);
drawImage(getRaceImg(player1.race), { left: centerX - playerSpace, top: 320 + i * 150, width:65, height: 65, opacity: 0.85, glow: '#fff'})();
ctx.textAlign = 'left';
var player2 = half.clan2.players[i];
textGlow(player2.name, centerX + playerSpace, 320 + i * 150, 'white', '#00ccff', 30, 1);
drawImage(getRaceImg(player2.race), { left: centerX + playerSpace - 65, top: 320 + i * 150, width:65, height: 65, opacity: 0.85, glow: '#fff'})();
ctx.textAlign = 'center';
ctx.font = "38px '微軟正黑體'";
textGlow(half.maps[i], centerX, 390 + i * 150, '#11ccff', '#00e', 25, 1);
}
}
drawlogo();
});
}
function textGlow(text, x, y, color, glowColor, blur, level) {
ctx.save();
ctx.shadowColor = glowColor;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.shadowBlur = blur;
ctx.fillStyle = color;
for (var i = 0; i < level; i++) {
ctx.fillText(text, x, y);
}
ctx.fillText(text, x, y);
ctx.restore();
}
function getRaceImg(race) {
return 'assets/images/race' + race + '.png';
}
function drawImage(url, options) {
return function() {
var deferred = $.Deferred();
var img = new Image;
if (!options) options = {};
img.onload = function(){
ctx.save();
if (options.opacity) {
ctx.globalAlpha = options.opacity;
}
if (options.glow) {
ctx.shadowColor = options.glow;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.shadowBlur = 20;
}
ctx.drawImage(img, options.left || 0, options.top || 0, options.width || 1920, options.height || 1080);
ctx.restore();
deferred.resolve();
};
img.src = url;
return deferred.promise();
}
}
});
|
var FS = require('fs'),
Path = require('path'),
Model = require('api/model');
exports['test basic'] = function (test, assert) {
var userModel = new Model({
username : String,
password : String
}, {
folder : Path.resolve(__dirname, 'fixtures', 'db'),
filename : 'username'
});
var x = new userModel();
assert.ok(x.username instanceof String);
assert.ok(x.password instanceof String);
test.finish();
};
exports['test persist'] = function (test, assert) {
var folder = Path.resolve(__dirname, 'fixtures', 'db');
var userModel = new Model({
username : String,
password : String
}, {
folder : folder,
filename : 'username'
});
var x = new userModel();
x.username = 'brian';
x.password = 'secret';
x.persist(function () {
var file = FS.readFileSync(Path.resolve(folder, 'brian'), 'utf8');
var obj = JSON.parse(file);
assert.equal(obj.username, 'brian');
assert.equal(obj.password, 'secret');
test.finish();
});
};
exports['test load'] = function (test, assert) {
var folder = Path.resolve(__dirname, 'fixtures', 'db');
var userModel = new Model({
username : String,
password : String
}, {
folder : folder,
filename : 'username'
});
var x = new userModel();
x.username = 'brian2';
x.password = 'secret';
x.persist(function () {
var obj = userModel.load();
assert.equal(obj['brian2'].username, 'brian2');
assert.equal(obj['brian2'].password, 'secret');
test.finish();
});
};
|
/* global define */
define(['jquery'], function ($) {
/**
* @export orocrm/contact/widgets/account-contacts-widget
* @class oro.AccountContactWidgetHandler
*/
return {
/**
* @desc Fire name link click
* @callback
*/
boxClickHandler: function (even) {
/**
* @desc if target item has class contact-box-link
* we does not click redirection link(name link)
*/
if ($(even.target).hasClass('contact-box-link')) {
return;
}
$(this).find('.contact-box-name-link').click();
},
/**
* @constructs
*/
init: function () {
$('.contact-box').click(this.boxClickHandler);
}
};
});
|
angular.module(
"aanimals.module.logdown.service.logdown",
[]
)
.service("Logdown", function() {
var logdown;
if (
typeof module !== "undefined" &&
typeof module.exports !== "undefined" &&
typeof require === "function"
) {
logdown = require("logdown");
} else {
logdown = window.Logdown;
}
if (typeof logdown !== "function") {
throw new Error("Logdown is not defined; did you include the logdown script?");
}
return logdown;
});
|
/*
* mobile navbar unit tests
*/
(function($){
test( "navbar button gets active button class when clicked", function() {
var link = $("#disabled-btn-click a:not(.ui-disabled)").first();
link.click();
ok( link.hasClass($.mobile.activeBtnClass), "link has active button class" );
});
test( "disabled navbar button doesn't add active button class when clicked", function() {
var link = $("#disabled-btn-click a.ui-disabled").first();
link.click();
ok( !link.hasClass($.mobile.activeBtnClass), "link doesn't have active button class" );
});
test( "grids inside an ignored container do not enhance", function() {
var $ignored = $( "#ignored-grid" ), $enhanced = $( "#enhanced-grid" );
$.mobile.ignoreContentEnabled = true;
$("#foo").trigger( "create" );
same( $ignored.attr( "class" ), undefined, "ignored list doesn't have the grid theme" );
same( $enhanced.attr( "class" ).indexOf("ui-grid"), 0, "enhanced list has the grid theme" );
$.mobile.ignoreContentEnabled = false;
});
})(jQuery); |
//this controller simply tells the dialogs service to open a mediaPicker window
//with a specified callback, this callback will receive an object with a selection on it
function mediaPickerController($scope, dialogService, entityResource, $log, iconHelper) {
function trim(str, chr) {
var rgxtrim = (!chr) ? new RegExp('^\\s+|\\s+$', 'g') : new RegExp('^' + chr + '+|' + chr + '+$', 'g');
return str.replace(rgxtrim, '');
}
$scope.renderModel = [];
var dialogOptions = {
multiPicker: false,
entityType: "Media",
section: "media",
treeAlias: "media",
callback: function(data) {
if (angular.isArray(data)) {
_.each(data, function (item, i) {
$scope.add(item);
});
}
else {
$scope.clear();
$scope.add(data);
}
}
};
$scope.openContentPicker = function(){
var d = dialogService.treePicker(dialogOptions);
};
$scope.remove =function(index){
$scope.renderModel.splice(index, 1);
};
$scope.clear = function() {
$scope.renderModel = [];
};
$scope.add = function (item) {
var currIds = _.map($scope.renderModel, function (i) {
return i.id;
});
if (currIds.indexOf(item.id) < 0) {
item.icon = iconHelper.convertFromLegacyIcon(item.icon);
$scope.renderModel.push({name: item.name, id: item.id, icon: item.icon});
}
};
$scope.$on("formSubmitting", function (ev, args) {
var currIds = _.map($scope.renderModel, function (i) {
return i.id;
});
$scope.model.value = trim(currIds.join(), ",");
});
//load media data
var modelIds = $scope.model.value ? $scope.model.value.split(',') : [];
entityResource.getByIds(modelIds, dialogOptions.entityType).then(function (data) {
_.each(data, function (item, i) {
item.icon = iconHelper.convertFromLegacyIcon(item.icon);
$scope.renderModel.push({ name: item.name, id: item.id, icon: item.icon });
});
});
}
angular.module('umbraco').controller("Umbraco.PrevalueEditors.MediaPickerController",mediaPickerController); |
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function(Controller) {
"use strict";
return Controller.extend("BikeRentalApp.controller.bikestationslist", {
getDefaultModel: function() {
return this.getView().getModel();
},
/**
* Called when a controller is instantiated and its View controls (if available) are already created.
* Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization.
* @memberOf BikeRentalApp.view.bikestationslist
*/
onInit: function() {
},
/**
* Similar to onAfterRendering, but this hook is invoked before the controller's View is re-rendered
* (NOT before the first rendering! onInit() is used for that one!).
* @memberOf BikeRentalApp.view.bikestationslist
*/
// onBeforeRendering: function() {
//
// },
/**
* Called when the View has been rendered (so its HTML is part of the document). Post-rendering manipulations of the HTML could be done here.
* This hook is the same one that SAPUI5 controls get after being rendered.
* @memberOf BikeRentalApp.view.bikestationslist
*/
onAfterRendering: function() {
console.log("inside bikestation list");
var oModel = this.getView().getModel();
console.log(oModel);
}
/**
* Called when the Controller is destroyed. Use this one to free resources and finalize activities.
* @memberOf BikeRentalApp.view.bikestationslist
*/
// onExit: function() {
//
// }
});
}); |
/* global __utils__ */
casper.test.begin('todomvc', 63, function (test) {
casper
.start('examples/todomvc/index.html')
.then(function () {
this.viewport(1000, 1000) // for appearing destroy buttons by mouse hover
test.assertNotVisible('.main', '.main should be hidden')
test.assertNotVisible('.footer', '.footer should be hidden')
test.assertElementCount('.filters .selected', 1, 'should have one filter selected')
test.assertSelectorHasText('.filters .selected', 'All', 'default filter should be "All"')
})
// let's add a new item -----------------------------------------------
.then(function () {
casper.sendKeys('.new-todo', 'test')
})
.then(function () {
// wait before hitting enter
// so v-model unlocks
createNewItem()
})
.then(function () {
test.assertElementCount('.todo', 1, 'new item should be created')
test.assertNotVisible('.todo .edit', 'new item edit box should be hidden')
test.assertSelectorHasText('.todo label', 'test', 'new item should have correct label text')
test.assertSelectorHasText('.todo-count strong', '1', 'remaining count should be 1')
test.assertEvalEquals(function () {
return __utils__.findOne('.todo .toggle').checked
}, false, 'new item toggle should not be checked')
test.assertVisible('.main', '.main should now be visible')
test.assertVisible('.footer', '.footer should now be visible')
test.assertNotVisible('.clear-completed', '.clear-completed should be hidden')
test.assertField({type: 'css', path: '.new-todo'}, '', 'new todo input should be reset')
})
// add another item ---------------------------------------------------
.then(function () {
createNewItem('test2')
})
.then(function () {
test.assertElementCount('.todo', 2, 'should have 2 items now')
test.assertSelectorHasText('.todo:nth-child(2) label', 'test2', 'new item should have correct label text')
test.assertSelectorHasText('.todo-count strong', '2', 'remaining count should be 2')
})
// mark one item as completed -----------------------------------------
.thenClick('.todo .toggle', function () {
test.assertElementCount('.todo.completed', 1, 'should have 1 item completed')
test.assertEval(function () {
return __utils__.findOne('.todo').classList.contains('completed')
}, 'it should be the first one')
test.assertSelectorHasText('.todo-count strong', '1', 'remaining count should be 1')
test.assertVisible('.clear-completed', '.clear-completed should now be visible')
})
// add yet another item -----------------------------------------------
.then(function () {
createNewItem('test3')
})
.then(function () {
test.assertElementCount('.todo', 3, 'should have 3 items now')
test.assertSelectorHasText('.todo:nth-child(3) label', 'test3', 'new item should have correct label text')
test.assertSelectorHasText('.todo-count strong', '2', 'remaining count should be 2')
})
// add moreeee, now we assume they all work properly ------------------
.then(function () {
createNewItem('test4')
createNewItem('test5')
})
.then(function () {
test.assertElementCount('.todo', 5, 'should have 5 items now')
test.assertSelectorHasText('.todo-count strong', '4', 'remaining count should be 4')
})
// check more as completed --------------------------------------------
.then(function () {
this.click('.todo:nth-child(4) .toggle')
this.click('.todo:nth-child(5) .toggle')
})
.then(function () {
test.assertElementCount('.todo.completed', 3, 'should have 3 item completed')
test.assertSelectorHasText('.todo-count strong', '2', 'remaining count should be 2')
})
// remove a completed item --------------------------------------------
.then(function () {
this.mouse.move('.todo:nth-child(1)')
})
.thenClick('.todo:nth-child(1) .destroy', function () {
test.assertElementCount('.todo', 4, 'should have 4 items now')
test.assertElementCount('.todo.completed', 2, 'should have 2 item completed')
test.assertSelectorHasText('.todo-count strong', '2', 'remaining count should be 2')
})
// remove a incompleted item ------------------------------------------
.then(function () {
this.mouse.move('.todo:nth-child(2)')
})
.thenClick('.todo:nth-child(2) .destroy', function () {
test.assertElementCount('.todo', 3, 'should have 3 items now')
test.assertElementCount('.todo.completed', 2, 'should have 2 item completed')
test.assertSelectorHasText('.todo-count strong', '1', 'remaining count should be 1')
})
// remove all completed ------------------------------------------------
.thenClick('.clear-completed', function () {
test.assertElementCount('.todo', 1, 'should have 1 item now')
test.assertSelectorHasText('.todo label', 'test2', 'the remaining one should be the second one')
test.assertElementCount('.todo.completed', 0, 'should have no completed items now')
test.assertSelectorHasText('.todo-count strong', '1', 'remaining count should be 1')
test.assertNotVisible('.clear-completed', '.clear-completed should be hidden')
})
// prepare to test filters ------------------------------------------------
.then(function () {
createNewItem('test')
createNewItem('test')
})
.then(function () {
this.click('.todo:nth-child(2) .toggle')
this.click('.todo:nth-child(3) .toggle')
})
// active filter ----------------------------------------------------------
.thenClick('.filters li:nth-child(2) a', function () {
test.assertElementCount('.todo', 1, 'filter active should have 1 item')
test.assertElementCount('.todo.completed', 0, 'visible items should be incomplete')
})
// add item with filter active --------------------------------------------
// mostly make sure v-repeat works well with v-if
.then(function () {
createNewItem('test')
})
.then(function () {
test.assertElementCount('.todo', 2, 'should be able to create new item when fitler active')
})
// completed filter -------------------------------------------------------
.thenClick('.filters li:nth-child(3) a', function () {
test.assertElementCount('.todo', 2, 'filter completed should have 2 items')
test.assertElementCount('.todo.completed', 2, 'visible items should be completed')
})
// active filter on page load ---------------------------------------------
.thenOpen('examples/todomvc/index.html#/active', function () {
test.assertElementCount('.todo', 2, 'filter active should have 2 items')
test.assertElementCount('.todo.completed', 0, 'visible items should be incompleted')
test.assertSelectorHasText('.todo-count strong', '2', 'remaining count should be 2')
})
// completed filter on page load ------------------------------------------
.thenOpen('examples/todomvc/index.html#/completed', function () {
test.assertElementCount('.todo', 2, 'filter completed should have 2 items')
test.assertElementCount('.todo.completed', 2, 'visible items should be completed')
test.assertSelectorHasText('.todo-count strong', '2', 'remaining count should be 2')
})
// toggling todos when filter is active -----------------------------------
.thenClick('.todo .toggle', function () {
test.assertElementCount('.todo', 1, 'should have only 1 item left')
})
.thenClick('.filters li:nth-child(2) a', function () {
test.assertElementCount('.todo', 3, 'should have only 3 items now')
})
.thenClick('.todo .toggle', function () {
test.assertElementCount('.todo', 2, 'should have only 2 items now')
})
// test editing triggered by blur ------------------------------------------
.thenClick('.filters li:nth-child(1) a')
.then(function () {
doubleClick('.todo:nth-child(1) label')
})
.then(function () {
test.assertElementCount('.todo.editing', 1, 'should have one item being edited')
test.assertEval(function () {
var input = document.querySelector('.todo:nth-child(1) .edit')
return input === document.activeElement
}, 'edit input should be focused')
})
.then(function () {
resetField()
this.sendKeys('.todo:nth-child(1) .edit', 'edited!') // doneEdit triggered by blur
})
.then(function () {
test.assertElementCount('.todo.editing', 0, 'item should no longer be edited')
test.assertSelectorHasText('.todo:nth-child(1) label', 'edited!', 'item should have updated text')
})
// test editing triggered by enter ----------------------------------------
.then(function () {
doubleClick('.todo label')
})
.then(function () {
resetField()
this.sendKeys('.todo:nth-child(1) .edit', 'edited again!', { keepFocus: true })
keyUp(13) // Enter
})
.then(function () {
test.assertElementCount('.todo.editing', 0, 'item should no longer be edited')
test.assertSelectorHasText('.todo:nth-child(1) label', 'edited again!', 'item should have updated text')
})
// test cancel ------------------------------------------------------------
.then(function () {
doubleClick('.todo label')
})
.then(function () {
resetField()
this.sendKeys('.todo:nth-child(1) .edit', 'cancel test', { keepFocus: true })
keyUp(27) // ESC
})
.then(function () {
test.assertElementCount('.todo.editing', 0, 'item should no longer be edited')
test.assertSelectorHasText('.todo label', 'edited again!', 'item should not have updated text')
})
// test empty input remove ------------------------------------------------
.then(function () {
doubleClick('.todo label')
})
.then(function () {
resetField()
this.sendKeys('.todo:nth-child(1) .edit', ' ')
})
.then(function () {
test.assertElementCount('.todo', 3, 'item should have been deleted')
})
// test toggle all
.thenClick('.toggle-all', function () {
test.assertElementCount('.todo.completed', 3, 'should toggle all items to completed')
})
.thenClick('.toggle-all', function () {
test.assertElementCount('.todo:not(.completed)', 3, 'should toggle all items to active')
})
// run
.run(function () {
test.done()
})
// helper ===============
function createNewItem (text) {
if (text) {
casper.sendKeys('.new-todo', text)
}
casper.evaluate(function () {
// casper.mouseEvent can't set keyCode
var field = document.querySelector('.new-todo')
var e = document.createEvent('HTMLEvents')
e.initEvent('keyup', true, true)
e.keyCode = 13
field.dispatchEvent(e)
})
}
function doubleClick (selector) {
casper.evaluate(function (selector) {
var el = document.querySelector(selector)
var e = document.createEvent('MouseEvents')
e.initMouseEvent('dblclick', true, true, null, 1, 0, 0, 0, 0, false, false, false, false, 0, null)
el.dispatchEvent(e)
}, selector)
}
function keyUp (code) {
casper.evaluate(function (code) {
var input = document.querySelector('.todo:nth-child(1) .edit')
var e = document.createEvent('HTMLEvents')
e.initEvent('keyup', true, true)
e.keyCode = code
input.dispatchEvent(e)
}, code)
}
function resetField () {
// somehow casper.sendKey() option reset:true doesn't work
casper.evaluate(function () {
document.querySelector('.todo:nth-child(1) .edit').value = ''
})
}
})
|
require('./server/server.js'); |
export default( component , file ) =>
new Promise((resolve , reject) => {
component.setState({ isUploading: true});
component.upload.send(file , (error , url ) => {
if (error){
reject(error);
} else {
resolve(url);
}
});
});
|
"use strict";
var t = exports.t = require('chai').assert;
var extend = require('util')._extend;
var express = require('express');
var sira = require('sira');
exports.setup = function setup(fns) {
return function (done) {
var test = this;
exports.createSapp(fns, function (err, sapp) {
test.sapp = sapp;
for(var name in sapp.models) test[name] = sapp.models[name];
test.app = express();
done();
});
}
};
exports.createSapp = function createSapp(fns, cb) {
var sapp = sira();
sapp.set('remoting', {json: {limit: '1kb'}});
if (fns) {
fns = Array.isArray(fns) ? fns : [fns];
fns.forEach(function (fn) {
fn(sapp);
})
}
sapp.phase(sira.boot.database());
sapp.boot(function (err) {
cb(err, sapp);
});
return sapp;
};
exports.createSharedClass = function createSharedClass(config) {
// create a class that can be remoted
var SharedClass = function(id) {
this.id = id;
};
extend(SharedClass, config);
SharedClass.shared = true;
SharedClass.sharedCtor = function(id, cb) {
cb(null, new SharedClass(id));
};
extend(SharedClass.sharedCtor, {
shared: true,
accepts: [ { arg: 'id', type: 'any', http: { source: 'path' }}],
http: { path: '/:id' },
returns: { root: true }
});
return SharedClass;
};
|
/*
* Monitor remote server uptime.
*/
var http = require('http');
var url = require('url');
http.createServer(function(req, res) {
var arg = url.parse(req.url).pathname.substr(1);
var chanceToGetOkResponse = parseFloat(arg) / 100;
if (!chanceToGetOkResponse || Math.random() > chanceToGetOkResponse) {
res.writeHead(500, {'Content-Type': 'text/plain'});
setTimeout(function() { res.end('Bad Request')}, Math.random() * 1000 );
} else {
res.writeHead(200, {'Content-Type': 'text/plain'});
setTimeout(function() { res.end('Success')}, Math.random() * 1000 );
}
}).listen(8888); |
'use strict'
const WebIdTlsCertificate = require('../models/webid-tls-certificate')
const debug = require('./../debug').accounts
/**
* Represents an 'add new certificate to account' request
* (a POST to `/api/accounts/cert` endpoint).
*
* Note: The account has to exist, and the user must be already logged in,
* for this to succeed.
*/
class AddCertificateRequest {
/**
* @param [options={}] {Object}
* @param [options.accountManager] {AccountManager}
* @param [options.userAccount] {UserAccount}
* @param [options.certificate] {WebIdTlsCertificate}
* @param [options.response] {HttpResponse}
*/
constructor (options) {
this.accountManager = options.accountManager
this.userAccount = options.userAccount
this.certificate = options.certificate
this.response = options.response
}
/**
* Handles the HTTP request (from an Express route handler).
*
* @param req
* @param res
* @param accountManager {AccountManager}
*
* @throws {TypeError}
* @throws {Error} HTTP 401 if the user is not logged in (`req.session.userId`
* does not match the intended account to which the cert is being added).
*
* @return {Promise}
*/
static handle (req, res, accountManager) {
let request
try {
request = AddCertificateRequest.fromParams(req, res, accountManager)
} catch (error) {
return Promise.reject(error)
}
return AddCertificateRequest.addCertificate(request)
}
/**
* Factory method, returns an initialized instance of `AddCertificateRequest`.
*
* @param req
* @param res
* @param accountManager {AccountManager}
*
* @throws {TypeError} If required parameters missing
* @throws {Error} HTTP 401 if the user is not logged in (`req.session.userId`
* does not match the intended account to which the cert is being added).
*
* @return {AddCertificateRequest}
*/
static fromParams (req, res, accountManager) {
const userAccount = accountManager.userAccountFrom(req.body)
const certificate = WebIdTlsCertificate.fromSpkacPost(
req.body.spkac,
userAccount,
accountManager.host)
debug(`Adding a new certificate for ${userAccount.webId}`)
if (req.session.userId !== userAccount.webId) {
debug(`Cannot add new certificate: signed in user is "${req.session.userId}"`)
const error = new Error("You are not logged in, so you can't create a certificate")
error.status = 401
throw error
}
const options = {
accountManager,
userAccount,
certificate,
response: res
}
return new AddCertificateRequest(options)
}
/**
* Generates a new certificate for a given user account, and adds it to that
* account's WebID Profile graph.
*
* @param request {AddCertificateRequest}
*
* @throws {Error} HTTP 400 if there were errors during certificate generation
*
* @returns {Promise}
*/
static addCertificate (request) {
const { certificate, userAccount, accountManager } = request
return certificate.generateCertificate()
.catch(err => {
err.status = 400
err.message = 'Error generating a certificate: ' + err.message
throw err
})
.then(() => {
return accountManager.addCertKeyToProfile(certificate, userAccount)
})
.catch(err => {
err.status = 400
err.message = 'Error adding certificate to profile: ' + err.message
throw err
})
.then(() => {
request.sendResponse(certificate)
})
}
/**
* Sends the generated certificate in the response object.
*
* @param certificate {WebIdTlsCertificate}
*/
sendResponse (certificate) {
const { response, userAccount } = this
response.set('User', userAccount.webId)
response.status(200)
response.set('Content-Type', 'application/x-x509-user-cert')
response.send(certificate.toDER())
}
}
module.exports = AddCertificateRequest
|
describeIntegration("Cluster Configuration", function() {
var TRANSPORTS = {
"ws": Pusher.WSTransport,
"flash": Pusher.FlashTransport,
"sockjs": Pusher.SockJSTransport,
"xhr_streaming": Pusher.XHRStreamingTransport,
"xhr_polling": Pusher.XHRPollingTransport,
"xdr_streaming": Pusher.XDRStreamingTransport,
"xdr_polling": Pusher.XDRPollingTransport
};
function subscribe(pusher, channelName, callback) {
var channel = pusher.subscribe(channelName);
channel.bind("pusher:subscription_succeeded", function(param) {
callback(channel, param);
});
return channel;
}
var pusher;
function describeClusterTest(options) {
var environment = { encrypted: options.encrypted };
if (!TRANSPORTS[options.transport].isSupported(environment)) {
return;
}
describe("with " + options.transport + ", encrypted=" + options.encrypted, function() {
beforeEach(function() {
Pusher.Util.objectApply(TRANSPORTS, function(transport, name) {
spyOn(transport, "isSupported").andReturn(false);
});
TRANSPORTS[options.transport].isSupported.andReturn(true);
spyOn(Pusher.Util, "getLocalStorage").andReturn({});
});
it("should open a connection to the 'eu' cluster", function() {
pusher = new Pusher("4d31fbea7080e3b4bf6d", {
authTransport: 'jsonp',
authEndpoint: Pusher.Integration.API_EU_URL + "/auth",
cluster: "eu",
encrypted: options.encrypted,
disableStats: true
});
waitsFor(function() {
return pusher.connection.state === "connected";
}, "connection to be established", 20000);
});
it("should subscribe and receive a message sent via REST API", function() {
var channelName = Pusher.Integration.getRandomName("private-integration");
var onSubscribed = jasmine.createSpy("onSubscribed");
var channel = subscribe(pusher, channelName, onSubscribed);
var eventName = "integration_event";
var data = { x: 1, y: "z" };
var received = null;
waitsFor(function() {
return onSubscribed.calls.length;
}, "subscription to succeed", 10000);
runs(function() {
channel.bind(eventName, function(message) {
received = message;
});
Pusher.Integration.sendAPIMessage({
url: Pusher.Integration.API_EU_URL + "/v2/send",
channel: channelName,
event: eventName,
data: data
});
});
waitsFor(function() {
return received !== null;
}, "message to get delivered", 10000);
runs(function() {
expect(received).toEqual(data);
pusher.unsubscribe(channelName);
});
});
it("should disconnect the connection", function() {
pusher.disconnect();
});
});
}
var _VERSION;
var _channel_auth_transport;
var _channel_auth_endpoint;
var _Dependencies;
it("should prepare the global config", function() {
// TODO fix how versions work in unit tests
_VERSION = Pusher.VERSION;
_channel_auth_transport = Pusher.channel_auth_transport;
_channel_auth_endpoint = Pusher.channel_auth_endpoint;
_Dependencies = Pusher.Dependencies;
Pusher.VERSION = "8.8.8";
Pusher.channel_auth_transport = "";
Pusher.channel_auth_endpoint = "";
Pusher.Dependencies = new Pusher.DependencyLoader({
cdn_http: Pusher.Integration.JS_HOST,
cdn_https: Pusher.Integration.JS_HOST,
version: Pusher.VERSION,
suffix: "",
receivers: Pusher.DependenciesReceivers
});
});
if (!/version\/5.*safari/i.test(navigator.userAgent)) {
// Safari 5 uses hixie-75/76, which is not supported on EU
describeClusterTest({ transport: "ws", encrypted: false});
describeClusterTest({ transport: "ws", encrypted: true});
}
// describeClusterTest({ transport: "flash", encrypted: false});
// there's a problem with Flash policy file on EU when encrypted
// describeClusterTest({ transport: "flash", encrypted: true});
if (Pusher.Util.isXHRSupported()) {
// CORS-compatible browsers
if (!/Android 2\./i.test(navigator.userAgent)) {
// Android 2.x does a lot of buffering, which kills streaming
describeClusterTest({ transport: "xhr_streaming", encrypted: false});
describeClusterTest({ transport: "xhr_streaming", encrypted: true});
}
describeClusterTest({ transport: "xhr_polling", encrypted: false});
describeClusterTest({ transport: "xhr_polling", encrypted: true});
} else if (Pusher.Util.isXDRSupported(false)) {
describeClusterTest({ transport: "xdr_streaming", encrypted: false});
describeClusterTest({ transport: "xdr_streaming", encrypted: true});
describeClusterTest({ transport: "xdr_polling", encrypted: false});
describeClusterTest({ transport: "xdr_polling", encrypted: true});
// IE can fall back to SockJS if protocols don't match
// No SockJS encrypted tests due to the way JS files are served
describeClusterTest({ transport: "sockjs", encrypted: false});
} else {
// Browsers using SockJS
describeClusterTest({ transport: "sockjs", encrypted: false});
describeClusterTest({ transport: "sockjs", encrypted: true});
}
it("should restore the global config", function() {
Pusher.Dependencies = _Dependencies;
Pusher.channel_auth_endpoint = _channel_auth_endpoint;
Pusher.channel_auth_transport = _channel_auth_transport;
Pusher.VERSION = _VERSION;
});
});
|
import React from 'react'
import { shallow } from 'enzyme'
import StateControl from './StateControl'
import * as CONTENT from '../../../content/text'
it('renders without crashing', () => {
shallow(<StateControl />)
})
|
module.exports = ContactGroupAssign = require('typedef')
// THIS CODE WAS GENERATED BY AN AUTOMATED TOOL. Editing it is not recommended.
// For more information, see http://github.com/bvalosek/grunt-infusionsoft
// Generated on Wed Jan 08 2014 12:43:55 GMT-0600 (CST)
// This table has one entry for each tag a single contact has. If you have one
// contact with five tags, you will find five entries in this table for that given
// contact
.class('ContactGroupAssign') .define({
__static__field__number__read__GroupId:
'GroupId',
__static__field__string__read__ContactGroup:
'ContactGroup',
__static__field__datetime__read__DateCreated:
'DateCreated',
__static__field__number__read__ContactId:
'ContactId'
}); |
var HelloWorld = cc.Scene.extend({
onEnter:function(){
this._super();
var winSize = cc.visibleRect;
//从flax输出的素材文件中,创建id为anim的动画,对应flash库中链接名为mc.anim的动画
//添加到this中,并设置位置为舞台中心
var anim = flax.assetsManager.createDisplay(res.anim, "helloWorld", {parent: this, x: winSize.width/2, y: winSize.height/2});
//在最后一帧停住
anim.autoStopWhenOver = true;
//从当前帧就是第1帧开始播放
anim.play();
}
}); |
//------------------------------------//
// Three Config
//------------------------------------//
define(['jquery', 'three', 'angular'], function($, THREE, angular) {
(function(window, document, undefined) {
var mouseX = 0,
mouseY = 0,
scene = new THREE.Scene(),
renderer = new THREE.WebGLRenderer({alpha:true}),
camera = new THREE.PerspectiveCamera(10, window.innerWidth / window.innerHeight, .1, 1000);
camera.position.set( 0, 0, 400 );
renderer.setPixelRatio( window.devicePixelRatio );
var particles = new THREE.Geometry;
for (var p = 0; p <= 2000; p++) {
var particle = new THREE.Vector3(Math.random() * 500 - 250, Math.random() * 500 - 250, Math.random() * 500 - 250);
particles.vertices.push(particle);
}
var particleMaterial = new THREE.ParticleBasicMaterial({ color: 0xffffff, size: 2 });
var particleSystem = new THREE.ParticleSystem(particles, particleMaterial);
scene.add(particleSystem);
/*
THREE.ImageUtils.crossOrigin = '';
var mapOverlay = THREE.ImageUtils.loadTexture('https://i.ytimg.com/vi/XV9LHg2dHa4/hqdefault.jpg');
*/
/*
var cubeGEO = new THREE.BoxGeometry(20,20,20),
cubeMAT = new THREE.MeshBasicMaterial({color: 0xdddddd, wireframe: true}), // + map: mapOverlay
cube = new THREE.Mesh(cubeGEO, cubeMAT);
cube.position.x = 0;
cube.position.y = 0;
cube.position.z = 0;
scene.add(cube);
*/
/*
var cylinderGEO = new THREE.CylinderGeometry(20,10,20),
cylinderMAT = new THREE.MeshBasicMaterial({color:0xdddddd, wireframe:true}),
cylinder = new THREE.Mesh(cylinderGEO, cylinderMAT);
cylinder.position.x = 0;
cylinder.position.y = 0;
cylinder.position.z = 0;
scene.add(cylinder);
*/
$('.ejo-WebGL').append(renderer.domElement);
function onDocumentMouseMove(e) {
var windowHalfX = window.innerWidth / 2,
windowHalfY = window.innerHeight / 2;
mouseX = ( event.clientX - windowHalfX ) / 2;
mouseY = ( event.clientY - windowHalfY ) / 2;
}
function size(e) {
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame( animate );
camera.position.x += ( mouseX - camera.position.x ) * .05;
camera.position.y += ( -mouseY - camera.position.y ) * .05;
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
size();
animate();
$(window).on('resize', size);
$(document).on('mousemove', onDocumentMouseMove);
})(window, document);
});
|
/////////////////////////////////////////////////////////////
// ContextMenu
//
/////////////////////////////////////////////////////////////
import './ContextMenu.scss'
export default class ContextMenu {
constructor (viewer) {
this.viewer = viewer;
this.menus = [];
this.container = null;
this.open = false;
}
addCallbackToMenuItem (menuItem, target) {
var that = this;
menuItem.addEventListener('click', function (event) {
that.hide();
target();
event.preventDefault();
return false;
}, false);
}
addSubmenuCallbackToMenuItem (menuItem, menu, x, y) {
var that = this;
menuItem.addEventListener('click', function () {
that.showMenu(menu, x, y);
}, false);
}
/////////////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////////////
show (event, menu) {
var viewport = this.viewer.container.getBoundingClientRect();
// Normalize Hammer events
if (Array.isArray(event.changedPointers) && event.changedPointers.length > 0) {
event.clientX = event.changedPointers[0].clientX;
event.clientY = event.changedPointers[0].clientY;
}
var x = event.clientX - viewport.left;
var y = event.clientY - viewport.top;
if (!this.open) {
var self = this;
this.showMenu(menu, x, y);
this.open = true;
this.hideEventListener = function(event) {
if (event.target.className !== "menuItem") {
self.hide(event);
}
}
this.isTouch = (event.type === "press")
document.body.addEventListener(
this.isTouch
? "touchstart"
: "mousedown", this.hideEventListener, true)
}
}
/////////////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////////////
showMenu (menu, x, y) {
var container = document.createElement('div'),
menuItem,
submenus = [];
container.className = 'menu';
this.viewer.container.appendChild(container);
this.menus.push(container);
for (var i = 0; i < menu.length; ++i) {
var defn = menu[i], target = defn.target;
menuItem = this.createMenuItem(container, defn);
if (typeof target === 'function') {
this.addCallbackToMenuItem(menuItem, target);
} else if (Array.isArray(target)) {
submenus.push({menuItem: menuItem, target: target});
} else {
console.warn("Invalid context menu option:", title, target);
}
}
var rect = container.getBoundingClientRect(),
containerWidth = rect.width,
containerHeight = rect.height,
viewerRect = this.viewer.container.getBoundingClientRect(),
viewerWidth = viewerRect.width,
viewerHeight = viewerRect.height,
shiftLeft = isTouchDevice() && !this.viewer.navigation.getUseLeftHandedInput();
if (shiftLeft) {
x -= containerWidth;
}
if (x < 0) {
x = 0;
}
if (viewerWidth < x + containerWidth) {
x = viewerWidth - containerWidth;
if (x < 0) {
x = 0;
}
}
if (y < 0) {
y = 0;
}
if (viewerHeight < y + containerHeight) {
y = viewerHeight - containerHeight;
if (y < 0) {
y = 0;
}
}
container.style.top = Math.round(y) + "px";
container.style.left = Math.round(x) + "px";
for (i = 0; i < submenus.length; ++i) {
var submenu = submenus[i];
menuItem = submenu.menuItem;
rect = menuItem.getBoundingClientRect();
x = Math.round((shiftLeft ? rect.left : rect.right) - viewerRect.left);
y = Math.round(rect.top - viewerRect.top);
this.addSubmenuCallbackToMenuItem(menuItem, submenu.target, x, y);
}
}
/////////////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////////////
createMenuItem (parentItem, menuItemDef) {
const menuItemId = this.guid()
const text = menuItemDef.title
$(parentItem).append(`
<div id="${menuItemId}" class="menuItem" data-i18n=${text}>
<span class="${menuItemDef.icon || ''}">
</span>
${Autodesk.Viewing.i18n.translate(text)}
</div>
`)
return document.getElementById (menuItemId)
}
/////////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////////
hide () {
if (this.open) {
for (var index=0; index<this.menus.length; ++index) {
if(this.menus[index]) {
this.menus[index].parentNode.removeChild(this.menus[index]);
}
}
this.menus = [];
this.open = false;
document.body.removeEventListener(
this.isTouch
? "touchstart"
: "mousedown", this.hideEventListener)
this.isTouch = false;
return true;
}
return false;
}
/////////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////////
guid (format = 'xxxxxxxx') {
var d = new Date().getTime()
var guid = format.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 guid
}
}
|
/* Date Math
-----------------------------------------------------------------------------*/
var DAY_MS = 86400000,
HOUR_MS = 3600000,
MINUTE_MS = 60000;
function addYears(d, n, keepTime) {
d.setFullYear(d.getFullYear() + n);
if (!keepTime) {
clearTime(d);
}
return d;
}
function addMonths(d, n, keepTime) { // prevents day overflow/underflow
if (+d) { // prevent infinite looping on invalid dates
var m = d.getMonth() + n,
check = cloneDate(d);
check.setDate(1);
check.setMonth(m);
d.setMonth(m);
if (!keepTime) {
clearTime(d);
}
while (d.getMonth() != check.getMonth()) {
d.setDate(d.getDate() + (d < check ? 1 : -1));
}
}
return d;
}
function addDays(d, n, keepTime) { // deals with daylight savings
if (+d) {
var dd = d.getDate() + n,
check = cloneDate(d);
check.setHours(9); // set to middle of day
check.setDate(dd);
d.setDate(dd);
if (!keepTime) {
clearTime(d);
}
fixDate(d, check);
}
return d;
}
fc.addDays = addDays;
function fixDate(d, check) { // force d to be on check's YMD, for daylight savings purposes
if (+d) { // prevent infinite looping on invalid dates
while (d.getDate() != check.getDate()) {
d.setTime(+d + (d < check ? 1 : -1) * HOUR_MS);
}
}
}
function addMinutes(d, n) {
d.setMinutes(d.getMinutes() + n);
return d;
}
function clearTime(d) {
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
return d;
}
function cloneDate(d, dontKeepTime) {
if (dontKeepTime) {
return clearTime(new Date(+d));
}
return new Date(+d);
}
function zeroDate() { // returns a Date with time 00:00:00 and dateOfMonth=1
var i=0, d;
do {
d = new Date(1970, i++, 1);
} while (d.getHours() != 0);
return d;
}
function skipWeekend(date, inc, excl) {
inc = inc || 1;
while (date.getDay()==0 || (excl && date.getDay()==1 || !excl && date.getDay()==6)) {
addDays(date, inc);
}
return date;
}
/* Date Parsing
-----------------------------------------------------------------------------*/
var parseDate = fc.parseDate = function(s) {
if (typeof s == 'object') { // already a Date object
return s;
}
if (typeof s == 'number') { // a UNIX timestamp
return new Date(s * 1000);
}
if (typeof s == 'string') {
if (s.match(/^\d+$/)) { // a UNIX timestamp
return new Date(parseInt(s) * 1000);
}
return parseISO8601(s, true) || (s ? new Date(s) : null);
}
// TODO: never return invalid dates (like from new Date(<string>)), return null instead
return null;
}
var parseISO8601 = fc.parseISO8601 = function(s, ignoreTimezone) {
// derived from http://delete.me.uk/2005/03/iso8601.html
// TODO: for a know glitch/feature, read tests/issue_206_parseDate_dst.html
var m = s.match(/^([0-9]{4})(-([0-9]{2})(-([0-9]{2})([T ]([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?$/);
if (!m) {
return null;
}
var date = new Date(m[1], 0, 1),
check = new Date(m[1], 0, 1, 9, 0),
offset = 0;
if (m[3]) {
date.setMonth(m[3] - 1);
check.setMonth(m[3] - 1);
}
if (m[5]) {
date.setDate(m[5]);
check.setDate(m[5]);
}
fixDate(date, check);
if (m[7]) {
date.setHours(m[7]);
}
if (m[8]) {
date.setMinutes(m[8]);
}
if (m[10]) {
date.setSeconds(m[10]);
}
if (m[12]) {
date.setMilliseconds(Number("0." + m[12]) * 1000);
}
fixDate(date, check);
if (!ignoreTimezone) {
if (m[14]) {
offset = Number(m[16]) * 60 + Number(m[17]);
offset *= m[15] == '-' ? 1 : -1;
}
offset -= date.getTimezoneOffset();
}
return new Date(+date + (offset * 60 * 1000));
}
var parseTime = fc.parseTime = function(s) { // returns minutes since start of day
if (typeof s == 'number') { // an hour
return s * 60;
}
if (typeof s == 'object') { // a Date object
return s.getHours() * 60 + s.getMinutes();
}
var m = s.match(/(\d+)(?::(\d+))?\s*(\w+)?/);
if (m) {
var h = parseInt(m[1]);
if (m[3]) {
h %= 12;
if (m[3].toLowerCase().charAt(0) == 'p') {
h += 12;
}
}
return h * 60 + (m[2] ? parseInt(m[2]) : 0);
}
};
/* Date Formatting
-----------------------------------------------------------------------------*/
var formatDate = fc.formatDate = function(date, format, options) {
return formatDates(date, null, format, options);
}
var formatDates = fc.formatDates = function(date1, date2, format, options) {
options = options || defaults;
var date = date1,
otherDate = date2,
i, len = format.length, c,
i2, formatter,
res = '';
for (i=0; i<len; i++) {
c = format.charAt(i);
if (c == "'") {
for (i2=i+1; i2<len; i2++) {
if (format.charAt(i2) == "'") {
if (date) {
if (i2 == i+1) {
res += "'";
}else{
res += format.substring(i+1, i2);
}
i = i2;
}
break;
}
}
}
else if (c == '(') {
for (i2=i+1; i2<len; i2++) {
if (format.charAt(i2) == ')') {
var subres = formatDate(date, format.substring(i+1, i2), options);
if (parseInt(subres.replace(/\D/, ''))) {
res += subres;
}
i = i2;
break;
}
}
}
else if (c == '[') {
for (i2=i+1; i2<len; i2++) {
if (format.charAt(i2) == ']') {
var subformat = format.substring(i+1, i2);
var subres = formatDate(date, subformat, options);
if (subres != formatDate(otherDate, subformat, options)) {
res += subres;
}
i = i2;
break;
}
}
}
else if (c == '{') {
date = date2;
otherDate = date1;
}
else if (c == '}') {
date = date1;
otherDate = date2;
}
else {
for (i2=len; i2>i; i2--) {
if (formatter = dateFormatters[format.substring(i, i2)]) {
if (date) {
res += formatter(date, options);
}
i = i2 - 1;
break;
}
}
if (i2 == i) {
if (date) {
res += c;
}
}
}
}
return res;
}
var dateFormatters = {
s : function(d) { return d.getSeconds() },
ss : function(d) { return zeroPad(d.getSeconds()) },
m : function(d) { return d.getMinutes() },
mm : function(d) { return zeroPad(d.getMinutes()) },
h : function(d) { return d.getHours() % 12 || 12 },
hh : function(d) { return zeroPad(d.getHours() % 12 || 12) },
H : function(d) { return d.getHours() },
HH : function(d) { return zeroPad(d.getHours()) },
d : function(d) { return d.getDate() },
dd : function(d) { return zeroPad(d.getDate()) },
ddd : function(d,o) { return o.dayNamesShort[d.getDay()] },
dddd: function(d,o) { return o.dayNames[d.getDay()] },
M : function(d) { return d.getMonth() + 1 },
MM : function(d) { return zeroPad(d.getMonth() + 1) },
MMM : function(d,o) { return o.monthNamesShort[d.getMonth()] },
MMMM: function(d,o) { return o.monthNames[d.getMonth()] },
yy : function(d) { return (d.getFullYear()+'').substring(2) },
yyyy: function(d) { return d.getFullYear() },
t : function(d) { return d.getHours() < 12 ? 'a' : 'p' },
tt : function(d) { return d.getHours() < 12 ? 'am' : 'pm' },
T : function(d) { return d.getHours() < 12 ? 'A' : 'P' },
TT : function(d) { return d.getHours() < 12 ? 'AM' : 'PM' },
u : function(d) { return formatDate(d, "yyyy-MM-dd'T'HH:mm:ss'Z'") },
S : function(d) {
var date = d.getDate();
if (date > 10 && date < 20) return 'th';
return ['st', 'nd', 'rd'][date%10-1] || 'th';
}
};
/* Element Dimensions
-----------------------------------------------------------------------------*/
function setOuterWidth(element, width, includeMargins) {
element.each(function() {
var e = $(this);
var w = width - horizontalSides(e);
if (includeMargins) {
w -= (parseInt(e.css('margin-left')) || 0) +
(parseInt(e.css('margin-right')) || 0);
}
e.width(w);
});
}
function horizontalSides(e) {
return (parseInt(e.css('border-left-width')) || 0) +
(parseInt(e.css('padding-left')) || 0) +
(parseInt(e.css('padding-right')) || 0) +
(parseInt(e.css('border-right-width')) || 0);
}
function setOuterHeight(element, height, includeMargins) {
element.each(function() {
var e = $(this);
var h = height - verticalSides(e);
if (includeMargins) {
h -= (parseInt(e.css('margin-top')) || 0) +
(parseInt(e.css('margin-bottom')) || 0);
}
e.height(h);
});
}
function verticalSides(e) {
return (parseInt(e.css('border-top-width')) || 0) +
(parseInt(e.css('padding-top')) || 0) +
(parseInt(e.css('padding-bottom')) || 0) +
(parseInt(e.css('border-bottom-width')) || 0);
}
/* Position Calculation
-----------------------------------------------------------------------------*/
// nasty bugs in opera 9.25
// position() returning relative to direct parent
var operaPositionBug;
function reportTBody(tbody) {
if (operaPositionBug == undefined) {
operaPositionBug = tbody.position().top != tbody.find('tr').position().top;
}
}
function safePosition(element, td, tr, tbody) {
var position = element.position();
if (operaPositionBug) {
position.top += tbody.position().top + tr.position().top - td.position().top;
}
return position;
}
/* Hover Matrix
-----------------------------------------------------------------------------*/
function HoverMatrix(changeCallback) {
var tops=[], lefts=[],
prevRowE, prevColE,
origRow, origCol,
currRow, currCol;
this.row = function(e, topBug) {
prevRowE = $(e);
tops.push(prevRowE.offset().top + (
(operaPositionBug && prevRowE.is('tr')) ? prevRowE.parent().position().top : 0
));
};
this.col = function(e) {
prevColE = $(e);
lefts.push(prevColE.offset().left);
};
this.mouse = function(x, y) {
if (origRow == undefined) {
tops.push(tops[tops.length-1] + prevRowE.outerHeight());
lefts.push(lefts[lefts.length-1] + prevColE.outerWidth());
currRow = currCol = -1;
}
var r, c;
for (r=0; r<tops.length && y>=tops[r]; r++) ;
for (c=0; c<lefts.length && x>=lefts[c]; c++) ;
r = r >= tops.length ? -1 : r - 1;
c = c >= lefts.length ? -1 : c - 1;
if (r != currRow || c != currCol) {
currRow = r;
currCol = c;
if (r == -1 || c == -1) {
this.cell = null;
}else{
if (origRow == undefined) {
origRow = r;
origCol = c;
}
this.cell = {
row: r,
col: c,
top: tops[r],
left: lefts[c],
width: lefts[c+1] - lefts[c],
height: tops[r+1] - tops[r],
isOrig: r==origRow && c==origCol,
rowDelta: r-origRow,
colDelta: c-origCol
};
}
changeCallback(this.cell);
}
};
}
/* Misc Utils
-----------------------------------------------------------------------------*/
var undefined,
dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
function zeroPad(n) {
return (n < 10 ? '0' : '') + n;
}
function smartProperty(obj, name) { // get a camel-cased/namespaced property
if (obj[name] != undefined) {
return obj[name];
}
var parts = name.split(/(?=[A-Z])/),
i=parts.length-1, res;
for (; i>=0; i--) {
res = obj[parts[i].toLowerCase()];
if (res != undefined) {
return res;
}
}
return obj[''];
}
|
export default function acceptArgumentList(children) {
let args = [];
children.skipNonCode();
children.passToken('Punctuator', '(');
children.skipNonCode();
while (!children.isToken('Punctuator', ')')) {
if (children.isToken('Punctuator', ',')) {
children.moveNext();
children.skipNonCode();
children.assertToken('Punctuator', ')');
} else {
args.push(children.passExpressionOrSpreadElement());
children.skipNonCode();
if (children.isToken('Punctuator', ',')) {
children.moveNext();
children.skipNonCode();
}
}
}
children.passToken('Punctuator', ')');
children.assertEnd();
return args;
}
|
module.exports = function(app,extend){
var passport = require('passport');
var PrivateCtrl = require( app.locals.__app + '/controllers/private')(app);
var PageCtrl = require( app.locals.__app + '/controllers/page')(app);
var PostCtrl = require( app.locals.__app + '/controllers/post')(app);
var CommentCtrl = require( app.locals.__app + '/controllers/comment')(app);
var ApiCtrl = require( app.locals.__app + '/controllers/api')(app);
var UserCtrl = require( app.locals.__app + '/controllers/user')(app);
var MediaCtrl = require( app.locals.__app + '/controllers/media')(app);
var ConfCtrl = require( app.locals.__app + '/controllers/configuration')(app);
var CustomfCtrl = require( app.locals.__app + '/controllers/custom-post')(app);
/**
* AUTHORIZATIONS
*/
var guest = require( app.locals.__app + '/middlewares/roles')('guest');
var moderator = require( app.locals.__app + '/middlewares/roles')('moderator');
var admin = require( app.locals.__app + '/middlewares/roles')('admin');
extend.routes.private(app);
app.get('/admin',function(req,res){
res.redirect('/admin/panel');
});
app.get('/admin/logout',function(req,res){
req.logout();
res.redirect('/admin/login');
});
// ADMIN PANEL
app.get('/admin/panel' , PrivateCtrl.dashboard );
/**
* POSTS
*/
app.get('/admin/posts' , PostCtrl.index_admin );
app.get('/admin/post' , PostCtrl.create );
app.get('/admin/post/:id' , PostCtrl.edit );
/**
* PAGES
*/
app.get('/admin/pages' , PageCtrl.index_admin );
app.get('/admin/page' , PageCtrl.create );
app.get('/admin/page/:id' , PageCtrl.edit );
/**
* CUSTOM POSTS
*/
app.get('/admin/custom/:type' , CustomfCtrl.index );
app.get('/admin/custom/create/:type' , CustomfCtrl.create );
app.get('/admin/custom/edit/:type/:id' , CustomfCtrl.edit );
/**
* USERS
*/
app.get('/admin/users' , admin, UserCtrl.index );
app.get('/admin/users/:id' , guest, UserCtrl.show );
app.get('/admin/user' , admin, UserCtrl.create );
app.get('/admin/register' , PrivateCtrl.register );
app.get('/admin/reset-password' , PrivateCtrl.resetPassword );
/**
* MEDIA
*/
app.get('/admin/media' , MediaCtrl.index );
/**
* COMMENTS
*/
app.get('/admin/comments' , CommentCtrl.index_admin );
/**
* CONFIGURATION && CUSTOMIZATION
*/
app.get('/admin/configurations' , admin, ConfCtrl.index_configurations );
app.get('/admin/navigation' , admin, ConfCtrl.index_nav );
app.get('/admin/themes' , admin, ConfCtrl.index_themes );
app.get('/admin/custom-css' , admin, ConfCtrl.index_custom_css );
/**
* LOGIN
*/
app.get('/admin/login' , PrivateCtrl.login );
app.post('/admin/login',
passport.authenticate('local', { successRedirect: '/admin/panel', failureRedirect: '/admin/login', failureFlash: true })
);
}
|
'use strict';
const path = require('path');
const webpack = require('webpack');
const baseConfig = require('./base');
const defaultSettings = require('./defaults');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const config = Object.assign({}, baseConfig, {
entry: [
'webpack-dev-server/client?http://127.0.0.1:' + defaultSettings.port,
'webpack/hot/only-dev-server',
'./src/index.tsx'
],
cache: true,
devtool: 'eval-source-map',
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new BundleAnalyzerPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"development"',
'process.env.REACT_DIRSTO': '"anujs"'
}),
],
module: defaultSettings.getDefaultModules()
});
// Add needed loaders to the defaults here
config.module.rules.push({
test: /\.(js|jsx)$/,
loader: 'babel-loader',
include: [
path.join(__dirname, '/../src')
]
});
module.exports = config;
|
$(document).ready(function() {
var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({
el: $('#paper'),
width: 800,
height: 480,
gridSize: 1,
model: graph
});
var erd = joint.shapes.erd;
var element = function(elm, x, y, label) {
var cell = new elm({ position: { x: x, y: y }, attrs: { text: { text: label }}});
graph.addCell(cell);
return cell;
};
var link = function(elm1, elm2) {
var myLink = new erd.Line({ source: { id: elm1.id }, target: { id: elm2.id }});
graph.addCell(myLink);
return myLink;
};
$('#entity').click(function() {
element(erd.Entity, 0, 0, "New Entity");
});
$('#relationship').click(function() {
element(erd.Relationship, 0, 0, "New Relationship");
});
$('#attribute').click(function() {
element(erd.Normal, 0, 0, "New Attribute");
});
});
|
(function () {
'use strict';
var directiveId = 'remiChart';
angular.module('app').directive(directiveId, [remiChart]);
function remiChart() {
return {
restrict: 'A',
templateUrl: 'app/common/directives/tmpls/remiChart.html',
scope: {
measurement: '@',
charts: '=',
chartTitle: '@',
state: '@'
},
controller: function ($scope, $element, $http, $compile, $templateCache, $filter, $location) {
var vm = $scope;
vm.measurementData = undefined;
vm.fillmeasurementData = fillmeasurementData;
vm.changePage = changePage;
vm.changePageSize = changePageSize;
vm.index = index;
vm.pagesNumber = pagesNumber;
vm.toggleSample = toggleSample;
vm.loadedContextMenuTemplate = loadedContextMenuTemplate;
vm.turnOnPopupWindow = turnOnPopupWindow;
vm.parseTemplate = parseTemplate;
vm.loadedContextMenuTemplate = loadedContextMenuTemplate;
vm.allowManage = {
pageNumber: { up: false, down: false },
pageSize: { down: false }
};
vm.tableData = undefined;
vm.busy = false;
vm.pages = 1;
vm.page = 1;
vm.pageSize = 20;
vm.table = "Hide";
vm.$parent.$watch(vm.measurement, function (val) {
vm.measurements = $filter('orderBy')(val, 'ReleaseWindow.StartTime');
vm.fillmeasurementData();
}, true);
vm.$parent.$watch(vm.state, function (val) {
vm.busy = val;
}, true);
vm.turnOnPopupWindow();
$scope.$on('$destroy', function () {
$(document).unbind('click', vm.documentClickHandler);
if (vm.$chartContextMenu) {
vm.$chartContextMenu.hide();
vm.$chartContextMenu.remove();
}
vm.$chartContextMenu = null;
});
vm.options = {
chart: {
type: 'lineChart',
height: 350,
margin: {
top: 20,
right: 65,
bottom: 60,
left: 65
},
x: function (d) {
return d[0];
},
y: function (d) {
return d[1];
},
color: d3.scale.category10().range(),
useInteractiveGuideline: true,
xAxis: {
tickFormat: function (d) {
if (d == parseInt(d) && vm.measurements) {
var comment;
var m = vm.measurements[d];
if (m) {
comment = moment(new Date(m.ReleaseWindow.StartTime)).format('DD/MM/YY');
return comment;
}
}
return '';
},
showMaxMin: true
},
yAxis: {
axisLabel: 'Duration, minutes',
axisLabelDistance: 30
},
forceY: [0],
callback: function () {
d3.selectAll('.nvd3.nv-legend g').style('fill', "red");
d3.selectAll('.nv-group circle').style('cursor', 'pointer');
d3.selectAll('.nv-group circle').on('click', function () {
if (!vm.$chartContextMenu) return;
var circleData = d3.select(this).data();
if (circleData && circleData.length >= 0 && circleData[0].length >= 3) {
var releaseWindowId = circleData[0][2];
vm.clickOnReleaseWindowExternalId = releaseWindowId;
var br = getOffsetRect(d3.select(this)[0][0]);
$(document).unbind('click', vm.documentClickHandler);
$(vm.$chartContextMenu)
.data('ExternalId', releaseWindowId)
.css({ left: br.left, top: br.top })
.show();
setTimeout(function () {
$(document).bind('click', vm.documentClickHandler);
}, 200);
}
});
}
}
};
function fillmeasurementData() {
if (vm.measurements) {
vm.pages = vm.pagesNumber();
vm.allowManage.pageNumber.up = vm.page < vm.pages;
vm.allowManage.pageNumber.down = vm.page > 1;
vm.allowManage.pageSize.down = vm.pageSize > 1;
if (vm.charts && vm.charts.length == 0 && vm.measurements.length > 0) {
//populate columns if they empty
var columns = [];
var metrics = vm.measurements[0].Metrics;
for (var i = 0; i < metrics.length; i++) {
columns.push(metrics[i].Name);
}
vm.charts = columns;
}
vm.measurementData = [];
for (var m = 0; m < vm.charts.length; m++) {
vm.measurementData.push({
key: vm.charts[m],
values: []
});
}
var finish = vm.measurements.length - (vm.page - 1) * vm.pageSize;
var start = finish <= vm.pageSize ? 0 : finish - vm.pageSize;
vm.tableData = [];
for (var counter = start; counter < finish; counter++) {
vm.tableData[counter - start] = [];
for (var c = 0; c < vm.charts.length; c++) {
vm.measurementData[c].values
.push([
counter,
vm.measurements[counter]
.Metrics
.filter(function (x) {
return x.Name == vm.charts[c];
})[0].Value,
vm.measurements[counter].ReleaseWindow.ExternalId
]);
}
vm.tableData[counter - start] = {
values: [],
window: vm.measurements[counter].ReleaseWindow
};
for (var v = 0; v < vm.charts.length; v++) {
vm.tableData[counter - start].values.push(
vm.measurements[counter].Metrics.filter(function (item) {
return item.Name == vm.charts[v];
})[0].Value);
}
}
}
}
function getOffsetRect(elem) {
var box = elem.getBoundingClientRect();
var body = document.body;
var docElem = document.documentElement;
var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
var clientTop = docElem.clientTop || body.clientTop || 0;
var clientLeft = docElem.clientLeft || body.clientLeft || 0;
var top = box.top + scrollTop - clientTop;
var left = box.left + scrollLeft - clientLeft;
return { top: Math.round(top), left: Math.round(left) };
}
function turnOnPopupWindow() {
if (!vm.$chartContextMenu) {
vm.loadedContextMenuTemplate();
}
vm.documentClickHandler = function (e) {
$(vm.$chartContextMenu).hide();
$(document).unbind('click', vm.documentClickHandler);
};
vm.clickOnReleaseWindowExternalId = undefined;
vm.navigateToReleaseExecution = function () {
if (vm.clickOnReleaseWindowExternalId) {
$location.path('/releasePlan').search({ 'releaseWindowId': vm.clickOnReleaseWindowExternalId, 'tab': 'execution' });
}
};
}
function loadedContextMenuTemplate() {
var templ = $templateCache.get('remiChartContextMenu.html');
if (!templ) {
$http({ method: 'GET', url: 'app/common/directives/tmpls/remiChartContextMenu.html' })
.success(function (data) {
$templateCache.put('remiChartContextMenu.html', data);
parseTemplate(data);
});
} else {
parseTemplate(templ);
}
};
function parseTemplate(content) {
var el = $(content);
$('body').append(el);
el.find('a').bind('click', function (e) {
e.preventDefault();
$scope.$apply(function () {
vm.navigateToReleaseExecution();
vm.$chartContextMenu.hide();
});
});
$scope.$chartContextMenu = $compile(el)($scope);
};
function pagesNumber() {
if (vm.measurements) {
return (vm.measurements.length % vm.pageSize) == 0 ?
vm.measurements.length / vm.pageSize :
parseInt((vm.measurements.length / vm.pageSize) + 1);
}
return 0;
}
function changePage(par) {
if ((par >= 1) && (par <= vm.pages)) {
vm.page = par;
vm.fillmeasurementData();
}
}
function changePageSize(par) {
if ((par >= 1)) {
vm.pageSize = par;
vm.page = 1;
vm.fillmeasurementData();
}
}
function toggleSample() {
if (vm.table == 'Show') {
vm.table = 'Hide';
} else {
vm.table = 'Show';
}
}
function index($index) {
return $index + 1 + ((vm.page - 1) * vm.pageSize);
}
}
};
}
})()
|
/**
* Test ValidateNotEmpty
*/
Tinytest.add('ValidateNotEmpty returns true', function (test) {
var v = new ValidateNotEmpty();
test.equal(true, v.validate('wow'));
});
Tinytest.add('ValidateNotEmpty returns message', function (test) {
var v = new ValidateNotEmpty();
test.equal('Please enter some text', v.validate(''));
});
Tinytest.add('ValidateNotEmpty returns custom message', function (test) {
var v = new ValidateNotEmpty();
test.equal('custom message', v.validate('', 'custom message'));
});
|
// flow-typed signature: d8f46a9244d16065ff75ce08ca6c3726
// flow-typed version: <<STUB>>/react-transition-group_v^2.2.0/flow_v0.52.0
/**
* This is an autogenerated libdef stub for:
*
* 'react-transition-group'
*
* 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 'react-transition-group' {
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 'react-transition-group/CSSTransition' {
declare module.exports: any;
}
declare module 'react-transition-group/dist/react-transition-group' {
declare module.exports: any;
}
declare module 'react-transition-group/dist/react-transition-group.min' {
declare module.exports: any;
}
declare module 'react-transition-group/Transition' {
declare module.exports: any;
}
declare module 'react-transition-group/TransitionGroup' {
declare module.exports: any;
}
declare module 'react-transition-group/utils/ChildMapping' {
declare module.exports: any;
}
declare module 'react-transition-group/utils/PropTypes' {
declare module.exports: any;
}
declare module 'react-transition-group/utils/SimpleSet' {
declare module.exports: any;
}
// Filename aliases
declare module 'react-transition-group/CSSTransition.js' {
declare module.exports: $Exports<'react-transition-group/CSSTransition'>;
}
declare module 'react-transition-group/dist/react-transition-group.js' {
declare module.exports: $Exports<'react-transition-group/dist/react-transition-group'>;
}
declare module 'react-transition-group/dist/react-transition-group.min.js' {
declare module.exports: $Exports<'react-transition-group/dist/react-transition-group.min'>;
}
declare module 'react-transition-group/index' {
declare module.exports: $Exports<'react-transition-group'>;
}
declare module 'react-transition-group/index.js' {
declare module.exports: $Exports<'react-transition-group'>;
}
declare module 'react-transition-group/Transition.js' {
declare module.exports: $Exports<'react-transition-group/Transition'>;
}
declare module 'react-transition-group/TransitionGroup.js' {
declare module.exports: $Exports<'react-transition-group/TransitionGroup'>;
}
declare module 'react-transition-group/utils/ChildMapping.js' {
declare module.exports: $Exports<'react-transition-group/utils/ChildMapping'>;
}
declare module 'react-transition-group/utils/PropTypes.js' {
declare module.exports: $Exports<'react-transition-group/utils/PropTypes'>;
}
declare module 'react-transition-group/utils/SimpleSet.js' {
declare module.exports: $Exports<'react-transition-group/utils/SimpleSet'>;
}
|
const elm = document.createElement('h1');
elm.textContent = 'index.js';
document.body.append(elm);
|
requirejs.config({
baseUrl : "./scripts" //paths/shim use this as starting point
,packages : ["controllers","services","directives","filters"] //folders contain solution's files, entry point is main.js in each folder
,paths : {
app : "app"
//custom modules
,"angular-modules" : "angular-modules"
//lib
,"angular" : "../node_modules/angular/angular"
,"angular-animate" : "../node_modules/angular-animate/angular-animate"
,"angular-resource" : "../node_modules/angular-resource/angular-resource"
,"angular-route" : "../node_modules/angular-route/angular-route"
,"angular-ui-router" : "../node_modules/angular-ui-router/angular-ui-router"
},
// priority : ['angular'],
shim : { //set a load train...choo choo
angular : { exports : 'angular'}
,"angular-animate" : { deps : ["angular"], exports : "angular-animate"}
,"angular-resource" : { deps : ["angular"], exports : "angular-resource"}
,"angular-route" : { deps : ["angular"], exports : "angular-route"}
,"angular-ui-route" : { deps : ["angular"], exports : "angular-ui-route"}
,bootstrap : {
deps : ['angular-modules','app']
}
}
}); |
import { connect } from "react-redux"
import { projectsActions, pointsActions } from "../../src/actions"
import * as selectors from "../../src/selectors"
import SidebarPoint from "./SidebarPoint"
const mapStateToProps = (state, props) => ({
gridStep: selectors.gridStepSelector(state, props),
activePoints: selectors.activePointsSelector(state, props),
point: selectors.pointSelector(state, props),
previousPoint: selectors.previousPointSelector(state, props),
})
const mapDispatchToProps = (dispatch, props) => ({
onCodeChange(pointId, code, parameters) {
dispatch(projectsActions.update(props.project.id))
dispatch(pointsActions.setPointCode(pointId, code))
dispatch(pointsActions.setPointParameters(pointId, parameters))
},
onXPositionChange(pointId, x) {
dispatch(projectsActions.update(props.project.id))
dispatch(pointsActions.setPointX(pointId, x))
},
onYPositionChange(pointId, y) {
dispatch(projectsActions.update(props.project.id))
dispatch(pointsActions.setPointY(pointId, y))
},
onParamsChange(pointId, parameters) {
dispatch(projectsActions.update(props.project.id))
dispatch(pointsActions.setPointParameters(pointId, parameters))
},
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(SidebarPoint)
|
/*jslint node: true */
'use strict';
var validators = require('../lib/forms').validators;
var async = require('async');
var test = require('tape');
test('matchField', function (t) {
var v = validators.matchField('field1', 'f2 dnm %s'),
data = {
fields: {
field1: {data: 'one'},
field2: {data: 'two'}
}
};
t.plan(2);
v(data, data.fields.field2, function (err) {
t.equal(err, 'f2 dnm field1');
data.fields.field2.data = 'one';
v(data, data.fields.field2, function (err) {
t.equal(err, undefined);
t.end();
});
});
});
test('matchValue', function (t) {
var data = {
fields: {
field1: { data: 'one' }
}
};
t.test('passes when matching the value', function (st) {
var getter = function () { return 'one'; }
var v = validators.matchValue(getter, 'name: %s | value: %s');
st.plan(1);
v(data, data.fields.field1, function (err) {
st.equal(err, undefined);
st.end();
});
});
t.test('fails when not matching the value', function (st) {
var getter = function () { return 'NOPE FAILURE'; }
var v = validators.matchValue(getter, 'name: %s | value: %s');
st.plan(1);
v(data, data.fields.field1, function (err) {
st.equal(err, 'name: This field | value: NOPE FAILURE');
st.end();
});
});
t.test('fails when not provided a function', function (st) {
var nonFunctions = [undefined, null, 42, /a/g, 'foo', [], {}];
st.plan(nonFunctions.length);
nonFunctions.forEach(function (nonFunction) {
st.throws(function () { validators.matchValue(nonFunction); }, TypeError, nonFunction + ' is not a function');
});
st.end();
});
t.end();
});
test('required', function (t) {
t.plan(3);
var v = validators.required();
var emptyFields = { field: { name: 'field', data: '' } };
var whitespaceFields = { field: { name: 'field', data: ' ' } };
var filledFields = { field: { name: 'field', data: 'foo' } };
v({ fields: emptyFields }, emptyFields.field, function (err) {
t.equal(err, 'field is required.');
v({ fields: whitespaceFields }, whitespaceFields.field, function (err) {
t.equal(err, 'field is required.');
v({ fields: filledFields }, filledFields.field, function (err) {
t.equal(err, undefined);
t.end();
});
});
});
});
test('requiresFieldIfEmpty', function (t) {
t.plan(4);
var v = validators.requiresFieldIfEmpty('alternate_field', 'field 1: %s field2: %s'),
empty_fields = {
field: {name: 'field', data: ' '},
alternate_field: {name: 'alternate_field', data: ''}
},
filled_fields = {
field: {name: 'field', data: 'filled'},
alternate_field: {name: 'alternate_field', data: 'also filled'}
},
first_filled = {
field: {name: 'field', data: 'filled'},
alternate_field: {name: 'alternate_field', data: ''}
},
second_filled = {
field: {name: 'field', data: ''},
alternate_field: {name: 'alternate_field', data: 'filled'}
};
v({ fields: empty_fields }, empty_fields.field, function (err) {
t.equal(err, 'field 1: field field2: alternate_field');
v({ fields: filled_fields }, filled_fields.field, function (err) {
t.equal(err, undefined);
v({ fields: first_filled }, first_filled.field, function (err) {
t.equal(err, undefined);
v({ fields: second_filled }, second_filled.field, function (err) {
t.equal(err, undefined);
t.end();
});
});
});
});
});
test('min', function (t) {
t.plan(2);
validators.min(100, 'Value must be greater than or equal to %s.')('form', {data: 50}, function (err) {
t.equal(err, 'Value must be greater than or equal to 100.');
validators.min(100)('form', {data: 100}, function (err) {
t.equal(err, undefined);
t.end();
});
});
});
test('max', function (t) {
t.plan(2);
validators.max(100, 'Value must be less than or equal to %s.')('form', {data: 150}, function (err) {
t.equal(err, 'Value must be less than or equal to 100.');
validators.max(100)('form', {data: 100}, function (err) {
t.equal(err, undefined);
t.end();
});
});
});
test('range', function (t) {
t.plan(2);
validators.range(10, 20, 'Value must be between %s and %s.')('form', {data: 50}, function (err) {
t.equal(err, 'Value must be between 10 and 20.');
validators.range(10, 20)('form', {data: 15}, function (err) {
t.equal(err, undefined);
t.end();
});
});
});
test('regexp', function (t) {
t.plan(3);
validators.regexp(/^\d+$/)('form', {data: 'abc123'}, function (err) {
t.equal(err, 'Invalid format.');
validators.regexp(/^\d+$/)('form', {data: '123'}, function (err) {
t.equal(err, undefined);
var v = validators.regexp('^\\d+$', 'my message');
v('form', {data: 'abc123'}, function (err) {
t.equal(err, 'my message');
t.end();
});
});
});
});
test('email', function (t) {
t.plan(3);
validators.email('Email was invalid.')('form', {data: 'asdf'}, function (err) {
t.equal(err, 'Email was invalid.');
var v = validators.email();
v('form', {data: 'asdf@asdf.com'}, function (err) {
t.equal(err, undefined);
v('form', {data: 'a←+b@f.museum'}, function (err) {
t.equal(err, undefined);
t.end();
});
});
});
});
test('url', function (t) {
t.plan(4);
validators.url(false, 'URL was invalid.')('form', {data: 'asdf.com'}, function (err) {
t.equal(err, 'URL was invalid.');
validators.url()('form', {data: 'http://asdf.com'}, function (err) {
t.equal(err, undefined);
});
});
validators.url(true)('form', {data: 'localhost/test.html'}, function (err) {
t.equal(err, 'Please enter a valid URL.');
validators.url(true)('form', {data: 'http://localhost/test.html'}, function (err) {
t.equal(err, undefined);
});
});
t.end();
});
test('date', function (t) {
t.plan(4);
validators.date('Date input must contain a valid date.')('form', {data: '02/28/2012'}, function (err) {
t.equal(err, 'Date input must contain a valid date.');
validators.date()('form', {data: '2012-02-28'}, function (err) {
t.equal(err, undefined);
});
});
validators.date()('form', {data: '2012.02.30'}, function (err) {
t.equal(err, 'Inputs of type "date" must be valid dates in the format "yyyy-mm-dd"');
validators.date()('form', {data: '2012-02-30'}, function (err) {
t.equal(err, undefined);
});
});
t.end();
});
test('minlength', function (t) {
t.plan(2);
validators.minlength(5, 'Enter at least %s characters.')('form', {data: '1234'}, function (err) {
t.equal(err, 'Enter at least 5 characters.');
validators.minlength(5)('form', {data: '12345'}, function (err) {
t.equal(err, undefined);
t.end();
});
});
});
test('maxlength', function (t) {
t.plan(2);
validators.maxlength(5)('form', {data: '123456'}, function (err) {
t.equal(err, 'Please enter no more than 5 characters.');
validators.maxlength(5)('form', {data: '12345'}, function (err) {
t.equal(err, undefined);
t.end();
});
});
});
test('rangelength', function (t) {
t.plan(4);
validators.rangelength(2, 4, 'Enter between %s and %s characters.')('form', {data: '12345'}, function (err) {
t.equal(err, 'Enter between 2 and 4 characters.');
});
validators.rangelength(2, 4)('form', {data: '1'}, function (err) {
t.equal(err, 'Please enter a value between 2 and 4 characters long.');
});
validators.rangelength(2, 4)('form', {data: '12'}, function (err) {
t.equal(err, undefined);
});
validators.rangelength(2, 4)('form', {data: '1234'}, function (err) {
t.equal(err, undefined);
});
t.end();
});
test('color', function (t) {
t.test('valid colors', function (st) {
var v = validators.color();
var valids = ['#ABC', '#DEF123', '#ABCDEF12', '#01234567', '#890'];
st.plan(valids.length);
valids.forEach(function (color) {
v('form', { data: color }, function (err) {
st.equal(err, undefined);
});
});
st.end();
});
t.test('invalid colors', function (st) {
var invalids = ['ABC', 'DEF123', '#ABCDEG', '#0123.3', null, true, false];
st.plan(invalids.length);
var msg = 'Color inputs require hex notation.';
var v = validators.color(msg);
invalids.forEach(function (color) {
v('form', { data: color }, function (err) {
st.equal(err, msg);
});
});
st.end();
});
t.end();
});
test('alphanumeric', function (t) {
var v = validators.alphanumeric();
t.test('valid input', function (st) {
var valids = ['asdf', '278', '123abc'];
st.plan(valids.length);
valids.forEach(function (input) {
v('form', { data: input }, function (err) {
st.equal(err, undefined);
});
});
st.end();
});
t.test('valid with extra spaces', function (st) {
var almostValids = [' qwer', ' 1 ', 'abc123 '];
st.plan(almostValids.length);
almostValids.forEach(function (input) {
v('form', { data: input }, function (err) {
st.equal(err, 'Letters and numbers only.');
});
});
st.end();
});
t.test('invalid', function (st) {
var invalids = ['d%d', 'c!c', 'b_b', 'a-a'];
st.plan(invalids.length);
invalids.forEach(function (input) {
v('form', { data: input }, function (err) {
st.equal(err, 'Letters and numbers only.');
});
});
st.end();
});
t.end();
});
test('nonFormatMessage1', function (t) {
t.plan(2);
var v = validators.matchField('field1', 'f2 dnm f1'),
data = {
fields: {
field1: {data: 'one'},
field2: {data: 'two'}
}
};
v(data, data.fields.field2, function (err) {
t.equals(err, 'f2 dnm f1');
data.fields.field2.data = 'one';
v(data, data.fields.field2, function (err) {
t.equals(err, undefined);
t.end();
});
});
});
test('nonFormatMessage2', function (t) {
t.plan(2);
var v = validators.min(100, '1234567890');
v('form', {data: 50}, function (err) {
t.equals(err, '1234567890');
validators.min(100)('form', {data: 100}, function (err) {
t.equals(err, undefined);
t.end();
});
});
});
test('nonFormatMessage3', function (t) {
t.plan(2);
var v = validators.minlength(5, 'qwertyuiop');
v('form', {data: '1234'}, function (err) {
t.equals(err, 'qwertyuiop');
validators.minlength(5)('form', {data: '12345'}, function (err) {
t.equals(err, undefined);
t.end();
});
});
});
test('integer', function (t) {
var v = validators.integer();
t.test('valid integers', function (st) {
var valids = ['1', '10', '-1', '-10', '-10'];
st.plan(valids.length);
valids.forEach(function (input) {
v('form', { data: input }, function (err) {
st.equal(err, undefined);
});
});
st.end();
});
t.test('invalid integers', function (st) {
var invalids = ['1.5', 'one', '1,5', 'FFFFF', '+10'];
var msg = 'Please enter an integer value.';
st.plan(invalids.length);
invalids.forEach(function (input) {
v('form', { data: input }, function (err) {
st.equal(err, msg);
});
});
st.end();
});
t.end();
});
test('digits', function (t) {
var v = validators.digits();
t.test('valid digits', function (st) {
var valids = ['1', '10', '100'];
st.plan(valids.length);
valids.forEach(function (input) {
v('form', { data: input }, function (err) {
st.equal(err, undefined);
});
});
st.end();
});
t.test('invalid digits', function (st) {
var invalids = ['-1', '+10', 'one', '1.5'];
var msg = 'Numbers only.';
st.plan(invalids.length);
invalids.forEach(function (input) {
v('form', { data: input }, function (err) {
st.equal(err, msg);
});
});
st.end();
});
t.end();
});
|
if (!Cache.prototype.add) {
Cache.prototype.add = function add(request) {
return this.addAll([request]);
};
}
if (!Cache.prototype.addAll) {
Cache.prototype.addAll = function addAll(requests) {
var cache = this;
// Since DOMExceptions are not constructable:
function NetworkError(message) {
this.name = 'NetworkError';
this.code = 19;
this.message = message;
}
NetworkError.prototype = Object.create(Error.prototype);
return Promise.resolve().then(function() {
if (arguments.length < 1) throw new TypeError();
// Simulate sequence<(Request or USVString)> binding:
var sequence = [];
requests = requests.map(function(request) {
if (request instanceof Request) {
return request;
}
else {
return String(request); // may throw TypeError
}
});
return Promise.all(
requests.map(function(request) {
if (typeof request === 'string') {
request = new Request(request);
}
var scheme = new URL(request.url).protocol;
if (scheme !== 'http:' && scheme !== 'https:') {
throw new NetworkError("Invalid scheme");
}
return fetch(request.clone());
})
);
}).then(function(responses) {
// TODO: check that requests don't overwrite one another
// (don't think this is possible to polyfill due to opaque responses)
return Promise.all(
responses.map(function(response, i) {
return cache.put(requests[i], response);
})
);
}).then(function() {
return undefined;
});
};
} |
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* The Tween Repeat Event.
*
* This event is dispatched by a Tween when one of the properties it is tweening repeats.
*
* This event will only be dispatched if the Tween has a property with a repeat count set.
*
* If a Tween has a `repeatDelay` set, this event will fire after that delay expires.
*
* The difference between `loop` and `repeat` is that `repeat` is a property setting,
* where-as `loop` applies to the entire Tween.
*
* Listen to it from a Tween instance using `Tween.on('repeat', listener)`, i.e.:
*
* ```javascript
* var tween = this.tweens.add({
* targets: image,
* x: 500,
* ease: 'Power1',
* duration: 3000,
* repeat: 4
* });
* tween.on('repeat', listener);
* ```
*
* @event Phaser.Tweens.Events#TWEEN_REPEAT
* @since 3.19.0
*
* @param {Phaser.Tweens.Tween} tween - A reference to the Tween instance that emitted the event.
* @param {string} key - The key of the property that just repeated.
* @param {any} target - The target that the property just repeated on.
*/
module.exports = 'repeat';
|
version https://git-lfs.github.com/spec/v1
oid sha256:2d4c2843085e1add81a58ad81c28255b3dc3887766cfc674413d2ddec9dfe7d1
size 27212
|
/****************************************
* 协同云基础
****************************************/
var CC = CC || {};
(function (u, undefined) {
u.listingThemeObject = {
//// Listing area colors for texts and backgrounds for listing items.
////item_TextColor_Hot: '#000000',//'#ffffff',
////item_TextColor_Selected: '#000000',//'#ffffff',
////item_TextColor_HotSelected: '#000000',//'#ffffff',
////item_TextColor_SelectedNoFocus: '#000000',//'#ffffff',
//item_BackgroundColor_Hot: '#b7d8f3',
//item_BackgroundColor_Selected: '#f5c779',
//item_BackgroundColor_HotSelected: '#ffe2b0',
//item_BackgroundColor_SelectedNoFocus: '#f5c779',
//// Listing area colors for texts and backgrounds for grouping headers.
//groupHeader_LabelColor: '#ffffff',
//groupHeader_LineColor: '#ffffff',
//groupHeader_ButtonTextColor: 'default',
//groupHeader_ButtonEdgeHighlightColor: 'default',
//groupHeader_ButtonHighlightColor: 'default',
//groupHeader_BackgroundColor: '#000000',
//groupHeader_BackgroundColor_Hot: '#000000',
//groupHeader_BackgroundColor_Selected: '#000000',
//groupHeader_BackgroundColor_HotSelected: '#000000',
// Listing area colors for sorting headers (main headers).
//sortableHeader_DividerColor_Inactive: '#000000',
//sortableHeader_DividerColor_Active: '#000000',
sortableHeader_BackgroundColor_Inactive: '#c9caca', //'#3589c4',
sortableHeader_BackgroundColor_Active: '#c9caca',//'#1d639d',
// The listing area background image.
//backgroundImage: '',
last: 0
};
u.commThemeObject = {
sortableHeader_BackgroundColor_Inactive: '#2276bc',
sortableHeader_BackgroundColor_Active: '#0087d1'
};
u.SetListingTheme = function(listingObj) {
listingObj.SetTheme(this.listingThemeObject);
};
u.SetCommTheme = function (listingObj) {
listingObj.SetTheme(this.commThemeObject);
};
u.getInstallPath = function (vault) {
///<summary>获取DBWorld客户端的安装路径</summary>
if (vault) {
var ns = 'DBWorld.' + vault.SessionInfo.UserID;
this._installPath = MF.vault.getNamedValue(vault, MFUserDefinedValue, ns, "InstallPath");
}
try {
this._installPath = wshUtils.readRegValue('HKCU\\Software\\DBWorld\\Client\\INSTDIR');
} catch (e) {
this._installPath = '';
}
return this._installPath;
};
u.getUserId = function(vault) {
if (this.userId === undefined) {
try {
var ns = 'DBWorld.' + vault.SessionInfo.UserID;
this.userId = MF.vault.getNamedValue(vault, MFUserDefinedValue, ns, 'DBUserId');
} catch (e) {
MFiles.ReportException(e);
this.userId = null;
}
}
return this.userId;
};
u.getUserEmail = function(vault) {
if (this.userEmail === undefined) {
try {
var ns = 'DBWorld.' + vault.SessionInfo.UserID;
this.userEmail = MF.vault.getNamedValue(vault, MFUserDefinedValue, ns, 'UserEmail');
} catch (e) {
MFiles.ReportException(e);
this.userEmail = null;
}
}
return this.userEmail;
};
u.getToken = function (vault) {
///<summary>获取token</summary>
if (this.token === undefined) {
try {
var ns = 'DBWorld.' + vault.SessionInfo.UserID;
this.token = MF.vault.getNamedValue(vault, MFUserDefinedValue, ns, 'UserToken');
} catch (e) {
MFiles.ReportException(e);
this.token = null;
}
}
return this.token;
};
u.isCloudAppEnabled = function (vault) {
///<summary>当前用户是否启用了云应用</summary>
if (this.cloudAppEnabled === undefined) {
try {
var ns = 'DBWorld.' + vault.SessionInfo.UserID;
this.cloudAppEnabled = MF.getNamedValue(vault, MFUserDefinedValue, ns, 'CloudAppEnabled');
} catch (e) {
this.cloudAppEnabled = null;
}
}
return this.cloudAppEnabled;
};
u.getProjectId = function(vault) {
///<summary>获取当前库的项目ID</summary>
if (this.projId === undefined) {
try {
var ns = 'DBWorld.' + vault.SessionInfo.UserID;
this.projId = MF.vault.getNamedValue(vault, MFUserDefinedValue, ns, 'ProjectId');
} catch (e) {
MFiles.ReportException(e);
this.projId = null;
}
}
return this.projId;
};
// mfAlias.js, metadataAlias.js, client.js
u.getProjectName = function(vault) {
var projType = MF.alias.objectType(vault, md.proj.typeAlias);
var projClass = MF.alias.classType(vault, md.proj.classAlias);
var scs = MF.createObject('SearchConditions');
MF.vault.addBaseConditions(scs, projType, projClass, false);
var res = vault.ObjectSearchOperations.SearchForObjectsByConditions(scs, MFSearchFlagNone, false);
if (res.Count > 0) {
return res.Item(1).Title;
}
};
u.getView = function(vault, guid) {
this.views = this.views || {};
if (!this.views[guid] && this.views[guid] !== 0) {
var vId = vault.ViewOperations.GetViewIDByGUID(guid);
this.views[guid] = vId;
}
return this.views[guid];
};
u.getCloudAppUrl = function (vault) {
//云应用服务器
if (!this._cloudappHost) {
var ns = "DBWorld." + vault.SessionInfo.UserID;
var nvs = vault.NamedValueStorageOperations.GetNamedValues(MFUserDefinedValue,
ns);
this._cloudappHost = nvs.Value('CloudApp');
}
return this._cloudappHost;
//return "http://192.168.2.101";
//return "http://211.152.38.103";
//return "http://vapp.dbworld.cn";
};
})(CC);
/*****************************
* 获取当前用户的项目角色
*****************************/
var CC = CC || {};
(function (u, undefined) {
var role = {
//判断是否设总
isChiefDesigner: function(vault) {
var ugId = MF.alias.usergroup(vault, md.userGroups.ChiefDesigner);
return this.hasRole(vault, ugId);
},
//判断是否项目经理
isPM: function (vault) {
var ugId = MF.alias.usergroup(vault, md.userGroups.PM);
return this.hasRole(vault, ugId);
},
//项目副理
isVicePM: function (vault) {
var ugId = MF.alias.usergroup(vault, md.userGroups.VicePM);
return this.hasRole(vault, ugId);
},
//一般成员
isMember: function (vault) {
var ugId = MF.alias.usergroup(vault, md.userGroups.Member);
return this.hasRole(vault, ugId);
},
//外包成员
isOutsourceMember: function (vault) {
var ugId = MF.alias.usergroup(vault, md.userGroups.Outsource);
return this.hasRole(vault, ugId);
},
//是否包含某角色: ugId,角色对应的用户组
hasRole: function (vault, ugId) {
var flag = false;
var ugs = this._getUserGroups(vault);
for (var i = 0; i < ugs.length; i++) {
if (ugs[i] === ugId) {
flag = true;
break;
}
}
return flag;
},
_getUserGroups: function (vault) {
this.groups = this.groups || [];
if (this.groups.length == 0) {
var ugs = vault.SessionInfo.UserAndGroupMemberships;
for (var i = 1; i <= ugs.Count; i++) {
var ug = ugs.Item(i);
if (ug.UserOrGroupType === MFUserOrUserGroupTypeUserGroup && ug.UserOrGroupID > 100) {
this.groups.push(ug.UserOrGroupID);
}
}
}
return this.groups;
}
};
u.userRole = role;
})(CC); |
version https://git-lfs.github.com/spec/v1
oid sha256:788e819fbb07f073e1ec84dc8b2a4c938537107f7c7759f6f59e2faa9b1bf386
size 2401
|
function outputa(msg) {
alert(msg);
}
function outputb(isTrue, msg) {
if (isTrue) {
alert(msg);
} else {
alert(10.00 + 20.00 * (300 + 400));
}
}
|
// api/services/protocols/openid.js
var _ = require('lodash');
var _super = require('sails-permissions/api/services/protocols/openid');
function protocols () { }
protocols.prototype = Object.create(_super);
_.extend(protocols.prototype, {
// Extend with custom logic here by adding additional fields and methods,
// and/or overriding methods in the superclass.
/**
* For example:
*
* foo: function (bar) {
* bar.x = 1;
* bar.y = 2;
* return _super.foo.call(this, bar);
* }
*/
});
module.exports = new protocols();
|
export * from './get';
export * from './post';
export * from './put';
export * from './delete';
|
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { Autowired, Component, PostConstruct } from "@ag-grid-community/core";
import { HorizontalResizeComp } from "./horizontalResizeComp";
var ToolPanelWrapper = /** @class */ (function (_super) {
__extends(ToolPanelWrapper, _super);
function ToolPanelWrapper() {
return _super.call(this, ToolPanelWrapper.TEMPLATE) || this;
}
ToolPanelWrapper.prototype.getToolPanelId = function () {
return this.toolPanelId;
};
ToolPanelWrapper.prototype.setToolPanelDef = function (toolPanelDef) {
this.toolPanelId = toolPanelDef.id;
var params = {
api: this.gridOptionsWrapper.getApi(),
columnApi: this.gridOptionsWrapper.getColumnApi()
};
var componentPromise = this.userComponentFactory.newToolPanelComponent(toolPanelDef, params);
if (componentPromise == null) {
console.warn("ag-grid: error processing tool panel component " + toolPanelDef.id + ". You need to specify either 'toolPanel' or 'toolPanelFramework'");
return;
}
componentPromise.then(this.setToolPanelComponent.bind(this));
};
ToolPanelWrapper.prototype.setupResize = function () {
var resizeBar = this.resizeBar = new HorizontalResizeComp();
this.getContext().createBean(resizeBar);
resizeBar.setElementToResize(this.getGui());
this.appendChild(resizeBar);
};
ToolPanelWrapper.prototype.setToolPanelComponent = function (compInstance) {
var _this = this;
this.toolPanelCompInstance = compInstance;
this.appendChild(compInstance.getGui());
this.addDestroyFunc(function () {
_this.destroyBean(compInstance);
});
};
ToolPanelWrapper.prototype.getToolPanelInstance = function () {
return this.toolPanelCompInstance;
};
ToolPanelWrapper.prototype.setResizerSizerSide = function (side) {
var isRtl = this.gridOptionsWrapper.isEnableRtl();
var isLeft = side === 'left';
var inverted = isRtl ? isLeft : !isLeft;
this.resizeBar.setInverted(inverted);
};
ToolPanelWrapper.prototype.refresh = function () {
this.toolPanelCompInstance.refresh();
};
ToolPanelWrapper.TEMPLATE = "<div class=\"ag-tool-panel-wrapper\"/>";
__decorate([
Autowired("userComponentFactory")
], ToolPanelWrapper.prototype, "userComponentFactory", void 0);
__decorate([
PostConstruct
], ToolPanelWrapper.prototype, "setupResize", null);
return ToolPanelWrapper;
}(Component));
export { ToolPanelWrapper };
|
var class_drachenhorn_1_1_xml_1_1_objects_1_1_currency_part =
[
[ "Convert", "class_drachenhorn_1_1_xml_1_1_objects_1_1_currency_part.html#ae0572201079dd9e99e2b7fc93c875f76", null ],
[ "Parse", "class_drachenhorn_1_1_xml_1_1_objects_1_1_currency_part.html#adc93a864bd894b06fdcabf1e91121cfb", null ],
[ "ToString", "class_drachenhorn_1_1_xml_1_1_objects_1_1_currency_part.html#a99f4e4e8770436d65894560de21d0455", null ],
[ "Name", "class_drachenhorn_1_1_xml_1_1_objects_1_1_currency_part.html#a1ae45cc2d84578ace865839ef164e6d7", null ],
[ "Symbol", "class_drachenhorn_1_1_xml_1_1_objects_1_1_currency_part.html#a60971bd59f95d3a6e74dba13817b0a79", null ],
[ "Value", "class_drachenhorn_1_1_xml_1_1_objects_1_1_currency_part.html#a9f36987c56d0a5147c605dfff01bb478", null ]
]; |
(function () {
"use strict";
angular.module('astInterpreter')
.factory('l9.treeFactory', function(){
function Tree(element) {
this.element = element;
this.subTrees = [];
for(var x = 1; x < arguments.length; x++) {
if (arguments[x] !== null) {
this.subTrees.push(arguments[x]);
}
}
this.addSubTree = function(tree) {
this.subTrees.push(tree);
}
this.getSubTree = function(index) {
return this.subTrees[index];
}
this.degree = function() {
return this.subTrees.length;
}
this.depth = function() {
var result = 0;
if (this.degree() > 0) {
var max = 0;
for(var y = 0; y < this.degree(); y++) {
var temp = this.getSubTree(y).depth();
if (temp > max) {
max = temp;
}
}
result = 1 + max;
}
return result;
}
this.toString = function() {
var result = "";
if (this.subTrees == []) {
result += element;
}
else {
result += "(" + this.element;
for(var z = 0; z < this.subTrees.length; z++) {
result += " " + this.subTrees[z];
}
result += ")";
}
return result;
}
}
return {
"Tree": Tree
};
});
})();
|
// 1. load bars stacked beside eachother.
// 2. only one full-width load bar appears each slide.
// 3. no load bars just dots.
// 4. video background.
// 5. one back ground.
"use strict";
/*
Plugin: jQuery AnimateSlider
Version 1.0.0
Author: John John
*/
(function($) {
$.fn.animateSlider = function(slideDur) {
this.each(function() {
var $container = $(this);
//Json Object for container
$container[0].faderConfig = {};
//Private vars
var slideSelector = ".slide", //Slide selector
slideTimer, //Timeout
activeSlide, //Index of active slide
newSlide, //Index of next or prev slide
$slides = $container.find(slideSelector), //All slides
totalSlides = $slides.length, //Nb of slides
config = $container[0].faderConfig; //Configuration
// change background function
function changeBG() {
if ($container.attr("data-background-1")) {
$(".as-background").each(function() {
var indexOfSlide = $(this).data("slide-num");
if (newSlide == (indexOfSlide)) {
$(this).css("opacity", 1).addClass("active-as-background");
} else {
$(this).css("opacity", 0).removeClass("active-as-background");
}
});
}
}
config = {
slideDur: slideDur
};
// make active dots function
function activDot() {
$(".as-indicator").each(function() {
var indexOfSlide = $(this).data("slide-number");
if (newSlide == indexOfSlide) {
$(this).addClass("active");
} else {
$(this).removeClass("active");
}
});
}
function progress(percent, $element) {
if (!$container.hasClass("show-indicators")) {
var progressBarPercent = percent * $element.width() / 100;
$element.find("span").animate({
width: progressBarPercent
}, slideDur);
}
}
slideTimer = setTimeout(function() {
changeSlides("next");
}, config.slideDur);
/**
* Function to change slide
* @param {type} target, next ou prev
* @returns {undefined}
*/
function changeSlides(target) {
//If want to forward
if (target === "next") {
//index of next slide
newSlide = activeSlide + 1;
if (newSlide > totalSlides - 1) {
newSlide = 0;
$(".as-indicator .as-load-bar").stop().width(0);
}
} else if (target === "prev") {
newSlide = activeSlide - 1;
if (newSlide < 0) {
newSlide = totalSlides - 1;
}
} else {
newSlide = target;
}
$(".slide" + newSlide).find(".as-load-bar").width(0);
$(".slide" + activeSlide).find(".as-load-bar").stop().width(0);
if (newSlide < totalSlides) {
$(".slide" + newSlide).prevAll().each(function(index, element) {
$(element).find(".as-load-bar").stop().css("width", "100%");
});
}
animateSlides(activeSlide, newSlide);
// active the curret dot
changeBG();
activDot();
}
if (!$container.hasClass("single-loadbar")) {
var fireEventProgressBar = false;
//Change slide by clicking on progress bar
$("body").delegate(".as-indicator", "click", function() {
if (!fireEventProgressBar) {
//To avoid spam clicks
fireEventProgressBar = true;
setTimeout(function() {
fireEventProgressBar = false;
}, 1000);
$this = $(this);
$this.find(".as-load-bar").stop().width(0);
var indexOfSlide = $this.data("slide-number");
if (indexOfSlide > activeSlide) {
$this.prevAll().each(function(index, element) {
$(element).find(".as-load-bar").stop().css("width", "100%");
});
} else if (indexOfSlide < activeSlide) {
$this.nextAll().each(function(index, element) {
$(element).find(".as-load-bar").stop().width(0);
});
}
newSlide = indexOfSlide;
changeBG();
// active the curret dot
activDot();
clearTimeout(slideTimer);
animateSlides(activeSlide, newSlide);
}
});
slideTimer;
}
var arrows = $container.find(".as-nav-arrows .as-arrow");
if (arrows.length) {
var fireEventArrow = false;
arrows.on("click", function() {
if (!fireEventArrow) {
fireEventArrow = true;
setTimeout(function() {
fireEventArrow = false;
}, 1000);
var target = $(this).data("target");
clearTimeout(slideTimer);
changeSlides(target);
}
});
slideTimer;
}
/**
* Animation of slides
* @param {type} indexOfActiveSlide
* @param {type} indexOfnewSlide
* @returns {undefined}
*/
function animateSlides(indexOfActiveSlide, indexOfnewSlide) {
$slides.eq(indexOfActiveSlide).css("z-index", 5);
var childsOfSlide = $slides.eq(indexOfActiveSlide).children();
$(childsOfSlide).each(function(index, element) {
if (typeof $(element).data("effect-in") !== "undefined" && typeof $(element).data("effect-out") !== "undefined") {
$(element).removeClass($(element).data("effect-in") + " animated");
$(element).addClass($(element).data("effect-out") + " animated slide-out");
} else {
$(element).children().each(function(index, child) {
if (typeof $(child).data("effect-in") !== "undefined" && typeof $(child).data("effect-out") !== "undefined") {
$(child).removeClass($(child).data("effect-in") + " animated");
$(child).addClass($(child).data("effect-out") + " animated slide-out");
}
});
}
});
$slides.eq(indexOfActiveSlide).delay(700).queue(function(next) {
$(this).css("opacity", 0);
activeSlide = indexOfnewSlide;
$slides.eq(indexOfActiveSlide).removeAttr("style");
showSlide($slides.eq(indexOfnewSlide), indexOfnewSlide);
waitForNext();
next();
});
}
//Whait for next slide
function waitForNext() {
slideTimer = setTimeout(function() {
changeSlides("next");
}, config.slideDur);
}
/**
* Show slides
* @param {type} $element
* @returns {undefined}
*/
function showSlide($element, indexOfNewSlide) {
//Animate progress bar
progress(100, $(".slide" + indexOfNewSlide));
$element.children().each(function(index, element) {
$(element).delay(200).queue(function(next) {
if (typeof $(this).data("effect-out") !== "undefined") {
$(this).removeClass($(this).data("effect-out") + " animated slide-out");
} else {
$(this).children().each(function(index, child) {
$(child).removeClass($(child).data("effect-out") + " animated slide-out");
});
}
$element.css({
"z-index": 4,
"opacity": 1
});
if (typeof $(this).data("effect-in") !== "undefined") {
$(this).stop(true, true).addClass($(this).data("effect-in") + " animated");
} else {
$(this).children().each(function(i, child) {
$(child).stop(true, true).addClass($(child).data("effect-in") + " animated");
});
}
next();
});
});
}
// $container.find(".slide").mouseenter(function() {
// clearTimeout(slideTimer);
// }).mouseleave(function() {
// setTimeout(function() {
// //index of next slide
// newSlide = activeSlide + 1;
// if (newSlide > totalSlides - 1) {
// newSlide = 0;
// $(".as-indicator .as-load-bar").stop().width(0);
// }
// animateSlides(activeSlide, newSlide);
// slideTimer;
// changeBG();
// // active the curret dot
// activDot();
// }, slideDur);
// });
/*Build progress bar for slides*/
for (var i = 0; i < totalSlides; i++) {
var htmlProgressBar = "<div class='as-indicator slide" + i + "' data-slide-number='" + i + "'><span class='as-load-bar'></span></div>";
$(".as-indicators").append(htmlProgressBar);
}
// var dotWidth = 100/totalSlides;
if ($container.hasClass("alltogether-loadbars")) {
$(".as-indicator").width((100 / totalSlides) - 4 + "%");
}
if ($container.attr("data-background-1")) {
for (var i = 0; i < totalSlides; i++) {
var background = $container.attr("data-background-" + i),
fakeBackground = "<div class='as-background' data-slide-num='" + i + "' style='background-image: url(" + background + ")'></div>";
$container.append(fakeBackground);
}
}
// start progress the first slide
//Opacity for first element
$slides.eq(0).css({
"opacity": 1,
"z-index": 4
});
activeSlide = 0;
progress(100, $(".slide" + activeSlide));
newSlide = 0;
changeBG();
activDot();
});
};
})(jQuery);
|
/**
* Namespace of the Thread.js library.
* @namespace thread
*/
// Calls the toString method to determine the
// type of the object.
function typeOf(value) {
return Object.prototype.toString.call(value).slice(8, -1);
}
// Regular expression that matches native Error constructors.
var ERROR_REGEX = /^(?:Eval|Range|Reference|Syntax|Type|URI)?Error$/,
// Regular expression that matches native TypedArray constructors.
TYPED_ARRAY_REGEX = /^(?:DataView|(?:(Int8|Uint8|Uint8Clamped|Int16|Uint16|Int32|Uint32|Float32|Float64)Array))$/,
// Function regular expression that checks for simple function syntax,
// and can return the argument list and the function body.
FN_REGEX = /^function[^\(]*\(([^\(\)\{\}]*)\)\s*\{((?:\s|\S)*)\}[^\}]*$/,
// Regular expression that matches the name of a function. Only works
// for functions with alphanumeric characters (which is the use here).
FN_NAME_REGEX = /^\s*function\s+(\w+)\s*\(/;
/**
* Function that does nothing, useful when a function argument
* is required but not provided.
* @method thread.emptyFn
*/
thread.emptyFn = function() {};
/**
* Checks whether the argument is a number literal or a Number object.
* @method thread.isNumber
* @param {*} value - Value to check.
* @returns {boolean} True if argument is a number.
*/
thread.isNumber = function(value) {
return typeof value === 'number' || typeOf(value) === 'Number';
};
/**
* Checks whether the argument is a string literal or a String object.
* @method thread.isString
* @param {*} value - Value to check.
* @returns {boolean} True if argument is a string.
*/
thread.isString = function(value) {
return typeof value === 'string' || typeOf(value) === 'String';
};
/**
* Checks whether the argument is a function.
* @method thread.isFunction
* @param {*} value - Value to check.
* @returns {boolean} True if argument is a function.
*/
thread.isFunction = function(value) {
return typeof value === 'function';
};
/**
* Checks whether the argument is an object, and not null.
* @method thread.isObject
* @param {*} value - Value to check.
* @returns {boolean} True if argument is an object.
*/
thread.isObject = function(value) {
return !!value && typeof value === 'object';
};
/**
* Checks whether the argument is an object literal.
* @method thread.isLiteral
* @param {*} value - Value to check.
* @returns {boolean} True if argument is an object literal.
*/
thread.isLiteral = function(value) {
return typeOf(value) === 'Object';
};
/**
* Checks whether the argument is an Error object.
* @method thread.isError
* @param {*} value - Value to check.
* @returns {boolean} True if argument is an Error.
*/
thread.isError = function(value) {
return typeOf(value) === 'Error';
};
/**
* Checks whether the argument is an ArrayBuffer object.
* @method thread.isBuffer
* @param {*} value - Value to check.
* @returns {boolean} True if argument is an ArrayBuffer.
*/
thread.isBuffer = function(value) {
return typeOf(value) === 'ArrayBuffer';
};
/**
* Checks whether the argument is a typed array object.
* @method thread.isTypedArray
* @param {*} value - Value to check.
* @returns {boolean} True if argument is a typed array.
*/
thread.isTypedArray = (function() {
if (ArrayBuffer && ArrayBuffer.isView) {
// use ArrayBuffer.isView if possible
return ArrayBuffer.isView;
} else {
return function(value) {
return thread.isObject(value) &&
// use constructor name if available
(value.constructor.name ? TYPED_ARRAY_REGEX.test(value.constructor.name) :
// use toString method otherwise,
// and fallback to instanceof for compatibility
TYPED_ARRAY_REGEX.test(typeOf(value)) || value instanceof DataView);
};
}
})();
/**
* Generates a unique identifier.
* @method thread.uuid
* @returns {number} Unique identifier.
*/
thread.uuid = (function() {
var id = 0;
return function() {
return ++id;
};
})();
|
'use strict';
var fs = require('fs');
var path = require('path');
/**
* Get a Handlebars template file out of a theme and compile it into
* a template function
*
* @param {Object} Handlebars handlebars instance
* @param {string} themeModule base directory of themey
* @param {string} name template name
* @returns {Function} template function
*/
function getTemplate(Handlebars, themeModule, name) {
try {
return Handlebars
.compile(fs.readFileSync(path.join(themeModule, name), 'utf8'));
} catch (e) {
throw new Error('Template file ' + name + ' missing');
}
}
module.exports = getTemplate;
|
'use strict';
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
// project configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
config: {
sources: 'lib',
tests: 'test'
},
jshint: {
src: [
['<%=config.sources %>']
],
options: {
jshintrc: true
}
},
release: {
options: {
tagName: 'v<%= version %>',
commitMessage: 'chore(project): release v<%= version %>',
tagMessage: 'chore(project): tag v<%= version %>'
}
},
mochaTest: {
test: {
options: {
reporter: 'spec',
require: [
'./test/expect.js'
]
},
src: ['test/**/*.js']
}
},
watch: {
test: {
files: [ '<%= config.sources %>/**/*.js', '<%= config.tests %>/**/*.js' ],
tasks: [ 'test' ]
}
},
jsdoc: {
dist: {
src: [ '<%= config.sources %>/**/*.js' ],
options: {
destination: 'docs/api',
plugins: [ 'plugins/markdown' ]
}
}
}
});
// tasks
grunt.registerTask('test', [ 'mochaTest' ]);
grunt.registerTask('auto-test', [ 'test', 'watch:test' ]);
grunt.registerTask('default', [ 'jshint', 'test', 'jsdoc' ]);
}; |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M21 6H3v12h18V6zm-2 10H5V8h14v8z" />
, 'Crop169Sharp');
|
{
load: 'Chargement des données ...',
reload: 'Chargement des données ...',
update: 'Mise à jour des données ...',
submit: 'Envoi de données ...',
save: 'Mise à jour des données ...',
destroy: 'Mise à jour des données ...'
} |
var five = require("../lib/johnny-five.js"),
board, button;
board = new five.Board();
board.on("ready", function() {
// Create a new `button` hardware instance.
// This example allows the button module to
// create a completely default instance
button = new five.Button(7);
// Inject the `button` hardware into
// the Repl instance's context;
// allows direct command line access
board.repl.inject({
button: button
});
// Button Event API
// "down" the button is pressed
button.on("down", function() {
console.log("down");
});
// "hold" the button is pressed for specified time.
// defaults to 500ms (1/2 second)
// set
button.on("hold", function() {
console.log("hold");
});
// "up" the button is released
button.on("up", function() {
console.log("up");
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:75878cad45bd534fb1b3387b254481302906d748c656e4356664cf444c127f36
size 2931
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
export * from './index.js';
export {
act,
createComponentSelector,
createHasPseudoClassSelector,
createRoleSelector,
createTestNameSelector,
createTextSelector,
getFindAllNodesFailureDescription,
findAllNodes,
findBoundingRects,
focusWithin,
observeVisibleRects,
} from 'react-reconciler/src/ReactFiberReconciler';
|
/*
* Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* sisane: The stunning micro-library that helps you to develop easily
* AJAX web applications by using Angular.js 1.x & sisane-server
* sisane is distributed under the MIT License (MIT)
* Sources at https://github.com/rafaelaznar/
*
* 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';
moduloEpisodio.controller('EpisodioPListFromPacienteController', ['$scope', '$routeParams', '$location', 'serverService', 'episodioService', '$uibModal',
function ($scope, $routeParams, $location, serverService, episodioService, $uibModal) {
$scope.fields = episodioService.getFields();
$scope.obtitle = episodioService.getObTitle();
$scope.icon = episodioService.getIcon();
$scope.ob = episodioService.getTitle();
$scope.op = "plistfrompaciente";
$scope.numpage = serverService.checkDefault(1, $routeParams.page);
$scope.rpp = serverService.checkDefault(10, $routeParams.rpp);
$scope.neighbourhood = serverService.getGlobalNeighbourhood();
$scope.order = "";
$scope.ordervalue = "";
$scope.filter = "id";
$scope.filteroperator = "like";
$scope.fechas = [];
$scope.importes = [];
$scope.filtervalue = "";
$scope.filterParams = serverService.checkNull($routeParams.filter)
$scope.orderParams = serverService.checkNull($routeParams.order)
$scope.sfilterParams = serverService.checkNull($routeParams.sfilter)
$scope.filterExpression = serverService.getFilterExpression($routeParams.filter, $routeParams.sfilter);
$scope.status = null;
$scope.debugging = serverService.debugging();
//-------------------------------------------
$scope.id_paciente = serverService.checkNull($routeParams.id_paciente)
if ($scope.id_paciente) {
serverService.promise_getOne('paciente', $scope.id_paciente).then(function (response) {
if (response.status == 200) {
if (response.data.status == 200) {
$scope.status = null;
$scope.bean = {};
$scope.bean.obj_paciente = {};
$scope.bean.obj_paciente = response.data.message;
$scope.title = "Episodios para el/la paciente " + $scope.bean.obj_paciente.name + " " + $scope.bean.obj_paciente.primer_apellido + " " + $scope.bean.obj_paciente.segundo_apellido;
} else {
$scope.status = "Error en la recepción de datos del servidor";
}
} else {
$scope.status = "Error en la recepción de datos del servidor";
}
}).catch(function (data) {
$scope.status = "Error en la recepción de datos del servidor";
});
$scope.url = $scope.ob + '/' + $scope.op + '/' + $scope.id_paciente;
$scope.urlnew = $scope.ob + '/newfrompaciente/' + +$scope.id_paciente;
if ($scope.filterExpression) {
$scope.filterExpression += "+and,id_paciente,equa," + $scope.id_paciente;
} else {
$scope.filterExpression = "and,id_paciente,equa," + $scope.id_paciente;
}
} else {
$scope.url = $scope.ob + '/' + $scope.op;
$scope.urlnew = $scope.ob + '/new';
$scope.title = "Listado de " + $scope.obtitle;
}
//-------------------------------------------
function getDataFromServer() {
serverService.promise_getCount($scope.ob, $scope.filterExpression).then(function (response) {
if (response.status == 200) {
$scope.registers = response.data.message;
$scope.pages = serverService.calculatePages($scope.rpp, $scope.registers);
if ($scope.numpage > $scope.pages) {
$scope.numpage = $scope.pages;
}
return serverService.promise_getPage($scope.ob, $scope.rpp, $scope.numpage, $scope.filterExpression, $routeParams.order);
} else {
$scope.status = "Error en la recepción de datos del servidor";
}
}).then(function (response) {
if (response.status == 200) {
$scope.page = response.data.message;
for (var i = 0; i < $scope.page.length; i++) {
$scope.fechas.push($scope.page[i].fecha);
$scope.importes.push($scope.page[i].importe);
}
console.log($scope.importes + " " + $scope.fechas);
$scope.status = "";
} else {
$scope.status = "Error en la recepción de datos del servidor";
}
}).catch(function (data) {
$scope.status = "Error en la recepción de datos del servidor";
});
}
$scope.pop = function (id, foreignObjectName, foreignContollerName, foreignViewName) {
var modalInstance = $uibModal.open({
templateUrl: 'js/' + foreignObjectName + '/' + foreignViewName + '.html',
controller: foreignContollerName,
size: 'lg',
resolve: {
id: function () {
return id;
}
}
}).result.then(function (modalResult) {
if (modalResult) {
getDataFromServer();
}
});
};
getDataFromServer();
}]);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.