code stringlengths 2 1.05M |
|---|
function test(chart) {
var point = chart.series[0].points[4],
offset = $(chart.container).offset();
// Set hoverPoint
point.onMouseOver();
chart.pointer.onContainerMouseMove({
type: 'mousemove',
pageX: point.plotX + chart.plotLeft + offset.left,
pageY: point.plotY + chart.plotTop + offset.top,
target: chart.container
});
} |
const https = require('https');
const options = {
hostname: process.argv[2],
path: '/',
method: 'GET',
headers:{
'Accept': '*/*'
}
};
const bids = [
'ZyBnHSGLqPSnhM%2F95ehFLg%3D%3D',
'UJyfMBEsf%2BXP425crU7j4w%3D%3D',
's6lgGPUqkTqvzaXJCua9lg%3D%3D',
'YaXE19Fuygtmq%2F7s5l25yQ%3D%3D',
'0qmsj78C04BSLQ6a2QRdQw%3D%3D'
];
const events = [
'error',
'pageview',
'conversion',
'lead',
'addtocart',
'search',
'buttonclick'
];
let count = 0;
const limit = parseInt(process.argv[3]);
const intervalTime = Number(process.argv[4]) ? parseInt(process.argv[4]) : Math.ceil(Math.random() * 100);
function loop(){
setTimeout(() => {
let randBID = bids[Math.floor(Math.random() * 5)];
let randEvent = events[Math.floor(Math.random() * 7)];
let eventURIString = eventSelection(randEvent);
options.path = `/?b=test_${randBID}&p=${randBID.substring(0,8)}&u=https://test.fuelx.com&t=${Date.now()}&v=1${eventURIString}`;
let request = https.request( options , (res) => {
console.log(`Status: ${res.statusCode} , Count: ${++count}`);
console.log(options.path);
if(count < limit){
loop();
}
});
request.on('error', (e) => {
console.log(`Error: ${e.message}`);
})
request.end();
}, intervalTime);
}
function eventSelection(selectedEvent){
let queryURI;
switch (selectedEvent){
case 'error':
queryURI = `&y=ex&exm=window%20is%20not%20defined`;
break;
case 'pageview':
let pageArray = [
'&y=js&l=%5B%7B%22ev%22%3A%22pageview%22%2C%22pn%22%3A%22general%22%7D%5D',
'&y=js&l=%5B%7B%22ev%22%3A%22pageview%22%2C%22pn%22%3A%22testingpage%22%7D%5D',
'&y=js&l=%5B%7B%22ev%22%3A%22pageview%22%2C%22pn%22%3A%22testingpage2%22%7D%5D'
];
queryURI = pageArray[Math.floor(Math.random() * 3)];
break;
case 'conversion':
let conversionEmail = Math.round(Math.random()) ? '&em=loadtesting%40fuelx.com' : '' ;
let products = function(l){
let productsArray = [];
for(let i = 0;i < l; i++){
let singleProd = `prod${Math.floor(Math.random() * 100000) + 100000}`;
productsArray.push(singleProd);
}
return productsArray.join('%3B');
}(Math.random() * 10 + 1);
queryURI = `&y=qs&ev=conversion&oid=${parseInt(Math.random() * 1000000000) + 100000}&ov=${(Math.random() * 1000).toFixed(2)}&pr=${products}${conversionEmail}`;
break;
case 'lead':
let businessArray = [
'BTB',
'BTC',
'website_signup'
];
let leadEmail = Math.round(Math.random()) ? '&em=loadtesting%40fuelx.com' : '' ;
queryURI = `&y=qs&ev=lead&lid=${parseInt(Math.random() * 1000000000 + 100000)}<=${businessArray[Math.floor(Math.random() * 3)]}${leadEmail}`;
break;
case 'addtocart':
queryURI = `&y=qs&ev=add_to_cart&pid=${Math.ceil(Math.random() * 100000000)}&va=${(Math.random() * 100).toFixed(2)}&qt=${parseInt((Math.random() * 10)) + 1}`;
break;
case 'search':
queryURI = '&y=qs&ev=search&kw=fuelx;load;testing;new;pixel';
break;
case 'buttonclick':
let buttonArray = [
'&y=qs&ev=button_click&bn=homepage%20signup',
'&y=qs&ev=button_click&bn=marketing%20page%20signup',
'&y=qs&ev=button_click&bn=registration'
];
queryURI = buttonArray[Math.floor(Math.random() * 3)];
break;
}
return queryURI;
}
loop();
//first 8 characters for pixelID and use the same for the bid
|
/**
* @module opcua.server
*/
import Dequeue from "dequeue";
import subscription_service from "lib/services/subscription_service";
const NotificationMessage = subscription_service.NotificationMessage;
const StatusChangeNotification = subscription_service.StatusChangeNotification;
import { StatusCodes } from "lib/datamodel/opcua_status_code";
import Enum from "lib/misc/enum";
import assert from "better-assert";
import _ from "underscore";
import AttributeIds from "lib/datamodel/attribute-ids/AttributeIds";
import { SequenceNumberGenerator } from "lib/misc/sequence_number_generator";
import { EventEmitter } from "events";
import util from "util";
import { ObjectRegistry } from "lib/misc/objectRegistry";
import MonitoredItem from "lib/server/MonitoredItem";
import { MonitoredItemCreateRequest } from "lib/services/subscription_service";
import { checkSelectClauses } from "lib/tools/tools_event_filter";
import UAVariable from "lib/address_space/UAVariable";
import validateFilter from "./validateFilter";
import { is_valid_dataEncoding } from "lib/misc/data_encoding";
import SubscriptionState from "lib/server/SubscriptionState";
import {
make_debugLog,
checkDebugFlag
} from "lib/misc/utils";
const debugLog = make_debugLog(__filename);
const doDebug = checkDebugFlag(__filename);
import { SubscriptionDiagnostics } from "_generated_/_auto_generated_SubscriptionDiagnostics";
const minimumPublishingInterval = 100; // fastest possible
const defaultPublishingInterval = 100;
const maximumPublishingInterval = 1000 * 60 * 60 * 24 * 30; // 1 month
function _adjust_publishing_interval(publishingInterval) {
publishingInterval = publishingInterval || defaultPublishingInterval;
publishingInterval = Math.max(publishingInterval, minimumPublishingInterval);
publishingInterval = Math.min(publishingInterval, maximumPublishingInterval);
return publishingInterval;
}
const minimumMaxKeepAliveCount = 2;
const maximumMaxKeepAliveCount = 12000;
function _adjust_maxKeepAliveCount(maxKeepAliveCount, publishingInterval) {
maxKeepAliveCount = maxKeepAliveCount || minimumMaxKeepAliveCount;
maxKeepAliveCount = Math.max(maxKeepAliveCount, minimumMaxKeepAliveCount);
maxKeepAliveCount = Math.min(maxKeepAliveCount, maximumMaxKeepAliveCount);
return maxKeepAliveCount;
}
function _adjust_lifeTimeCount(lifeTimeCount, maxKeepAliveCount) {
lifeTimeCount = lifeTimeCount || 1;
// let's make sure that lifeTimeCount is at least three time maxKeepAliveCount
// Note : the specs say ( part 3 - CreateSubscriptionParameter )
// "The lifetime count shall be a minimum of three times the keep keep-alive count."
lifeTimeCount = Math.max(lifeTimeCount, maxKeepAliveCount * 3);
return lifeTimeCount;
}
function _adjust_publishinEnable(publishingEnabled) {
return (publishingEnabled === null || publishingEnabled === undefined) ? true : !!publishingEnabled;
}
function _adjust_maxNotificationsPerPublish(maxNotificationsPerPublish) {
maxNotificationsPerPublish += 0;
assert(_.isNumber(maxNotificationsPerPublish));
return (maxNotificationsPerPublish >= 0) ? maxNotificationsPerPublish : 0;
}
// verify that the injected publishEngine provides the expected services
// regarding the Subscription requirements...
function _assert_valid_publish_engine(publishEngine) {
assert(_.isObject(publishEngine));
assert(_.isNumber(publishEngine.pendingPublishRequestCount));
assert(_.isFunction(publishEngine.send_notification_message));
assert(_.isFunction(publishEngine.send_keep_alive_response));
assert(_.isFunction(publishEngine.on_close_subscription));
}
function installSubscriptionDiagnostics(self) {
self.subscriptionDiagnostics = new SubscriptionDiagnostics({});
// "sessionId"
self.subscriptionDiagnostics.__defineGetter__("sessionId", () => self.sessionId);
self.subscriptionDiagnostics.__defineGetter__("subscriptionId", () => self.id);
self.subscriptionDiagnostics.__defineGetter__("priority", () => self.priority);
self.subscriptionDiagnostics.__defineGetter__("publishingInterval", () => self.publishingInterval);
self.subscriptionDiagnostics.__defineGetter__("maxLifetimeCount", () => self.lifeTimeCount);
self.subscriptionDiagnostics.__defineGetter__("maxKeepAliveCount", () => self.maxKeepAliveCount);
self.subscriptionDiagnostics.__defineGetter__("maxNotificationsPerPublish", () => self.maxNotificationsPerPublish);
self.subscriptionDiagnostics.__defineGetter__("publishingEnabled", () => self.publishingEnabled);
self.subscriptionDiagnostics.__defineGetter__("monitoredItemCount", () => self.monitoredItemCount);
self.subscriptionDiagnostics.__defineGetter__("nextSequenceNumber", () => self._get_future_sequence_number());
self.subscriptionDiagnostics.__defineGetter__("disabledMonitoredItemCount", () => self.disabledMonitoredItemCount);
/* those member of self.subscriptionDiagnostics are handled directly
modifyCount
enableCount,
disableCount,
republishRequestCount,
notificationsCount,
publishRequestCount,
dataChangeNotificationsCount,
eventNotificationsCount,
*/
/*
those members are not updated yet in the code :
"republishMessageRequestCount",
"republishMessageCount",
"transferRequestCount",
"transferredToAltClientCount",
"transferredToSameClientCount",
"latePublishRequestCount",
"currentKeepAliveCount",
"currentLifetimeCount",
"unacknowledgedMessageCount",
"discardedMessageCount",
"monitoringQueueOverflowCount",
"eventQueueOverFlowCount"
*/
// add object in Variable SubscriptionDiagnosticArray (i=2290) ( Array of SubscriptionDiagnostics)
// add properties in Variable to reflect
}
/**
* The Subscription class used in the OPCUA server side.
* @class Subscription
* @param {Object} options
* @param options.id {Integer} - a unique identifier
* @param options.publishingInterval {Integer} - [optional](default:1000) the publishing interval.
* @param options.maxKeepAliveCount {Integer} - [optional](default:10) the max KeepAlive Count.
* @param options.lifeTimeCount {Integer} - [optional](default:10) the max Life Time Count
* @param options.publishingEnabled {Boolean} - [optional](default:true)
* @param options.maxNotificationsPerPublish {Integer} - [optional](default:0)
* @param options.priority {Byte}
* @constructor
*/
class Subscription extends EventEmitter {
constructor(options = {}) {
super(...arguments);
const self = this;
self.publishEngine = options.publishEngine;
_assert_valid_publish_engine(self.publishEngine);
self.id = options.id || "<invalid_id>";
self.priority = options.priority || 0;
/**
* the Subscription publishing interval
* @property publishingInterval
* @type {number}
* @default 1000
*/
self.publishingInterval = _adjust_publishing_interval(options.publishingInterval);
/**
* The keep alive count defines how many times the publish interval need to
* expires without having notifications available before the server send an
* empty message.
* OPCUA Spec says: a value of 0 is invalid.
* @property maxKeepAliveCount
* @type {number}
* @default 10
*
*/
self.maxKeepAliveCount = _adjust_maxKeepAliveCount(
options.maxKeepAliveCount,
self.publishingInterval);
self.resetKeepAliveCounter();
/**
* The life time count defines how many times the publish interval expires without
* having a connection to the client to deliver data.
* If the life time count reaches maxKeepAliveCount, the subscription will
* automatically terminate.
* OPCUA Spec: The life-time count shall be a minimum of
* three times the keep keep-alive count.
*
* Note: this has to be interpreted as without having a PublishRequest available
* @property lifeTimeCount
* @type {Number}
* @default 1
*/
self.lifeTimeCount = _adjust_lifeTimeCount(
options.lifeTimeCount,
self.maxKeepAliveCount);
/**
* The maximum number of notifications that the Client wishes to receive in a
* single Publish response. A value of zero indicates that there is no limit.
* The number of notifications per Publish is the sum of monitoredItems in the
* DataChangeNotification and events in the EventNotificationList.
*
* @property maxNotificationsPerPublish
* @type {Number}
* #default 0
*/
self.maxNotificationsPerPublish = _adjust_maxNotificationsPerPublish(
options.maxNotificationsPerPublish);
self._life_time_counter = 0;
self.resetLifeTimeCounter();
// notification message that are ready to be sent to the client
self._pending_notifications = new Dequeue();
self._sent_notifications = [];
self._sequence_number_generator = new SequenceNumberGenerator();
// initial state of the subscription
self.state = SubscriptionState.CREATING;
self.publishIntervalCount = 0;
self.monitoredItems = {}; // monitored item map
/**
* number of monitored Item
* @property monitoredItemIdCounter
* @type {Number}
*/
self.monitoredItemIdCounter = 0;
self.publishingEnabled = _adjust_publishinEnable(options.publishingEnabled);
installSubscriptionDiagnostics(self);
// A boolean value that is set to TRUE to mean that
// either a NotificationMessage or a keep-alive Message has been
// sent on the Subscription.
// It is a flag that is used to ensure that either a NotificationMessage or a keep-alive
// Message is sent out the first time the publishing timer expires.
self.messageSent = false;
self.timerId = null;
self._start_timer();
}
toString() {
const self = this;
let str = "";
str += ` publishingEnabled ${self.publishingEnabled}\n`;
str += ` maxKeepAliveCount ${self.maxKeepAliveCount}\n`;
str += ` publishingInterval ${self.publishingInterval}\n`;
str += ` lifeTimeCount ${self.lifeTimeCount}\n`;
str += ` maxKeepAliveCount ${self.maxKeepAliveCount}\n`;
return str;
}
/**
* @method modify
* @param param {Object}
* @param param.requestedPublishingInterval {Duration}
* requestedPublishingInterval =0 means fastest possible
* @param param.requestedLifetimeCount {Counter}
* requestedLifetimeCount ===0 means no change
* @param param.requestedMaxKeepAliveCount {Counter}
* requestedMaxKeepAliveCount ===0 means no change
* @param param.maxNotificationsPerPublish {Counter}
* @param param.priority {Byte}
*
*/
modify(param) {
const self = this;
// update diagnostic counter
self.subscriptionDiagnostics.modifyCount += 1;
const publishingInterval_old = self.publishingInterval;
param.requestedPublishingInterval = param.requestedPublishingInterval || 0;
param.requestedMaxKeepAliveCount = param.requestedMaxKeepAliveCount || self.maxKeepAliveCount;
param.requestedLifetimeCount = param.requestedLifetimeCount || self.lifeTimeCount;
self.publishingInterval = _adjust_publishing_interval(param.requestedPublishingInterval);
self.maxKeepAliveCount = _adjust_maxKeepAliveCount(param.requestedMaxKeepAliveCount);
self.lifeTimeCount = _adjust_lifeTimeCount(param.requestedLifetimeCount, self.maxKeepAliveCount);
self.maxNotificationsPerPublish = param.maxNotificationsPerPublish;
self.priority = param.priority;
self.resetLifeTimeAndKeepAliveCounters();
if (publishingInterval_old !== self.publishingInterval) {
// todo
}
self._stop_timer();
self._start_timer();
}
_stop_timer() {
const self = this;
if (self.timerId) {
debugLog("Subscription#_stop_timer subscriptionId=".bgWhite.blue, self.id);
clearInterval(self.timerId);
self.timerId = null;
Subscription.registry.unregister(self);
}
}
_start_timer() {
const self = this;
debugLog("Subscription#_start_timer subscriptionId=".bgWhite.blue, self.id, " publishingInterval = ", self.publishingInterval);
assert(self.timerId === null);
// from the spec:
// When a Subscription is created, the first Message is sent at the end of the first publishing cycle to
// inform the Client that the Subscription is operational. A NotificationMessage is sent if there are
// Notifications ready to be reported. If there are none, a keep-alive Message is sent instead that
// contains a sequence number of 1, indicating that the first NotificationMessage has not yet been sent.
// This is the only time a keep-alive Message is sent without waiting for the maximum keep-alive count
// to be reached, as specified in (f) above.
// make sure that a keep-alive Message will be send at the end of the first publishing cycle
// if there are no Notifications ready.
self._keep_alive_counter = self.maxKeepAliveCount;
assert(self.publishingInterval >= minimumPublishingInterval);
self.timerId = setInterval(self._tick.bind(self), self.publishingInterval);
Subscription.registry.register(self);
}
// counter
_get_next_sequence_number() {
return this._sequence_number_generator.next();
}
// counter
_get_future_sequence_number() {
return this._sequence_number_generator.future();
}
setPublishingMode(publishingEnabled) {
this.publishingEnabled = !!publishingEnabled;
// update diagnostics
if (this.publishingEnabled) {
this.subscriptionDiagnostics.enableCount += 1;
} else {
this.subscriptionDiagnostics.disableCount += 1;
}
this.resetLifeTimeCounter();
if (!publishingEnabled && this.state !== SubscriptionState.CLOSED) {
this.state = SubscriptionState.NORMAL;
}
return StatusCodes.Good;
}
/**
* _publish_pending_notifications send a "notification" event:
*
* @method _publish_pending_notifications *
* @private
*
*/
_publish_pending_notifications() {
const self = this;
const publishEngine = self.publishEngine;
const subscriptionId = self.id;
// preconditions
assert(publishEngine.pendingPublishRequestCount > 0);
assert(self.hasPendingNotifications);
function _count_notification_message(notifData) {
if (notifData instanceof DataChangeNotification) {
self.subscriptionDiagnostics.dataChangeNotificationsCount += 1;
} else if (notifData instanceof EventNotificationList) {
self.subscriptionDiagnostics.eventNotificationsCount += 1;
} else {
// TODO
}
}
// todo : get rid of this....
self.emit("notification");
const notificationMessage = self._popNotificationToSend().notification;
self.emit("notificationMessage", notificationMessage);
// update diagnostics
self.subscriptionDiagnostics.notificationsCount += 1;
assert(_.isArray(notificationMessage.notificationData));
notificationMessage.notificationData.forEach(_count_notification_message);
assert(notificationMessage.hasOwnProperty("sequenceNumber"));
assert(notificationMessage.hasOwnProperty("notificationData"));
const moreNotifications = (self.hasPendingNotifications);
self.subscriptionDiagnostics.publishRequestCount += 1;
publishEngine.send_notification_message({
subscriptionId,
sequenceNumber: notificationMessage.sequenceNumber,
notificationData: notificationMessage.notificationData,
moreNotifications
}, false);
self.messageSent = true;
self.resetLifeTimeAndKeepAliveCounters();
if (doDebug) {
debugLog("Subscription sending a notificationMessage subscriptionId=", subscriptionId, notificationMessage.toString());
}
if (self.state !== SubscriptionState.CLOSED) {
assert(notificationMessage.notificationData.length > 0, "We are not expecting a keep-alive message here");
self.state = SubscriptionState.NORMAL;
debugLog(`subscription ${self.id}${" set to NORMAL".bgYellow}`);
}
}
_process_keepAlive() {
const self = this;
// xx assert(!self.publishingEnabled || (!self.hasPendingNotifications && !self.hasMonitoredItemNotifications));
self.increaseKeepAliveCounter();
if (self.keepAliveCounterHasExpired) {
if (self._sendKeepAliveResponse()) {
self.resetLifeTimeAndKeepAliveCounters();
} else {
debugLog(" -> subscription.state === LATE , because keepAlive Response cannot be send due to lack of PublishRequest");
self.state = SubscriptionState.LATE;
}
}
}
process_subscription() {
const self = this;
assert(self.publishEngine.pendingPublishRequestCount > 0);
if (!self.publishingEnabled) {
// no publish to do, except keep alive
self._process_keepAlive();
return;
}
if (!self.hasPendingNotifications && self.hasMonitoredItemNotifications) {
// collect notification from monitored items
self._harvestMonitoredItems();
}
// let process them first
if (self.hasPendingNotifications) {
self._publish_pending_notifications();
if (self.state === SubscriptionState.NORMAL && self.hasPendingNotifications) {
// istanbul ignore next
if (doDebug) {
debugLog(" -> pendingPublishRequestCount > 0 && normal state => re-trigger tick event immediately ");
}
// let process an new publish request
setImmediate(self._tick.bind(self));
}
} else {
self._process_keepAlive();
}
}
/**
* @method _tick
* @private
*/
_tick() {
const self = this;
self.discardOldSentNotifications();
// istanbul ignore next
if (doDebug) {
debugLog(" Subscription#_tick processing subscriptionId=", self.id, "hasMonitoredItemNotifications = ", self.hasMonitoredItemNotifications, " publishingIntervalCount =", self.publishIntervalCount);
}
if (self.publishEngine._on_tick) {
self.publishEngine._on_tick();
}
self.publishIntervalCount += 1;
self.increaseLifeTimeCounter();
if (self.lifeTimeHasExpired) {
/* istanbul ignore next */
if (doDebug) {
debugLog(`Subscription ${self.id}${" has expired !!!!! => Terminating".red.bold}`);
}
/**
* notify the subscription owner that the subscription has expired by exceeding its life time.
* @event expired
*
*/
self.emit("expired");
// notify new terminated status only when subscription has timeout.
debugLog("adding StatusChangeNotification notification message for BadTimeout subscription = ", self.id);
self._addNotificationMessage([new StatusChangeNotification({ statusCode: StatusCodes.BadTimeout })]);
// kill timer and delete monitored items
self.terminate();
return;
}
const publishEngine = self.publishEngine;
// istanbul ignore next
if (doDebug) { debugLog("Subscription#_tick self._pending_notifications= ", self._pending_notifications.length); }
if (publishEngine.pendingPublishRequestCount === 0 && (self.hasPendingNotifications || self.hasMonitoredItemNotifications)) {
// istanbul ignore next
if (doDebug) {
debugLog("subscription set to LATE hasPendingNotifications = ", self.hasPendingNotifications, " hasMonitoredItemNotifications =", self.hasMonitoredItemNotifications);
}
self.state = SubscriptionState.LATE;
return;
}
if (publishEngine.pendingPublishRequestCount > 0) {
if (self.hasPendingNotifications) {
// simply pop pending notification and send it
self.process_subscription();
} else if (self.hasMonitoredItemNotifications) {
self.process_subscription();
} else {
self._process_keepAlive();
}
} else {
self._process_keepAlive();
}
}
/**
* @method _sendKeepAliveResponse
* @private
*/
_sendKeepAliveResponse() {
const self = this;
const future_sequence_number = self._get_future_sequence_number();
debugLog(" -> Subscription#_sendKeepAliveResponse subscriptionId", self.id);
if (self.publishEngine.send_keep_alive_response(self.id, future_sequence_number)) {
self.messageSent = true;
/**
* notify the subscription owner that a keepalive message has to be sent.
* @event keepalive
*
*/
self.emit("keepalive", future_sequence_number);
self.state = SubscriptionState.KEEPALIVE;
return true;
}
return false;
}
/**
* @method resetKeepAliveCounter
* @private
* Reset the Lifetime Counter Variable to the value specified for the lifetime of a Subscription in
* the CreateSubscription Service( 5.13.2).
*/
resetKeepAliveCounter() {
const self = this;
self._keep_alive_counter = 0;
// istanbul ignore next
if (doDebug) {
debugLog(" -> subscriptionId", self.id, " Resetting keepAliveCounter = ", self._keep_alive_counter, self.maxKeepAliveCount);
}
}
/**
* @method increaseKeepAliveCounter
* @private
*/
increaseKeepAliveCounter() {
const self = this;
self._keep_alive_counter += 1;
// istanbul ignore next
if (doDebug) {
debugLog(" -> subscriptionId", self.id, " Increasing keepAliveCounter = ", self._keep_alive_counter, self.maxKeepAliveCount);
}
}
/**
* Reset the Lifetime Counter Variable to the value specified for the lifetime of a Subscription in
* the CreateSubscription Service( 5.13.2).
* @method resetLifeTimeCounter
* @private
*/
resetLifeTimeCounter() {
const self = this;
self._life_time_counter = 0;
}
/**
* @method increaseLifeTimeCounter
* @private
*/
increaseLifeTimeCounter() {
const self = this;
self._life_time_counter += 1;
}
/**
*
* the server invokes the resetLifeTimeAndKeepAliveCounters method of the subscription
* when the server has send a Publish Response, so that the subscription
* can reset its life time counter.
*
* @method resetLifeTimeAndKeepAliveCounters
*
*/
resetLifeTimeAndKeepAliveCounters() {
const self = this;
self.resetLifeTimeCounter();
self.resetKeepAliveCounter();
}
/**
* Terminates the subscription.
* @method terminate
*
* Calling this method will also remove any monitored items.
*
*/
terminate() {
const self = this;
if (self.state === SubscriptionState.CLOSED) {
// todo verify if asserting is required here
return;
}
assert(self.state !== SubscriptionState.CLOSED, "terminate already called ?");
// stop timer
self._stop_timer();
debugLog("terminating Subscription ", self.id, " with ", self.monitoredItemCount, " monitored items");
// dispose all monitoredItem
const keys = Object.keys(self.monitoredItems);
keys.forEach((key) => {
const status = self.removeMonitoredItem(key);
assert(status === StatusCodes.Good);
});
assert(self.monitoredItemCount === 0);
self.state = SubscriptionState.CLOSED;
self.publishEngine.on_close_subscription(self);
/**
* notify the subscription owner that the subscription has been terminated.
* @event "terminated"
*/
self.emit("terminated");
}
/**
* @method _addNotificationMessage
* @param notificationData {Array<DataChangeNotification|EventNotificationList|StatusChangeNotification>}
*/
_addNotificationMessage(notificationData) {
assert(_.isArray(notificationData));
assert(notificationData.length === 1 || notificationData.length === 2); // as per spec part 3.
// istanbul ignore next
if (doDebug) {
debugLog("Subscription#_addNotificationMessage".yellow, notificationData.toString());
}
const self = this;
assert(_.isObject(notificationData[0]));
assert_validNotificationData(notificationData[0]);
if (notificationData.length === 2) {
assert_validNotificationData(notificationData[1]);
}
const notification_message = new NotificationMessage({
sequenceNumber: self._get_next_sequence_number(),
publishTime: new Date(),
notificationData
});
self._pending_notifications.push({
notification: notification_message,
start_tick: self.publishIntervalCount,
publishTime: new Date(),
sequenceNumber: notification_message.sequenceNumber
});
}
getMessageForSequenceNumber(sequenceNumber) {
const self = this;
function filter_func(e) {
return e.sequenceNumber === sequenceNumber;
}
const notification_message = _.find(self._sent_notifications, filter_func);
if (!notification_message) {
return null;
}
return notification_message;
}
/**
* Extract the next Notification that is ready to be sent to the client.
* @method _popNotificationToSend
* @return {NotificationMessage} the Notification to send._pending_notifications
*/
_popNotificationToSend() {
const self = this;
assert(self._pending_notifications.length > 0);
const notification_message = self._pending_notifications.shift();
self._sent_notifications.push(notification_message);
return notification_message;
}
/**
* returns true if the notification has expired
* @method notificationHasExpired
* @param notification
* @return {boolean}
*/
notificationHasExpired(notification) {
const self = this;
assert(notification.hasOwnProperty("start_tick"));
assert(_.isFinite(notification.start_tick + self.maxKeepAliveCount));
return (notification.start_tick + self.maxKeepAliveCount) < self.publishIntervalCount;
}
/**
* discardOldSentNotification find all sent notification message that have expired keep-alive
* and destroy them.
* @method discardOldSentNotifications
* @private
*
* Subscriptions maintain a retransmission queue of sent NotificationMessages.
* NotificationMessages are retained in this queue until they are acknowledged or until they have
* been in the queue for a minimum of one keep-alive interval.
*
*/
discardOldSentNotifications() {
const self = this;
// Sessions maintain a retransmission queue of sent NotificationMessages. NotificationMessages
// are retained in this queue until they are acknowledged. The Session shall maintain a
// retransmission queue size of at least two times the number of Publish requests per Session the
// Server supports. Clients are required to acknowledge NotificationMessages as they are received. In the
// case of a retransmission queue overflow, the oldest sent NotificationMessage gets deleted. If a
// Subscription is transferred to another Session, the queued NotificationMessages for this
// Subscription are moved from the old to the new Session.
if (maxNotificationMessagesInQueue <= self._sent_notifications.length) {
self._sent_notifications.splice(self._sent_notifications.length - maxNotificationMessagesInQueue);
}
//
// var arr = _.filter(self._sent_notifications,function(notification){
// return self.notificationHasExpired(notification);
// });
// var results = arr.map(function(notification){
// return self.acknowledgeNotification(notification.sequenceNumber);
// });
// xx return results;
}
/**
* returns in an array the sequence numbers of the notifications that haven't been
* acknowledged yet.
*
* @method getAvailableSequenceNumbers
* @return {Integer[]}
*
*/
getAvailableSequenceNumbers() {
const self = this;
const availableSequenceNumbers = getSequenceNumbers(self._sent_notifications);
return availableSequenceNumbers;
}
/**
* @method acknowledgeNotification
* @param sequenceNumber {Number}
* @return {StatusCode}
*/
acknowledgeNotification(sequenceNumber) {
const self = this;
let foundIndex = -1;
_.find(self._sent_notifications, (e, index) => {
if (e.sequenceNumber === sequenceNumber) {
foundIndex = index;
}
});
if (foundIndex === -1) {
return StatusCodes.BadSequenceNumberUnknown;
}
self._sent_notifications.splice(foundIndex, 1);
return StatusCodes.Good;
}
/**
* adjust monitored item sampling interval
* - an samplingInterval ===0 means that we use a event-base model ( no sampling)
* - otherwise the sampling is adjusted
*
* @method adjustSamplingInterval
* @param samplingInterval
* @param node
* @return {number|*}
* @private
*/
adjustSamplingInterval(samplingInterval, node) {
const self = this;
if (samplingInterval < 0) {
// - The value -1 indicates that the default sampling interval defined by the publishing
// interval of the Subscription is requested.
// - Any negative number is interpreted as -1.
samplingInterval = self.publishingInterval;
} else if (samplingInterval === 0) {
// OPCUA 1.0.3 Part 4 - 5.12.1.2
// The value 0 indicates that the Server should use the fastest practical rate.
// The fastest supported sampling interval may be equal to 0, which indicates
// that the data item is exception-based rather than being sampled at some period.
// An exception-based model means that the underlying system does not require sampling and reports data changes.
const dataValueSamplingInterval = node.readAttribute(AttributeIds.MinimumSamplingInterval);
// TODO if attributeId === AttributeIds.Value : sampling interval required here
if (dataValueSamplingInterval.statusCode === StatusCodes.Good) {
// node provides a Minimum sampling interval ...
samplingInterval = dataValueSamplingInterval.value.value;
assert(samplingInterval >= 0 && samplingInterval <= MonitoredItem.maximumSamplingInterval);
// note : at this stage, a samplingInterval===0 means that the data item is really exception-based
}
} else if (samplingInterval < MonitoredItem.minimumSamplingInterval) {
samplingInterval = MonitoredItem.minimumSamplingInterval;
} else if (samplingInterval > MonitoredItem.maximumSamplingInterval) {
// If the requested samplingInterval is higher than the
// maximum sampling interval supported by the Server, the maximum sampling
// interval is returned.
samplingInterval = MonitoredItem.maximumSamplingInterval;
}
const node_minimumSamplingInterval = (node && node.minimumSamplingInterval) ? node.minimumSamplingInterval : 0;
samplingInterval = Math.max(samplingInterval, node_minimumSamplingInterval);
return samplingInterval;
}
createMonitoredItem(addressSpace, timestampsToReturn, monitoredItemCreateRequest) {
const self = this;
assert(addressSpace.constructor.name === "AddressSpace");
assert(monitoredItemCreateRequest instanceof MonitoredItemCreateRequest);
function handle_error(statusCode) {
return new subscription_service.MonitoredItemCreateResult({ statusCode });
}
const itemToMonitor = monitoredItemCreateRequest.itemToMonitor;
const node = addressSpace.findNode(itemToMonitor.nodeId);
if (!node) {
return handle_error(StatusCodes.BadNodeIdUnknown);
}
if (itemToMonitor.attributeId === AttributeIds.Value && !(node instanceof UAVariable)) {
// AttributeIds.Value is only valid for monitoring value of UAVariables.
return handle_error(StatusCodes.BadAttributeIdInvalid);
}
if (itemToMonitor.attributeId === AttributeIds.INVALID) {
return handle_error(StatusCodes.BadAttributeIdInvalid);
}
if (!itemToMonitor.indexRange.isValid()) {
return handle_error(StatusCodes.BadIndexRangeInvalid);
}
// check dataEncoding applies only on Values
if (itemToMonitor.dataEncoding.name && itemToMonitor.attributeId !== AttributeIds.Value) {
return handle_error(StatusCodes.BadDataEncodingInvalid);
}
// check dataEncoding
if (!is_valid_dataEncoding(itemToMonitor.dataEncoding)) {
return handle_error(StatusCodes.BadDataEncodingUnsupported);
}
// filter
const requestedParameters = monitoredItemCreateRequest.requestedParameters;
const filter = requestedParameters.filter;
const statusCodeFilter = validateFilter(filter, itemToMonitor, node);
if (statusCodeFilter !== StatusCodes.Good) {
return handle_error(statusCodeFilter);
}
// xx var monitoringMode = monitoredItemCreateRequest.monitoringMode; // Disabled, Sampling, Reporting
// xx var requestedParameters = monitoredItemCreateRequest.requestedParameters;
const monitoredItemCreateResult = self._createMonitoredItemStep2(timestampsToReturn, monitoredItemCreateRequest, node);
assert(monitoredItemCreateResult.statusCode === StatusCodes.Good);
const monitoredItem = self.getMonitoredItem(monitoredItemCreateResult.monitoredItemId);
assert(monitoredItem);
// TODO: fix old way to set node. !!!!
monitoredItem.setNode(node);
self.emit("monitoredItem", monitoredItem, itemToMonitor);
self._createMonitoredItemStep3(monitoredItem, monitoredItemCreateRequest);
return monitoredItemCreateResult;
}
/**
*
* @method _createMonitoredItemStep2
* @param timestampsToReturn
* @param {MonitoredItemCreateRequest} monitoredItemCreateRequest - the parameters describing the monitored Item to create
* @param node {BaseNode}
* @return {subscription_service.MonitoredItemCreateResult}
* @private
*/
_createMonitoredItemStep2(timestampsToReturn, monitoredItemCreateRequest, node) {
const self = this;
// note : most of the parameter inconsistencies shall have been handled by the caller
// any error here will raise an assert here
assert(monitoredItemCreateRequest instanceof MonitoredItemCreateRequest);
const itemToMonitor = monitoredItemCreateRequest.itemToMonitor;
// xx check if attribute Id invalid (we only support Value or EventNotifier )
// xx assert(itemToMonitor.attributeId !== AttributeIds.INVALID);
self.monitoredItemIdCounter += 1;
const monitoredItemId = getNextMonitoredItemId();
const requestedParameters = monitoredItemCreateRequest.requestedParameters;
// adjust requestedParameters.samplingInterval
requestedParameters.samplingInterval = self.adjustSamplingInterval(requestedParameters.samplingInterval, node);
// reincorporate monitoredItemId and itemToMonitor into the requestedParameters
requestedParameters.monitoredItemId = monitoredItemId;
requestedParameters.itemToMonitor = itemToMonitor;
const monitoredItem = new MonitoredItem(requestedParameters);
monitoredItem.timestampsToReturn = timestampsToReturn;
assert(monitoredItem.monitoredItemId === monitoredItemId);
self.monitoredItems[monitoredItemId] = monitoredItem;
const filterResult = _process_filter(node, requestedParameters.filter);
const monitoredItemCreateResult = new subscription_service.MonitoredItemCreateResult({
statusCode: StatusCodes.Good,
monitoredItemId,
revisedSamplingInterval: monitoredItem.samplingInterval,
revisedQueueSize: monitoredItem.queueSize,
filterResult
});
return monitoredItemCreateResult;
}
_createMonitoredItemStep3(monitoredItem, monitoredItemCreateRequest) {
assert(monitoredItem.monitoringMode === MonitoringMode.Invalid);
assert(_.isFunction(monitoredItem.samplingFunc));
const monitoringMode = monitoredItemCreateRequest.monitoringMode; // Disabled, Sampling, Reporting
monitoredItem.setMonitoringMode(monitoringMode);
}
/**
* get a monitoredItem by Id.
* @method getMonitoredItem
* @param monitoredItemId {Number} the id of the monitored item to get.
* @return {MonitoredItem}
*/
getMonitoredItem(monitoredItemId) {
assert(_.isFinite(monitoredItemId));
const self = this;
return self.monitoredItems[monitoredItemId];
}
/**
* getMonitoredItems is used to get information about monitored items of a subscription.Its intended
* use is defined in Part 4. This method is the implementation of the Standard OPCUA GetMonitoredItems Method.
* @method getMonitoredItems
* @param result.serverHandles {Int32[]} Array of serverHandles for all MonitoredItems of the subscription identified by subscriptionId.
* result.clientHandles {Int32[]} Array of clientHandles for all MonitoredItems of the subscription identified by subscriptionId.
* result.statusCode {StatusCode}
* from spec:
* This method can be used to get the list of monitored items in a subscription if CreateMonitoredItems failed due to
* a network interruption and the client does not know if the creation succeeded in the server.
*
*/
getMonitoredItems(/* out*/ result) {
result = result || {};
const subscription = this;
result.serverHandles = [];
result.clientHandles = [];
result.statusCode = StatusCodes.Good;
Object.keys(subscription.monitoredItems).forEach((monitoredItemId) => {
const monitoredItem = subscription.getMonitoredItem(monitoredItemId);
result.clientHandles.push(monitoredItem.clientHandle);
// TODO: serverHandle is defined anywhere in the OPCUA Specification 1.02
// I am not sure what shall be reported for serverHandle...
// using monitoredItem.monitoredItemId instead...
// May be a clarification in the OPCUA Spec is required.
result.serverHandles.push(monitoredItemId);
});
return result;
}
resendInitialValues() {
const subscription = this;
_.forEach(subscription.monitoredItems, (monitoredItem, monitoredItemId) => {
monitoredItem.resendInitialValues();
});
}
/**
* remove a monitored Item from the subscription.
* @method removeMonitoredItem
* @param monitoredItemId {Number} the id of the monitored item to get.
*/
removeMonitoredItem(monitoredItemId) {
debugLog("Removing monitoredIem ", monitoredItemId);
assert(_.isFinite(monitoredItemId));
const self = this;
if (!self.monitoredItems.hasOwnProperty(monitoredItemId)) {
return StatusCodes.BadMonitoredItemIdInvalid;
}
const monitoredItem = self.monitoredItems[monitoredItemId];
monitoredItem.terminate();
/**
*
* notify that a monitored item has been removed from the subscription
* @event removeMonitoredItem
* @param monitoredItem {MonitoredItem}
*/
self.emit("removeMonitoredItem", monitoredItem);
delete self.monitoredItems[monitoredItemId];
return StatusCodes.Good;
}
// collect DataChangeNotification
_collectNotificationData() {
const self = this;
// reset cache ...
self._hasMonitoredItemNotifications = false;
const all_notifications = new Dequeue();
// visit all monitored items
const keys = Object.keys(self.monitoredItems);
let i;
let key;
const n = keys.length;
for (i = 0; i < n; i++) {
key = keys[i];
const monitoredItem = self.monitoredItems[key];
var notifications = monitoredItem.extractMonitoredItemNotifications();
add_all_in(notifications, all_notifications);
}
const notificationsMessage = [];
while (all_notifications.length > 0) {
// split into one or multiple dataChangeNotification with no more than
// self.maxNotificationsPerPublish monitoredItems
const notifications_chunk = extract_notifications_chunk(all_notifications, self.maxNotificationsPerPublish);
// separate data for DataChangeNotification (MonitoredItemNotification) from data for EventNotificationList(EventFieldList)
const dataChangedNotificationData = notifications_chunk.filter(filter_instanceof.bind(null, subscription_service.MonitoredItemNotification));
const eventNotificationListData = notifications_chunk.filter(filter_instanceof.bind(null, subscription_service.EventFieldList));
assert(notifications_chunk.length === dataChangedNotificationData.length + eventNotificationListData.length);
var notifications = [];
// add dataChangeNotification
if (dataChangedNotificationData.length) {
const dataChangeNotification = new DataChangeNotification({
monitoredItems: dataChangedNotificationData,
diagnosticInfos: []
});
notifications.push(dataChangeNotification);
}
// add dataChangeNotification
if (eventNotificationListData.length) {
const eventNotificationList = new EventNotificationList({
events: eventNotificationListData
});
notifications.push(eventNotificationList);
}
assert(notifications.length === 1 || notifications.length === 2);
notificationsMessage.push(notifications);
}
assert(notificationsMessage instanceof Array);
return notificationsMessage;
}
_harvestMonitoredItems() {
const self = this;
// Only collect data change notification for the time being
const notificationData = self._collectNotificationData();
assert(notificationData instanceof Array);
// istanbul ignore next
if (doDebug) {
debugLog("Subscription#_harvestMonitoredItems =>", notificationData.length);
}
notificationData.forEach((notificationMessage) => {
self._addNotificationMessage(notificationMessage);
});
self._hasMonitoredItemNotifications = false;
}
notifyTransfer() {
// OPCUA UA Spec 1.0.3 : part 3 - page 82 - 5.13.7 TransferSubscriptions:
// If the Server transfers the Subscription to the new Session, the Server shall issue a StatusChangeNotification
// notificationMessage with the status code Good_SubscriptionTransferred to the old Session.
const self = this;
console.log(" Subscription => Notifying Transfer ".bgWhite.red);
const notificationData = [new StatusChangeNotification({ statusCode: StatusCodes.GoodSubscriptionTransferred })];
self.publishEngine.send_notification_message({
subscriptionId: self.id,
sequenceNumber: self._get_next_sequence_number(),
notificationData,
moreNotifications: false
}, true);
}
/**
* @property keepAliveCounterHasExpired
* @private
* @type {Boolean} true if the keep alive counter has reach its limit.
*/
get keepAliveCounterHasExpired() {
const self = this;
return self._keep_alive_counter >= self.maxKeepAliveCount;
}
/**
* True if the subscription life time has expired.
*
* @property lifeTimeHasExpired
* @type {boolean} - true if the subscription life time has expired.
*/
get lifeTimeHasExpired() {
const self = this;
assert(self.lifeTimeCount > 0);
return self._life_time_counter >= self.lifeTimeCount;
}
/**
* number of milliseconds before this subscription times out (lifeTimeHasExpired === true);
* @property timeToExpiration
* @type {Number}
*/
get timeToExpiration() {
const self = this;
return (self.lifeTimeCount - self._life_time_counter) * self.publishingInterval;
}
get timeToKeepAlive() {
const self = this;
return (self.maxKeepAliveCount - self._keep_alive_counter) * self.publishingInterval;
}
/**
*
* @property pendingNotificationsCount - number of pending notifications
* @type {Number}
*/
get pendingNotificationsCount() {
return this._pending_notifications.length;
}
/**
* return True is there are pending notifications for this subscription. (i.e moreNotifications)
*
* @property hasPendingNotifications
* @type {Boolean}
*/
get hasPendingNotifications() {
const self = this;
return self.pendingNotificationsCount > 0;
}
/**
* number of sent notifications
* @property sentNotificationsCount
* @type {Number}
*/
get sentNotificationsCount() {
return this._sent_notifications.length;
}
/**
* number of monitored items.
* @property monitoredItemCount
* @type {Number}
*/
get monitoredItemCount() {
return Object.keys(this.monitoredItems).length;
}
/**
* number of disabled monitored items.
* @property disabledMonitoredItemCount
* @type {Number}
*/
get disabledMonitoredItemCount() {
return _.reduce(
_.values(this.monitoredItems),
(cumul, monitoredItem) => cumul + ((monitoredItem.monitoringMode === MonitoringMode.Disabled)
? 1
: 0
), 0);
}
/**
* The number of unacknowledged messages saved in the republish queue.
* @property unacknowledgedMessageCount
* @type {Number}
*/
get unacknowledgedMessageCount() {
return 0;
}
/**
* @property hasMonitoredItemNotifications true if monitored Item have uncollected Notifications
* @type {Boolean}
*/
get hasMonitoredItemNotifications() {
const self = this;
if (self._hasMonitoredItemNotifications) {
return true;
}
const keys = Object.keys(self.monitoredItems);
let i;
let key;
const n = keys.length;
for (i = 0; i < n; i++) {
key = keys[i];
const monitoredItem = self.monitoredItems[key];
if (monitoredItem.hasMonitoredItemNotifications) {
self._hasMonitoredItemNotifications = true;
return true;
}
}
return false;
}
get subscriptionId() {
return this.id;
}
}
Subscription.registry = new ObjectRegistry();
function assert_validNotificationData(n) {
assert(
n instanceof DataChangeNotification ||
n instanceof EventNotificationList ||
n instanceof StatusChangeNotification
);
}
const maxNotificationMessagesInQueue = 100;
function getSequenceNumbers(arr) {
return arr.map(e => e.notification.sequenceNumber);
}
function analyseEventFilterResult(node, eventFilter) {
assert(eventFilter instanceof subscription_service.EventFilter);
const selectClauseResults = checkSelectClauses(node, eventFilter.selectClauses);
const whereClauseResult = new subscription_service.ContentFilterResult();
return new subscription_service.EventFilterResult({
selectClauseResults,
selectClauseDiagnosticInfos: [],
whereClauseResult
});
}
function analyseDataChangeFilterResult(node, dataChangeFilter) {
assert(dataChangeFilter instanceof subscription_service.DataChangeFilter);
// the opcua specification doesn't provide dataChangeFilterResult
return null;
}
function analyseAggregateFilterResult(node, aggregateFilter) {
assert(aggregateFilter instanceof subscription_service.AggregateFilter);
return new subscription_service.AggregateFilterResult({});
}
function _process_filter(node, filter) {
if (!filter) {
return null;
}
if (filter instanceof subscription_service.EventFilter) {
return analyseEventFilterResult(node, filter);
} else if (filter instanceof subscription_service.DataChangeFilter) {
return analyseDataChangeFilterResult(node, filter);
} else if (filter instanceof subscription_service.AggregateFilter) {
return analyseAggregateFilterResult(node, filter);
}
// istanbul ignore next
throw new Error("invalid filter");
}
let g_monitoredItemId = 1;
function getNextMonitoredItemId() {
return g_monitoredItemId++;
}
let MonitoringMode = subscription_service.MonitoringMode;
MonitoredItem.prototype.resendInitialValues = function () {
// te first Publish response(s) after the TransferSubscriptions call shall contain the current values of all
// Monitored Items in the Subscription where the Monitoring Mode is set to Reporting.
// the first Publish response after the TransferSubscriptions call shall contain only the value changes since
// the last Publish response was sent.
// This parameter only applies to MonitoredItems used for monitoring Attribute changes.
const self = this;
self._stop_sampling();
self._start_sampling(true);
};
let DataChangeNotification = subscription_service.DataChangeNotification;
let EventNotificationList = subscription_service.EventNotificationList;
/**
* extract up to maxNotificationsPerPublish notifications
* @param monitoredItems
* @param maxNotificationsPerPublish
* @return {Array}
*/
function extract_notifications_chunk(monitoredItems, maxNotificationsPerPublish) {
let n = maxNotificationsPerPublish === 0 ?
monitoredItems.length :
Math.min(monitoredItems.length, maxNotificationsPerPublish);
const chunk_monitoredItems = [];
while (n) {
chunk_monitoredItems.push(monitoredItems.shift());
n--;
}
return chunk_monitoredItems;
}
function add_all_in(notifications, all_notifications) {
for (let i = 0; i < notifications.length; i++) {
const n = notifications[i];
all_notifications.push(n);
}
}
function filter_instanceof(Class, e) {
return (e instanceof Class);
}
export default Subscription;
|
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['1608',"Tlece.Recruitment.Models.Agent Namespace","topic_0000000000000547.html"],['1664',"PersonDatatableDto Class","topic_0000000000000560.html"],['1666',"Properties","topic_0000000000000560_props--.html"],['1667',"Persons Property","topic_0000000000000562.html"]]; |
import React, { PropTypes as T } from 'react'
import mdl from '../mdl'
export default React.createClass({
displayName: 'Menu',
propTypes: {
align: T.oneOf(['left', 'right']),
valign: T.oneOf(['bottom', 'top']),
target: T.string.isRequired,
children: T.node
},
getDefaultProps: function() {
return {
align: 'left',
valign: 'bottom'
}
},
handleMenuEl(ref) {
if (ref === null) {
if (this._menuEl) {
mdl.downgradeElements(this._menuEl)
this._menuEl = null
}
} else {
this._menuEl = ref
mdl.upgradeElement(this._menuEl)
}
},
render() {
const { align, target, valign, children } = this.props
const classes = `mdl-menu mdl-js-menu mdl-menu--${valign}-${align}`
return <ul className={classes} htmlFor={target} ref={this.handleMenuEl}>
{children}
</ul>
}
})
|
//
// ILC Server.js v.0.0.1
//
var express = require('express')
, engine = require('ejs').__express
, config = require('./config/env.json')
, menu = require('./config/menu.json')
, flashcardscat = require('./config/flashcards-cat.json')
, app = express()
, mongo = require('mongodb')
, mongoose = require('mongoose')
, session = require('express-session')
, passport = require('passport')
, FacebookStrategy = require('passport-facebook').Strategy
, RedisStore = require('connect-redis')(session)
, hanzi = require('./modules/hanzi')
, users = require('./modules/users')
, data = require('./config/database.js')(mongoose)
, colors = require('colors');
Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
app.configure(function () {
app.set('port', process.env.PORT || 8088);
app.set( 'views', __dirname+'/views');
app.engine( 'ejs', engine );
app.use( express.favicon(__dirname + '/public/img/favicon.ico') );
app.use( express.cookieParser() );
app.use(express.session({
key:config.session.key,
secret: config.session.secret,
store: new RedisStore({
host: 'localhost',
port: 6379,
}),
cookie: {maxAge:604800},
}));
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use('/public', express.static(__dirname + '/public'));
app.use(passport.initialize());
app.use(passport.session());
});
db = new Db('hanzidb', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {safe: true});
db.open(function(err, db) {
if(!err) {
console.log("Connected to 'ILC' database".cyan);
db.collection('hanzi', {strict:true}, function(err, collection) {
if (collection == null) {
console.log("The 'hanzi' collection doesn't exist. Creating it with sample data...");
populateDB();
}
else{
require('./config/passport')(passport,mongoose,config);
}
});
}
});
require('./config/routes.js')(app, passport,hanzi,flashcardscat,menu,users);
app.listen(8088);
console.log('Listening on port '.grey + app.get('port'));
console.log('App launched'.green.bold); |
var React = require('react/addons');
import {mergeProps} from 'pui-react-helpers';
/**
* @component UIButton
* @description A wrapper around the Pivotal UI button component
*
* @property href {String} Makes a button-styled link pointing to the given URL
* @property block {Boolean} Makes the button fill the width of its container
* @property large {Boolean} Enlarges the button
*
* @example ```js
* var UIButton = require('pui-react-buttons').UIButton;
* var MyComponent = React.createClass({
* render() {
* return <UIButton>The action was successful.</UIButton>;
* }
* });
* ```
*
* @see [Pivotal UI React](http://styleguide.pivotal.io/react.html#button_react)
* @see [Pivotal UI CSS](http://styleguide.pivotal.io/elements.html#button)
*/
var UIButton = React.createClass({
propTypes: {
block: React.PropTypes.bool,
href: React.PropTypes.string,
kind: React.PropTypes.oneOf([
'default',
'default-alt',
'lowlight',
'danger',
'highlight',
'highlight-alt'
]),
large: React.PropTypes.bool
},
render: function () {
var {block, large, kind='default', children, ...others} = this.props;
let defaultProps = {
className: [
'btn',
`btn-${kind}`,
{
'btn-block': block,
'btn-lg': large
}
]
};
let props = mergeProps(others, defaultProps);
return this.props.href ?
<a {...props}>{children}</a> :
<button {...props}>{children}</button>;
}
});
function defButton(propOverrides) {
return React.createClass({
propTypes: {
block: React.PropTypes.bool,
href: React.PropTypes.string,
kind: React.PropTypes.oneOf([
'default',
'default-alt',
'lowlight',
'danger',
'highlight',
'highlight-alt'
]),
large: React.PropTypes.bool
},
render: function() {
return <UIButton {...this.props} {...propOverrides}/>;
}
});
}
module.exports = {
UIButton,
/**
* @component DefaultButton
*
* @property href {String} Makes a button-styled link pointing to the given URL
* @property block {Boolean} Makes the button fill the width of its container
* @property large {Boolean} Enlarges the button
*
* @see [Pivotal UI React](http://styleguide.pivotal.io/react.html#button_react)
* @see [Pivotal UI CSS](http://styleguide.pivotal.io/elements.html#button)
*/
DefaultButton: defButton({kind: 'default'}),
/**
* @component DefaultAltButton
*
* @property href {String} Makes a button-styled link pointing to the given URL
* @property block {Boolean} Makes the button fill the width of its container
* @property large {Boolean} Enlarges the button
*
* @see [Pivotal UI React](http://styleguide.pivotal.io/react.html#button_react)
* @see [Pivotal UI CSS](http://styleguide.pivotal.io/elements.html#button)
*/
DefaultAltButton: defButton({kind: 'default-alt'}),
/**
* @component LowlightButton
*
* @property href {String} Makes a button-styled link pointing to the given URL
* @property block {Boolean} Makes the button fill the width of its container
* @property large {Boolean} Enlarges the button
*
* @see [Pivotal UI React](http://styleguide.pivotal.io/react.html#button_react)
* @see [Pivotal UI CSS](http://styleguide.pivotal.io/elements.html#button)
*/
LowlightButton: defButton({kind: 'lowlight'}),
/**
* @component DangerButton
*
* @property href {String} Makes a button-styled link pointing to the given URL
* @property block {Boolean} Makes the button fill the width of its container
* @property large {Boolean} Enlarges the button
*
* @see [Pivotal UI React](http://styleguide.pivotal.io/react.html#button_react)
* @see [Pivotal UI CSS](http://styleguide.pivotal.io/elements.html#button)
*/
DangerButton: defButton({kind: 'danger'}),
/**
* @component HighlightButton
*
* @property href {String} Makes a button-styled link pointing to the given URL
* @property block {Boolean} Makes the button fill the width of its container
* @property large {Boolean} Enlarges the button
*
* @see [Pivotal UI React](http://styleguide.pivotal.io/react.html#button_react)
* @see [Pivotal UI CSS](http://styleguide.pivotal.io/elements.html#button)
*/
HighlightButton: defButton({kind: 'highlight'}),
/**
* @component HighlightAltButton
*
* @property href {String} Makes a button-styled link pointing to the given URL
* @property block {Boolean} Makes the button fill the width of its container
* @property large {Boolean} Enlarges the button
*
* @see [Pivotal UI React](http://styleguide.pivotal.io/react.html#button_react)
* @see [Pivotal UI CSS](http://styleguide.pivotal.io/elements.html#button)
*/
HighlightAltButton: defButton({kind: 'highlight-alt'})
};
/*doc
---
title: Buttons
name: button_react
categories:
- React
---
<code class="pam">
<i class="fa fa-download" alt="Install the Component">
npm install pui-react-buttons --save
</i>
</code>
Require the subcomponents:
```
var DefaultButton = require('pui-react-buttons').DefaultButton;
var DefaultAltButton = require('pui-react-buttons').DefaultAltButton;
var LowlightButton = require('pui-react-buttons').LowlightButton;
var DangerButton = require('pui-react-buttons').DangerButton;
var HighlightButton = require('pui-react-buttons').HighlightButton;
var HighlightAltButton = require('pui-react-buttons').HighlightAltButton;
var UIButton = require('pui-react-buttons').UIButton;
```
Buttons use the button tag by default. If you'd like a link rather than a button, simply add an `href` attribute.
```react_example_table
<DefaultButton href="http://example.com">
Default
</DefaultButton>
```
To make a button large, set the `large` property to true.
```react_example_table
<HighlightButton large={true}>
Big Button
</HighlightButton>
```
To make a button full-width, set the `block` property to true.
```react_example
<DangerButton block={true} >
Danger Zone
</DangerButton>
```
Specific button types.
```react_example_table
<DefaultButton>
Default
</DefaultButton>
<DefaultAltButton>
Default alternate
</DefaultAltButton>
<LowlightButton>
Lowlight
</LowlightButton>
<DangerButton>
Danger
</DangerButton>
<HighlightButton>
Highlight
</HighlightButton>
<HighlightAltButton>
Highlight alternate
</HighlightAltButton>
```
The base button renderer. You won't really interact with this directly.
```react_example_table
<UIButton>
I'm a button
</UIButton>
```
*/
|
export default (err, req, res, next) => {
res.status(500).render('error', {
message: err.message,
error: err
});
} |
/**
* 更新系统配置编辑上面的标签名称
* @param realName
* @returns
*/
function refrehConfigEditTabName(realName) {
var editConfig_span = $("#editConfig_span_id");
editConfig_span.text(realName);
editConfig_span.text("系统配置编辑");
}
/**
* 配置类型转换为字符串
* @param configType
* @returns
*/
function stringFromConfigType(configType) {
var htmlStr = "";
switch(configType) {
case 1:
htmlStr = "只读";
break;
case 2:
htmlStr = "可维护";
break;
case 3:
default:
htmlStr = "可修改不可删除";
break;
}
return htmlStr;
}
/**
* 显示系统配置列表标签
* @returns
*/
function showConfigListTab() {
var editConfig_span = $("#editConfig_span_id");
editConfig_span.hide();
var detailConfig_span = $("#detailConfig_span_id");
detailConfig_span.hide();
var listConfig_span = $("#listConfig_span_id");
listConfig_span.show();
changeTab(listConfig_span, "listConfig_div_id");
}
/**
* 显示系统配置添加标签
* @returns
*/
function showConfigAddTab() {
var editConfig_span = $("#editConfig_span_id");
editConfig_span.hide();
var detailConfig_span = $("#detailConfig_span_id");
detailConfig_span.hide();
var addConfig_span = $("#addConfig_span_id");
addConfig_span.show();
changeTab(addConfig_span, "addConfig_div_id");
}
/**
* 显示系统配置修改标签
* @returns
*/
function showConfigEditTab(realName) {
var editConfig_span = $("#editConfig_span_id");
editConfig_span.show();
refrehConfigEditTabName(realName);
changeTab(editConfig_span, "editConfig_div_id");
}
/**
* 显示系统配置详情标签
* @param realName
* @returns
*/
function showConfigDetailTab(realName) {
var detailConfig_span = $("#detailConfig_span_id");
detailConfig_span.show();
detailConfig_span.text(realName);
detailConfig_span.text("系统配置详情");
changeTab(detailConfig_span, "detailConfig_div_id");
}
/**
* 清空添加标签下的输入框内容
* @returns
*/
function clearConfigAddInput() {
$("#addConfigName_input_id").val("");
$("#addConfigType_select_id").val(1);
$("#addConfigKey_input_id").val("");
$("#addConfigValue_input_id").val("");
$("#addConfigDesc_textarea_id").val("");
}
/**
* 初始化页面时候加载数据
* @returns
*/
function loadConfigPage() {
$("#grid-data").bootgrid({
sorting:false,
navigation:3, // Default value is 3. 0 for none, 1 for header, 2 for footer and 3 for both.
columnSelection: false, //启用或禁用下拉框隐藏/显示列。默认值为true
ajax: true,
ajaxSettings: {
method: "POST",
cache: false
},
requestHandler: function (request) { //自定义参数处理
var configName = $("#configName_input_id").val();
request.configName = configName;
var configKey = $("#configKey_input_id").val();
request.configKey = configKey;
return request;
},
url: yyoa_context+"/sys/conf/searchConfigByPage.do",
rowCount: [10, 25, 50],
labels : {
infos : "显示 {{ctx.start}} 至 {{ctx.end}} 共 {{ctx.total}} 条"
},
formatters: {
"confType": function(column, row)
{
return stringFromConfigType(row.confType);
},
"link": function(column, row)
{
var htmlstr = '';
htmlstr = '<span id="detailConfig_span_id" onclick="detailConfig_span_onclick(' + row.id + ')">'+'详情'+'</span>';
switch(row.confType) {
case 1: // 只读
break;
case 2: // 可维护
{
htmlstr += '|';
htmlstr += '<span id="modifyConfig_span_id" onclick="modifyConfig_span_onclick(' + row.id + ')">'+'修改'+'</span>'+'|';
htmlstr += '<span id="deleteConfig_span_id" onclick="deleteConfig_span_onclick(' + row.id + ')">'+'删除'+'</span>';
}
break;
case 3: // 可修改不可删除
default:
{
htmlstr += '|';
htmlstr += '<span id="modifyConfig_span_id" onclick="modifyConfig_span_onclick(' + row.id + ')">'+'修改'+'</span>';
}
break;
}
return htmlstr;
}
}
});
}
/**
* 根据输入的条件刷新页面
* @returns
*/
function refreshConfigList () {
$("#grid-data").bootgrid("reload", true);
}
/**
* 系统配置列表标签事件
* @returns
*/
function listConfig_span_onclick() {
showConfigListTab();
}
/**
* 系统配置添加标签事件
* @returns
*/
function addConfig_span_onclick() {
showConfigAddTab();
}
/**
* 查询按钮事件
* @returns
*/
function search_button_onclick() {
$("#grid-data").bootgrid("repage", true);
}
/**
* 保存更新系统配置
* @returns
*/
function saveUpdateConfig_button_onclick() {
var flag = $.html5Validate.isAllpass($("#editConfig_form_id"));
if (flag) {
var id = $("#editConfigId_input_id").val();
var confName = $("#editConfigName_input_id").val();
var confType = $("#editConfigType_select_id").val();
var confKey = $("#editConfigKey_input_id").val();
var confValue = $("#editConfigValue_input_id").val();
var confDesc = $("#editConfigDesc_textarea_id").val();
$.ajax({
type:'POST',
data:{
id:id,
confName:confName,
confType:confType,
confKey:confKey,
confValue:confValue,
confDesc:confDesc
},
url: yyoa_context +'/sys/conf/updateConfig.do',
dataType:'json',
async:false,
success:function(data){
Modal.alert({ msg: data.message });
if(data.state){
refreshConfigList();
showConfigListTab();
}
}
});
}
}
/**
* 取消更新系统配置
* @returns
*/
function cancelUpdateConfig_button_onclick() {
showConfigListTab();
}
/**
* 保存添加系统配置
* @returns
*/
function saveAddConfig_button_onclick() {
var flag = $.html5Validate.isAllpass($("#addConfig_form_id"));
if (flag) {
var confName = $("#addConfigName_input_id").val();
var confType = $("#addConfigType_select_id").val();
var confKey = $("#addConfigKey_input_id").val();
var confValue = $("#addConfigValue_input_id").val();
var confDesc = $("#addConfigDesc_textarea_id").val();
$.ajax({
type:'POST',
data:{
confName:confName,
confType:confType,
confKey:confKey,
confValue:confValue,
confDesc:confDesc
},
url: yyoa_context +'/sys/conf/addConfig.do',
dataType:'json',
async:false,
success:function(data){
Modal.alert({ msg: data.message });
if(data.state){
clearConfigAddInput();
refreshConfigList();
showConfigListTab();
}
}
});
}
}
/**
* 取消添加系统配置
* @returns
*/
function cancelAddConfig_button_onclick() {
showConfigListTab();
clearConfigAddInput();
}
function cancelDetailConfig_button_onclick() {
showConfigListTab();
}
/**
* 系统配置详情
* @param id
* @returns
*/
function detailConfig_span_onclick(id) {
$.ajax({
type:'POST',
data:{id:id},
url: yyoa_context +'/sys/conf/selectByConfigId.do',
dataType:'json',
async:false,
success:function(data){
$("#detailConfigName_input_id").val(data.confName);
$("#detailConfigType_input_id").val(stringFromConfigType(data.confType));
$("#detailConfigKey_input_id").val(data.confKey);
$("#detailConfigValue_input_id").val(data.confValue);
$("#detailConfigDesc_textarea_id").val(data.confDesc);
showConfigDetailTab(data.confName);
}
});
}
/**
* 更新系统配置事件
* @param id
* @returns
*/
function modifyConfig_span_onclick(id) {
$.ajax({
type:'POST',
data:{id:id},
url: yyoa_context +'/sys/conf/selectByConfigId.do',
dataType:'json',
async:false,
success:function(data){
$("#editConfigId_input_id").val(data.id);
$("#editConfigName_input_id").val(data.confName);
$("#editConfigType_select_id").val(data.confType);
$("#editConfigKey_input_id").val(data.confKey);
$("#editConfigValue_input_id").val(data.confValue);
$("#editConfigDesc_textarea_id").val(data.confDesc);
showConfigEditTab(data.confName);
}
});
}
/**
* 删除系统配置
* @param id
* @returns
*/
function deleteConfig_span_onclick(id) {
Modal.confirm(
{
msg: "确定要删除系统配置吗?"
}).on( function (e) {
if (e) {
$.ajax({
type: 'POST',
data: {id: id},
url: yyoa_context + '/sys/conf/deleteByConfigId.do',
dataType: 'json',
async: false,
success: function (data) {
Modal.alert({ msg: data.message });
if (data.state) {
refreshConfigList();
}
}
});
}
});
}
|
'use strict';
define([
], function () {
var AuthService = function (BORAYU, $q, $http, $rootScope, ngProgress) {
this.baseUrl = BORAYU.API_URL + ':' + BORAYU.API_PORT;
this.user = null;
this.token = null;
this.group = null;
this.getHttpOptions = function () {
var authToken = "Token " + this.token,
httpOptions;
httpOptions = {
headers: {
Authorization: authToken
}
};
return httpOptions;
};
this.initialize = function () {
this.getSessionFromStorage();
this.configureNgProgress();
};
this.configureNgProgress = function () {
ngProgress.height(BORAYU.NGPROGRESS_HEIGHT);
ngProgress.color(BORAYU.NGPROGRESS_COLOR);
};
this.logout = function () {
sessionStorage.removeItem("user");
sessionStorage.removeItem("token");
};
this.logIn = function (username, password) {
var self = this,
deferred = $q.defer();
ngProgress.start();
$http.post(this.baseUrl + '/api-token-auth/', {
username: username,
password: password
})
.success(function (data) {
self.setUserSession(data.user, data.token, data.group);
self.saveSessionToStorage();
deferred.resolve(data);
ngProgress.complete();
})
.error(function (status) {
deferred.reject(status);
ngProgress.complete();
});
return deferred.promise;
};
this.setUserSession = function (user, token, group) {
this.user = user;
this.token = token;
this.group = group;
$rootScope.$broadcast(BORAYU.EVENT_LOGIN);
};
this.getSessionFromStorage = function () {
var sessionUser = sessionStorage.getItem('user'),
sessionToken = sessionStorage.getItem('token'),
sessionGroup = sessionStorage.getItem('group');
if (!sessionUser || !sessionToken) {
return;
}
sessionUser = JSON.parse(sessionUser);
this.setUserSession(sessionUser, sessionToken);
};
this.saveSessionToStorage = function () {
sessionStorage.setItem("user", JSON.stringify(this.user));
sessionStorage.setItem("token", this.token);
sessionStorage.setItem("group", this.group);
};
this.initialize();
};
return ['BORAYU', '$q', '$http', '$rootScope', 'ngProgress', AuthService];
});
|
'use strict';
var querystring = require('querystring');
function encoder(key, value) {
if (typeof value === 'number') {
return ['\\', value].join('');
}
if (value === true) {
return '\\true';
}
if (value === false) {
return '\\false';
}
if (value === null) {
return '\\null';
}
if (value === undefined) {
return '\\undefined';
}
return value;
}
function decoder(value) {
var parsed;
if (value === '\\true') {
return true;
}
if (value === '\\false') {
return false;
}
if (value === '\\null') {
return null;
}
if (value === '\\undefined') {
return undefined;
}
if (value.substr(0, 1) === '\\') {
parsed = parseFloat(value.substr(1));
if (String(parsed) === value.substr(1)) {
return parsed;
}
}
return value;
}
function passThrough(value) {
return value;
}
function decode(query) {
var obj = querystring.decode(query, '&', '=', {decodeURIComponent: decoder});
Object.keys(obj).forEach(function (key) {
if (typeof(obj[key]) === 'string' && obj[key].match(/\:/)) {
obj[key] = querystring.decode(obj[key], ',', ':', {decodeURIComponent: decoder});
}
});
return obj;
}
function encode(obj) {
obj = JSON.parse(JSON.stringify(obj, encoder));
Object.keys(obj).forEach(function (key) {
if (obj[key] !== null && typeof obj[key] === 'object') {
Object.keys(obj[key]).forEach(function (key2) {
if (obj[key][key2] !== null && typeof obj[key][key2] === 'object') {
throw new Error('Maximum allowed object depth is 2');
}
});
obj[key] = querystring.stringify(obj[key], ',', ':', {encodeURIComponent: passThrough});
}
});
return querystring.stringify(obj, '&', '=', {encodeURIComponent: passThrough});
}
exports.decode = decode;
exports.encode = encode;
|
/**
* 引入css文件
* 支持css,less,scss三种格式
*/
require('bootstrap/dist/css/bootstrap.min.css');
require('metismenu/dist/metisMenu.min.css');
require('font-awesome/css/font-awesome.min.css');
require('../../styles/common/sb-admin-2.scss');
/**
* 引入js
*/
require('jquery');
require('bootstrap');
require('metisMenu');
require('chart.js');
require('../common/sb-admin-2.js');
require('../common/utils.js');
var chart=require('../data/chart-data.js');
chart.drawArea();
chart.drawBar();
chart.drawLine();
chart.drawDount();
|
describe("DrawChemCache service tests", function () {
beforeEach(module("mmAngularDrawChem"));
var DrawChemCache;
beforeEach(inject(function (_DrawChemCache_) {
DrawChemCache = _DrawChemCache_;
}));
it("should store data in cachedStructures array and retrieve them", function () {
DrawChemCache.addStructure("test");
expect(DrawChemCache.getCurrentStructure()).toEqual("test");
});
it("should not exceed 10 elements in cachedStructures array", function () {
var data = [], i;
for (i = 0; i < 10; i += 1) {
data.push("test" + i);
}
data.forEach(function (d) {
DrawChemCache.addStructure(d);
});
DrawChemCache.addStructure("test10");
expect(DrawChemCache.getCurrentStructure()).toEqual("test10");
expect(DrawChemCache.getStructureLength()).toEqual(10);
});
it("should remember which element in cachedStructures array is currently active", function () {
var data = [], i;
for (i = 0; i < 4; i += 1) {
data.push("test" + i);
}
data.forEach(function (d) {
DrawChemCache.addStructure(d);
});
expect(DrawChemCache.getCurrentStructure()).toEqual("test3");
DrawChemCache.moveLeftInStructures();
expect(DrawChemCache.getCurrentStructure()).toEqual("test2");
DrawChemCache.moveLeftInStructures();
expect(DrawChemCache.getCurrentStructure()).toEqual("test1");
DrawChemCache.moveLeftInStructures();
expect(DrawChemCache.getCurrentStructure()).toEqual("test0");
DrawChemCache.moveLeftInStructures();
expect(DrawChemCache.getCurrentStructure()).toEqual(null);
DrawChemCache.moveLeftInStructures();
expect(DrawChemCache.getCurrentStructure()).toEqual(null);
DrawChemCache.moveRightInStructures();
expect(DrawChemCache.getCurrentStructure()).toEqual("test0");
DrawChemCache.moveRightInStructures();
expect(DrawChemCache.getCurrentStructure()).toEqual("test1");
DrawChemCache.moveRightInStructures();
expect(DrawChemCache.getCurrentStructure()).toEqual("test2");
DrawChemCache.moveRightInStructures();
expect(DrawChemCache.getCurrentStructure()).toEqual("test3");
DrawChemCache.moveRightInStructures();
expect(DrawChemCache.getCurrentStructure()).toEqual("test3");
});
it("should add new data correctly", function () {
var data = [], i;
for (i = 0; i < 4; i += 1) {
data.push("test" + i);
}
data.forEach(function (d) {
DrawChemCache.addStructure(d);
});
expect(DrawChemCache.getCurrentStructure()).toEqual("test3");
DrawChemCache.moveLeftInStructures();
expect(DrawChemCache.getCurrentStructure()).toEqual("test2");
DrawChemCache.moveLeftInStructures();
expect(DrawChemCache.getCurrentStructure()).toEqual("test1");
DrawChemCache.moveLeftInStructures();
DrawChemCache.addStructure("andrzej");
expect(DrawChemCache.getCurrentStructure()).toEqual("andrzej");
DrawChemCache.moveLeftInStructures();
expect(DrawChemCache.getCurrentStructure()).toEqual("test0");
expect(DrawChemCache.getStructureLength()).toEqual(3);
});
}); |
define(['angular',
'ap.config',
'angular.route',
'cfail/filter/filter-user/filter-user',
'cfail/filter/filter-url/filter-url',
'cfail/filter/filter-failures/filter-failures',
'cfail/filter/filter-client/filter-client',
'cfail/exception/exception',
'cfail/admin/admin',
'cfail/report/report',
'cfail/settings/settings',
'cfail/application/application-create-dialog/application-create-dialog'], function(angular, config) {
var deps = ['cfail',
'ngRoute',
'cfail.filter.user',
'cfail.filter.failures',
'cfail.filter.url',
'cfail.filter.client',
'cfail.exception',
'cfail.admin',
'cfail.report',
'cfail.settings',
'application.create',
'ui.bootstrap'];
angular.module('cfail.main', deps).
config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.
when('/app/:appId/filter-user', {
templateUrl: '/cfail/filter/filter-user/filter-user.html',
controller: 'FilterUserController'
}).
when('/app/:appId/filter-url', {
templateUrl: '/cfail/filter/filter-url/filter-url.html',
controller: 'FilterUrlController'
}).
when('/app/:appId/filter-failures', {
templateUrl: '/cfail/filter/filter-failures/filter-failures.html',
controller: 'FilterFailuresController'
}).
when('/app/:appId/filter-client', {
templateUrl: '/cfail/filter/filter-client/filter-client.html',
controller: 'FilterClientController'
}).
when('/app/:appId/admin/:subsection?', {
templateUrl: '/cfail/admin/admin.html',
controller: 'AdminController'
}).
when('/app/:appId/report', {
templateUrl: '/cfail/report/report.html',
controller: 'ReportController'
}).
when('/app/failure/:exceptionId', {
templateUrl: '/cfail/exception/exception.html',
controller: 'ExceptionController'
}).
when('/settings', {
templateUrl: '/cfail/settings/settings.html',
controller: 'SettingsController'
}).
otherwise({
redirectTo: '/app/' + config.stagedList[0].id + '/filter-failures'
});
$locationProvider.html5Mode(true);
}]).
controller('MainController', ['$scope', '$modal', '$rootScope', '$routeParams', '$location',
function($scope, $modal, $rootScope, $routeParams, $location) {
$scope.stagedList = config.stagedList;
$scope.currentStaged = config.stagedList[0];
$scope.createApplication = function() {
var modal = $modal.open({
templateUrl: '/cfail/application/application-create-dialog/application-create-dialog.html',
controller: 'ApplicationCreateController',
keyboard: true
});
};
$rootScope.$on('$routeChangeSuccess', function(e) {
if (!$routeParams.appId) return;
var activeNavItem = $location.path().split('/').pop();
$scope.activeNavItem = activeNavItem;
});
}]);
}); |
/**
* chester
*/
angular.module("SkyboxApp", ['angularSpinner', 'angularSoap','ngRoute','base64','ngCookies'])
.controller('SkyboxController',['$rootScope', '$scope', 'icSOAPServices', '$soap', '$http', function($rootScope, $scope, icSOAPServices, $soap, $http) {
$scope.Acct = "";
// Tab counter
// var counter = 1;
// Array to store the tabs
$scope.LoggedIN = false;
$scope.tabs = [{
title: "Main",
url: "MainPanel/Main.html",
pgclass:"fa fa-shield",
ref:"#main"
}];
$rootScope.$on('loggin_event', function () {
$scope.LoggedIN = true;
});
$scope.$on('savedata',function(event,data) {
//receive the data as second parameter
$scope.Acct = data;
});
}])
.controller('testController',function($scope){
$scope.msg="hi there";
})
.config(function($routeProvider, $locationProvider, $httpProvider){
// $httpProvider.defaults.useXdomain = true;
// delete $httpProvider.defaults.headers.common['X-Requested-With'];
$routeProvider
.when('/info',{
templateUrl:'icLogin/login.html',
controller: 'View1Ctrl'
})
.when('/newPW',{
templateUrl:'UserLogin/ChangePW.html',
controller: 'ChangePWCtrl'
})
.when('/',{
templateUrl:'UserLogin/UserLogin.html',
controller: 'UserLoginCtrl'
})
.when('/initialization',{
templateUrl:'icLogin/login.html',
controller: 'View1Ctrl'
})
.when('/team',{
templateUrl:'TeamPanel/Team.html',
controller: 'TeamCtrl'
})
.when('/teammod',{
templateUrl:'TeamPanel/TeamAdd.html',
controller: 'TeammodCtrl'
})
.when('/teamadd',{
templateUrl:'TeamPanel/TeamAdd.html',
controller: 'TeamaddCtrl'
})
.when('/disposition',{
templateUrl:'DispositionPanel/Disposition.html',
controller: 'DispositionCtrl'
})
.when('/dispositionmod',{
templateUrl:'DispositionPanel/DispositionAdd.html',
controller: 'DispositionmodCtrl'
})
.when('/dispositionadd',{
templateUrl:'DispositionPanel/DispositionAdd.html',
controller: 'DispositionaddCtrl'
})
.when('/displistmod',{
templateUrl:'DispositionPanel/DispositionListMod.html',
controller: 'DispositionListCtrl'
})
.when('/teamoutstate',{
templateUrl:'TeamOutState/TeamOutState.html',
controller: 'TeamOutstateCtrl'
})
.when('/skilldisp',{
templateUrl:'SkillDisposition/SkillDisp.html',
controller: 'SkillDispCtrl'
})
.when('/outstate',{
templateUrl:'OutStatePanel/OutState.html',
controller: 'OutstateCtrl'
})
.when('/outstatemod',{
templateUrl:'OutStatePanel/OutStateAdd.html',
controller: 'OutstatemodCtrl'
})
.when('/outstateadd',{
templateUrl:'OutStatePanel/OutStateAdd.html',
controller: 'OutstateaddCtrl'
})
.when('/campaign',{
templateUrl:'CampaignPanel/Campaign.html',
controller: 'CampaignCtrl'
})
.when('/campaignmod',{
templateUrl:'CampaignPanel/CampaignAdd.html',
controller: 'CampaignmodCtrl'
})
.when('/campaignadd',{
templateUrl:'CampaignPanel/CampaignAdd.html',
controller: 'CampaignaddCtrl'
})
.when('/skillAdd',{
templateUrl:'SkillPanel/SkillAddMod.html',
controller: 'SkillAddCtrl'
})
.when('/skillBRDAdd',{
templateUrl:'SkillPanel/SkillBRDAdd.html',
controller: 'SkillBRDAddCtrl'
})
.when('/skillMod',{
templateUrl:'SkillPanel/SkillAddMod.html',
controller: 'SkillModCtrl'
})
.when('/skill',{
templateUrl:'SkillPanel/Skill.html',
controller: 'SkillCtrl'
})
.when('/skillPost',{
templateUrl:'SkillPanel/SkillPostContactMapping.html',
controller: 'SkillPostContactCtrl'
})
.when('/skillList',{
templateUrl:'SkillPanel/SkillListMod.html',
controller: 'SkillListModCtrl'
})
.when('/agent',{
templateUrl:'Agents/Agent.html',
controller: 'AgentCtrl'
})
.when('/POC',{
templateUrl:'POCs/POCs.html',
controller: 'POCCtrl'
})
.when('/agentSkill',{
templateUrl:'AgentSkill/AgentSkill.html',
controller: 'AgentSkillCtrl'
})
.when('/main',{
templateUrl:'MainPanel/Main.html',
controller: 'MainCtrl'
});
$locationProvider.html5Mode({
enable:true,
requireBase:false
});
});
|
'use strict';
angular.module('mean.trialmatch').factory('Trialmatch', [
function() {
return {
name: 'trialmatch'
};
}
]);
|
'use strict';
var createStore = require('fluxible/addons/createStore');
var makeHandlers = require('../lib/fluxible/makeHandlers');
var Actions = require('../constants/Actions');
var _ = require('lodash');
module.exports = createStore({
storeName: 'BusinessLeadStore',
handlers: makeHandlers({
onHairdresserRegistration: Actions.HAIRDRESSER_REGISTRATION_SUCCESS
}),
initialize: function () {
this.registeredHairdresser = false;
},
dehydrate: function () {
return { registeredHairdresser: this.registeredHairdresser };
},
rehydrate: function (state) {
this.registeredHairdresser = state.registeredHairdresser;
},
onHairdresserRegistration: function (subscriber) {
this.registeredHairdresser = true;
this.emitChange();
},
getHairdresserRegistrationStatus: function () {
return this.registeredHairdresser;
}
}); |
/*************************************************************
*
* MathJax/localization/lki/HTML-CSS.js
*
* Copyright (c) 2009-2016 The MathJax Consortium
*
* 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.
*
*/
MathJax.Localization.addTranslation("lki","HTML-CSS",{
version: "2.7.0-beta",
isLoaded: true,
strings: {
LoadWebFont: "\u0628\u0627\u0631\u06AF\u06CC\u0631\u06CC \u0642\u0644\u0645 \u0648\u0628\u06CC %1",
CantLoadWebFont: "\u0646\u0645\u06CC\u200C\u062A\u0648\u0627\u0646 \u0642\u0644\u0645 \u0648\u0628\u06CC %1 \u0631\u0627 \u0628\u0627\u0631\u06AF\u06CC\u0631\u06CC \u06A9\u0631\u062F",
FirefoxCantLoadWebFont: "\u0641\u0627\u06CC\u0631\u0641\u0627\u06A9\u0633 \u0646\u0645\u06CC\u200C\u062A\u0648\u0627\u0646\u062F \u0642\u0644\u0645\u200C\u0647\u0627\u06CC \u0648\u0628\u06CC \u0631\u0627 \u0627\u0632 \u06CC\u06A9 \u0645\u06CC\u0632\u0627\u0646 \u0627\u0632 \u0631\u0627\u0647 \u062F\u0648\u0631 \u0628\u0627\u0631\u06AF\u06CC\u0631\u06CC \u06A9\u0646\u062F",
CantFindFontUsing: "\u0646\u0645\u06CC\u200C\u062A\u0648\u0627\u0646 \u06CC\u06A9 \u0642\u0644\u0645 \u0645\u0639\u062A\u0628\u0631 \u0628\u0627\u0627\u0633\u062A\u0641\u0627\u062F\u0647 \u0627\u0632 %1 \u06CC\u0627\u0641\u062A",
WebFontsNotAvailable: "\u0642\u0644\u0645\u200C\u0647\u0627\u06CC \u0648\u0628\u06CC \u0646\u0627\u0645\u0648\u062C\u0648\u062F\u0646\u062F -- \u0627\u0633\u062A\u0641\u0627\u062F\u0647 \u0627\u0632 \u0642\u0644\u0645\u200C\u0647\u0627\u06CC \u062A\u0635\u0648\u06CC\u0631\u06CC \u0628\u0647 \u062C\u0627\u06CC \u0622\u0646"
}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/lki/HTML-CSS.js");
|
'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const request = require('request')
const app = express()
app.set('port', (process.env.PORT || 5000))
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}))
// parse application/json
app.use(bodyParser.json())
// index
app.get('/', function (req, res) {
res.send('hello world i am a secret bot')
})
// for facebook verification
app.get('/webhook/', function (req, res) {
if (req.query['hub.verify_token'] === 'my_voice_is_my_password_verify_me') {
res.send(req.query['hub.challenge'])
}
res.send('Error, wrong token')
})
// to post data
app.post('/webhook/', function (req, res) {
let messaging_events = req.body.entry[0].messaging
for (let i = 0; i < messaging_events.length; i++) {
let event = req.body.entry[0].messaging[i]
let sender = event.sender.id
if (event.message && event.message.text) {
let text = event.message.text
if (text === 'Major') {
sendGenericMessage(sender)
continue
}
if (text === 'Hello') {
sendTextMessage(sender, "How can I help you?")
continue
}
if (text === 'Thanks') {
sendTextMessage(sender, "You're welcome! Would you like our agent contact you to better assist you?")
continue
}
if (text === 'Financial aid') {
sendTextMessage(sender, "Receive up to $5,775 in Federal Pell Grants, if you qualify")
continue
}
if (text === 'Call center hours') {
sendTextMessage(sender, "Our agent will call you within 9am EST to 5pm EST hours")
continue
}
sendTextMessage(sender, "Text received, echo: " + text.substring(0, 200))
}
if (event.postback) {
let text = JSON.stringify(event.postback)
sendTextMessage(sender, "Postback received: "+text.substring(0, 200), token)
continue
}
}
res.sendStatus(200)
})
const token = "EAALFMaX6ry0BAHHWQvrJ5aKPXDcJ9xPd6YgLMQp2yAbkwrTK4aZAmEVZBZAnkl9PGujW1Ei5BSXaiTmJMHL6GXUWd3DB9DPZBjIv2ZB7eNSWt6GCNsasZAhDmAPOigZAZAJ3T26KMZBRrN4OaAXaaHSsA9IulQrfhtpOgw60PZCUTnyNp1PAXKW4rA"
function sendTextMessage(sender, text) {
let messageData = { text:text }
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
function sendGenericMessage(sender) {
let messageData = {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [{
"title": "Art&Design",
"subtitle": "Areas of Interest",
"image_url": "https://raw.githubusercontent.com/jennyzzz00/hello-world/master/ArtDesign.png",
"buttons": [{
"type": "web_url",
"url": "https://www.messenger.com",
"title": "web url"
}, {
"type": "postback",
"title": "Postback",
"payload": "Payload for first element in a generic bubble",
}],
}, {
"title": "Business",
"subtitle": "Areas of Interest",
"image_url": "https://raw.githubusercontent.com/jennyzzz00/hello-world/master/Business.png",
"buttons": [{
"type": "postback",
"title": "Postback",
"payload": "Payload for second element in a generic bubble",
}],
}]
}
}
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error)
} else if (response.body.error) {
console.log('Error: ', response.body.error)
}
})
}
// spin spin sugar
app.listen(app.get('port'), function() {
console.log('running on port', app.get('port'))
})
|
(function(){
"use strict";
angular.module( 'app.controllers' ).controller( 'GradientCreatorCtrl', function(){
//
});
})();
|
const koa = require('koa');
const logger = require('koa-logger');
const limit = require('koa-better-ratelimit');
const compress = require('koa-compress');
const responseTime = require('koa-response-time');
const cors = require('koa-cors');
const config = require('../config/config');
const users = require('./resources/users');
const lessons = require('./resources/lessons');
const resources = [
users,
lessons,
];
const app = koa();
app.use(logger());
app.use(responseTime());
app.use(cors({
origin: config.app.host,
}));
app.use(limit({
duration: 3*60*1000,
max: 100,
blacklist: ['127.0.0.1'],
}));
app.use(compress({
flush: require('zlib').Z_SYNC_FLUSH,
}));
for (const resource of resources) {
app.use(resource.middleware());
}
app.listen(3000);
|
'use strict';
// Employers controller
angular.module('employers').controller('EmployersController', ['$scope', '$stateParams', '$location', 'Authentication', 'Employers',
function($scope, $stateParams, $location, Authentication, Employers ) {
$scope.authentication = Authentication;
// Create new Employer
$scope.create = function() {
// Create new Employer object
var employer = new Employers ({
name: this.name
});
// Redirect after save
employer.$save(function(response) {
$location.path('employers/' + response._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
// Clear form fields
this.name = '';
};
// Remove existing Employer
$scope.remove = function( employer ) {
if ( employer ) { employer.$remove();
for (var i in $scope.employers ) {
if ($scope.employers [i] === employer ) {
$scope.employers.splice(i, 1);
}
}
} else {
$scope.employer.$remove(function() {
$location.path('employers');
});
}
};
// Update existing Employer
$scope.update = function() {
var employer = $scope.employer ;
employer.$update(function() {
$location.path('employers/' + employer._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Employers
$scope.find = function() {
$scope.employers = Employers.query();
};
// Find existing Employer
$scope.findOne = function() {
$scope.employer = Employers.get({
employerId: $stateParams.employerId
});
};
}
]); |
import path from 'path'
import webpack from 'webpack'
const { NODE_ENV } = process.env
const plugins = [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
}),
]
const filename = `redux-promise-bind${NODE_ENV === 'production' ? '.min' : ''}.js`
NODE_ENV === 'production' && plugins.push(
new webpack.optimize.UglifyJsPlugin({
compressor: {
pure_getters: true,
unsafe: true,
unsafe_comps: true,
screw_ie8: true,
warnings: false,
},
})
)
export default {
entry: ['./src/index'],
output: {
path: path.join(__dirname, 'dist'),
filename,
library: 'ReduxPromiseBind',
libraryTarget: 'umd',
},
resolve: {
modules: [path.resolve(__dirname, 'src'), 'node_modules'],
extensions: ['.js', '.jsx'],
},
plugins,
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' },
],
},
}
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Keyboard class monitors keyboard input and dispatches keyboard events.
*
* _Note_: many keyboards are unable to process certain combinations of keys due to hardware limitations known as ghosting.
* See http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/ for more details.
*
* Also please be aware that certain browser extensions can disable or override Phaser keyboard handling.
* For example the Chrome extension vimium is known to disable Phaser from using the D key. And there are others.
* So please check your extensions before opening Phaser issues.
*
* @class Phaser.Keyboard
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
*/
Phaser.Keyboard = function (game)
{
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = game;
/**
* Whether the handler has started.
* @property {boolean} active
* @default
*/
this.active = false;
/**
* Keyboard input will only be processed if enabled.
* @property {boolean} enabled
* @default
*/
this.enabled = true;
/**
* @property {KeyboardEvent} event - The most recent DOM event from keydown or keyup. This is updated every time a new key is pressed or released.
*/
this.event = null;
/**
* @property {object} pressEvent - The most recent DOM event from keypress.
*/
this.pressEvent = null;
/**
* @property {object} callbackContext - The context under which the callbacks are run.
*/
this.callbackContext = this;
/**
* @property {function} onDownCallback - This callback is invoked every time a key is pressed down, including key repeats when a key is held down. One argument is passed: {KeyboardEvent} event.
*/
this.onDownCallback = null;
/**
* @property {function} onPressCallback - This callback is invoked every time a DOM onkeypress event is raised, which is only for printable keys. Two arguments are passed: {string} `String.fromCharCode(event.charCode)` and {KeyboardEvent} event.
*/
this.onPressCallback = null;
/**
* @property {function} onUpCallback - This callback is invoked every time a key is released. One argument is passed: {KeyboardEvent} event.
*/
this.onUpCallback = null;
/**
* @property {array<Phaser.Key>} _keys - The array the Phaser.Key objects are stored in.
* @private
*/
this._keys = [];
/**
* @property {array} _capture - The array the key capture values are stored in.
* @private
*/
this._capture = [];
/**
* @property {function} _onKeyDown
* @private
* @default
*/
this._onKeyDown = null;
/**
* @property {function} _onKeyPress
* @private
* @default
*/
this._onKeyPress = null;
/**
* @property {function} _onKeyUp
* @private
* @default
*/
this._onKeyUp = null;
/**
* @property {number} _i - Internal cache var
* @private
*/
this._i = 0;
/**
* @property {number} _k - Internal cache var
* @private
*/
this._k = 0;
};
Phaser.Keyboard.prototype = {
/**
* Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated.
*
* @method Phaser.Keyboard#addCallbacks
* @param {object} context - The context under which the callbacks are run.
* @param {function} [onDown=null] - This callback is invoked every time a key is pressed down.
* @param {function} [onUp=null] - This callback is invoked every time a key is released.
* @param {function} [onPress=null] - This callback is invoked every time the onkeypress event is raised.
*/
addCallbacks: function (context, onDown, onUp, onPress)
{
this.callbackContext = context;
if (onDown !== undefined && onDown !== null)
{
this.onDownCallback = onDown;
}
if (onUp !== undefined && onUp !== null)
{
this.onUpCallback = onUp;
}
if (onPress !== undefined && onPress !== null)
{
this.onPressCallback = onPress;
}
},
/**
* Removes callbacks added by {@link #addCallbacks} and restores {@link #callbackContext}.
*
* @method Phaser.Keyboard#removeCallbacks
*/
removeCallbacks: function ()
{
this.callbackContext = this;
this.onDownCallback = null;
this.onUpCallback = null;
this.onPressCallback = null;
},
/**
* If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method.
* The Key object can then be polled, have events attached to it, etc.
*
* @method Phaser.Keyboard#addKey
* @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key.
* @return {Phaser.Key} The Key object which you can store locally and reference directly.
*/
addKey: function (keycode)
{
if (!this._keys[keycode])
{
this._keys[keycode] = new Phaser.Key(this.game, keycode);
this.addKeyCapture(keycode);
}
return this._keys[keycode];
},
/**
* A practical way to create an object containing user selected hotkeys.
*
* For example,
*
* addKeys( { 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S, 'left': Phaser.KeyCode.A, 'right': Phaser.KeyCode.D } );
*
* would return an object containing properties (`up`, `down`, `left` and `right`) referring to {@link Phaser.Key} object.
*
* @method Phaser.Keyboard#addKeys
* @param {object} keys - A key mapping object, i.e. `{ 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S }` or `{ 'up': 52, 'down': 53 }`.
* @return {object} An object containing the properties mapped to {@link Phaser.Key} values.
*/
addKeys: function (keys)
{
var output = {};
for (var key in keys)
{
output[key] = this.addKey(keys[key]);
}
return output;
},
/**
* Removes a Key object from the Keyboard manager.
*
* @method Phaser.Keyboard#removeKey
* @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to remove.
*/
removeKey: function (keycode)
{
if (this._keys[keycode])
{
this._keys[keycode] = null;
this.removeKeyCapture(keycode);
}
},
/**
* Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right.
*
* @method Phaser.Keyboard#createCursorKeys
* @return {object} An object containing properties: `up`, `down`, `left` and `right` of {@link Phaser.Key} objects.
*/
createCursorKeys: function ()
{
return this.addKeys({ up: Phaser.KeyCode.UP, down: Phaser.KeyCode.DOWN, left: Phaser.KeyCode.LEFT, right: Phaser.KeyCode.RIGHT });
},
/**
* Starts the Keyboard event listeners running (keydown, keyup and keypress). They are attached to the window.
* This is called automatically by Phaser.Input and should not normally be invoked directly.
*
* @method Phaser.Keyboard#start
* @protected
* @return {boolean}
*/
start: function ()
{
if (this.game.device.cocoonJS)
{
return false;
}
if (this.active)
{
// Avoid setting multiple listeners
return false;
}
var _this = this;
this._onKeyDown = function (event)
{
return _this.processKeyDown(event);
};
this._onKeyUp = function (event)
{
return _this.processKeyUp(event);
};
this._onKeyPress = function (event)
{
return _this.processKeyPress(event);
};
window.addEventListener('keydown', this._onKeyDown, false);
window.addEventListener('keyup', this._onKeyUp, false);
window.addEventListener('keypress', this._onKeyPress, false);
this.active = true;
return true;
},
/**
* Stops the Keyboard event listeners from running (keydown, keyup and keypress). They are removed from the window.
*
* @method Phaser.Keyboard#stop
*/
stop: function ()
{
window.removeEventListener('keydown', this._onKeyDown);
window.removeEventListener('keyup', this._onKeyUp);
window.removeEventListener('keypress', this._onKeyPress);
this._onKeyDown = null;
this._onKeyUp = null;
this._onKeyPress = null;
this.active = false;
},
/**
* Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window.
* Also clears all key captures and currently created Key objects.
*
* @method Phaser.Keyboard#destroy
*/
destroy: function ()
{
this.stop();
this.clearCaptures();
this._keys.length = 0;
this._i = 0;
},
/**
* By default when a key is pressed Phaser will not stop the event from propagating up to the browser.
* There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll.
*
* The `addKeyCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser
* and cause the default browser behavior.
*
* Pass in either a single keycode or an array/hash of keycodes.
*
* @method Phaser.Keyboard#addKeyCapture
* @param {integer|integer[]|object} keycode - Either a single {@link Phaser.KeyCode keycode} or an array/hash of keycodes such as `[65, 67, 68]`.
*/
addKeyCapture: function (keycode)
{
if (typeof keycode === 'object')
{
for (var key in keycode)
{
this._capture[keycode[key]] = true;
}
}
else
{
this._capture[keycode] = true;
}
},
/**
* Removes an existing key capture.
*
* @method Phaser.Keyboard#removeKeyCapture
* @param {integer} keycode - The {@link Phaser.KeyCode keycode} to remove capturing of.
*/
removeKeyCapture: function (keycode)
{
delete this._capture[keycode];
},
/**
* Clear all set key captures.
*
* @method Phaser.Keyboard#clearCaptures
*/
clearCaptures: function ()
{
this._capture = {};
},
/**
* Updates all currently defined keys.
*
* @method Phaser.Keyboard#update
*/
update: function ()
{
this._i = this._keys.length;
while (this._i--)
{
if (this._keys[this._i])
{
this._keys[this._i].update();
}
}
},
/**
* Process the keydown event.
*
* @method Phaser.Keyboard#processKeyDown
* @param {KeyboardEvent} event
* @protected
*/
processKeyDown: function (event)
{
this.event = event;
if (!this.game.input.enabled || !this.enabled)
{
return;
}
var key = event.keyCode;
// The event is being captured but another hotkey may need it
if (this._capture[key])
{
event.preventDefault();
}
if (!this._keys[key])
{
this._keys[key] = new Phaser.Key(this.game, key);
}
this._keys[key].processKeyDown(event);
this._k = key;
if (this.onDownCallback)
{
this.onDownCallback.call(this.callbackContext, event);
}
},
/**
* Process the keypress event.
*
* @method Phaser.Keyboard#processKeyPress
* @param {KeyboardEvent} event
* @protected
*/
processKeyPress: function (event)
{
this.pressEvent = event;
if (!this.game.input.enabled || !this.enabled)
{
return;
}
if (this.onPressCallback)
{
this.onPressCallback.call(this.callbackContext, String.fromCharCode(event.charCode), event);
}
},
/**
* Process the keyup event.
*
* @method Phaser.Keyboard#processKeyUp
* @param {KeyboardEvent} event
* @protected
*/
processKeyUp: function (event)
{
this.event = event;
if (!this.game.input.enabled || !this.enabled)
{
return;
}
var key = event.keyCode;
if (this._capture[key])
{
event.preventDefault();
}
if (!this._keys[key])
{
this._keys[key] = new Phaser.Key(this.game, key);
}
this._keys[key].processKeyUp(event);
if (this.onUpCallback)
{
this.onUpCallback.call(this.callbackContext, event);
}
},
/**
* Resets all Keys.
*
* @method Phaser.Keyboard#reset
* @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to the Keys. A hard reset will.
*/
reset: function (hard)
{
if (hard === undefined) { hard = true; }
this.event = null;
var i = this._keys.length;
while (i--)
{
if (this._keys[i])
{
this._keys[i].reset(hard);
}
}
},
/**
* Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down,
* or was pressed down longer ago than then given duration.
*
* @method Phaser.Keyboard#downDuration
* @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR.
* @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms.
* @return {boolean} True if the key was pressed down within the given duration, false if not or null if the Key wasn't found.
*/
downDuration: function (keycode, duration)
{
if (this._keys[keycode])
{
return this._keys[keycode].downDuration(duration);
}
else
{
return null;
}
},
/**
* Returns `true` if the Key has been up *only* within the `duration` value given, or `false` if it either isn't up,
* or was has been up longer than the given duration.
*
* @method Phaser.Keyboard#upDuration
* @param {Phaser.KeyCode|integer} keycode - The keycode of the key to check, i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR.
* @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms.
* @return {boolean} True if the key was released within the given duration, false if not or null if the Key wasn't found.
*/
upDuration: function (keycode, duration)
{
if (this._keys[keycode])
{
return this._keys[keycode].upDuration(duration);
}
else
{
return null;
}
},
justPressed: function (keycode)
{
if (this._keys[keycode])
{
return this._keys[keycode].justPressed();
}
else
{
return null;
}
},
justReleased: function (keycode)
{
if (this._keys[keycode])
{
return this._keys[keycode].justReleased();
}
else
{
return null;
}
},
/**
* Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser.
*
* @method Phaser.Keyboard#isDown
* @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR.
* @return {boolean} True if the key is currently down, false if not or null if the Key wasn't found.
*/
isDown: function (keycode)
{
if (this._keys[keycode])
{
return this._keys[keycode].isDown;
}
else
{
return null;
}
}
};
/**
* Returns the string value of the most recently pressed key.
* @name Phaser.Keyboard#lastChar
* @property {string} lastChar - The string value of the most recently pressed key.
* @readonly
*/
Object.defineProperty(Phaser.Keyboard.prototype, 'lastChar', {
get: function ()
{
if (this.event && this.event.charCode === 32)
{
return '';
}
else if (this.pressEvent)
{
return String.fromCharCode(this.pressEvent.charCode);
}
else
{
return null;
}
}
});
/**
* Returns the most recently pressed Key. This is a Phaser.Key object and it changes every time a key is pressed.
* @name Phaser.Keyboard#lastKey
* @property {Phaser.Key} lastKey - The most recently pressed Key.
* @readonly
*/
Object.defineProperty(Phaser.Keyboard.prototype, 'lastKey', {
get: function ()
{
return this._keys[this._k];
}
});
Phaser.Keyboard.prototype.constructor = Phaser.Keyboard;
/**
* A key code represents a physical key on a keyboard.
*
* The KeyCode class contains commonly supported keyboard key codes which can be used
* as keycode`-parameters in several {@link Phaser.Keyboard} and {@link Phaser.Key} methods.
*
* _Note_: These values should only be used indirectly, eg. as `Phaser.KeyCode.KEY`.
* Future versions may replace the actual values, such that they remain compatible with `keycode`-parameters.
* The current implementation maps to the {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode KeyboardEvent.keyCode} property.
*
* _Note_: Use `Phaser.KeyCode.KEY` instead of `Phaser.Keyboard.KEY` to refer to a key code;
* the latter approach is supported for compatibility.
*
* @class Phaser.KeyCode
*/
Phaser.KeyCode = {
/** @static */
A: 'A'.charCodeAt(0),
/** @static */
B: 'B'.charCodeAt(0),
/** @static */
C: 'C'.charCodeAt(0),
/** @static */
D: 'D'.charCodeAt(0),
/** @static */
E: 'E'.charCodeAt(0),
/** @static */
F: 'F'.charCodeAt(0),
/** @static */
G: 'G'.charCodeAt(0),
/** @static */
H: 'H'.charCodeAt(0),
/** @static */
I: 'I'.charCodeAt(0),
/** @static */
J: 'J'.charCodeAt(0),
/** @static */
K: 'K'.charCodeAt(0),
/** @static */
L: 'L'.charCodeAt(0),
/** @static */
M: 'M'.charCodeAt(0),
/** @static */
N: 'N'.charCodeAt(0),
/** @static */
O: 'O'.charCodeAt(0),
/** @static */
P: 'P'.charCodeAt(0),
/** @static */
Q: 'Q'.charCodeAt(0),
/** @static */
R: 'R'.charCodeAt(0),
/** @static */
S: 'S'.charCodeAt(0),
/** @static */
T: 'T'.charCodeAt(0),
/** @static */
U: 'U'.charCodeAt(0),
/** @static */
V: 'V'.charCodeAt(0),
/** @static */
W: 'W'.charCodeAt(0),
/** @static */
X: 'X'.charCodeAt(0),
/** @static */
Y: 'Y'.charCodeAt(0),
/** @static */
Z: 'Z'.charCodeAt(0),
/** @static */
ZERO: '0'.charCodeAt(0),
/** @static */
ONE: '1'.charCodeAt(0),
/** @static */
TWO: '2'.charCodeAt(0),
/** @static */
THREE: '3'.charCodeAt(0),
/** @static */
FOUR: '4'.charCodeAt(0),
/** @static */
FIVE: '5'.charCodeAt(0),
/** @static */
SIX: '6'.charCodeAt(0),
/** @static */
SEVEN: '7'.charCodeAt(0),
/** @static */
EIGHT: '8'.charCodeAt(0),
/** @static */
NINE: '9'.charCodeAt(0),
/** @static */
NUMPAD_0: 96,
/** @static */
NUMPAD_1: 97,
/** @static */
NUMPAD_2: 98,
/** @static */
NUMPAD_3: 99,
/** @static */
NUMPAD_4: 100,
/** @static */
NUMPAD_5: 101,
/** @static */
NUMPAD_6: 102,
/** @static */
NUMPAD_7: 103,
/** @static */
NUMPAD_8: 104,
/** @static */
NUMPAD_9: 105,
/** @static */
NUMPAD_MULTIPLY: 106,
/** @static */
NUMPAD_ADD: 107,
/** @static */
NUMPAD_ENTER: 108,
/** @static */
NUMPAD_SUBTRACT: 109,
/** @static */
NUMPAD_DECIMAL: 110,
/** @static */
NUMPAD_DIVIDE: 111,
/** @static */
F1: 112,
/** @static */
F2: 113,
/** @static */
F3: 114,
/** @static */
F4: 115,
/** @static */
F5: 116,
/** @static */
F6: 117,
/** @static */
F7: 118,
/** @static */
F8: 119,
/** @static */
F9: 120,
/** @static */
F10: 121,
/** @static */
F11: 122,
/** @static */
F12: 123,
/** @static */
F13: 124,
/** @static */
F14: 125,
/** @static */
F15: 126,
/** @static */
COLON: 186,
/** @static */
EQUALS: 187,
/** @static */
COMMA: 188,
/** @static */
UNDERSCORE: 189,
/** @static */
PERIOD: 190,
/** @static */
QUESTION_MARK: 191,
/** @static */
TILDE: 192,
/** @static */
OPEN_BRACKET: 219,
/** @static */
BACKWARD_SLASH: 220,
/** @static */
CLOSED_BRACKET: 221,
/** @static */
QUOTES: 222,
/** @static */
BACKSPACE: 8,
/** @static */
TAB: 9,
/** @static */
CLEAR: 12,
/** @static */
ENTER: 13,
/** @static */
SHIFT: 16,
/** @static */
CONTROL: 17,
/** @static */
ALT: 18,
/** @static */
CAPS_LOCK: 20,
/** @static */
ESC: 27,
/** @static */
SPACEBAR: 32,
/** @static */
PAGE_UP: 33,
/** @static */
PAGE_DOWN: 34,
/** @static */
END: 35,
/** @static */
HOME: 36,
/** @static */
LEFT: 37,
/** @static */
UP: 38,
/** @static */
RIGHT: 39,
/** @static */
DOWN: 40,
/** @static */
PLUS: 43,
/** @static */
MINUS: 44,
/** @static */
INSERT: 45,
/** @static */
DELETE: 46,
/** @static */
HELP: 47,
/** @static */
NUM_LOCK: 144
};
// Duplicate Phaser.KeyCode values in Phaser.Keyboard for compatibility
for (var key in Phaser.KeyCode)
{
if (Phaser.KeyCode.hasOwnProperty(key) && !key.match(/[a-z]/))
{
Phaser.Keyboard[key] = Phaser.KeyCode[key];
}
}
|
/*
---
description: Creates instances of Drag for resizable elements.
provides: [Behavior.Resizable]
requires: [Behavior/Behavior, More/Drag]
script: Behavior.Resizable.js
name: Behavior.Resizable
...
*/
Behavior.addGlobalFilter('Resizable', {
//deprecated options
deprecated: {
handle: 'resize-handle',
child: 'resize-child'
},
deprecatedAsJSON: {
modifiers: 'resize-modifiers'
},
setup: function(element, api){
var options = {};
if (api.get('handle')) options.handle = element.getElement(api.get('handle'));
if (api.get('modifiers')) options.modifiers = api.getAs(Object, 'modifiers');
var target = element;
if (api.get('child')) target = element.getElement(api.get('child'));
var drag = target.makeResizable(options);
api.onCleanup(drag.detach.bind(drag));
return drag;
}
});
|
function log(str) {
self.postMessage({
log: str
});
}
self.onmessage = function (e) {
importScripts('http://' + e.data.host + '/kissy/build/seed.js');
KISSY.config('base', 'http://' + e.data.host + '/kissy/build/');
//KISSY.config('combine',true);
KISSY.config('loadModsFn', function (rs, config) {
importScripts(rs.fullpath);
config.success();
});
var S = KISSY;
S.use('color', function (S, Color) {
// reuse
var color = new Color({
r: 0,
g: 0,
b: 0
});
self.onmessage = function (e) {
var originalImageData = e.data.data;
var percentage = e.data.percentage;
var pixelData = [];
for (var i = 0; i < originalImageData.length; i += 4) {
var r = originalImageData[i];
var g = originalImageData[i + 1];
var b = originalImageData[i + 2];
color.set({
r: r,
g: g,
b: b
});
var hsl = color.getHSL();
hsl.h *= percentage.h;
hsl.s *= percentage.s;
hsl.l *= percentage.l;
color.setHSL(hsl);
pixelData[i] = color.get('r');
pixelData[i + 1] = color.get('g');
pixelData[i + 2] = color.get('b');
pixelData[i + 3] = originalImageData[i + 3];
}
self.postMessage({
data: pixelData,
callback: e.data.callback
});
};
self.postMessage({
complete: 1
});
});
}; |
const assert = require("assert");
const XRegExp = require("xregexp");
const quotemeta = require("./xregexp-quotemeta");
quotemeta.addSupportTo(XRegExp);
assert(XRegExp('^\\Q(?*+)').test('(?*+)'));
assert(XRegExp('^\\Q.\\E.').test('.x'));
assert(!XRegExp('^\\Q.\\E.').test('xx'));
assert(XRegExp('^\\Q\\E$').test(''));
assert(!XRegExp('^\\Q\\E$').test('x'));
assert.throws(() => XRegExp('\\E'));
|
/******************************************************************************
* Spine Runtimes Software License
* Version 2.3
*
* Copyright (c) 2013-2015, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable and
* non-transferable license to use, install, execute and perform the Spine
* Runtimes Software (the "Software") and derivative works solely for personal
* or internal use. Without the written permission of Esoteric Software (see
* Section 2 of the Spine Software License Agreement), you may not (a) modify,
* translate, adapt or otherwise create derivative works, improvements of the
* Software or develop new applications using the Software or (b) remove,
* delete, alter or obscure any trademarks or any copyright, trademark, patent
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
var spine = {
radDeg: 180 / Math.PI,
degRad: Math.PI / 180,
temp: [],
Float32Array: (typeof(Float32Array) === 'undefined') ? Array : Float32Array,
Uint16Array: (typeof(Uint16Array) === 'undefined') ? Array : Uint16Array
};
spine.BoneData = function (name, parent) {
this.name = name;
this.parent = parent;
};
spine.BoneData.prototype = {
length: 0,
x: 0, y: 0,
rotation: 0,
scaleX: 1, scaleY: 1,
inheritScale: true,
inheritRotation: true,
flipX: false, flipY: false
};
spine.BlendMode = {
normal: 0,
additive: 1,
multiply: 2,
screen: 3
};
spine.SlotData = function (name, boneData) {
this.name = name;
this.boneData = boneData;
};
spine.SlotData.prototype = {
r: 1, g: 1, b: 1, a: 1,
attachmentName: null,
blendMode: spine.BlendMode.normal
};
spine.IkConstraintData = function (name) {
this.name = name;
this.bones = [];
};
spine.IkConstraintData.prototype = {
target: null,
bendDirection: 1,
mix: 1
};
spine.Bone = function (boneData, skeleton, parent) {
this.data = boneData;
this.skeleton = skeleton;
this.parent = parent;
this.setToSetupPose();
};
spine.Bone.yDown = false;
spine.Bone.prototype = {
x: 0, y: 0,
rotation: 0, rotationIK: 0,
scaleX: 1, scaleY: 1,
flipX: false, flipY: false,
m00: 0, m01: 0, worldX: 0, // a b x
m10: 0, m11: 0, worldY: 0, // c d y
worldRotation: 0,
worldScaleX: 1, worldScaleY: 1,
worldFlipX: false, worldFlipY: false,
updateWorldTransform: function () {
var parent = this.parent;
if (parent) {
this.worldX = this.x * parent.m00 + this.y * parent.m01 + parent.worldX;
this.worldY = this.x * parent.m10 + this.y * parent.m11 + parent.worldY;
if (this.data.inheritScale) {
this.worldScaleX = parent.worldScaleX * this.scaleX;
this.worldScaleY = parent.worldScaleY * this.scaleY;
} else {
this.worldScaleX = this.scaleX;
this.worldScaleY = this.scaleY;
}
this.worldRotation = this.data.inheritRotation ? (parent.worldRotation + this.rotationIK) : this.rotationIK;
this.worldFlipX = parent.worldFlipX != this.flipX;
this.worldFlipY = parent.worldFlipY != this.flipY;
} else {
var skeletonFlipX = this.skeleton.flipX, skeletonFlipY = this.skeleton.flipY;
this.worldX = skeletonFlipX ? -this.x : this.x;
this.worldY = (skeletonFlipY != spine.Bone.yDown) ? -this.y : this.y;
this.worldScaleX = this.scaleX;
this.worldScaleY = this.scaleY;
this.worldRotation = this.rotationIK;
this.worldFlipX = skeletonFlipX != this.flipX;
this.worldFlipY = skeletonFlipY != this.flipY;
}
var radians = this.worldRotation * spine.degRad;
var cos = Math.cos(radians);
var sin = Math.sin(radians);
if (this.worldFlipX) {
this.m00 = -cos * this.worldScaleX;
this.m01 = sin * this.worldScaleY;
} else {
this.m00 = cos * this.worldScaleX;
this.m01 = -sin * this.worldScaleY;
}
if (this.worldFlipY != spine.Bone.yDown) {
this.m10 = -sin * this.worldScaleX;
this.m11 = -cos * this.worldScaleY;
} else {
this.m10 = sin * this.worldScaleX;
this.m11 = cos * this.worldScaleY;
}
},
setToSetupPose: function () {
var data = this.data;
this.x = data.x;
this.y = data.y;
this.rotation = data.rotation;
this.rotationIK = this.rotation;
this.scaleX = data.scaleX;
this.scaleY = data.scaleY;
this.flipX = data.flipX;
this.flipY = data.flipY;
},
worldToLocal: function (world) {
var dx = world[0] - this.worldX, dy = world[1] - this.worldY;
var m00 = this.m00, m10 = this.m10, m01 = this.m01, m11 = this.m11;
if (this.worldFlipX != (this.worldFlipY != spine.Bone.yDown)) {
m00 = -m00;
m11 = -m11;
}
var invDet = 1 / (m00 * m11 - m01 * m10);
world[0] = dx * m00 * invDet - dy * m01 * invDet;
world[1] = dy * m11 * invDet - dx * m10 * invDet;
},
localToWorld: function (local) {
var localX = local[0], localY = local[1];
local[0] = localX * this.m00 + localY * this.m01 + this.worldX;
local[1] = localX * this.m10 + localY * this.m11 + this.worldY;
}
};
spine.Slot = function (slotData, bone) {
this.data = slotData;
this.bone = bone;
this.setToSetupPose();
};
spine.Slot.prototype = {
r: 1, g: 1, b: 1, a: 1,
_attachmentTime: 0,
attachment: null,
attachmentVertices: [],
setAttachment: function (attachment) {
this.attachment = attachment;
this._attachmentTime = this.bone.skeleton.time;
this.attachmentVertices.length = 0;
},
setAttachmentTime: function (time) {
this._attachmentTime = this.bone.skeleton.time - time;
},
getAttachmentTime: function () {
return this.bone.skeleton.time - this._attachmentTime;
},
setToSetupPose: function () {
var data = this.data;
this.r = data.r;
this.g = data.g;
this.b = data.b;
this.a = data.a;
var slotDatas = this.bone.skeleton.data.slots;
for (var i = 0, n = slotDatas.length; i < n; i++) {
if (slotDatas[i] == data) {
this.setAttachment(!data.attachmentName ? null : this.bone.skeleton.getAttachmentBySlotIndex(i, data.attachmentName));
break;
}
}
}
};
spine.IkConstraint = function (data, skeleton) {
this.data = data;
this.mix = data.mix;
this.bendDirection = data.bendDirection;
this.bones = [];
for (var i = 0, n = data.bones.length; i < n; i++)
this.bones.push(skeleton.findBone(data.bones[i].name));
this.target = skeleton.findBone(data.target.name);
};
spine.IkConstraint.prototype = {
apply: function () {
var target = this.target;
var bones = this.bones;
switch (bones.length) {
case 1:
spine.IkConstraint.apply1(bones[0], target.worldX, target.worldY, this.mix);
break;
case 2:
spine.IkConstraint.apply2(bones[0], bones[1], target.worldX, target.worldY, this.bendDirection, this.mix);
break;
}
}
};
/** Adjusts the bone rotation so the tip is as close to the target position as possible. The target is specified in the world
* coordinate system. */
spine.IkConstraint.apply1 = function (bone, targetX, targetY, alpha) {
var parentRotation = (!bone.data.inheritRotation || !bone.parent) ? 0 : bone.parent.worldRotation;
var rotation = bone.rotation;
var rotationIK = Math.atan2(targetY - bone.worldY, targetX - bone.worldX) * spine.radDeg;
if (bone.worldFlipX != (bone.worldFlipY != spine.Bone.yDown)) rotationIK = -rotationIK;
rotationIK -= parentRotation;
bone.rotationIK = rotation + (rotationIK - rotation) * alpha;
};
/** Adjusts the parent and child bone rotations so the tip of the child is as close to the target position as possible. The
* target is specified in the world coordinate system.
* @param child Any descendant bone of the parent. */
spine.IkConstraint.apply2 = function (parent, child, targetX, targetY, bendDirection, alpha) {
var childRotation = child.rotation, parentRotation = parent.rotation;
if (!alpha) {
child.rotationIK = childRotation;
parent.rotationIK = parentRotation;
return;
}
var positionX, positionY, tempPosition = spine.temp;
var parentParent = parent.parent;
if (parentParent) {
tempPosition[0] = targetX;
tempPosition[1] = targetY;
parentParent.worldToLocal(tempPosition);
targetX = (tempPosition[0] - parent.x) * parentParent.worldScaleX;
targetY = (tempPosition[1] - parent.y) * parentParent.worldScaleY;
} else {
targetX -= parent.x;
targetY -= parent.y;
}
if (child.parent == parent) {
positionX = child.x;
positionY = child.y;
} else {
tempPosition[0] = child.x;
tempPosition[1] = child.y;
child.parent.localToWorld(tempPosition);
parent.worldToLocal(tempPosition);
positionX = tempPosition[0];
positionY = tempPosition[1];
}
var childX = positionX * parent.worldScaleX, childY = positionY * parent.worldScaleY;
var offset = Math.atan2(childY, childX);
var len1 = Math.sqrt(childX * childX + childY * childY), len2 = child.data.length * child.worldScaleX;
// Based on code by Ryan Juckett with permission: Copyright (c) 2008-2009 Ryan Juckett, http://www.ryanjuckett.com/
var cosDenom = 2 * len1 * len2;
if (cosDenom < 0.0001) {
child.rotationIK = childRotation + (Math.atan2(targetY, targetX) * spine.radDeg - parentRotation - childRotation) * alpha;
return;
}
var cos = (targetX * targetX + targetY * targetY - len1 * len1 - len2 * len2) / cosDenom;
if (cos < -1)
cos = -1;
else if (cos > 1)
cos = 1;
var childAngle = Math.acos(cos) * bendDirection;
var adjacent = len1 + len2 * cos, opposite = len2 * Math.sin(childAngle);
var parentAngle = Math.atan2(targetY * adjacent - targetX * opposite, targetX * adjacent + targetY * opposite);
var rotation = (parentAngle - offset) * spine.radDeg - parentRotation;
if (rotation > 180)
rotation -= 360;
else if (rotation < -180) //
rotation += 360;
parent.rotationIK = parentRotation + rotation * alpha;
rotation = (childAngle + offset) * spine.radDeg - childRotation;
if (rotation > 180)
rotation -= 360;
else if (rotation < -180) //
rotation += 360;
child.rotationIK = childRotation + (rotation + parent.worldRotation - child.parent.worldRotation) * alpha;
};
spine.Skin = function (name) {
this.name = name;
this.attachments = {};
};
spine.Skin.prototype = {
addAttachment: function (slotIndex, name, attachment) {
this.attachments[slotIndex + ":" + name] = attachment;
},
getAttachment: function (slotIndex, name) {
return this.attachments[slotIndex + ":" + name];
},
_attachAll: function (skeleton, oldSkin) {
for (var key in oldSkin.attachments) {
var colon = key.indexOf(":");
var slotIndex = parseInt(key.substring(0, colon));
var name = key.substring(colon + 1);
var slot = skeleton.slots[slotIndex];
if (slot.attachment && slot.attachment.name == name) {
var attachment = this.getAttachment(slotIndex, name);
if (attachment) slot.setAttachment(attachment);
}
}
}
};
spine.Animation = function (name, timelines, duration) {
this.name = name;
this.timelines = timelines;
this.duration = duration;
};
spine.Animation.prototype = {
apply: function (skeleton, lastTime, time, loop, events) {
if (loop && this.duration != 0) {
time %= this.duration;
lastTime %= this.duration;
}
var timelines = this.timelines;
for (var i = 0, n = timelines.length; i < n; i++)
timelines[i].apply(skeleton, lastTime, time, events, 1);
},
mix: function (skeleton, lastTime, time, loop, events, alpha) {
if (loop && this.duration != 0) {
time %= this.duration;
lastTime %= this.duration;
}
var timelines = this.timelines;
for (var i = 0, n = timelines.length; i < n; i++)
timelines[i].apply(skeleton, lastTime, time, events, alpha);
}
};
spine.Animation.binarySearch = function (values, target, step) {
var low = 0;
var high = Math.floor(values.length / step) - 2;
if (!high) return step;
var current = high >>> 1;
while (true) {
if (values[(current + 1) * step] <= target)
low = current + 1;
else
high = current;
if (low == high) return (low + 1) * step;
current = (low + high) >>> 1;
}
};
spine.Animation.binarySearch1 = function (values, target) {
var low = 0;
var high = values.length - 2;
if (!high) return 1;
var current = high >>> 1;
while (true) {
if (values[current + 1] <= target)
low = current + 1;
else
high = current;
if (low == high) return low + 1;
current = (low + high) >>> 1;
}
};
spine.Animation.linearSearch = function (values, target, step) {
for (var i = 0, last = values.length - step; i <= last; i += step)
if (values[i] > target) return i;
return -1;
};
spine.Curves = function (frameCount) {
this.curves = []; // type, x, y, ...
//this.curves.length = (frameCount - 1) * 19/*BEZIER_SIZE*/;
};
spine.Curves.prototype = {
setLinear: function (frameIndex) {
this.curves[frameIndex * 19/*BEZIER_SIZE*/] = 0/*LINEAR*/;
},
setStepped: function (frameIndex) {
this.curves[frameIndex * 19/*BEZIER_SIZE*/] = 1/*STEPPED*/;
},
/** Sets the control handle positions for an interpolation bezier curve used to transition from this keyframe to the next.
* cx1 and cx2 are from 0 to 1, representing the percent of time between the two keyframes. cy1 and cy2 are the percent of
* the difference between the keyframe's values. */
setCurve: function (frameIndex, cx1, cy1, cx2, cy2) {
var subdiv1 = 1 / 10/*BEZIER_SEGMENTS*/, subdiv2 = subdiv1 * subdiv1, subdiv3 = subdiv2 * subdiv1;
var pre1 = 3 * subdiv1, pre2 = 3 * subdiv2, pre4 = 6 * subdiv2, pre5 = 6 * subdiv3;
var tmp1x = -cx1 * 2 + cx2, tmp1y = -cy1 * 2 + cy2, tmp2x = (cx1 - cx2) * 3 + 1, tmp2y = (cy1 - cy2) * 3 + 1;
var dfx = cx1 * pre1 + tmp1x * pre2 + tmp2x * subdiv3, dfy = cy1 * pre1 + tmp1y * pre2 + tmp2y * subdiv3;
var ddfx = tmp1x * pre4 + tmp2x * pre5, ddfy = tmp1y * pre4 + tmp2y * pre5;
var dddfx = tmp2x * pre5, dddfy = tmp2y * pre5;
var i = frameIndex * 19/*BEZIER_SIZE*/;
var curves = this.curves;
curves[i++] = 2/*BEZIER*/;
var x = dfx, y = dfy;
for (var n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) {
curves[i] = x;
curves[i + 1] = y;
dfx += ddfx;
dfy += ddfy;
ddfx += dddfx;
ddfy += dddfy;
x += dfx;
y += dfy;
}
},
getCurvePercent: function (frameIndex, percent) {
percent = percent < 0 ? 0 : (percent > 1 ? 1 : percent);
var curves = this.curves;
var i = frameIndex * 19/*BEZIER_SIZE*/;
var type = curves[i];
if (type === 0/*LINEAR*/) return percent;
if (type == 1/*STEPPED*/) return 0;
i++;
var x = 0;
for (var start = i, n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) {
x = curves[i];
if (x >= percent) {
var prevX, prevY;
if (i == start) {
prevX = 0;
prevY = 0;
} else {
prevX = curves[i - 2];
prevY = curves[i - 1];
}
return prevY + (curves[i + 1] - prevY) * (percent - prevX) / (x - prevX);
}
}
var y = curves[i - 1];
return y + (1 - y) * (percent - x) / (1 - x); // Last point is 1,1.
}
};
spine.RotateTimeline = function (frameCount) {
this.curves = new spine.Curves(frameCount);
this.frames = []; // time, angle, ...
this.frames.length = frameCount * 2;
};
spine.RotateTimeline.prototype = {
boneIndex: 0,
getFrameCount: function () {
return this.frames.length / 2;
},
setFrame: function (frameIndex, time, angle) {
frameIndex *= 2;
this.frames[frameIndex] = time;
this.frames[frameIndex + 1] = angle;
},
apply: function (skeleton, lastTime, time, firedEvents, alpha) {
var frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
var bone = skeleton.bones[this.boneIndex];
if (time >= frames[frames.length - 2]) { // Time is after last frame.
var amount = bone.data.rotation + frames[frames.length - 1] - bone.rotation;
while (amount > 180)
amount -= 360;
while (amount < -180)
amount += 360;
bone.rotation += amount * alpha;
return;
}
// Interpolate between the previous frame and the current frame.
var frameIndex = spine.Animation.binarySearch(frames, time, 2);
var prevFrameValue = frames[frameIndex - 1];
var frameTime = frames[frameIndex];
var percent = 1 - (time - frameTime) / (frames[frameIndex - 2/*PREV_FRAME_TIME*/] - frameTime);
percent = this.curves.getCurvePercent(frameIndex / 2 - 1, percent);
var amount = frames[frameIndex + 1/*FRAME_VALUE*/] - prevFrameValue;
while (amount > 180)
amount -= 360;
while (amount < -180)
amount += 360;
amount = bone.data.rotation + (prevFrameValue + amount * percent) - bone.rotation;
while (amount > 180)
amount -= 360;
while (amount < -180)
amount += 360;
bone.rotation += amount * alpha;
}
};
spine.TranslateTimeline = function (frameCount) {
this.curves = new spine.Curves(frameCount);
this.frames = []; // time, x, y, ...
this.frames.length = frameCount * 3;
};
spine.TranslateTimeline.prototype = {
boneIndex: 0,
getFrameCount: function () {
return this.frames.length / 3;
},
setFrame: function (frameIndex, time, x, y) {
frameIndex *= 3;
this.frames[frameIndex] = time;
this.frames[frameIndex + 1] = x;
this.frames[frameIndex + 2] = y;
},
apply: function (skeleton, lastTime, time, firedEvents, alpha) {
var frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
var bone = skeleton.bones[this.boneIndex];
if (time >= frames[frames.length - 3]) { // Time is after last frame.
bone.x += (bone.data.x + frames[frames.length - 2] - bone.x) * alpha;
bone.y += (bone.data.y + frames[frames.length - 1] - bone.y) * alpha;
return;
}
// Interpolate between the previous frame and the current frame.
var frameIndex = spine.Animation.binarySearch(frames, time, 3);
var prevFrameX = frames[frameIndex - 2];
var prevFrameY = frames[frameIndex - 1];
var frameTime = frames[frameIndex];
var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*PREV_FRAME_TIME*/] - frameTime);
percent = this.curves.getCurvePercent(frameIndex / 3 - 1, percent);
bone.x += (bone.data.x + prevFrameX + (frames[frameIndex + 1/*FRAME_X*/] - prevFrameX) * percent - bone.x) * alpha;
bone.y += (bone.data.y + prevFrameY + (frames[frameIndex + 2/*FRAME_Y*/] - prevFrameY) * percent - bone.y) * alpha;
}
};
spine.ScaleTimeline = function (frameCount) {
this.curves = new spine.Curves(frameCount);
this.frames = []; // time, x, y, ...
this.frames.length = frameCount * 3;
};
spine.ScaleTimeline.prototype = {
boneIndex: 0,
getFrameCount: function () {
return this.frames.length / 3;
},
setFrame: function (frameIndex, time, x, y) {
frameIndex *= 3;
this.frames[frameIndex] = time;
this.frames[frameIndex + 1] = x;
this.frames[frameIndex + 2] = y;
},
apply: function (skeleton, lastTime, time, firedEvents, alpha) {
var frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
var bone = skeleton.bones[this.boneIndex];
if (time >= frames[frames.length - 3]) { // Time is after last frame.
bone.scaleX += (bone.data.scaleX * frames[frames.length - 2] - bone.scaleX) * alpha;
bone.scaleY += (bone.data.scaleY * frames[frames.length - 1] - bone.scaleY) * alpha;
return;
}
// Interpolate between the previous frame and the current frame.
var frameIndex = spine.Animation.binarySearch(frames, time, 3);
var prevFrameX = frames[frameIndex - 2];
var prevFrameY = frames[frameIndex - 1];
var frameTime = frames[frameIndex];
var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*PREV_FRAME_TIME*/] - frameTime);
percent = this.curves.getCurvePercent(frameIndex / 3 - 1, percent);
bone.scaleX += (bone.data.scaleX * (prevFrameX + (frames[frameIndex + 1/*FRAME_X*/] - prevFrameX) * percent) - bone.scaleX) * alpha;
bone.scaleY += (bone.data.scaleY * (prevFrameY + (frames[frameIndex + 2/*FRAME_Y*/] - prevFrameY) * percent) - bone.scaleY) * alpha;
}
};
spine.ColorTimeline = function (frameCount) {
this.curves = new spine.Curves(frameCount);
this.frames = []; // time, r, g, b, a, ...
this.frames.length = frameCount * 5;
};
spine.ColorTimeline.prototype = {
slotIndex: 0,
getFrameCount: function () {
return this.frames.length / 5;
},
setFrame: function (frameIndex, time, r, g, b, a) {
frameIndex *= 5;
this.frames[frameIndex] = time;
this.frames[frameIndex + 1] = r;
this.frames[frameIndex + 2] = g;
this.frames[frameIndex + 3] = b;
this.frames[frameIndex + 4] = a;
},
apply: function (skeleton, lastTime, time, firedEvents, alpha) {
var frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
var r, g, b, a;
if (time >= frames[frames.length - 5]) {
// Time is after last frame.
var i = frames.length - 1;
r = frames[i - 3];
g = frames[i - 2];
b = frames[i - 1];
a = frames[i];
} else {
// Interpolate between the previous frame and the current frame.
var frameIndex = spine.Animation.binarySearch(frames, time, 5);
var prevFrameR = frames[frameIndex - 4];
var prevFrameG = frames[frameIndex - 3];
var prevFrameB = frames[frameIndex - 2];
var prevFrameA = frames[frameIndex - 1];
var frameTime = frames[frameIndex];
var percent = 1 - (time - frameTime) / (frames[frameIndex - 5/*PREV_FRAME_TIME*/] - frameTime);
percent = this.curves.getCurvePercent(frameIndex / 5 - 1, percent);
r = prevFrameR + (frames[frameIndex + 1/*FRAME_R*/] - prevFrameR) * percent;
g = prevFrameG + (frames[frameIndex + 2/*FRAME_G*/] - prevFrameG) * percent;
b = prevFrameB + (frames[frameIndex + 3/*FRAME_B*/] - prevFrameB) * percent;
a = prevFrameA + (frames[frameIndex + 4/*FRAME_A*/] - prevFrameA) * percent;
}
var slot = skeleton.slots[this.slotIndex];
if (alpha < 1) {
slot.r += (r - slot.r) * alpha;
slot.g += (g - slot.g) * alpha;
slot.b += (b - slot.b) * alpha;
slot.a += (a - slot.a) * alpha;
} else {
slot.r = r;
slot.g = g;
slot.b = b;
slot.a = a;
}
}
};
spine.AttachmentTimeline = function (frameCount) {
this.curves = new spine.Curves(frameCount);
this.frames = []; // time, ...
this.frames.length = frameCount;
this.attachmentNames = [];
this.attachmentNames.length = frameCount;
};
spine.AttachmentTimeline.prototype = {
slotIndex: 0,
getFrameCount: function () {
return this.frames.length;
},
setFrame: function (frameIndex, time, attachmentName) {
this.frames[frameIndex] = time;
this.attachmentNames[frameIndex] = attachmentName;
},
apply: function (skeleton, lastTime, time, firedEvents, alpha) {
var frames = this.frames;
if (time < frames[0]) {
if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0);
return;
} else if (lastTime > time) //
lastTime = -1;
var frameIndex = time >= frames[frames.length - 1] ? frames.length - 1 : spine.Animation.binarySearch1(frames, time) - 1;
if (frames[frameIndex] < lastTime) return;
var attachmentName = this.attachmentNames[frameIndex];
skeleton.slots[this.slotIndex].setAttachment(
!attachmentName ? null : skeleton.getAttachmentBySlotIndex(this.slotIndex, attachmentName));
}
};
spine.EventTimeline = function (frameCount) {
this.frames = []; // time, ...
this.frames.length = frameCount;
this.events = [];
this.events.length = frameCount;
};
spine.EventTimeline.prototype = {
getFrameCount: function () {
return this.frames.length;
},
setFrame: function (frameIndex, time, event) {
this.frames[frameIndex] = time;
this.events[frameIndex] = event;
},
/** Fires events for frames > lastTime and <= time. */
apply: function (skeleton, lastTime, time, firedEvents, alpha) {
if (!firedEvents) return;
var frames = this.frames;
var frameCount = frames.length;
if (lastTime > time) { // Fire events after last time for looped animations.
this.apply(skeleton, lastTime, Number.MAX_VALUE, firedEvents, alpha);
lastTime = -1;
} else if (lastTime >= frames[frameCount - 1]) // Last time is after last frame.
return;
if (time < frames[0]) return; // Time is before first frame.
var frameIndex;
if (lastTime < frames[0])
frameIndex = 0;
else {
frameIndex = spine.Animation.binarySearch1(frames, lastTime);
var frame = frames[frameIndex];
while (frameIndex > 0) { // Fire multiple events with the same frame.
if (frames[frameIndex - 1] != frame) break;
frameIndex--;
}
}
var events = this.events;
for (; frameIndex < frameCount && time >= frames[frameIndex]; frameIndex++)
firedEvents.push(events[frameIndex]);
}
};
spine.DrawOrderTimeline = function (frameCount) {
this.frames = []; // time, ...
this.frames.length = frameCount;
this.drawOrders = [];
this.drawOrders.length = frameCount;
};
spine.DrawOrderTimeline.prototype = {
getFrameCount: function () {
return this.frames.length;
},
setFrame: function (frameIndex, time, drawOrder) {
this.frames[frameIndex] = time;
this.drawOrders[frameIndex] = drawOrder;
},
apply: function (skeleton, lastTime, time, firedEvents, alpha) {
var frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
var frameIndex;
if (time >= frames[frames.length - 1]) // Time is after last frame.
frameIndex = frames.length - 1;
else
frameIndex = spine.Animation.binarySearch1(frames, time) - 1;
var drawOrder = skeleton.drawOrder;
var slots = skeleton.slots;
var drawOrderToSetupIndex = this.drawOrders[frameIndex];
if (!drawOrderToSetupIndex) {
for (var i = 0, n = slots.length; i < n; i++)
drawOrder[i] = slots[i];
} else {
for (var i = 0, n = drawOrderToSetupIndex.length; i < n; i++)
drawOrder[i] = skeleton.slots[drawOrderToSetupIndex[i]];
}
}
};
spine.FfdTimeline = function (frameCount) {
this.curves = new spine.Curves(frameCount);
this.frames = [];
this.frames.length = frameCount;
this.frameVertices = [];
this.frameVertices.length = frameCount;
};
spine.FfdTimeline.prototype = {
slotIndex: 0,
attachment: 0,
getFrameCount: function () {
return this.frames.length;
},
setFrame: function (frameIndex, time, vertices) {
this.frames[frameIndex] = time;
this.frameVertices[frameIndex] = vertices;
},
apply: function (skeleton, lastTime, time, firedEvents, alpha) {
var slot = skeleton.slots[this.slotIndex];
if (slot.attachment != this.attachment) return;
var frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
var frameVertices = this.frameVertices;
var vertexCount = frameVertices[0].length;
var vertices = slot.attachmentVertices;
if (vertices.length != vertexCount) alpha = 1;
vertices.length = vertexCount;
if (time >= frames[frames.length - 1]) { // Time is after last frame.
var lastVertices = frameVertices[frames.length - 1];
if (alpha < 1) {
for (var i = 0; i < vertexCount; i++)
vertices[i] += (lastVertices[i] - vertices[i]) * alpha;
} else {
for (var i = 0; i < vertexCount; i++)
vertices[i] = lastVertices[i];
}
return;
}
// Interpolate between the previous frame and the current frame.
var frameIndex = spine.Animation.binarySearch1(frames, time);
var frameTime = frames[frameIndex];
var percent = 1 - (time - frameTime) / (frames[frameIndex - 1] - frameTime);
percent = this.curves.getCurvePercent(frameIndex - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));
var prevVertices = frameVertices[frameIndex - 1];
var nextVertices = frameVertices[frameIndex];
if (alpha < 1) {
for (var i = 0; i < vertexCount; i++) {
var prev = prevVertices[i];
vertices[i] += (prev + (nextVertices[i] - prev) * percent - vertices[i]) * alpha;
}
} else {
for (var i = 0; i < vertexCount; i++) {
var prev = prevVertices[i];
vertices[i] = prev + (nextVertices[i] - prev) * percent;
}
}
}
};
spine.IkConstraintTimeline = function (frameCount) {
this.curves = new spine.Curves(frameCount);
this.frames = []; // time, mix, bendDirection, ...
this.frames.length = frameCount * 3;
};
spine.IkConstraintTimeline.prototype = {
ikConstraintIndex: 0,
getFrameCount: function () {
return this.frames.length / 3;
},
setFrame: function (frameIndex, time, mix, bendDirection) {
frameIndex *= 3;
this.frames[frameIndex] = time;
this.frames[frameIndex + 1] = mix;
this.frames[frameIndex + 2] = bendDirection;
},
apply: function (skeleton, lastTime, time, firedEvents, alpha) {
var frames = this.frames;
if (time < frames[0]) return; // Time is before first frame.
var ikConstraint = skeleton.ikConstraints[this.ikConstraintIndex];
if (time >= frames[frames.length - 3]) { // Time is after last frame.
ikConstraint.mix += (frames[frames.length - 2] - ikConstraint.mix) * alpha;
ikConstraint.bendDirection = frames[frames.length - 1];
return;
}
// Interpolate between the previous frame and the current frame.
var frameIndex = spine.Animation.binarySearch(frames, time, 3);
var prevFrameMix = frames[frameIndex + -2/*PREV_FRAME_MIX*/];
var frameTime = frames[frameIndex];
var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*PREV_FRAME_TIME*/] - frameTime);
percent = this.curves.getCurvePercent(frameIndex / 3 - 1, percent);
var mix = prevFrameMix + (frames[frameIndex + 1/*FRAME_MIX*/] - prevFrameMix) * percent;
ikConstraint.mix += (mix - ikConstraint.mix) * alpha;
ikConstraint.bendDirection = frames[frameIndex + -1/*PREV_FRAME_BEND_DIRECTION*/];
}
};
spine.FlipXTimeline = function (frameCount) {
this.curves = new spine.Curves(frameCount);
this.frames = []; // time, flip, ...
this.frames.length = frameCount * 2;
};
spine.FlipXTimeline.prototype = {
boneIndex: 0,
getFrameCount: function () {
return this.frames.length / 2;
},
setFrame: function (frameIndex, time, flip) {
frameIndex *= 2;
this.frames[frameIndex] = time;
this.frames[frameIndex + 1] = flip ? 1 : 0;
},
apply: function (skeleton, lastTime, time, firedEvents, alpha) {
var frames = this.frames;
if (time < frames[0]) {
if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0);
return;
} else if (lastTime > time) //
lastTime = -1;
var frameIndex = (time >= frames[frames.length - 2] ? frames.length : spine.Animation.binarySearch(frames, time, 2)) - 2;
if (frames[frameIndex] < lastTime) return;
skeleton.bones[this.boneIndex].flipX = frames[frameIndex + 1] != 0;
}
};
spine.FlipYTimeline = function (frameCount) {
this.curves = new spine.Curves(frameCount);
this.frames = []; // time, flip, ...
this.frames.length = frameCount * 2;
};
spine.FlipYTimeline.prototype = {
boneIndex: 0,
getFrameCount: function () {
return this.frames.length / 2;
},
setFrame: function (frameIndex, time, flip) {
frameIndex *= 2;
this.frames[frameIndex] = time;
this.frames[frameIndex + 1] = flip ? 1 : 0;
},
apply: function (skeleton, lastTime, time, firedEvents, alpha) {
var frames = this.frames;
if (time < frames[0]) {
if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0);
return;
} else if (lastTime > time) //
lastTime = -1;
var frameIndex = (time >= frames[frames.length - 2] ? frames.length : spine.Animation.binarySearch(frames, time, 2)) - 2;
if (frames[frameIndex] < lastTime) return;
skeleton.bones[this.boneIndex].flipY = frames[frameIndex + 1] != 0;
}
};
spine.SkeletonData = function () {
this.bones = [];
this.slots = [];
this.skins = [];
this.events = [];
this.animations = [];
this.ikConstraints = [];
};
spine.SkeletonData.prototype = {
name: null,
defaultSkin: null,
width: 0, height: 0,
version: null, hash: null,
/** @return May be null. */
findBone: function (boneName) {
var bones = this.bones;
for (var i = 0, n = bones.length; i < n; i++)
if (bones[i].name == boneName) return bones[i];
return null;
},
/** @return -1 if the bone was not found. */
findBoneIndex: function (boneName) {
var bones = this.bones;
for (var i = 0, n = bones.length; i < n; i++)
if (bones[i].name == boneName) return i;
return -1;
},
/** @return May be null. */
findSlot: function (slotName) {
var slots = this.slots;
for (var i = 0, n = slots.length; i < n; i++) {
if (slots[i].name == slotName) return slot[i];
}
return null;
},
/** @return -1 if the bone was not found. */
findSlotIndex: function (slotName) {
var slots = this.slots;
for (var i = 0, n = slots.length; i < n; i++)
if (slots[i].name == slotName) return i;
return -1;
},
/** @return May be null. */
findSkin: function (skinName) {
var skins = this.skins;
for (var i = 0, n = skins.length; i < n; i++)
if (skins[i].name == skinName) return skins[i];
return null;
},
/** @return May be null. */
findEvent: function (eventName) {
var events = this.events;
for (var i = 0, n = events.length; i < n; i++)
if (events[i].name == eventName) return events[i];
return null;
},
/** @return May be null. */
findAnimation: function (animationName) {
var animations = this.animations;
for (var i = 0, n = animations.length; i < n; i++)
if (animations[i].name == animationName) return animations[i];
return null;
},
/** @return May be null. */
findIkConstraint: function (ikConstraintName) {
var ikConstraints = this.ikConstraints;
for (var i = 0, n = ikConstraints.length; i < n; i++)
if (ikConstraints[i].name == ikConstraintName) return ikConstraints[i];
return null;
}
};
spine.Skeleton = function (skeletonData) {
this.data = skeletonData;
this.bones = [];
for (var i = 0, n = skeletonData.bones.length; i < n; i++) {
var boneData = skeletonData.bones[i];
var parent = !boneData.parent ? null : this.bones[skeletonData.bones.indexOf(boneData.parent)];
this.bones.push(new spine.Bone(boneData, this, parent));
}
this.slots = [];
this.drawOrder = [];
for (var i = 0, n = skeletonData.slots.length; i < n; i++) {
var slotData = skeletonData.slots[i];
var bone = this.bones[skeletonData.bones.indexOf(slotData.boneData)];
var slot = new spine.Slot(slotData, bone);
this.slots.push(slot);
this.drawOrder.push(slot);
}
this.ikConstraints = [];
for (var i = 0, n = skeletonData.ikConstraints.length; i < n; i++)
this.ikConstraints.push(new spine.IkConstraint(skeletonData.ikConstraints[i], this));
this.boneCache = [];
this.updateCache();
};
spine.Skeleton.prototype = {
x: 0, y: 0,
skin: null,
r: 1, g: 1, b: 1, a: 1,
time: 0,
flipX: false, flipY: false,
/** Caches information about bones and IK constraints. Must be called if bones or IK constraints are added or removed. */
updateCache: function () {
var ikConstraints = this.ikConstraints;
var ikConstraintsCount = ikConstraints.length;
var arrayCount = ikConstraintsCount + 1;
var boneCache = this.boneCache;
if (boneCache.length > arrayCount) boneCache.length = arrayCount;
for (var i = 0, n = boneCache.length; i < n; i++)
boneCache[i].length = 0;
while (boneCache.length < arrayCount)
boneCache[boneCache.length] = [];
var nonIkBones = boneCache[0];
var bones = this.bones;
outer:
for (var i = 0, n = bones.length; i < n; i++) {
var bone = bones[i];
var current = bone;
do {
for (var ii = 0; ii < ikConstraintsCount; ii++) {
var ikConstraint = ikConstraints[ii];
var parent = ikConstraint.bones[0];
var child= ikConstraint.bones[ikConstraint.bones.length - 1];
while (true) {
if (current == child) {
boneCache[ii].push(bone);
boneCache[ii + 1].push(bone);
continue outer;
}
if (child == parent) break;
child = child.parent;
}
}
current = current.parent;
} while (current);
nonIkBones[nonIkBones.length] = bone;
}
},
/** Updates the world transform for each bone. */
updateWorldTransform: function () {
var bones = this.bones;
for (var i = 0, n = bones.length; i < n; i++) {
var bone = bones[i];
bone.rotationIK = bone.rotation;
}
var i = 0, last = this.boneCache.length - 1;
while (true) {
var cacheBones = this.boneCache[i];
for (var ii = 0, nn = cacheBones.length; ii < nn; ii++)
cacheBones[ii].updateWorldTransform();
if (i == last) break;
this.ikConstraints[i].apply();
i++;
}
},
/** Sets the bones and slots to their setup pose values. */
setToSetupPose: function () {
this.setBonesToSetupPose();
this.setSlotsToSetupPose();
},
setBonesToSetupPose: function () {
var bones = this.bones;
for (var i = 0, n = bones.length; i < n; i++)
bones[i].setToSetupPose();
var ikConstraints = this.ikConstraints;
for (var i = 0, n = ikConstraints.length; i < n; i++) {
var ikConstraint = ikConstraints[i];
ikConstraint.bendDirection = ikConstraint.data.bendDirection;
ikConstraint.mix = ikConstraint.data.mix;
}
},
setSlotsToSetupPose: function () {
var slots = this.slots;
var drawOrder = this.drawOrder;
for (var i = 0, n = slots.length; i < n; i++) {
drawOrder[i] = slots[i];
slots[i].setToSetupPose(i);
}
},
/** @return May return null. */
getRootBone: function () {
return this.bones.length ? this.bones[0] : null;
},
/** @return May be null. */
findBone: function (boneName) {
var bones = this.bones;
for (var i = 0, n = bones.length; i < n; i++)
if (bones[i].data.name == boneName) return bones[i];
return null;
},
/** @return -1 if the bone was not found. */
findBoneIndex: function (boneName) {
var bones = this.bones;
for (var i = 0, n = bones.length; i < n; i++)
if (bones[i].data.name == boneName) return i;
return -1;
},
/** @return May be null. */
findSlot: function (slotName) {
var slots = this.slots;
for (var i = 0, n = slots.length; i < n; i++)
if (slots[i].data.name == slotName) return slots[i];
return null;
},
/** @return -1 if the bone was not found. */
findSlotIndex: function (slotName) {
var slots = this.slots;
for (var i = 0, n = slots.length; i < n; i++)
if (slots[i].data.name == slotName) return i;
return -1;
},
setSkinByName: function (skinName) {
var skin = this.data.findSkin(skinName);
if (!skin) throw "Skin not found: " + skinName;
this.setSkin(skin);
},
/** Sets the skin used to look up attachments before looking in the {@link SkeletonData#getDefaultSkin() default skin}.
* Attachments from the new skin are attached if the corresponding attachment from the old skin was attached. If there was
* no old skin, each slot's setup mode attachment is attached from the new skin.
* @param newSkin May be null. */
setSkin: function (newSkin) {
if (newSkin) {
if (this.skin)
newSkin._attachAll(this, this.skin);
else {
var slots = this.slots;
for (var i = 0, n = slots.length; i < n; i++) {
var slot = slots[i];
var name = slot.data.attachmentName;
if (name) {
var attachment = newSkin.getAttachment(i, name);
if (attachment) slot.setAttachment(attachment);
}
}
}
}
this.skin = newSkin;
},
/** @return May be null. */
getAttachmentBySlotName: function (slotName, attachmentName) {
return this.getAttachmentBySlotIndex(this.data.findSlotIndex(slotName), attachmentName);
},
/** @return May be null. */
getAttachmentBySlotIndex: function (slotIndex, attachmentName) {
if (this.skin) {
var attachment = this.skin.getAttachment(slotIndex, attachmentName);
if (attachment) return attachment;
}
if (this.data.defaultSkin) return this.data.defaultSkin.getAttachment(slotIndex, attachmentName);
return null;
},
/** @param attachmentName May be null. */
setAttachment: function (slotName, attachmentName) {
var slots = this.slots;
for (var i = 0, n = slots.length; i < n; i++) {
var slot = slots[i];
if (slot.data.name == slotName) {
var attachment = null;
if (attachmentName) {
attachment = this.getAttachmentBySlotIndex(i, attachmentName);
if (!attachment) throw "Attachment not found: " + attachmentName + ", for slot: " + slotName;
}
slot.setAttachment(attachment);
return;
}
}
throw "Slot not found: " + slotName;
},
/** @return May be null. */
findIkConstraint: function (ikConstraintName) {
var ikConstraints = this.ikConstraints;
for (var i = 0, n = ikConstraints.length; i < n; i++)
if (ikConstraints[i].data.name == ikConstraintName) return ikConstraints[i];
return null;
},
update: function (delta) {
this.time += delta;
}
};
spine.EventData = function (name) {
this.name = name;
};
spine.EventData.prototype = {
intValue: 0,
floatValue: 0,
stringValue: null
};
spine.Event = function (data) {
this.data = data;
};
spine.Event.prototype = {
intValue: 0,
floatValue: 0,
stringValue: null
};
spine.AttachmentType = {
region: 0,
boundingbox: 1,
mesh: 2,
skinnedmesh: 3
};
spine.RegionAttachment = function (name) {
this.name = name;
this.offset = [];
this.offset.length = 8;
this.uvs = [];
this.uvs.length = 8;
};
spine.RegionAttachment.prototype = {
type: spine.AttachmentType.region,
x: 0, y: 0,
rotation: 0,
scaleX: 1, scaleY: 1,
width: 0, height: 0,
r: 1, g: 1, b: 1, a: 1,
path: null,
rendererObject: null,
regionOffsetX: 0, regionOffsetY: 0,
regionWidth: 0, regionHeight: 0,
regionOriginalWidth: 0, regionOriginalHeight: 0,
setUVs: function (u, v, u2, v2, rotate) {
var uvs = this.uvs;
if (rotate) {
uvs[2/*X2*/] = u;
uvs[3/*Y2*/] = v2;
uvs[4/*X3*/] = u;
uvs[5/*Y3*/] = v;
uvs[6/*X4*/] = u2;
uvs[7/*Y4*/] = v;
uvs[0/*X1*/] = u2;
uvs[1/*Y1*/] = v2;
} else {
uvs[0/*X1*/] = u;
uvs[1/*Y1*/] = v2;
uvs[2/*X2*/] = u;
uvs[3/*Y2*/] = v;
uvs[4/*X3*/] = u2;
uvs[5/*Y3*/] = v;
uvs[6/*X4*/] = u2;
uvs[7/*Y4*/] = v2;
}
},
updateOffset: function () {
var regionScaleX = this.width / this.regionOriginalWidth * this.scaleX;
var regionScaleY = this.height / this.regionOriginalHeight * this.scaleY;
var localX = -this.width / 2 * this.scaleX + this.regionOffsetX * regionScaleX;
var localY = -this.height / 2 * this.scaleY + this.regionOffsetY * regionScaleY;
var localX2 = localX + this.regionWidth * regionScaleX;
var localY2 = localY + this.regionHeight * regionScaleY;
var radians = this.rotation * spine.degRad;
var cos = Math.cos(radians);
var sin = Math.sin(radians);
var localXCos = localX * cos + this.x;
var localXSin = localX * sin;
var localYCos = localY * cos + this.y;
var localYSin = localY * sin;
var localX2Cos = localX2 * cos + this.x;
var localX2Sin = localX2 * sin;
var localY2Cos = localY2 * cos + this.y;
var localY2Sin = localY2 * sin;
var offset = this.offset;
offset[0/*X1*/] = localXCos - localYSin;
offset[1/*Y1*/] = localYCos + localXSin;
offset[2/*X2*/] = localXCos - localY2Sin;
offset[3/*Y2*/] = localY2Cos + localXSin;
offset[4/*X3*/] = localX2Cos - localY2Sin;
offset[5/*Y3*/] = localY2Cos + localX2Sin;
offset[6/*X4*/] = localX2Cos - localYSin;
offset[7/*Y4*/] = localYCos + localX2Sin;
},
computeVertices: function (x, y, bone, vertices) {
x += bone.worldX;
y += bone.worldY;
var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11;
var offset = this.offset;
vertices[0/*X1*/] = offset[0/*X1*/] * m00 + offset[1/*Y1*/] * m01 + x;
vertices[1/*Y1*/] = offset[0/*X1*/] * m10 + offset[1/*Y1*/] * m11 + y;
vertices[2/*X2*/] = offset[2/*X2*/] * m00 + offset[3/*Y2*/] * m01 + x;
vertices[3/*Y2*/] = offset[2/*X2*/] * m10 + offset[3/*Y2*/] * m11 + y;
vertices[4/*X3*/] = offset[4/*X3*/] * m00 + offset[5/*X3*/] * m01 + x;
vertices[5/*X3*/] = offset[4/*X3*/] * m10 + offset[5/*X3*/] * m11 + y;
vertices[6/*X4*/] = offset[6/*X4*/] * m00 + offset[7/*Y4*/] * m01 + x;
vertices[7/*Y4*/] = offset[6/*X4*/] * m10 + offset[7/*Y4*/] * m11 + y;
}
};
spine.MeshAttachment = function (name) {
this.name = name;
};
spine.MeshAttachment.prototype = {
type: spine.AttachmentType.mesh,
vertices: null,
uvs: null,
regionUVs: null,
triangles: null,
hullLength: 0,
r: 1, g: 1, b: 1, a: 1,
path: null,
rendererObject: null,
regionU: 0, regionV: 0, regionU2: 0, regionV2: 0, regionRotate: false,
regionOffsetX: 0, regionOffsetY: 0,
regionWidth: 0, regionHeight: 0,
regionOriginalWidth: 0, regionOriginalHeight: 0,
edges: null,
width: 0, height: 0,
updateUVs: function () {
var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV;
var n = this.regionUVs.length;
if (!this.uvs || this.uvs.length != n) {
this.uvs = new spine.Float32Array(n);
}
if (this.regionRotate) {
for (var i = 0; i < n; i += 2) {
this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width;
this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height;
}
} else {
for (var i = 0; i < n; i += 2) {
this.uvs[i] = this.regionU + this.regionUVs[i] * width;
this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height;
}
}
},
computeWorldVertices: function (x, y, slot, worldVertices) {
var bone = slot.bone;
x += bone.worldX;
y += bone.worldY;
var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11;
var vertices = this.vertices;
var verticesCount = vertices.length;
if (slot.attachmentVertices.length == verticesCount) vertices = slot.attachmentVertices;
for (var i = 0; i < verticesCount; i += 2) {
var vx = vertices[i];
var vy = vertices[i + 1];
worldVertices[i] = vx * m00 + vy * m01 + x;
worldVertices[i + 1] = vx * m10 + vy * m11 + y;
}
}
};
spine.SkinnedMeshAttachment = function (name) {
this.name = name;
};
spine.SkinnedMeshAttachment.prototype = {
type: spine.AttachmentType.skinnedmesh,
bones: null,
weights: null,
uvs: null,
regionUVs: null,
triangles: null,
hullLength: 0,
r: 1, g: 1, b: 1, a: 1,
path: null,
rendererObject: null,
regionU: 0, regionV: 0, regionU2: 0, regionV2: 0, regionRotate: false,
regionOffsetX: 0, regionOffsetY: 0,
regionWidth: 0, regionHeight: 0,
regionOriginalWidth: 0, regionOriginalHeight: 0,
edges: null,
width: 0, height: 0,
updateUVs: function (u, v, u2, v2, rotate) {
var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV;
var n = this.regionUVs.length;
if (!this.uvs || this.uvs.length != n) {
this.uvs = new spine.Float32Array(n);
}
if (this.regionRotate) {
for (var i = 0; i < n; i += 2) {
this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width;
this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height;
}
} else {
for (var i = 0; i < n; i += 2) {
this.uvs[i] = this.regionU + this.regionUVs[i] * width;
this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height;
}
}
},
computeWorldVertices: function (x, y, slot, worldVertices) {
var skeletonBones = slot.bone.skeleton.bones;
var weights = this.weights;
var bones = this.bones;
var w = 0, v = 0, b = 0, f = 0, n = bones.length, nn;
var wx, wy, bone, vx, vy, weight;
if (!slot.attachmentVertices.length) {
for (; v < n; w += 2) {
wx = 0;
wy = 0;
nn = bones[v++] + v;
for (; v < nn; v++, b += 3) {
bone = skeletonBones[bones[v]];
vx = weights[b];
vy = weights[b + 1];
weight = weights[b + 2];
wx += (vx * bone.m00 + vy * bone.m01 + bone.worldX) * weight;
wy += (vx * bone.m10 + vy * bone.m11 + bone.worldY) * weight;
}
worldVertices[w] = wx + x;
worldVertices[w + 1] = wy + y;
}
} else {
var ffd = slot.attachmentVertices;
for (; v < n; w += 2) {
wx = 0;
wy = 0;
nn = bones[v++] + v;
for (; v < nn; v++, b += 3, f += 2) {
bone = skeletonBones[bones[v]];
vx = weights[b] + ffd[f];
vy = weights[b + 1] + ffd[f + 1];
weight = weights[b + 2];
wx += (vx * bone.m00 + vy * bone.m01 + bone.worldX) * weight;
wy += (vx * bone.m10 + vy * bone.m11 + bone.worldY) * weight;
}
worldVertices[w] = wx + x;
worldVertices[w + 1] = wy + y;
}
}
}
};
spine.BoundingBoxAttachment = function (name) {
this.name = name;
this.vertices = [];
};
spine.BoundingBoxAttachment.prototype = {
type: spine.AttachmentType.boundingbox,
computeWorldVertices: function (x, y, bone, worldVertices) {
x += bone.worldX;
y += bone.worldY;
var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11;
var vertices = this.vertices;
for (var i = 0, n = vertices.length; i < n; i += 2) {
var px = vertices[i];
var py = vertices[i + 1];
worldVertices[i] = px * m00 + py * m01 + x;
worldVertices[i + 1] = px * m10 + py * m11 + y;
}
}
};
spine.AnimationStateData = function (skeletonData) {
this.skeletonData = skeletonData;
this.animationToMixTime = {};
};
spine.AnimationStateData.prototype = {
defaultMix: 0,
setMixByName: function (fromName, toName, duration) {
var from = this.skeletonData.findAnimation(fromName);
if (!from) throw "Animation not found: " + fromName;
var to = this.skeletonData.findAnimation(toName);
if (!to) throw "Animation not found: " + toName;
this.setMix(from, to, duration);
},
setMix: function (from, to, duration) {
this.animationToMixTime[from.name + ":" + to.name] = duration;
},
getMix: function (from, to) {
var key = from.name + ":" + to.name;
return this.animationToMixTime.hasOwnProperty(key) ? this.animationToMixTime[key] : this.defaultMix;
}
};
spine.TrackEntry = function () {};
spine.TrackEntry.prototype = {
next: null, previous: null,
animation: null,
loop: false,
delay: 0, time: 0, lastTime: -1, endTime: 0,
timeScale: 1,
mixTime: 0, mixDuration: 0, mix: 1,
onStart: null, onEnd: null, onComplete: null, onEvent: null
};
spine.AnimationState = function (stateData) {
this.data = stateData;
this.tracks = [];
this.events = [];
};
spine.AnimationState.prototype = {
onStart: null,
onEnd: null,
onComplete: null,
onEvent: null,
timeScale: 1,
update: function (delta) {
delta *= this.timeScale;
for (var i = 0; i < this.tracks.length; i++) {
var current = this.tracks[i];
if (!current) continue;
current.time += delta * current.timeScale;
if (current.previous) {
var previousDelta = delta * current.previous.timeScale;
current.previous.time += previousDelta;
current.mixTime += previousDelta;
}
var next = current.next;
if (next) {
next.time = current.lastTime - next.delay;
if (next.time >= 0) this.setCurrent(i, next);
} else {
// End non-looping animation when it reaches its end time and there is no next entry.
if (!current.loop && current.lastTime >= current.endTime) this.clearTrack(i);
}
}
},
apply: function (skeleton) {
for (var i = 0; i < this.tracks.length; i++) {
var current = this.tracks[i];
if (!current) continue;
this.events.length = 0;
var time = current.time;
var lastTime = current.lastTime;
var endTime = current.endTime;
var loop = current.loop;
if (!loop && time > endTime) time = endTime;
var previous = current.previous;
if (!previous) {
if (current.mix == 1)
current.animation.apply(skeleton, current.lastTime, time, loop, this.events);
else
current.animation.mix(skeleton, current.lastTime, time, loop, this.events, current.mix);
} else {
var previousTime = previous.time;
if (!previous.loop && previousTime > previous.endTime) previousTime = previous.endTime;
previous.animation.apply(skeleton, previousTime, previousTime, previous.loop, null);
var alpha = current.mixTime / current.mixDuration * current.mix;
if (alpha >= 1) {
alpha = 1;
current.previous = null;
}
current.animation.mix(skeleton, current.lastTime, time, loop, this.events, alpha);
}
for (var ii = 0, nn = this.events.length; ii < nn; ii++) {
var event = this.events[ii];
if (current.onEvent) current.onEvent(i, event);
if (this.onEvent) this.onEvent(i, event);
}
// Check if completed the animation or a loop iteration.
if (loop ? (lastTime % endTime > time % endTime) : (lastTime < endTime && time >= endTime)) {
var count = Math.floor(time / endTime);
if (current.onComplete) current.onComplete(i, count);
if (this.onComplete) this.onComplete(i, count);
}
current.lastTime = current.time;
}
},
clearTracks: function () {
for (var i = 0, n = this.tracks.length; i < n; i++)
this.clearTrack(i);
this.tracks.length = 0;
},
clearTrack: function (trackIndex) {
if (trackIndex >= this.tracks.length) return;
var current = this.tracks[trackIndex];
if (!current) return;
if (current.onEnd) current.onEnd(trackIndex);
if (this.onEnd) this.onEnd(trackIndex);
this.tracks[trackIndex] = null;
},
_expandToIndex: function (index) {
if (index < this.tracks.length) return this.tracks[index];
while (index >= this.tracks.length)
this.tracks.push(null);
return null;
},
setCurrent: function (index, entry) {
var current = this._expandToIndex(index);
if (current) {
var previous = current.previous;
current.previous = null;
if (current.onEnd) current.onEnd(index);
if (this.onEnd) this.onEnd(index);
entry.mixDuration = this.data.getMix(current.animation, entry.animation);
if (entry.mixDuration > 0) {
entry.mixTime = 0;
// If a mix is in progress, mix from the closest animation.
if (previous && current.mixTime / current.mixDuration < 0.5)
entry.previous = previous;
else
entry.previous = current;
}
}
this.tracks[index] = entry;
if (entry.onStart) entry.onStart(index);
if (this.onStart) this.onStart(index);
},
setAnimationByName: function (trackIndex, animationName, loop) {
var animation = this.data.skeletonData.findAnimation(animationName);
if (!animation) throw "Animation not found: " + animationName;
return this.setAnimation(trackIndex, animation, loop);
},
/** Set the current animation. Any queued animations are cleared. */
setAnimation: function (trackIndex, animation, loop) {
var entry = new spine.TrackEntry();
entry.animation = animation;
entry.loop = loop;
entry.endTime = animation.duration;
this.setCurrent(trackIndex, entry);
return entry;
},
addAnimationByName: function (trackIndex, animationName, loop, delay) {
var animation = this.data.skeletonData.findAnimation(animationName);
if (!animation) throw "Animation not found: " + animationName;
return this.addAnimation(trackIndex, animation, loop, delay);
},
/** Adds an animation to be played delay seconds after the current or last queued animation.
* @param delay May be <= 0 to use duration of previous animation minus any mix duration plus the negative delay. */
addAnimation: function (trackIndex, animation, loop, delay) {
var entry = new spine.TrackEntry();
entry.animation = animation;
entry.loop = loop;
entry.endTime = animation.duration;
var last = this._expandToIndex(trackIndex);
if (last) {
while (last.next)
last = last.next;
last.next = entry;
} else
this.tracks[trackIndex] = entry;
if (delay <= 0) {
if (last)
delay += last.endTime - this.data.getMix(last.animation, animation);
else
delay = 0;
}
entry.delay = delay;
return entry;
},
/** May be null. */
getCurrent: function (trackIndex) {
if (trackIndex >= this.tracks.length) return null;
return this.tracks[trackIndex];
}
};
spine.SkeletonJson = function (attachmentLoader) {
this.attachmentLoader = attachmentLoader;
};
spine.SkeletonJson.prototype = {
scale: 1,
readSkeletonData: function (root, name) {
var skeletonData = new spine.SkeletonData();
skeletonData.name = name;
// Skeleton.
var skeletonMap = root["skeleton"];
if (skeletonMap) {
skeletonData.hash = skeletonMap["hash"];
skeletonData.version = skeletonMap["spine"];
skeletonData.width = skeletonMap["width"] || 0;
skeletonData.height = skeletonMap["height"] || 0;
}
// Bones.
var bones = root["bones"];
for (var i = 0, n = bones.length; i < n; i++) {
var boneMap = bones[i];
var parent = null;
if (boneMap["parent"]) {
parent = skeletonData.findBone(boneMap["parent"]);
if (!parent) throw "Parent bone not found: " + boneMap["parent"];
}
var boneData = new spine.BoneData(boneMap["name"], parent);
boneData.length = (boneMap["length"] || 0) * this.scale;
boneData.x = (boneMap["x"] || 0) * this.scale;
boneData.y = (boneMap["y"] || 0) * this.scale;
boneData.rotation = (boneMap["rotation"] || 0);
boneData.scaleX = boneMap.hasOwnProperty("scaleX") ? boneMap["scaleX"] : 1;
boneData.scaleY = boneMap.hasOwnProperty("scaleY") ? boneMap["scaleY"] : 1;
boneData.inheritScale = boneMap.hasOwnProperty("inheritScale") ? boneMap["inheritScale"] : true;
boneData.inheritRotation = boneMap.hasOwnProperty("inheritRotation") ? boneMap["inheritRotation"] : true;
skeletonData.bones.push(boneData);
}
// IK constraints.
var ik = root["ik"];
if (ik) {
for (var i = 0, n = ik.length; i < n; i++) {
var ikMap = ik[i];
var ikConstraintData = new spine.IkConstraintData(ikMap["name"]);
var bones = ikMap["bones"];
for (var ii = 0, nn = bones.length; ii < nn; ii++) {
var bone = skeletonData.findBone(bones[ii]);
if (!bone) throw "IK bone not found: " + bones[ii];
ikConstraintData.bones.push(bone);
}
ikConstraintData.target = skeletonData.findBone(ikMap["target"]);
if (!ikConstraintData.target) throw "Target bone not found: " + ikMap["target"];
ikConstraintData.bendDirection = (!ikMap.hasOwnProperty("bendPositive") || ikMap["bendPositive"]) ? 1 : -1;
ikConstraintData.mix = ikMap.hasOwnProperty("mix") ? ikMap["mix"] : 1;
skeletonData.ikConstraints.push(ikConstraintData);
}
}
// Slots.
var slots = root["slots"];
for (var i = 0, n = slots.length; i < n; i++) {
var slotMap = slots[i];
var boneData = skeletonData.findBone(slotMap["bone"]);
if (!boneData) throw "Slot bone not found: " + slotMap["bone"];
var slotData = new spine.SlotData(slotMap["name"], boneData);
var color = slotMap["color"];
if (color) {
slotData.r = this.toColor(color, 0);
slotData.g = this.toColor(color, 1);
slotData.b = this.toColor(color, 2);
slotData.a = this.toColor(color, 3);
}
slotData.attachmentName = slotMap["attachment"];
slotData.blendMode = spine.AttachmentType[slotMap["blend"] || "normal"];
skeletonData.slots.push(slotData);
}
// Skins.
var skins = root["skins"];
for (var skinName in skins) {
if (!skins.hasOwnProperty(skinName)) continue;
var skinMap = skins[skinName];
var skin = new spine.Skin(skinName);
for (var slotName in skinMap) {
if (!skinMap.hasOwnProperty(slotName)) continue;
var slotIndex = skeletonData.findSlotIndex(slotName);
var slotEntry = skinMap[slotName];
for (var attachmentName in slotEntry) {
if (!slotEntry.hasOwnProperty(attachmentName)) continue;
var attachment = this.readAttachment(skin, attachmentName, slotEntry[attachmentName]);
if (attachment) skin.addAttachment(slotIndex, attachmentName, attachment);
}
}
skeletonData.skins.push(skin);
if (skin.name == "default") skeletonData.defaultSkin = skin;
}
// Events.
var events = root["events"];
for (var eventName in events) {
if (!events.hasOwnProperty(eventName)) continue;
var eventMap = events[eventName];
var eventData = new spine.EventData(eventName);
eventData.intValue = eventMap["int"] || 0;
eventData.floatValue = eventMap["float"] || 0;
eventData.stringValue = eventMap["string"] || null;
skeletonData.events.push(eventData);
}
// Animations.
var animations = root["animations"];
for (var animationName in animations) {
if (!animations.hasOwnProperty(animationName)) continue;
this.readAnimation(animationName, animations[animationName], skeletonData);
}
return skeletonData;
},
readAttachment: function (skin, name, map) {
name = map["name"] || name;
var type = spine.AttachmentType[map["type"] || "region"];
var path = map["path"] || name;
var scale = this.scale;
if (type == spine.AttachmentType.region) {
var region = this.attachmentLoader.newRegionAttachment(skin, name, path);
if (!region) return null;
region.path = path;
region.x = (map["x"] || 0) * scale;
region.y = (map["y"] || 0) * scale;
region.scaleX = map.hasOwnProperty("scaleX") ? map["scaleX"] : 1;
region.scaleY = map.hasOwnProperty("scaleY") ? map["scaleY"] : 1;
region.rotation = map["rotation"] || 0;
region.width = (map["width"] || 0) * scale;
region.height = (map["height"] || 0) * scale;
var color = map["color"];
if (color) {
region.r = this.toColor(color, 0);
region.g = this.toColor(color, 1);
region.b = this.toColor(color, 2);
region.a = this.toColor(color, 3);
}
region.updateOffset();
return region;
} else if (type == spine.AttachmentType.mesh) {
var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path);
if (!mesh) return null;
mesh.path = path;
mesh.vertices = this.getFloatArray(map, "vertices", scale);
mesh.triangles = this.getIntArray(map, "triangles");
mesh.regionUVs = this.getFloatArray(map, "uvs", 1);
mesh.updateUVs();
color = map["color"];
if (color) {
mesh.r = this.toColor(color, 0);
mesh.g = this.toColor(color, 1);
mesh.b = this.toColor(color, 2);
mesh.a = this.toColor(color, 3);
}
mesh.hullLength = (map["hull"] || 0) * 2;
if (map["edges"]) mesh.edges = this.getIntArray(map, "edges");
mesh.width = (map["width"] || 0) * scale;
mesh.height = (map["height"] || 0) * scale;
return mesh;
} else if (type == spine.AttachmentType.skinnedmesh) {
var mesh = this.attachmentLoader.newSkinnedMeshAttachment(skin, name, path);
if (!mesh) return null;
mesh.path = path;
var uvs = this.getFloatArray(map, "uvs", 1);
var vertices = this.getFloatArray(map, "vertices", 1);
var weights = [];
var bones = [];
for (var i = 0, n = vertices.length; i < n; ) {
var boneCount = vertices[i++] | 0;
bones[bones.length] = boneCount;
for (var nn = i + boneCount * 4; i < nn; ) {
bones[bones.length] = vertices[i];
weights[weights.length] = vertices[i + 1] * scale;
weights[weights.length] = vertices[i + 2] * scale;
weights[weights.length] = vertices[i + 3];
i += 4;
}
}
mesh.bones = bones;
mesh.weights = weights;
mesh.triangles = this.getIntArray(map, "triangles");
mesh.regionUVs = uvs;
mesh.updateUVs();
color = map["color"];
if (color) {
mesh.r = this.toColor(color, 0);
mesh.g = this.toColor(color, 1);
mesh.b = this.toColor(color, 2);
mesh.a = this.toColor(color, 3);
}
mesh.hullLength = (map["hull"] || 0) * 2;
if (map["edges"]) mesh.edges = this.getIntArray(map, "edges");
mesh.width = (map["width"] || 0) * scale;
mesh.height = (map["height"] || 0) * scale;
return mesh;
} else if (type == spine.AttachmentType.boundingbox) {
var attachment = this.attachmentLoader.newBoundingBoxAttachment(skin, name);
var vertices = map["vertices"];
for (var i = 0, n = vertices.length; i < n; i++)
attachment.vertices.push(vertices[i] * scale);
return attachment;
}
throw "Unknown attachment type: " + type;
},
readAnimation: function (name, map, skeletonData) {
var timelines = [];
var duration = 0;
var slots = map["slots"];
for (var slotName in slots) {
if (!slots.hasOwnProperty(slotName)) continue;
var slotMap = slots[slotName];
var slotIndex = skeletonData.findSlotIndex(slotName);
for (var timelineName in slotMap) {
if (!slotMap.hasOwnProperty(timelineName)) continue;
var values = slotMap[timelineName];
if (timelineName == "color") {
var timeline = new spine.ColorTimeline(values.length);
timeline.slotIndex = slotIndex;
var frameIndex = 0;
for (var i = 0, n = values.length; i < n; i++) {
var valueMap = values[i];
var color = valueMap["color"];
var r = this.toColor(color, 0);
var g = this.toColor(color, 1);
var b = this.toColor(color, 2);
var a = this.toColor(color, 3);
timeline.setFrame(frameIndex, valueMap["time"], r, g, b, a);
this.readCurve(timeline, frameIndex, valueMap);
frameIndex++;
}
timelines.push(timeline);
duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 5 - 5]);
} else if (timelineName == "attachment") {
var timeline = new spine.AttachmentTimeline(values.length);
timeline.slotIndex = slotIndex;
var frameIndex = 0;
for (var i = 0, n = values.length; i < n; i++) {
var valueMap = values[i];
timeline.setFrame(frameIndex++, valueMap["time"], valueMap["name"]);
}
timelines.push(timeline);
duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
} else
throw "Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")";
}
}
var bones = map["bones"];
for (var boneName in bones) {
if (!bones.hasOwnProperty(boneName)) continue;
var boneIndex = skeletonData.findBoneIndex(boneName);
if (boneIndex == -1) throw "Bone not found: " + boneName;
var boneMap = bones[boneName];
for (var timelineName in boneMap) {
if (!boneMap.hasOwnProperty(timelineName)) continue;
var values = boneMap[timelineName];
if (timelineName == "rotate") {
var timeline = new spine.RotateTimeline(values.length);
timeline.boneIndex = boneIndex;
var frameIndex = 0;
for (var i = 0, n = values.length; i < n; i++) {
var valueMap = values[i];
timeline.setFrame(frameIndex, valueMap["time"], valueMap["angle"]);
this.readCurve(timeline, frameIndex, valueMap);
frameIndex++;
}
timelines.push(timeline);
duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2]);
} else if (timelineName == "translate" || timelineName == "scale") {
var timeline;
var timelineScale = 1;
if (timelineName == "scale")
timeline = new spine.ScaleTimeline(values.length);
else {
timeline = new spine.TranslateTimeline(values.length);
timelineScale = this.scale;
}
timeline.boneIndex = boneIndex;
var frameIndex = 0;
for (var i = 0, n = values.length; i < n; i++) {
var valueMap = values[i];
var x = (valueMap["x"] || 0) * timelineScale;
var y = (valueMap["y"] || 0) * timelineScale;
timeline.setFrame(frameIndex, valueMap["time"], x, y);
this.readCurve(timeline, frameIndex, valueMap);
frameIndex++;
}
timelines.push(timeline);
duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 3 - 3]);
} else if (timelineName == "flipX" || timelineName == "flipY") {
var x = timelineName == "flipX";
var timeline = x ? new spine.FlipXTimeline(values.length) : new spine.FlipYTimeline(values.length);
timeline.boneIndex = boneIndex;
var field = x ? "x" : "y";
var frameIndex = 0;
for (var i = 0, n = values.length; i < n; i++) {
var valueMap = values[i];
timeline.setFrame(frameIndex, valueMap["time"], valueMap[field] || false);
frameIndex++;
}
timelines.push(timeline);
duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2]);
} else
throw "Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")";
}
}
var ikMap = map["ik"];
for (var ikConstraintName in ikMap) {
if (!ikMap.hasOwnProperty(ikConstraintName)) continue;
var ikConstraint = skeletonData.findIkConstraint(ikConstraintName);
var values = ikMap[ikConstraintName];
var timeline = new spine.IkConstraintTimeline(values.length);
timeline.ikConstraintIndex = skeletonData.ikConstraints.indexOf(ikConstraint);
var frameIndex = 0;
for (var i = 0, n = values.length; i < n; i++) {
var valueMap = values[i];
var mix = valueMap.hasOwnProperty("mix") ? valueMap["mix"] : 1;
var bendDirection = (!valueMap.hasOwnProperty("bendPositive") || valueMap["bendPositive"]) ? 1 : -1;
timeline.setFrame(frameIndex, valueMap["time"], mix, bendDirection);
this.readCurve(timeline, frameIndex, valueMap);
frameIndex++;
}
timelines.push(timeline);
duration = Math.max(duration, timeline.frames[timeline.frameCount * 3 - 3]);
}
var ffd = map["ffd"];
for (var skinName in ffd) {
var skin = skeletonData.findSkin(skinName);
var slotMap = ffd[skinName];
for (slotName in slotMap) {
var slotIndex = skeletonData.findSlotIndex(slotName);
var meshMap = slotMap[slotName];
for (var meshName in meshMap) {
var values = meshMap[meshName];
var timeline = new spine.FfdTimeline(values.length);
var attachment = skin.getAttachment(slotIndex, meshName);
if (!attachment) throw "FFD attachment not found: " + meshName;
timeline.slotIndex = slotIndex;
timeline.attachment = attachment;
var isMesh = attachment.type == spine.AttachmentType.mesh;
var vertexCount;
if (isMesh)
vertexCount = attachment.vertices.length;
else
vertexCount = attachment.weights.length / 3 * 2;
var frameIndex = 0;
for (var i = 0, n = values.length; i < n; i++) {
var valueMap = values[i];
var vertices;
if (!valueMap["vertices"]) {
if (isMesh)
vertices = attachment.vertices;
else {
vertices = [];
vertices.length = vertexCount;
}
} else {
var verticesValue = valueMap["vertices"];
var vertices = [];
vertices.length = vertexCount;
var start = valueMap["offset"] || 0;
var nn = verticesValue.length;
if (this.scale == 1) {
for (var ii = 0; ii < nn; ii++)
vertices[ii + start] = verticesValue[ii];
} else {
for (var ii = 0; ii < nn; ii++)
vertices[ii + start] = verticesValue[ii] * this.scale;
}
if (isMesh) {
var meshVertices = attachment.vertices;
for (var ii = 0, nn = vertices.length; ii < nn; ii++)
vertices[ii] += meshVertices[ii];
}
}
timeline.setFrame(frameIndex, valueMap["time"], vertices);
this.readCurve(timeline, frameIndex, valueMap);
frameIndex++;
}
timelines[timelines.length] = timeline;
duration = Math.max(duration, timeline.frames[timeline.frameCount - 1]);
}
}
}
var drawOrderValues = map["drawOrder"];
if (!drawOrderValues) drawOrderValues = map["draworder"];
if (drawOrderValues) {
var timeline = new spine.DrawOrderTimeline(drawOrderValues.length);
var slotCount = skeletonData.slots.length;
var frameIndex = 0;
for (var i = 0, n = drawOrderValues.length; i < n; i++) {
var drawOrderMap = drawOrderValues[i];
var drawOrder = null;
if (drawOrderMap["offsets"]) {
drawOrder = [];
drawOrder.length = slotCount;
for (var ii = slotCount - 1; ii >= 0; ii--)
drawOrder[ii] = -1;
var offsets = drawOrderMap["offsets"];
var unchanged = [];
unchanged.length = slotCount - offsets.length;
var originalIndex = 0, unchangedIndex = 0;
for (var ii = 0, nn = offsets.length; ii < nn; ii++) {
var offsetMap = offsets[ii];
var slotIndex = skeletonData.findSlotIndex(offsetMap["slot"]);
if (slotIndex == -1) throw "Slot not found: " + offsetMap["slot"];
// Collect unchanged items.
while (originalIndex != slotIndex)
unchanged[unchangedIndex++] = originalIndex++;
// Set changed items.
drawOrder[originalIndex + offsetMap["offset"]] = originalIndex++;
}
// Collect remaining unchanged items.
while (originalIndex < slotCount)
unchanged[unchangedIndex++] = originalIndex++;
// Fill in unchanged items.
for (var ii = slotCount - 1; ii >= 0; ii--)
if (drawOrder[ii] == -1) drawOrder[ii] = unchanged[--unchangedIndex];
}
timeline.setFrame(frameIndex++, drawOrderMap["time"], drawOrder);
}
timelines.push(timeline);
duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
}
var events = map["events"];
if (events) {
var timeline = new spine.EventTimeline(events.length);
var frameIndex = 0;
for (var i = 0, n = events.length; i < n; i++) {
var eventMap = events[i];
var eventData = skeletonData.findEvent(eventMap["name"]);
if (!eventData) throw "Event not found: " + eventMap["name"];
var event = new spine.Event(eventData);
event.intValue = eventMap.hasOwnProperty("int") ? eventMap["int"] : eventData.intValue;
event.floatValue = eventMap.hasOwnProperty("float") ? eventMap["float"] : eventData.floatValue;
event.stringValue = eventMap.hasOwnProperty("string") ? eventMap["string"] : eventData.stringValue;
timeline.setFrame(frameIndex++, eventMap["time"], event);
}
timelines.push(timeline);
duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
}
skeletonData.animations.push(new spine.Animation(name, timelines, duration));
},
readCurve: function (timeline, frameIndex, valueMap) {
var curve = valueMap["curve"];
if (!curve)
timeline.curves.setLinear(frameIndex);
else if (curve == "stepped")
timeline.curves.setStepped(frameIndex);
else if (curve instanceof Array)
timeline.curves.setCurve(frameIndex, curve[0], curve[1], curve[2], curve[3]);
},
toColor: function (hexString, colorIndex) {
if (hexString.length != 8) throw "Color hexidecimal length must be 8, recieved: " + hexString;
return parseInt(hexString.substring(colorIndex * 2, (colorIndex * 2) + 2), 16) / 255;
},
getFloatArray: function (map, name, scale) {
var list = map[name];
var values = new spine.Float32Array(list.length);
var i = 0, n = list.length;
if (scale == 1) {
for (; i < n; i++)
values[i] = list[i];
} else {
for (; i < n; i++)
values[i] = list[i] * scale;
}
return values;
},
getIntArray: function (map, name) {
var list = map[name];
var values = new spine.Uint16Array(list.length);
for (var i = 0, n = list.length; i < n; i++)
values[i] = list[i] | 0;
return values;
}
};
spine.Atlas = function (atlasText, textureLoader) {
this.textureLoader = textureLoader;
this.pages = [];
this.regions = [];
var reader = new spine.AtlasReader(atlasText);
var tuple = [];
tuple.length = 4;
var page = null;
while (true) {
var line = reader.readLine();
if (line === null) break;
line = reader.trim(line);
if (!line.length)
page = null;
else if (!page) {
page = new spine.AtlasPage();
page.name = line;
if (reader.readTuple(tuple) == 2) { // size is only optional for an atlas packed with an old TexturePacker.
page.width = parseInt(tuple[0]);
page.height = parseInt(tuple[1]);
reader.readTuple(tuple);
}
page.format = spine.Atlas.Format[tuple[0]];
reader.readTuple(tuple);
page.minFilter = spine.Atlas.TextureFilter[tuple[0]];
page.magFilter = spine.Atlas.TextureFilter[tuple[1]];
var direction = reader.readValue();
page.uWrap = spine.Atlas.TextureWrap.clampToEdge;
page.vWrap = spine.Atlas.TextureWrap.clampToEdge;
if (direction == "x")
page.uWrap = spine.Atlas.TextureWrap.repeat;
else if (direction == "y")
page.vWrap = spine.Atlas.TextureWrap.repeat;
else if (direction == "xy")
page.uWrap = page.vWrap = spine.Atlas.TextureWrap.repeat;
textureLoader.load(page, line, this);
this.pages.push(page);
} else {
var region = new spine.AtlasRegion();
region.name = line;
region.page = page;
region.rotate = reader.readValue() == "true";
reader.readTuple(tuple);
var x = parseInt(tuple[0]);
var y = parseInt(tuple[1]);
reader.readTuple(tuple);
var width = parseInt(tuple[0]);
var height = parseInt(tuple[1]);
region.u = x / page.width;
region.v = y / page.height;
if (region.rotate) {
region.u2 = (x + height) / page.width;
region.v2 = (y + width) / page.height;
} else {
region.u2 = (x + width) / page.width;
region.v2 = (y + height) / page.height;
}
region.x = x;
region.y = y;
region.width = Math.abs(width);
region.height = Math.abs(height);
if (reader.readTuple(tuple) == 4) { // split is optional
region.splits = [parseInt(tuple[0]), parseInt(tuple[1]), parseInt(tuple[2]), parseInt(tuple[3])];
if (reader.readTuple(tuple) == 4) { // pad is optional, but only present with splits
region.pads = [parseInt(tuple[0]), parseInt(tuple[1]), parseInt(tuple[2]), parseInt(tuple[3])];
reader.readTuple(tuple);
}
}
region.originalWidth = parseInt(tuple[0]);
region.originalHeight = parseInt(tuple[1]);
reader.readTuple(tuple);
region.offsetX = parseInt(tuple[0]);
region.offsetY = parseInt(tuple[1]);
region.index = parseInt(reader.readValue());
this.regions.push(region);
}
}
};
spine.Atlas.prototype = {
findRegion: function (name) {
var regions = this.regions;
for (var i = 0, n = regions.length; i < n; i++)
if (regions[i].name == name) return regions[i];
return null;
},
dispose: function () {
var pages = this.pages;
for (var i = 0, n = pages.length; i < n; i++)
this.textureLoader.unload(pages[i].rendererObject);
},
updateUVs: function (page) {
var regions = this.regions;
for (var i = 0, n = regions.length; i < n; i++) {
var region = regions[i];
if (region.page != page) continue;
region.u = region.x / page.width;
region.v = region.y / page.height;
if (region.rotate) {
region.u2 = (region.x + region.height) / page.width;
region.v2 = (region.y + region.width) / page.height;
} else {
region.u2 = (region.x + region.width) / page.width;
region.v2 = (region.y + region.height) / page.height;
}
}
}
};
spine.Atlas.Format = {
alpha: 0,
intensity: 1,
luminanceAlpha: 2,
rgb565: 3,
rgba4444: 4,
rgb888: 5,
rgba8888: 6
};
spine.Atlas.TextureFilter = {
nearest: 0,
linear: 1,
mipMap: 2,
mipMapNearestNearest: 3,
mipMapLinearNearest: 4,
mipMapNearestLinear: 5,
mipMapLinearLinear: 6
};
spine.Atlas.TextureWrap = {
mirroredRepeat: 0,
clampToEdge: 1,
repeat: 2
};
spine.AtlasPage = function () {};
spine.AtlasPage.prototype = {
name: null,
format: null,
minFilter: null,
magFilter: null,
uWrap: null,
vWrap: null,
rendererObject: null,
width: 0,
height: 0
};
spine.AtlasRegion = function () {};
spine.AtlasRegion.prototype = {
page: null,
name: null,
x: 0, y: 0,
width: 0, height: 0,
u: 0, v: 0, u2: 0, v2: 0,
offsetX: 0, offsetY: 0,
originalWidth: 0, originalHeight: 0,
index: 0,
rotate: false,
splits: null,
pads: null
};
spine.AtlasReader = function (text) {
this.lines = text.split(/\r\n|\r|\n/);
};
spine.AtlasReader.prototype = {
index: 0,
trim: function (value) {
return value.replace(/^\s+|\s+$/g, "");
},
readLine: function () {
if (this.index >= this.lines.length) return null;
return this.lines[this.index++];
},
readValue: function () {
var line = this.readLine();
var colon = line.indexOf(":");
if (colon == -1) throw "Invalid line: " + line;
return this.trim(line.substring(colon + 1));
},
/** Returns the number of tuple values read (1, 2 or 4). */
readTuple: function (tuple) {
var line = this.readLine();
var colon = line.indexOf(":");
if (colon == -1) throw "Invalid line: " + line;
var i = 0, lastMatch = colon + 1;
for (; i < 3; i++) {
var comma = line.indexOf(",", lastMatch);
if (comma == -1) break;
tuple[i] = this.trim(line.substr(lastMatch, comma - lastMatch));
lastMatch = comma + 1;
}
tuple[i] = this.trim(line.substring(lastMatch));
return i + 1;
}
};
spine.AtlasAttachmentLoader = function (atlas) {
this.atlas = atlas;
};
spine.AtlasAttachmentLoader.prototype = {
newRegionAttachment: function (skin, name, path) {
var region = this.atlas.findRegion(path);
if (!region) throw "Region not found in atlas: " + path + " (region attachment: " + name + ")";
var attachment = new spine.RegionAttachment(name);
attachment.rendererObject = region;
attachment.setUVs(region.u, region.v, region.u2, region.v2, region.rotate);
attachment.regionOffsetX = region.offsetX;
attachment.regionOffsetY = region.offsetY;
attachment.regionWidth = region.width;
attachment.regionHeight = region.height;
attachment.regionOriginalWidth = region.originalWidth;
attachment.regionOriginalHeight = region.originalHeight;
return attachment;
},
newMeshAttachment: function (skin, name, path) {
var region = this.atlas.findRegion(path);
if (!region) throw "Region not found in atlas: " + path + " (mesh attachment: " + name + ")";
var attachment = new spine.MeshAttachment(name);
attachment.rendererObject = region;
attachment.regionU = region.u;
attachment.regionV = region.v;
attachment.regionU2 = region.u2;
attachment.regionV2 = region.v2;
attachment.regionRotate = region.rotate;
attachment.regionOffsetX = region.offsetX;
attachment.regionOffsetY = region.offsetY;
attachment.regionWidth = region.width;
attachment.regionHeight = region.height;
attachment.regionOriginalWidth = region.originalWidth;
attachment.regionOriginalHeight = region.originalHeight;
return attachment;
},
newSkinnedMeshAttachment: function (skin, name, path) {
var region = this.atlas.findRegion(path);
if (!region) throw "Region not found in atlas: " + path + " (skinned mesh attachment: " + name + ")";
var attachment = new spine.SkinnedMeshAttachment(name);
attachment.rendererObject = region;
attachment.regionU = region.u;
attachment.regionV = region.v;
attachment.regionU2 = region.u2;
attachment.regionV2 = region.v2;
attachment.regionRotate = region.rotate;
attachment.regionOffsetX = region.offsetX;
attachment.regionOffsetY = region.offsetY;
attachment.regionWidth = region.width;
attachment.regionHeight = region.height;
attachment.regionOriginalWidth = region.originalWidth;
attachment.regionOriginalHeight = region.originalHeight;
return attachment;
},
newBoundingBoxAttachment: function (skin, name) {
return new spine.BoundingBoxAttachment(name);
}
};
spine.SkeletonBounds = function () {
this.polygonPool = [];
this.polygons = [];
this.boundingBoxes = [];
};
spine.SkeletonBounds.prototype = {
minX: 0, minY: 0, maxX: 0, maxY: 0,
update: function (skeleton, updateAabb) {
var slots = skeleton.slots;
var slotCount = slots.length;
var x = skeleton.x, y = skeleton.y;
var boundingBoxes = this.boundingBoxes;
var polygonPool = this.polygonPool;
var polygons = this.polygons;
boundingBoxes.length = 0;
for (var i = 0, n = polygons.length; i < n; i++)
polygonPool.push(polygons[i]);
polygons.length = 0;
for (var i = 0; i < slotCount; i++) {
var slot = slots[i];
var boundingBox = slot.attachment;
if (boundingBox.type != spine.AttachmentType.boundingbox) continue;
boundingBoxes.push(boundingBox);
var poolCount = polygonPool.length, polygon;
if (poolCount > 0) {
polygon = polygonPool[poolCount - 1];
polygonPool.splice(poolCount - 1, 1);
} else
polygon = [];
polygons.push(polygon);
polygon.length = boundingBox.vertices.length;
boundingBox.computeWorldVertices(x, y, slot.bone, polygon);
}
if (updateAabb) this.aabbCompute();
},
aabbCompute: function () {
var polygons = this.polygons;
var minX = Number.MAX_VALUE, minY = Number.MAX_VALUE, maxX = Number.MIN_VALUE, maxY = Number.MIN_VALUE;
for (var i = 0, n = polygons.length; i < n; i++) {
var vertices = polygons[i];
for (var ii = 0, nn = vertices.length; ii < nn; ii += 2) {
var x = vertices[ii];
var y = vertices[ii + 1];
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
}
}
this.minX = minX;
this.minY = minY;
this.maxX = maxX;
this.maxY = maxY;
},
/** Returns true if the axis aligned bounding box contains the point. */
aabbContainsPoint: function (x, y) {
return x >= this.minX && x <= this.maxX && y >= this.minY && y <= this.maxY;
},
/** Returns true if the axis aligned bounding box intersects the line segment. */
aabbIntersectsSegment: function (x1, y1, x2, y2) {
var minX = this.minX, minY = this.minY, maxX = this.maxX, maxY = this.maxY;
if ((x1 <= minX && x2 <= minX) || (y1 <= minY && y2 <= minY) || (x1 >= maxX && x2 >= maxX) || (y1 >= maxY && y2 >= maxY))
return false;
var m = (y2 - y1) / (x2 - x1);
var y = m * (minX - x1) + y1;
if (y > minY && y < maxY) return true;
y = m * (maxX - x1) + y1;
if (y > minY && y < maxY) return true;
var x = (minY - y1) / m + x1;
if (x > minX && x < maxX) return true;
x = (maxY - y1) / m + x1;
if (x > minX && x < maxX) return true;
return false;
},
/** Returns true if the axis aligned bounding box intersects the axis aligned bounding box of the specified bounds. */
aabbIntersectsSkeleton: function (bounds) {
return this.minX < bounds.maxX && this.maxX > bounds.minX && this.minY < bounds.maxY && this.maxY > bounds.minY;
},
/** Returns the first bounding box attachment that contains the point, or null. When doing many checks, it is usually more
* efficient to only call this method if {@link #aabbContainsPoint(float, float)} returns true. */
containsPoint: function (x, y) {
var polygons = this.polygons;
for (var i = 0, n = polygons.length; i < n; i++)
if (this.polygonContainsPoint(polygons[i], x, y)) return this.boundingBoxes[i];
return null;
},
/** Returns the first bounding box attachment that contains the line segment, or null. When doing many checks, it is usually
* more efficient to only call this method if {@link #aabbIntersectsSegment(float, float, float, float)} returns true. */
intersectsSegment: function (x1, y1, x2, y2) {
var polygons = this.polygons;
for (var i = 0, n = polygons.length; i < n; i++)
if (polygons[i].intersectsSegment(x1, y1, x2, y2)) return this.boundingBoxes[i];
return null;
},
/** Returns true if the polygon contains the point. */
polygonContainsPoint: function (polygon, x, y) {
var nn = polygon.length;
var prevIndex = nn - 2;
var inside = false;
for (var ii = 0; ii < nn; ii += 2) {
var vertexY = polygon[ii + 1];
var prevY = polygon[prevIndex + 1];
if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) {
var vertexX = polygon[ii];
if (vertexX + (y - vertexY) / (prevY - vertexY) * (polygon[prevIndex] - vertexX) < x) inside = !inside;
}
prevIndex = ii;
}
return inside;
},
/** Returns true if the polygon contains the line segment. */
polygonIntersectsSegment: function (polygon, x1, y1, x2, y2) {
var nn = polygon.length;
var width12 = x1 - x2, height12 = y1 - y2;
var det1 = x1 * y2 - y1 * x2;
var x3 = polygon[nn - 2], y3 = polygon[nn - 1];
for (var ii = 0; ii < nn; ii += 2) {
var x4 = polygon[ii], y4 = polygon[ii + 1];
var det2 = x3 * y4 - y3 * x4;
var width34 = x3 - x4, height34 = y3 - y4;
var det3 = width12 * height34 - height12 * width34;
var x = (det1 * width34 - width12 * det2) / det3;
if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) {
var y = (det1 * height34 - height12 * det2) / det3;
if (((y >= y3 && y <= y4) || (y >= y4 && y <= y3)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1))) return true;
}
x3 = x4;
y3 = y4;
}
return false;
},
getPolygon: function (attachment) {
var index = this.boundingBoxes.indexOf(attachment);
return index == -1 ? null : this.polygons[index];
},
getWidth: function () {
return this.maxX - this.minX;
},
getHeight: function () {
return this.maxY - this.minY;
}
};
|
import List from '../list/list';
import { Group } from '../group';
class Registry extends List {
constructor() {
super([]);
}
/**
* Add unique group
*
* @param {Group} group
*/
add(group) {
if (!(group instanceof Group)) {
throw new Error('Invalid group. Only Group instances allowed.');
}
super.add(group);
}
/**
* Remove group from registry
*
* @param {Group} group
* @returns {Group}
*/
remove(group) {
group.reset();
return super.remove(group);
}
/**
* Get group by name
*
* @param {string} name
* @returns {Group}
*/
get(name) {
return this.list.find(g => g.name === name);
}
/**
* Get all group names from registry
*
* @returns {Array}
*/
groupNames() {
return this.list.map(g => g.name);
}
}
export default new Registry();
|
/**
* Crayola 1903 original colors.
*
* Includes alternative label names.
*/
module.exports = require('./lut').create({
"Red": "#ED0A3F",
"English Vermilion": "#CC474B", "Vermillion": "#CC474B",
"Madder Lake": "#CC3336",
"Permanent Geranium Lake": "#E12C2C",
"Indian Red": "#B94E48",
"Dark Venetian Red": "#B33B24", "Venetian Red, Dark": "#B33B24",
"Venetian Red": "#CC553D",
"Light Venetian Red": "#E6735C", "Venetian Red, Light": "#E6735C",
"Orange": "#FF8833",
"Gold Ochre": "#F2C649", "Golden Ochre": "#F2C649",
"Medium Chrome Yellow": "#FCD667",
"Yellow": "#FBE870",
"Olive Green": "#B5B35C",
"Light Chrome Yellow": "#FFFF9F", "Chrome Yellow, Light": "#FFFF9F",
"Light Chrome Green": "#BEE64B", "Chrome Green, Light": "#BEE64B",
"Green": "#3AA655",
"Medium Chrome Green": "#6CA67C", "Chrome Green, Medium": "#6CA67C",
"Dark Chrome Green": "#01786F", "Chrome Green, Dark": "#01786F",
"Blue": "#4997D0",
"Prussian Blue": "#00468C",
"Cobalt Blue": "#8C90C8",
"Celestial Blue": "#7070CC",
"Ultramarine Blue": "#3F26BF",
"Purple": "#732E6C", "Violet": "#732E6C",
"Permanent Magenta": "#F653A6",
"Rose Pink": "#FFA6C9",
"Burnt Sienna": "#E97451",
"Van Dyke Brown": "#664228",
"Flesh Tint": "#FFCBA4",
"Burnt Umber": "#805533",
"Raw Umber": "#665233",
"Raw Sienna": "#E6BC5C",
"Gold": "#92926E",
"Silver": "#C9C0BB",
"Copper": "#DA8A67",
"Black": "#000000",
"Charcoal Gray": "#736A62",
"White": "#FFFFFF"
}); |
'use strict';
/*
* Purpose:
* Address missing capability in jasmine to not run any more tests after the first failure.
* https://github.com/jasmine/jasmine/issues/414
*
* Usage:
* const JasmineDisableRemaining = require('jasmine-disable-remaining');
* ... somewhere the `jasmine` global is now set:
* const jasmineDisableRemainingReporter = new JasmineDisableRemaining(jasmine, optionalConfigInit);
* jasmine.getEnv().addReporter(jasmineDisableRemainingReporter);
*/
const _ = require('lodash');
module.exports = () => {
const defaultSuitesMatcherConfig = {
callback: null,
// .disableSpecs is intended to be set dynamically, e.g.:
// it would normally be set to true in a file's beforeAll
// and set to false in the file's afterAll
// which would only run if there were no failures
disableSpecs: false,
disableSuites: {
beforeAllFns: true,
afterAllFns: true,
beforeFns: true,
afterFns: true
},
// copy the following for your message
// '\nSpecs have FAILED and specified that all specs in suites matching /YOUR-PATTERN-HERE/ should be disabled',
defaultMessage: [
'----------------------------------------------------------------------------------------------',
'\nSpecs have FAILED and specified that all specs in suites matching a pattern should be disabled',
'\n----------------------------------------------------------------------------------------------'
]
};
/*
* usage for each of the `all*` config properties:
* callback - called as: callback.call(this, this, result, spec)
* disableSpecs - set to true to disable specs on first spec failure
* disableSuites:
* beforeAllFns - set to true to disable all "beforeAllFns"
* afterAllFns - set to true to disable all "afterAllFns"
* beforeFns - set to true to disable all "beforeFns"
* afterFns - set to true to disable all "afterFns"
* message - can be a string or an array or undefined
*/
const defaultConfig = {
allSpecsByCLI: {
callback: null,
// allSpecsByCLI.disableSpecs should never be set programatically
// because it is intended to be set from the command line
disableSpecs: false,
disableSuites: {
beforeAllFns: true,
afterAllFns: true,
beforeFns: true,
afterFns: true
},
defaultMessage: [
'---------------------------------------------------------------------------------------------------',
'\nThis spec has FAILED. You specified on the command line that all remaining specs should be disabled',
'\n---------------------------------------------------------------------------------------------------'
]
},
allSpecsDynamic: {
callback: null,
// allSpecsDynamic.disableSpecs is intended to be set dynamically, e.g.:
// it would normally be set to true in a file's beforeAll
// and set to false in the file's afterAll
// which would only run if there were no failures
disableSpecs: false,
disableSuites: {
beforeAllFns: true,
afterAllFns: true,
beforeFns: true,
afterFns: true
},
defaultMessage: [
'-------------------------------------------------------------------------------------',
'\nThis spec has FAILED and it has specified that all remaining specs should be disabled',
'\n-------------------------------------------------------------------------------------'
]
},
allFileSpecsDynamic: {
callback: null,
// allSpecsDynamic.disableSpecs is intended to be set dynamically, e.g.:
// it would normally be set to true in a file's beforeAll
// and set to false in the file's afterAll
// which would only run if there were no failures
disableSpecs: false,
disableSuites: {
beforeAllFns: true,
afterAllFns: false,
beforeFns: true,
afterFns: false
},
defaultMessage: [
'--------------------------------------------------------------------------------------------------',
'\nThis spec has FAILED and it has specified that all remaining specs in this file should be disabled',
'\n--------------------------------------------------------------------------------------------------'
]
},
allMatchingSuites: [],
log: console.log
};
class JasmineDisableRemaining {
constructor(instanceJasmine, optionalConfigInit) {
// store our controls in a property that should not collide with standard reporter methods
this.jasmineDisableRemaining = _.merge(
{
jasmine: instanceJasmine,
config: defaultConfig,
data: {
specs: {}
},
addSuitesMatcher: (match, config) => addSuitesMatcher.call(this, match, config),
removeSuitesMatcher: (guid) => removeSuitesMatcher.call(this, guid)
},
{
config: optionalConfigInit
}
);
}
// standard jasmine reporter methods
/*
* Jasmine calls this method once all describes/its have been "initialized"
*/
jasmineStarted() {
traverseSuiteHierarchy.call(this, this.jasmineDisableRemaining.jasmine.getEnv().topSuite(), processSpec);
}
/*
* Called every time a spec is done
*/
specDone(result) {
// we only do something with failed specs
if (result.status !== 'failed') {
return;
}
const _this = this;
const jasmineDisableRemaining = this.jasmineDisableRemaining;
const config = jasmineDisableRemaining.config;
const data = jasmineDisableRemaining.data;
const topSuite = jasmineDisableRemaining.jasmine.getEnv().topSuite();
const spec = data.specs[result.id];
// count all failures per suite
everyParentSuite(spec.parentSuite, (suite) => {
if (!_.isObject(suite.result)) {
suite.result = {};
}
if (!_.isNumber(suite.result.totalSpecFailures)) {
suite.result.totalSpecFailures = 1;
} else {
++suite.result.totalSpecFailures;
}
});
let disableConfig;
let disableSuite;
// while you could set multiple of these "disablers", we return because the "alls" would disable all the others anyway
// disable "all"s
if (config.allSpecsByCLI.disableSpecs) {
disableConfig = config.allSpecsByCLI;
disableSuite = topSuite;
disableAllChildren.call(this, disableConfig, disableSuite);
logAfterDisable.call(this, config, disableConfig);
callbackAfterDisable.call(this, disableConfig);
return;
} else if (config.allSpecsDynamic.disableSpecs) {
disableConfig = config.allSpecsDynamic;
disableSuite = topSuite;
disableAllChildren.call(this, disableConfig, disableSuite);
logAfterDisable.call(this, config, disableConfig);
callbackAfterDisable.call(this, disableConfig);
return;
}
// disable "all in file"
if (config.allFileSpecsDynamic.disableSpecs) {
disableConfig = config.allFileSpecsDynamic;
disableSuite = findFileSuite(spec.parentSuite);
disableAllChildren.call(this, disableConfig, disableSuite);
logAfterDisable.call(this, config, disableConfig);
callbackAfterDisable.call(this, disableConfig);
}
// disable "all matching suites" found
this.jasmineDisableRemaining.config.allMatchingSuites.forEach((matcher) => {
let foundMatch = false;
traverseSuiteHierarchy.call(_this, _this.jasmineDisableRemaining.jasmine.getEnv().topSuite(), null, (suite) => {
// since we might have already disabled matchers, make sure they're objects
if (matcher && matcher.match && suite.description.match(matcher.match)) {
foundMatch = true;
disableAllChildren.call(_this, matcher.config, suite);
}
});
if (foundMatch) {
logAfterDisable.call(_this, config, matcher.config);
callbackAfterDisable.call(_this, matcher.config);
// since we never need to use this matcher again, remove it
// plus, disableSuite might cause it to not be called in afterAll
removeSuitesMatcher.call(_this, matcher.guid);
}
});
}
}
// private methods
/*
* Add a new matcher for disabling suites anywhere
* returns the GUID to remove the matcher
*/
function addSuitesMatcher(match, argConfig) {
const _this = this;
const config = _.merge(
{},
defaultSuitesMatcherConfig,
argConfig
);
// naive GUID assumes we're not called async
const matcher = {
config,
guid: _this.jasmineDisableRemaining.config.allMatchingSuites.length,
match
};
_this.jasmineDisableRemaining.config.allMatchingSuites.push(matcher);
return matcher.guid;
}
/*
*/
function callbackAfterDisable(disableConfig) {
const _this = this;
// callback
if (_.isFunction(disableConfig.callback)) {
disableConfig.callback.call(_this, _this, result, spec);
}
}
/*
* Recursively disable all child specs and suites, starting at `startSuite`
*/
function disableAllChildren(config, startSuite) {
const _this = this;
// disable
traverseSuiteHierarchy.call(
_this,
startSuite,
(suite, childSpec) => disableSpec(childSpec),
(suite) => disableSuite(config, suite)
);
}
/*
* Disable spec
*/
function disableSpec(spec) {
spec.disable();
}
/*
* Disable suite.
* Really just means turning off the before/after stuff
*/
function disableSuite(config, suite) {
if (config.disableSuites.beforeAllFns) {
suite.beforeAllFns = [];
}
if (config.disableSuites.afterAllFns) {
suite.afterAllFns = [];
}
if (config.disableSuites.beforeFns) {
suite.beforeFns = [];
}
if (config.disableSuites.afterFns) {
suite.afterFns = [];
}
}
/*
* Reverse traverse the hierarchy by following `parentSuite`s
* calling `callbackForSuites` for each suite inclusive
*/
function everyParentSuite(suite, callbackForSuites) {
const _this = this;
if (suite) {
callbackForSuites.call(_this, suite);
if (suite.parentSuite) {
return everyParentSuite(suite.parentSuite, callbackForSuites);
}
}
}
/*
* Reverse traverse the hierarchy by following `parentSuite`s
* Since `jasmine.getEnv().topSuite()` has an undefined `parentSuite`,
* the hierarchy should look like:
* jasmine.getEnv().topSuite()
* fileSuite
* spec
* fileSuite
* subSuite
* spec
* Plus, given that we will only be called form `specDone`,
* we should not have to worry about being called with anything higher than a "fileSuite"
*/
function findFileSuite(suite) {
if (suite && suite.parentSuite) {
if (suite.parentSuite.parentSuite) {
return findFileSuite(suite.parentSuite);
} else {
return suite;
}
}
}
/*
*/
function logAfterDisable(config, disableConfig) {
const _this = this;
// log
if (_.isString(disableConfig.message)) {
config.log(disableConfig.message);
} else if (_.isArray(disableConfig.message)) {
config.log.apply(_this, disableConfig.message);
} else if (_.isArray(disableConfig.defaultMessage)) {
config.log.apply(_this, disableConfig.defaultMessage);
} else if (_.isString(disableConfig.defaultMessage)) {
config.log(disableConfig.defaultMessage);
}
// callback
if (_.isFunction(disableConfig.callback)) {
config.callback.call(_this, _this, result, spec);
}
}
/*
* Add `suite` as new property `parentSuite` to `childSpec` and store the spec
*/
function processSpec(suite, childSpec) {
childSpec.parentSuite = suite;
this.jasmineDisableRemaining.data.specs[childSpec.id] = childSpec;
}
/*
* Remove a new matcher
* To avoid complex GUID generation, keep the array entry, but just null it out
*/
function removeSuitesMatcher(guid) {
this.jasmineDisableRemaining.config.allMatchingSuites[guid] = null;
}
/*
* Depth First traverse.
* Call `callbackForSpecs` for every spec
* Call `callbackForSuites` for every suite
*/
function traverseSuiteHierarchy(suite, callbackForSpecs, callbackForSuites) {
const _this = this;
if (_.isFunction(callbackForSuites)) {
if (callbackForSuites) {
callbackForSuites.call(_this, suite);
}
}
suite.children
.filter((child) => child instanceof _this.jasmineDisableRemaining.jasmine.Suite)
.forEach((childSuite) => traverseSuiteHierarchy.call(_this, childSuite, callbackForSpecs, callbackForSuites));
if (callbackForSpecs) {
suite.children
.filter((child) => child instanceof _this.jasmineDisableRemaining.jasmine.Spec)
.forEach((childSpec) => callbackForSpecs.call(_this, suite, childSpec));
}
}
return JasmineDisableRemaining;
}();
|
module.exports = function( grunt ) {
"use strict"
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
//watch and compile all files
watch: {
html: {
files: 'prod/*.html',
},
css: {
files: 'prod/assets/styles/*.css',
},
jd: {
files: ['dev/*.jade','dev/**/*.jade'],
tasks: ['jade:compile'],
},
styl: {
files: ['dev/assets/styles/*.styl','dev/assets/**/*.styl'],
tasks: ['stylus:compile'],
},
javascript: {
files: 'dev/assets/scripts/*.js',
tasks: ['uglify'],
},
options: {
livereload: true
}
},
// The jade compile task
jade: {
//compile for production
compile: {
files: {
"prod/index.html": ["dev/index.jade"]
}
}
},
//The stylus compile task
stylus: {
//compile for production
compile: {
files: {
'prod/assets/styles/style.min.css':'dev/assets/styles/style.styl' // 1:1 compile
}
}
},
//concat all JS
concat: {
dist: {
src: 'dev/assets/scripts/*.js',
dest: 'prod/assets/scripts/scripts.js'
}
},
//compress all js
uglify: {
my_target: {
files: {
'prod/assets/scripts/scripts.min.js': ['dev/assets/scripts/*.js']
}
}
},
//Starts the static server
connect: {
server: {
options: {
port: 9000,
base: "prod/",
hostname: "localhost",
livereload: true,
open: true
}
}
},
'ftp-deploy': {
ap: {
auth: {
host: 'ftp.buscacariocaweb.com',
port: 21,
authKey: 'key1'
},
src: 'prod/',
dest: 'public_html/buscacarioca/ap/project_folder'
},
build: {
auth: {
host: 'ftp.buscacariocaweb.com',
port: 21,
authKey: 'key1'
},
src: 'prod/',
dest: 'public_html/project_folder'
}
},
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-jade');
grunt.loadNpmTasks('grunt-contrib-stylus');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-ftp-deploy');
grunt.registerTask('dev', ['connect','watch']);
grunt.registerTask('ap', ['ftp-deploy:ap']);
grunt.registerTask('deploy', ['ftp-deploy:build']);
};
|
'use strict';
const electron = require('electron');
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
// Define global reference to the python server (which we'll start next).
let server;
function createWindow() {
// Start python server.
if (process.platform === 'win32') {
// Make sure the virtualenv is set up with Python 3!
server = require('child_process').spawn('python', ['-m', 'pynetworktables2js']);
} else {
// If on unix-like/other OSes, use bash command (python3 ./server.py).
server = require('child_process').spawn('python3', ['-m', 'pynetworktables2js']);
}
// Create the browser window.
mainWindow = new BrowserWindow({
width: 1366,
height: 535,
// 1366x570 is a good standard height, but you may want to change this to fit your DriverStation computer's screen better.
// It's best if the dashboard takes up as much space as possible without covering the DriverStation application.
// The window is closed until the python server is ready
show: false
});
// Move window to top (left) of screen.
mainWindow.setPosition(0, 0);
// Load window.
mainWindow.loadURL('http://localhost:8888');
// Once the python server is ready, load window contents.
mainWindow.once('ready-to-show', function () {
mainWindow.loadURL('http://localhost:8888');
mainWindow.once('ready-to-show', function () {
// Once it has reloaded, show the window
mainWindow.show();
});
});
// Remove menu
mainWindow.setMenu(null);
// Emitted when the window is closed.
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', createWindow);
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q.
// For FRCDB, though? Screw the standard.
// That standard sucks for this application.
// So we're going to kill the application regardless.
// If you want to restore the standard behavior, uncomment the next line.
// if (process.platform !== 'darwin')
app.quit();
});
app.on('quit', function () {
console.log('Application quit. Killing tornado server.');
// Kill tornado server child process.
server.kill('SIGINT');
});
app.on('activate', function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
|
/* generated from Designfiles Public by generate_data_designfles */
require ('wh.ui.popup');
/*! LOAD: wh.ui.popup !*/
(function($) { //mootools wrapper
/* title: Dialog title (embedded as <h1> )
text: Dialog text (embedded as <div class="dialogtext">, supports linefeeds)
html: Dialog raw html code (embedded as <div class="dialogtext">)
buttons: array of:
[ title: Button text (eg 'Login' or Locale.get('wh-common.buttons.yes'))
, onClick: Handler to invoke on click (has an opportunity to event.stop()! )
, cancel: If true, this is a cancel button. It will go through onCancel checks
, result: Result to return in getResult(). This also closes the dialog.
, href: Hyperlink to follow.
]
If a button's title is missing, but cancel is set, Locale.get('wh-common.buttons.cancel') is used
If cancel is unset, but result is set, Locale.get('wh-common.buttons.<reslt>') is used
Events:
onResult - invoked if a result is set on the clicked button, AFTER closing the dialog.
receives { target:this, result:'resultname' }
onResultxxx - like onResult, but fires if the result was 'Xxx' - eg onResultok fires if the button with {result:'ok'} was clicked
*/
$wh.Popup.Dialog = new Class(
{ Extends: $wh.BasicPopup
, options: { title: ''
, text: null
, html: null
, buttons: []
, destroy_on_hide: true
}
, _result: null
, initialize: function(options)
{
this.parent(null, options);
this.nodes.container.addClass("wh-popup-dialog");
this.nodes.container.addEvent("click:relay(button)", this.onButtonClick.bind(this));
this.nodes.body.adopt(new Element("h1", { text: this.options.title }));
// this.nodes.add
var contents = new Element("div", { "class":"dialogtext"}).inject(this.nodes.body);
if(this.options.html)
contents.set('html', this.options.html);
else if(this.options.text)
$wh.setTextWithLinefeeds(contents, this.options.text);
if(this.options.buttons.length)
{
if (!(this.options.buttons instanceof Array))
{
console.error("Buttons must be an array with strings.");
return;
}
var buttons = new Element("div", { "class":"dialogbuttons"}).inject(this.nodes.body);
Array.each(this.options.buttons, function(button)
{
var title = button.title;
if(!title && window.Locale && button.cancel)
title = Locale.get('wh-common.buttons.cancel');
if(!title && window.Locale && button.result)
title = Locale.get('wh-common.buttons.' + button.result);
var buttonsettings = { "text": title
, "type": "button"
};
if (button.cssclass && button.cssclass != "")
buttonsettings["class"] = button.cssclass;
var newbutton = new Element("button", buttonsettings);
if(button.onClick)
newbutton.addEvent("click", button.onClick);
newbutton.store('dialog-button', button);
buttons.adopt(newbutton);
});
}
}
, onButtonClick:function(event, button)
{
var buttoninfo = button.retrieve('dialog-button');
if(buttoninfo.cancel)
{
this._result = 'cancel';
this.cancel();
return;
}
this._result = null;
if(buttoninfo.href)
{
event.stop();
location.href = buttoninfo.href;
}
if(buttoninfo.result)
{
this._result = buttoninfo.result;
this.hide();
}
}
, getResult:function()
{
return this._result;
}
, show:function()
{
this._result = null;
this.parent();
}
, hide:function()
{
this.parent();
if(this._result)
{
var evtobj = { target:this, result: this._result };
this.fireEvent("result", evtobj);
this.fireEvent("result" + this._result, evtobj);
}
}
});
})(document.id); //end mootools wrapper
|
define(["require", "exports", '../../src/easelts/display/Stage', '../../src/easelts/display/Shape', '../../src/easelts/behavior/ButtonBehavior', '../../src/easelts/display/BitmapProjective'], function (require, exports, Stage_1, Shape_1, ButtonBehavior_1, BitmapProjective_1) {
"use strict";
var holder = document.getElementById('holder');
var stage = new Stage_1.default(holder, true);
stage.enableMouseOver(20);
var points = [
[100, 100],
[200 + Math.random() * 200, 100],
[100, 200 + Math.random() * 200],
[200 + Math.random() * 200, 200 + Math.random() * 200]
];
var image = new BitmapProjective_1.default('../assets/image/ninepatch_red.png', points, 0, 0, 0);
stage.addChild(image);
stage.start();
var buttonPoints = [];
for (var i = 0; i < 4; i++) {
var btn = new Shape_1.default();
btn.graphics.beginFill('#FF0').beginStroke('#000').drawRect(0, 0, 30, 30);
btn.addBehavior(new ButtonBehavior_1.default);
btn.addEventListener(Stage_1.default.EVENT_PRESS_MOVE, function (index, event) {
var x = event.rawX;
var y = event.rawY;
var lx = event.getLocalX();
var ly = event.getLocalY();
points[index][0] = x;
points[index][1] = y;
this.x = x;
this.y = y;
image.setPoints(points);
}.bind(btn, i));
btn.x = points[i][0];
btn.y = points[i][1];
buttonPoints.push(btn);
stage.addChild(btn);
}
});
|
{
expect(/character/i.test(error.message)).toEqual(true);
}
|
const bcrypt = require('bcrypt-nodejs');
module.exports = {
password: (user) => {
const salt = bcrypt.genSaltSync();
const hash = bcrypt.hashSync(user.password, salt);
return hash;
},
comparePassword: (password, hash, done) => {
bcrypt.compare(password, hash, (err, isMatch) => {
done(err, isMatch);
});
},
};
|
'use strict'
import React from 'react'
import ReactDOM from 'react-dom'
import Request from 'superagent'
module.exports = class VerbGallery extends React.Component {
constructor(props){
super(props)
this.state = {images: []}
}
componentDidMount(){
Request
.get('/database')
.end(function(err, res){
this.setState(
{images: JSON.parse(res.text)}
)
}.bind(this))
}
render (){
var verbPics = this.props.text
return (
<div className="verbGallery">
{this.state.images.map(function(image){
switch(image.category) {
case "verbs":
return (<img className= "indAskImg Black" src={image.filepath} onClick={this.props.onClick} />)
break;
}
}, this)}
</div>
)
}
}
|
var Utils = require('./utils');
var condition = function() {
this.list = [];
};
Utils.apply(condition.prototype, {
add: function(key, op, value) {
this.list.push({
key: key,
op: op,
value: value
});
},
equal: function(key, value) {
this.add(key, '=', value);
},
like: function(key, value) {
value = Util.format('%{0}%', value);
this.add(key, 'like', value);
},
leftLike: function(key, value) {
value = Util.format('%{0}', value);
this.add(key, 'like', value);
},
rightLike: function(key, value) {
value = Util.format('{0}%', value);
this.add(key, 'like', value);
},
in : function() {
this.add(key, 'in', value);
},
between: function(key, value) {
// this.add(key, 'between', [value[0], 'and', value[1]]);
}
}); |
const xxSmall = '5px';
const xSmall = '10px';
const small = '20px';
const medium = '30px';
const large = '40px';
const xLarge = '50px';
const xxLarge = '100px';
export default function (type) {
switch (type) {
case 'margin-left-xx-small':
return `
margin-left: ${xxSmall};
`;
}
}
|
/**
* Menu class
*
* Vertical ordered list of buttons
*/
function Menu(x, y, buttons) {
Menu._super.constructor.call(this, x, y);
this.set("constructorName", "Menu");
this.buttons = buttons;
var offset = 0;
var maxWidth = 0;
this.buttons.forEach(function (button) {
button.setPosition(x, y + offset);
offset += button.height + 1;
if (button.width > maxWidth) {
maxWidth = button.width;
}
});
this.width = maxWidth;
this.height = offset;
this.setDrawingContext();
}
utils.inherits(Menu, Entity);
/**
* Draw menu entity
*/
Menu.prototype.draw = function () {
Menu._super.draw.call(this);
this.buttons.forEach(function (button) {
button.draw();
});
};
|
function ResourceStation(name, State, min, max) {
var station = this;
var eventCards = [];
var baseMinOut = min;
var baseMaxOut = max;
this.name = name;
this.MaxCrew = 5;
this.MetaData = {
get CrewCount() {
return State.player.Crew.StationCounts[station.name];
},
get MinGen() {
return station.calculatedMin();
},
get MaxGen() {
return station.calculatedMax();
}
};
this.initGUI = function(Stage) {
var Module = State.GUI.addGUIModule(this.name);
var TitleEle = Module.addGUIElement("Title", new PIXI.Text(this.name, {font:"21px Share Tech Mono", fill: "white"}));
TitleEle.anchor.x = TitleEle.anchor.y = 0.5;
var YRow = 20;
var MaxCrewLabel = Module.addGUIElement("MaxCrewLabel", new PIXI.Text("Max Crew", {font:"16px Share Tech Mono", fill: "white"}));
MaxCrewLabel.anchor.x = 0.5;
MaxCrewLabel.anchor.y = 0.5;
MaxCrewLabel.position.y = YRow;
YRow += 20;
var MaxCrew = Module.addTextElement("MaxCrew", new PIXI.Text(this.MaxCrew, {font:"16px Share Tech Mono", fill: "white"}), this, "MaxCrew");
MaxCrew.anchor.x = 0.5;
MaxCrew.anchor.y = 0.5;
MaxCrew.position.y = YRow;
YRow += 20;
var GenerationLabel = Module.addGUIElement("GenerationLabel", new PIXI.Text("Generation", {font:"16px Share Tech Mono", fill: "white"}));
GenerationLabel.anchor.x = 0.5;
GenerationLabel.anchor.y = 0.5;
GenerationLabel.position.y = YRow;
YRow += 20;
var GenDash = Module.addGUIElement("GenDash", new PIXI.Text("-", {font:"16px Share Tech Mono", fill: "white"}));
GenDash.anchor.x = 0.5;
GenDash.anchor.y = 0.5;
GenDash.position.y = YRow;
var GenMin = Module.addTextElement("GenMin", new PIXI.Text(this.MetaData.MinGen, {font:"16px Share Tech Mono", fill: "white"}), this.MetaData, "MinGen");
GenMin.anchor.x = 0.5;
GenMin.anchor.y = 0.5;
GenMin.position.y = YRow;
GenMin.position.x = -20;
var GenMax = Module.addTextElement("GenMax", new PIXI.Text(this.MetaData.MaxGen, {font:"16px Share Tech Mono", fill: "white"}), this.MetaData, "MaxGen");
GenMax.anchor.x = 0.5;
GenMax.anchor.y = 0.5;
GenMax.position.y = YRow;
GenMax.position.x = 20;
YRow += 20;
var CrewCount = Module.addTextElement("Count", new PIXI.Text(this.MetaData.CrewCount, {font:"16px Share Tech Mono", fill: "white"}), this.MetaData, "CrewCount");
CrewCount.anchor.x = CrewCount.anchor.y = 0.5;
CrewCount.position.y = YRow;
var Plus = Module.addGUIElement("Plus", PIXI.Sprite.fromImage('assets/plus.png'));
Plus.anchor.x = Plus.anchor.y = 0.5;
Plus.scale = new PIXI.Point(0.75,0.75);
Plus.position.x = 50;
Plus.position.y = YRow;
Plus.defaultCursor = "url('assets/cursor_hand.png'), pointer";
Plus.interactive = true;
Plus.buttonMode = true;
var Minus = Module.addGUIElement("Minus", PIXI.Sprite.fromImage('assets/minus.png'));
Minus.anchor.x = Minus.anchor.y = 0.5;
Minus.scale = new PIXI.Point(0.75,0.75);
Minus.position.x = -50;
Minus.position.y = YRow;
Minus.defaultCursor = "url('assets/cursor_hand.png'), pointer";
Minus.interactive = true;
Minus.buttonMode = true;
Stage.addChild(Module.LocalStage);
};
this.calculatedMin = function() {
var minOut = baseMinOut;
var crewCount = State.Crew.StationCounts[this.name];
minOut += Math.ceil((crewCount+2) / 2);
if(crewCount === 0)
minOut = baseMinOut;
eventCards.forEach(function(eventCard) {
if(eventCard.mod_type == "MIN")
minOut -= eventCard.value;
});
return minOut;
};
this.calculatedMax = function() {
var maxOut = baseMaxOut;
var crewCount = State.Crew.StationCounts[this.name];
maxOut += Math.ceil((crewCount+3) / 2);
if(crewCount === 0)
maxOut = baseMaxOut;
eventCards.forEach(function(eventCard) {
if(eventCard.mod_type == "MAX")
maxOut -= eventCard.value;
});
return maxOut;
};
this.doTurn = function() {
var minOut = this.calculatedMin();
var maxOut = this.calculatedMax();
var result = Math.floor((Math.random() * (maxOut - minOut + 1) + minOut) );
eventCards.forEach(function(eventCard) {
eventCard.duration--;
});
eventCards = _.reject(eventCards, function(eventCard) {
return eventCard.duration === 0;
});
return result;
};
this.increaseCrew = function(event) {
if(this.MetaData.CrewCount < this.MaxCrew)
State.player.Crew.assignCrew(this.name, event);
};
this.descreaseCrew = function() {
};
return this;
}
|
/**
* @author mrdoob / http://mrdoob.com/
* @author Mugen87 / https://github.com/Mugen87
*/
import { Geometry } from '../core/Geometry';
import { BufferGeometry } from '../core/BufferGeometry';
import { Float32BufferAttribute } from '../core/BufferAttribute';
import { Vector3 } from '../math/Vector3';
// BoxGeometry
function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
Geometry.call( this );
this.type = 'BoxGeometry';
this.parameters = {
width: width,
height: height,
depth: depth,
widthSegments: widthSegments,
heightSegments: heightSegments,
depthSegments: depthSegments
};
this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
this.mergeVertices();
}
BoxGeometry.prototype = Object.create( Geometry.prototype );
BoxGeometry.prototype.constructor = BoxGeometry;
// BoxBufferGeometry
function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
BufferGeometry.call( this );
this.type = 'BoxBufferGeometry';
this.parameters = {
width: width,
height: height,
depth: depth,
widthSegments: widthSegments,
heightSegments: heightSegments,
depthSegments: depthSegments
};
var scope = this;
// segments
widthSegments = Math.floor( widthSegments ) || 1;
heightSegments = Math.floor( heightSegments ) || 1;
depthSegments = Math.floor( depthSegments ) || 1;
// buffers
var indices = [];
var vertices = [];
var normals = [];
var uvs = [];
// helper variables
var numberOfVertices = 0;
var groupStart = 0;
// build each side of the box geometry
buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
// build geometry
this.setIndex( indices );
this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
var segmentWidth = width / gridX;
var segmentHeight = height / gridY;
var widthHalf = width / 2;
var heightHalf = height / 2;
var depthHalf = depth / 2;
var gridX1 = gridX + 1;
var gridY1 = gridY + 1;
var vertexCounter = 0;
var groupCount = 0;
var ix, iy;
var vector = new Vector3();
// generate vertices, normals and uvs
for ( iy = 0; iy < gridY1; iy ++ ) {
var y = iy * segmentHeight - heightHalf;
for ( ix = 0; ix < gridX1; ix ++ ) {
var x = ix * segmentWidth - widthHalf;
// set values to correct vector component
vector[ u ] = x * udir;
vector[ v ] = y * vdir;
vector[ w ] = depthHalf;
// now apply vector to vertex buffer
vertices.push( vector.x, vector.y, vector.z );
// set values to correct vector component
vector[ u ] = 0;
vector[ v ] = 0;
vector[ w ] = depth > 0 ? 1 : - 1;
// now apply vector to normal buffer
normals.push( vector.x, vector.y, vector.z );
// uvs
uvs.push( ix / gridX );
uvs.push( 1 - ( iy / gridY ) );
// counters
vertexCounter += 1;
}
}
// indices
// 1. you need three indices to draw a single face
// 2. a single segment consists of two faces
// 3. so we need to generate six (2*3) indices per segment
for ( iy = 0; iy < gridY; iy ++ ) {
for ( ix = 0; ix < gridX; ix ++ ) {
var a = numberOfVertices + ix + gridX1 * iy;
var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
// faces
indices.push( a, b, d );
indices.push( b, c, d );
// increase counter
groupCount += 6;
}
}
// add a group to the geometry. this will ensure multi material support
scope.addGroup( groupStart, groupCount, materialIndex );
// calculate new start value for groups
groupStart += groupCount;
// update total number of vertices
numberOfVertices += vertexCounter;
}
}
BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
export { BoxGeometry, BoxBufferGeometry };
|
import { from } from 'most'
import { NodeDescriptor } from './node'
import { createNodeDescriptors } from './node-helpers'
import { isObservable } from './kind'
export function createElementNode (scope, args) {
const { document, parentNamespaceUri } = scope
const {
nodeName,
nsUri,
name,
attrs = {},
nsAttrs = [],
props = {},
children = []
} = args
const namespaceUri = getNamespaceUri(scope, nsUri)
const domNode = document.createElementNS(namespaceUri, name)
const childScope = namespaceUri === parentNamespaceUri
? scope
: Object.assign({}, scope, { parentNamespaceUri: namespaceUri })
processAttributes(childScope, domNode, attrs)
processNamespacedAttributes(childScope, domNode, nsAttrs)
processProperties(childScope, domNode, props)
const childDescriptors = createNodeDescriptors(childScope, children)
if (childDescriptors.length > 0) {
const fragment = document.createDocumentFragment()
childDescriptors.forEach(descriptor => descriptor.insert(fragment))
domNode.appendChild(fragment)
}
return new ElementNodeDescriptor(nodeName, domNode, childDescriptors)
}
export function createTextNode (scope, str) {
return new TextNodeDescriptor(scope.document.createTextNode(str))
}
function processAttributes (scope, domNode, attributes) {
for (let name in attributes) {
// WORKAROUND:
// JSX spread attributes with namespace names are not yet supported.
// We cannot detect whether an property was specified via spread properties,
// so we detect and warn on embedded colon characters as a compromise.
if (/:/.test(name)) {
console.warn(
`\`attrs\` and JSX spread attributes which are added to \`attrs\` ` +
`may not include attributes prefixed with namespace names. ` +
`Ignoring '${name}'.`
)
} else {
handleAttribute(scope, domNode, name, attributes[name])
}
}
}
function processNamespacedAttributes (scope, domNode, namespacedAttributes) {
namespacedAttributes.forEach(a => handleAttribute(
scope, domNode, a.name, a.value, a.nsUri
))
}
function handleAttribute (scope, elementNode, name, valueOrStream, nsUri) {
const namespaceUri = getNamespaceUri(scope, nsUri)
// Avoid specifying the same namespace as the current element because
// IE 11 and earlier do not always process it the same as when specifying
// no namespace.
// For example, an `<input>` with namespace URI http://www.w3.org/1999/xhtml
// only correctly takes a `type` attribute when specified with no namespace.
// If the `type` attribute is set using namespace URI http://www.w3.org/1999/xhtml,
// the effective `<input> type` is unchanged.
const attributeNamespaceUri = namespaceUri === scope.parentNamespaceUri
? null
: namespaceUri
if (isObservable(valueOrStream)) {
const stream = valueOrStream
setWithObservable(scope, stream, value => {
setAttribute(elementNode, attributeNamespaceUri, name, value)
})
} else {
const value = valueOrStream
setAttribute(elementNode, attributeNamespaceUri, name, value)
}
}
function setAttribute (elementNode, namespaceUri, name, value) {
if (value === true || value === false) {
setBooleanAttribute(elementNode, namespaceUri, name, value)
} else if (namespaceUri) {
elementNode.setAttributeNS(namespaceUri, name, value)
} else {
elementNode.setAttribute(name, value)
}
}
function setBooleanAttribute (elementNode, namespaceUri, name, value) {
value
? namespaceUri
? elementNode.setAttributeNS(namespaceUri, name, ``)
: elementNode.setAttribute(name, ``)
: namespaceUri
? elementNode.removeAttributeNS(namespaceUri, name)
: elementNode.removeAttribute(name)
}
function getNamespaceUri (scope, nsUri) {
return nsUri || scope.parentNamespaceUri
}
function processProperties (scope, domNode, properties) {
for (let name in properties) {
handleProperty(scope, domNode, name, properties[name])
}
}
function handleProperty (scope, elementNode, name, value) {
isObservable(value)
? setWithObservable(scope, value, value => setProperty(elementNode, name, value))
: setProperty(elementNode, name, value)
}
function setProperty (elementNode, name, value) {
elementNode[name] = value
}
function setWithObservable (scope, valueObservable, setter) {
from(valueObservable).skipRepeats().until(scope.destroy$).observe(setter)
}
/**
* Abstract class for a DOM node descriptor.
*/
export class DomNodeDescriptor extends NodeDescriptor {
/**
* Create a DOM node descriptor.
* @param {string|null} name - The node name
* @param {NodeDescriptor[]|null} childDescriptors - The node's child descriptors
* @param {Node} domNode - The DOM node.
*/
constructor (name, domNode) {
super(name)
/**
* The DOM node.
* @type {Node}
*/
this.domNode = domNode
}
extractContents () {
return this.domNode
}
deleteContents () {
const { domNode } = this
domNode.parentNode.removeChild(domNode)
}
getBeforeNode () {
return this.domNode
}
getNextSiblingNode () {
return this.domNode.nextSibling
}
}
/**
* A descriptor for a DOM element.
*/
export class ElementNodeDescriptor extends DomNodeDescriptor {
get type () { return `element` }
constructor (name, domNode, childDescriptors) {
super(name, domNode)
/**
* The node's child descriptors
* @type {NodeDescriptor[]|null}
*/
this.childDescriptors = childDescriptors
}
get expose () {
return this.domNode
}
}
/**
* A descriptor for a DOM text node.
*/
export class TextNodeDescriptor extends DomNodeDescriptor {
get type () { return `text` }
constructor (textNode) {
super(undefined, textNode)
}
}
|
/*!
* Author : Matteo Bruni - https://www.matteobruni.it
* MIT license: https://opensource.org/licenses/MIT
* Demo / Generator : https://particles.matteobruni.it/
* GitHub : https://www.github.com/matteobruni/tsparticles
* How to use? : Check the GitHub README
* v1.17.3
*/
(function(e, a) { for(var i in a) e[i] = a[i]; }(window, /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 4);
/******/ })
/************************************************************************/
/******/ ({
/***/ 4:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, "MoveDirection", function() { return /* reexport */ MoveDirection; });
__webpack_require__.d(__webpack_exports__, "RotateDirection", function() { return /* reexport */ RotateDirection; });
__webpack_require__.d(__webpack_exports__, "ClickMode", function() { return /* reexport */ ClickMode; });
__webpack_require__.d(__webpack_exports__, "DivMode", function() { return /* reexport */ DivMode; });
__webpack_require__.d(__webpack_exports__, "HoverMode", function() { return /* reexport */ HoverMode; });
__webpack_require__.d(__webpack_exports__, "CollisionMode", function() { return /* reexport */ CollisionMode; });
__webpack_require__.d(__webpack_exports__, "OutMode", function() { return /* reexport */ OutMode; });
__webpack_require__.d(__webpack_exports__, "SizeMode", function() { return /* reexport */ SizeMode; });
__webpack_require__.d(__webpack_exports__, "SizeAnimationStatus", function() { return /* reexport */ SizeAnimationStatus; });
__webpack_require__.d(__webpack_exports__, "OpacityAnimationStatus", function() { return /* reexport */ OpacityAnimationStatus; });
__webpack_require__.d(__webpack_exports__, "DestroyType", function() { return /* reexport */ DestroyType; });
__webpack_require__.d(__webpack_exports__, "ProcessBubbleType", function() { return /* reexport */ ProcessBubbleType; });
__webpack_require__.d(__webpack_exports__, "ShapeType", function() { return /* reexport */ ShapeType; });
__webpack_require__.d(__webpack_exports__, "StartValueType", function() { return /* reexport */ StartValueType; });
__webpack_require__.d(__webpack_exports__, "DivType", function() { return /* reexport */ DivType; });
__webpack_require__.d(__webpack_exports__, "InteractivityDetect", function() { return /* reexport */ InteractivityDetect; });
__webpack_require__.d(__webpack_exports__, "particlesJS", function() { return /* binding */ particlesJS; });
__webpack_require__.d(__webpack_exports__, "pJSDom", function() { return /* binding */ pJSDom; });
__webpack_require__.d(__webpack_exports__, "tsParticles", function() { return /* binding */ tsParticles; });
// CONCATENATED MODULE: ./dist/pjs.js
const initPjs = main => {
const particlesJS = (tagId, options) => {
return main.load(tagId, options);
};
particlesJS.load = (tagId, pathConfigJson, callback) => {
main.loadJSON(tagId, pathConfigJson).then(container => {
if (container) {
callback(container);
}
});
};
particlesJS.setOnClickHandler = callback => {
main.setOnClickHandler(callback);
};
const pJSDom = main.dom();
return {
particlesJS,
pJSDom
};
};
// CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.js
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* 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 __());
}
var __assign = function() {
__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;
}
return __assign.apply(this, arguments);
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(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;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
var __createBinding = Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
function __exportStar(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
var __setModuleDefault = Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
}
// CONCATENATED MODULE: ./dist/ShapeDrawers/SquareDrawer.js
class SquareDrawer {
draw(context, particle, radius) {
context.rect(-radius, -radius, radius * 2, radius * 2);
}
}
// CONCATENATED MODULE: ./dist/Enums/Directions/MoveDirection.js
var MoveDirection;
(function (MoveDirection) {
MoveDirection["bottom"] = "bottom";
MoveDirection["bottomLeft"] = "bottom-left";
MoveDirection["bottomRight"] = "bottom-right";
MoveDirection["left"] = "left";
MoveDirection["none"] = "none";
MoveDirection["right"] = "right";
MoveDirection["top"] = "top";
MoveDirection["topLeft"] = "top-left";
MoveDirection["topRight"] = "top-right";
})(MoveDirection || (MoveDirection = {}));
// CONCATENATED MODULE: ./dist/Utils/Utils.js
class Utils_Utils {
static isSsr() {
return typeof window === "undefined" || !window;
}
static get animate() {
return this.isSsr() ? callback => setTimeout(callback) : callback => (window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || window.setTimeout)(callback);
}
static get cancelAnimation() {
return this.isSsr() ? handle => clearTimeout(handle) : handle => (window.cancelAnimationFrame || window.webkitCancelRequestAnimationFrame || window.mozCancelRequestAnimationFrame || window.oCancelRequestAnimationFrame || window.msCancelRequestAnimationFrame || window.clearTimeout)(handle);
}
static clamp(num, min, max) {
return Math.min(Math.max(num, min), max);
}
static isInArray(value, array) {
return value === array || array instanceof Array && array.indexOf(value) > -1;
}
static mix(comp1, comp2, weight1, weight2) {
return Math.floor((comp1 * weight1 + comp2 * weight2) / (weight1 + weight2));
}
static getParticleBaseVelocity(particle) {
let velocityBase;
switch (particle.direction) {
case MoveDirection.top:
velocityBase = {
x: 0,
y: -1
};
break;
case MoveDirection.topRight:
velocityBase = {
x: 0.5,
y: -0.5
};
break;
case MoveDirection.right:
velocityBase = {
x: 1,
y: -0
};
break;
case MoveDirection.bottomRight:
velocityBase = {
x: 0.5,
y: 0.5
};
break;
case MoveDirection.bottom:
velocityBase = {
x: 0,
y: 1
};
break;
case MoveDirection.bottomLeft:
velocityBase = {
x: -0.5,
y: 1
};
break;
case MoveDirection.left:
velocityBase = {
x: -1,
y: 0
};
break;
case MoveDirection.topLeft:
velocityBase = {
x: -0.5,
y: -0.5
};
break;
default:
velocityBase = {
x: 0,
y: 0
};
break;
}
return velocityBase;
}
static getDistances(pointA, pointB) {
const dx = pointA.x - pointB.x;
const dy = pointA.y - pointB.y;
return {
dx: dx,
dy: dy,
distance: Math.sqrt(dx * dx + dy * dy)
};
}
static getDistance(pointA, pointB) {
return this.getDistances(pointA, pointB).distance;
}
static loadFont(character) {
return __awaiter(this, void 0, void 0, function* () {
try {
yield document.fonts.load(`${character.weight} 36px '${character.font}'`);
} catch (_a) {}
});
}
static arrayRandomIndex(array) {
return Math.floor(Math.random() * array.length);
}
static itemFromArray(array, index) {
return array[index !== null && index !== void 0 ? index : this.arrayRandomIndex(array)];
}
static randomInRange(r1, r2) {
const max = Math.max(r1, r2),
min = Math.min(r1, r2);
return Math.random() * (max - min) + min;
}
static isPointInside(point, size, radius) {
return this.areBoundsInside(this.calculateBounds(point, radius !== null && radius !== void 0 ? radius : 0), size);
}
static areBoundsInside(bounds, size) {
return bounds.left < size.width && bounds.right > 0 && bounds.top < size.height && bounds.bottom > 0;
}
static calculateBounds(point, radius) {
return {
bottom: point.y + radius,
left: point.x - radius,
right: point.x + radius,
top: point.y - radius
};
}
static loadImage(source) {
return new Promise((resolve, reject) => {
if (!source) {
reject("Error tsParticles - No image.src");
return;
}
const image = {
source: source,
type: source.substr(source.length - 3)
};
const img = new Image();
img.addEventListener("load", () => {
image.element = img;
resolve(image);
});
img.addEventListener("error", () => {
reject(`Error tsParticles - loading image: ${source}`);
});
img.src = source;
});
}
static downloadSvgImage(source) {
return __awaiter(this, void 0, void 0, function* () {
if (!source) {
throw new Error("Error tsParticles - No image.src");
}
const image = {
source: source,
type: source.substr(source.length - 3)
};
if (image.type !== "svg") {
return this.loadImage(source);
}
const response = yield fetch(image.source);
if (!response.ok) {
throw new Error("Error tsParticles - Image not found");
}
image.svgData = yield response.text();
return image;
});
}
static deepExtend(destination, ...sources) {
for (const source of sources.filter(s => s !== undefined && s !== null)) {
if (typeof source !== "object") {
destination = source;
continue;
}
const sourceIsArray = Array.isArray(source);
if (sourceIsArray && (typeof destination !== "object" || !destination || !Array.isArray(destination))) {
destination = [];
} else if (!sourceIsArray && (typeof destination !== "object" || !destination || Array.isArray(destination))) {
destination = {};
}
for (const key in source) {
if (key === "__proto__") {
continue;
}
const value = source[key];
const isObject = typeof value === "object";
destination[key] = isObject && Array.isArray(value) ? value.map(v => this.deepExtend(destination[key], v)) : this.deepExtend(destination[key], value);
}
}
return destination;
}
static isDivModeEnabled(mode, divs) {
return divs instanceof Array ? !!divs.find(t => t.enable && Utils_Utils.isInArray(mode, t.mode)) : Utils_Utils.isInArray(mode, divs.mode);
}
static divModeExecute(mode, divs, callback) {
if (divs instanceof Array) {
for (const div of divs) {
const divMode = div.mode;
const divEnabled = div.enable;
if (divEnabled && Utils_Utils.isInArray(mode, divMode)) {
this.singleDivModeExecute(div, callback);
}
}
} else {
const divMode = divs.mode;
const divEnabled = divs.enable;
if (divEnabled && Utils_Utils.isInArray(mode, divMode)) {
this.singleDivModeExecute(divs, callback);
}
}
}
static singleDivModeExecute(div, callback) {
const ids = div.ids;
if (ids instanceof Array) {
for (const id of ids) {
callback(id, div);
}
} else {
callback(ids, div);
}
}
static divMode(divs, divId) {
if (!divId || !divs) {
return;
}
if (divs instanceof Array) {
return divs.find(d => Utils_Utils.isInArray(divId, d.ids));
} else if (Utils_Utils.isInArray(divId, divs.ids)) {
return divs;
}
}
}
// CONCATENATED MODULE: ./dist/Enums/Types/ShapeType.js
var ShapeType;
(function (ShapeType) {
ShapeType["char"] = "char";
ShapeType["character"] = "character";
ShapeType["circle"] = "circle";
ShapeType["edge"] = "edge";
ShapeType["image"] = "image";
ShapeType["images"] = "images";
ShapeType["line"] = "line";
ShapeType["polygon"] = "polygon";
ShapeType["square"] = "square";
ShapeType["star"] = "star";
ShapeType["triangle"] = "triangle";
})(ShapeType || (ShapeType = {}));
// CONCATENATED MODULE: ./dist/ShapeDrawers/TextDrawer.js
class TextDrawer_TextDrawer {
init(container) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const options = container.options;
if (Utils_Utils.isInArray(ShapeType.char, options.particles.shape.type) || Utils_Utils.isInArray(ShapeType.character, options.particles.shape.type)) {
const shapeOptions = (_a = options.particles.shape.options[ShapeType.character]) !== null && _a !== void 0 ? _a : options.particles.shape.options[ShapeType.char];
if (shapeOptions instanceof Array) {
for (const character of shapeOptions) {
yield Utils_Utils.loadFont(character);
}
} else {
if (shapeOptions !== undefined) {
yield Utils_Utils.loadFont(shapeOptions);
}
}
}
});
}
draw(context, particle, radius) {
const character = particle.shapeData;
if (character === undefined) {
return;
}
const textData = character.value;
if (textData === undefined) {
return;
}
const textParticle = particle;
if (textParticle.text === undefined) {
textParticle.text = textData instanceof Array ? Utils_Utils.itemFromArray(textData, particle.randomIndexData) : textData;
}
const text = textParticle.text;
const style = character.style;
const weight = character.weight;
const size = Math.round(radius) * 2;
const font = character.font;
const fill = particle.fill;
const offsetX = text.length * radius / 2;
context.font = `${style} ${weight} ${size}px "${font}"`;
const pos = {
x: -offsetX,
y: radius / 2
};
if (fill) {
context.fillText(text, pos.x, pos.y);
} else {
context.strokeText(text, pos.x, pos.y);
}
}
}
// CONCATENATED MODULE: ./dist/ShapeDrawers/ImageDrawer.js
class ImageDrawer_ImageDrawer {
constructor() {
this.images = [];
}
getImages(container) {
const containerImages = this.images.filter(t => t.id === container.id);
if (!containerImages.length) {
this.images.push({
id: container.id,
images: []
});
return this.getImages(container);
} else {
return containerImages[0];
}
}
addImage(container, image) {
const containerImages = this.getImages(container);
containerImages === null || containerImages === void 0 ? void 0 : containerImages.images.push(image);
}
init(container) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const options = container.options;
const shapeOptions = options.particles.shape;
if (!Utils_Utils.isInArray(ShapeType.image, shapeOptions.type) && !Utils_Utils.isInArray(ShapeType.images, shapeOptions.type)) {
return;
}
const imageOptions = (_a = shapeOptions.options[ShapeType.images]) !== null && _a !== void 0 ? _a : shapeOptions.options[ShapeType.image];
if (imageOptions instanceof Array) {
for (const optionsImage of imageOptions) {
yield this.loadImageShape(container, optionsImage);
}
} else {
yield this.loadImageShape(container, imageOptions);
}
});
}
destroy() {
this.images = [];
}
loadImageShape(container, imageShape) {
return __awaiter(this, void 0, void 0, function* () {
try {
const image = imageShape.replaceColor ? yield Utils_Utils.downloadSvgImage(imageShape.src) : yield Utils_Utils.loadImage(imageShape.src);
this.addImage(container, image);
} catch (_a) {
console.warn(`tsParticles error - ${imageShape.src} not found`);
}
});
}
draw(context, particle, radius, opacity) {
var _a, _b;
if (!context) {
return;
}
const image = particle.image;
const element = (_a = image === null || image === void 0 ? void 0 : image.data) === null || _a === void 0 ? void 0 : _a.element;
if (!element) {
return;
}
const ratio = (_b = image === null || image === void 0 ? void 0 : image.ratio) !== null && _b !== void 0 ? _b : 1;
const pos = {
x: -radius,
y: -radius
};
if (!(image === null || image === void 0 ? void 0 : image.data.svgData) || !(image === null || image === void 0 ? void 0 : image.replaceColor)) {
context.globalAlpha = opacity;
}
context.drawImage(element, pos.x, pos.y, radius * 2, radius * 2 / ratio);
if (!(image === null || image === void 0 ? void 0 : image.data.svgData) || !(image === null || image === void 0 ? void 0 : image.replaceColor)) {
context.globalAlpha = 1;
}
}
}
// CONCATENATED MODULE: ./dist/Utils/Plugins.js
class Plugins {
static getPlugin(plugin) {
return Plugins.plugins.filter(t => t.id === plugin)[0];
}
static addPlugin(plugin) {
if (!Plugins.getPlugin(plugin.id)) {
Plugins.plugins.push(plugin);
}
}
static getAvailablePlugins(container) {
const res = new Map();
const availablePlugins = Plugins.plugins.filter(t => t.needsPlugin(container.options));
for (const plugin of availablePlugins) {
res.set(plugin.id, plugin.getPlugin(container));
}
return res;
}
static loadOptions(options, sourceOptions) {
for (const plugin of Plugins.plugins) {
plugin.loadOptions(options, sourceOptions);
}
}
static getPreset(preset) {
return Plugins.presets.get(preset);
}
static addPreset(presetKey, options) {
if (!Plugins.getPreset(presetKey)) {
Plugins.presets.set(presetKey, options);
}
}
static addShapeDrawer(type, drawer) {
if (!Plugins.getShapeDrawer(type)) {
Plugins.drawers.set(type, drawer);
}
}
static getShapeDrawer(type) {
return Plugins.drawers.get(type);
}
static getSupportedShapes() {
return Plugins.drawers.keys();
}
}
Plugins.plugins = [];
Plugins.presets = new Map();
Plugins.drawers = new Map();
// CONCATENATED MODULE: ./dist/ShapeDrawers/LineDrawer.js
class LineDrawer {
draw(context, particle, radius) {
context.moveTo(0, -radius / 2);
context.lineTo(0, radius / 2);
}
}
// CONCATENATED MODULE: ./dist/ShapeDrawers/CircleDrawer.js
class CircleDrawer {
draw(context, particle, radius) {
context.arc(0, 0, radius, 0, Math.PI * 2, false);
}
}
// CONCATENATED MODULE: ./dist/ShapeDrawers/PolygonDrawerBase.js
class PolygonDrawerBase {
draw(context, particle, radius) {
const start = this.getCenter(particle, radius);
const side = this.getSidesData(particle, radius);
const sideCount = side.count.numerator * side.count.denominator;
const decimalSides = side.count.numerator / side.count.denominator;
const interiorAngleDegrees = 180 * (decimalSides - 2) / decimalSides;
const interiorAngle = Math.PI - Math.PI * interiorAngleDegrees / 180;
if (!context) {
return;
}
context.beginPath();
context.translate(start.x, start.y);
context.moveTo(0, 0);
for (let i = 0; i < sideCount; i++) {
context.lineTo(side.length, 0);
context.translate(side.length, 0);
context.rotate(interiorAngle);
}
}
}
// CONCATENATED MODULE: ./dist/ShapeDrawers/TriangleDrawer.js
class TriangleDrawer_TriangleDrawer extends PolygonDrawerBase {
getSidesData(particle, radius) {
return {
count: {
denominator: 2,
numerator: 3
},
length: radius * 2
};
}
getCenter(particle, radius) {
return {
x: -radius,
y: radius / 1.66
};
}
}
// CONCATENATED MODULE: ./dist/ShapeDrawers/StarDrawer.js
class StarDrawer {
draw(context, particle, radius) {
var _a, _b, _c;
const star = particle.shapeData;
const sides = (_b = (_a = star === null || star === void 0 ? void 0 : star.sides) !== null && _a !== void 0 ? _a : star === null || star === void 0 ? void 0 : star.nb_sides) !== null && _b !== void 0 ? _b : 5;
const inset = (_c = star === null || star === void 0 ? void 0 : star.inset) !== null && _c !== void 0 ? _c : 2;
context.moveTo(0, 0 - radius);
for (let i = 0; i < sides; i++) {
context.rotate(Math.PI / sides);
context.lineTo(0, 0 - radius * inset);
context.rotate(Math.PI / sides);
context.lineTo(0, 0 - radius);
}
}
}
// CONCATENATED MODULE: ./dist/ShapeDrawers/PolygonDrawer.js
class PolygonDrawer_PolygonDrawer extends PolygonDrawerBase {
getSidesData(particle, radius) {
var _a, _b;
const polygon = particle.shapeData;
const sides = (_b = (_a = polygon === null || polygon === void 0 ? void 0 : polygon.sides) !== null && _a !== void 0 ? _a : polygon === null || polygon === void 0 ? void 0 : polygon.nb_sides) !== null && _b !== void 0 ? _b : 5;
return {
count: {
denominator: 1,
numerator: sides
},
length: radius * 2.66 / (sides / 3)
};
}
getCenter(particle, radius) {
var _a, _b;
const polygon = particle.shapeData;
const sides = (_b = (_a = polygon === null || polygon === void 0 ? void 0 : polygon.sides) !== null && _a !== void 0 ? _a : polygon === null || polygon === void 0 ? void 0 : polygon.nb_sides) !== null && _b !== void 0 ? _b : 5;
return {
x: -radius / (sides / 3.5),
y: -radius / (2.66 / 3.5)
};
}
}
// CONCATENATED MODULE: ./dist/Utils/Constants.js
class Constants {}
Constants.canvasClass = "tsparticles-canvas-el";
Constants.randomColorValue = "random";
Constants.midColorValue = "mid";
Constants.touchEndEvent = "touchend";
Constants.mouseDownEvent = "mousedown";
Constants.mouseUpEvent = "mouseup";
Constants.mouseMoveEvent = "mousemove";
Constants.touchStartEvent = "touchstart";
Constants.touchMoveEvent = "touchmove";
Constants.mouseLeaveEvent = "mouseleave";
Constants.mouseOutEvent = "mouseout";
Constants.touchCancelEvent = "touchcancel";
Constants.resizeEvent = "resize";
Constants.visibilityChangeEvent = "visibilitychange";
Constants.noPolygonDataLoaded = "No polygon data loaded.";
Constants.noPolygonFound = "No polygon found, you need to specify SVG url in config.";
// CONCATENATED MODULE: ./dist/Utils/ColorUtils.js
class ColorUtils_ColorUtils {
static colorToRgb(input) {
var _a, _b;
if (input === undefined) {
return;
}
const color = typeof input === "string" ? {
value: input
} : input;
let res;
if (typeof color.value === "string") {
if (color.value === Constants.randomColorValue) {
res = this.getRandomRgbColor();
} else {
res = ColorUtils_ColorUtils.stringToRgb(color.value);
}
} else {
if (color.value instanceof Array) {
const colorSelected = Utils_Utils.itemFromArray(color.value);
res = ColorUtils_ColorUtils.colorToRgb({
value: colorSelected
});
} else {
const colorValue = color.value;
const rgbColor = (_a = colorValue.rgb) !== null && _a !== void 0 ? _a : color.value;
if (rgbColor.r !== undefined) {
res = rgbColor;
} else {
const hslColor = (_b = colorValue.hsl) !== null && _b !== void 0 ? _b : color.value;
if (hslColor.h !== undefined) {
res = ColorUtils_ColorUtils.hslToRgb(hslColor);
}
}
}
}
return res;
}
static colorToHsl(color) {
const rgb = this.colorToRgb(color);
return rgb !== undefined ? this.rgbToHsl(rgb) : rgb;
}
static rgbToHsl(color) {
const r1 = color.r / 255;
const g1 = color.g / 255;
const b1 = color.b / 255;
const max = Math.max(r1, g1, b1);
const min = Math.min(r1, g1, b1);
const res = {
h: 0,
l: (max + min) / 2,
s: 0
};
if (max != min) {
res.s = res.l < 0.5 ? (max - min) / (max + min) : (max - min) / (2.0 - max - min);
res.h = r1 === max ? (g1 - b1) / (max - min) : res.h = g1 === max ? 2.0 + (b1 - r1) / (max - min) : 4.0 + (r1 - g1) / (max - min);
}
res.l *= 100;
res.s *= 100;
res.h *= 60;
if (res.h < 0) {
res.h += 360;
}
return res;
}
static stringToAlpha(input) {
var _a;
return (_a = ColorUtils_ColorUtils.stringToRgba(input)) === null || _a === void 0 ? void 0 : _a.a;
}
static stringToRgb(input) {
return ColorUtils_ColorUtils.stringToRgba(input);
}
static hslToRgb(hsl) {
const result = {
b: 0,
g: 0,
r: 0
};
const hslPercent = {
h: hsl.h / 360,
l: hsl.l / 100,
s: hsl.s / 100
};
if (hslPercent.s === 0) {
result.b = hslPercent.l;
result.g = hslPercent.l;
result.r = hslPercent.l;
} else {
const q = hslPercent.l < 0.5 ? hslPercent.l * (1 + hslPercent.s) : hslPercent.l + hslPercent.s - hslPercent.l * hslPercent.s;
const p = 2 * hslPercent.l - q;
result.r = ColorUtils_ColorUtils.hue2rgb(p, q, hslPercent.h + 1 / 3);
result.g = ColorUtils_ColorUtils.hue2rgb(p, q, hslPercent.h);
result.b = ColorUtils_ColorUtils.hue2rgb(p, q, hslPercent.h - 1 / 3);
}
result.r = Math.floor(result.r * 255);
result.g = Math.floor(result.g * 255);
result.b = Math.floor(result.b * 255);
return result;
}
static hslaToRgba(hsla) {
const rgbResult = ColorUtils_ColorUtils.hslToRgb(hsla);
return {
a: hsla.a,
b: rgbResult.b,
g: rgbResult.g,
r: rgbResult.r
};
}
static getRandomRgbColor(min) {
const fixedMin = min !== null && min !== void 0 ? min : 0;
return {
b: Math.floor(Utils_Utils.randomInRange(fixedMin, 256)),
g: Math.floor(Utils_Utils.randomInRange(fixedMin, 256)),
r: Math.floor(Utils_Utils.randomInRange(fixedMin, 256))
};
}
static getStyleFromRgb(color, opacity) {
return `rgba(${color.r}, ${color.g}, ${color.b}, ${opacity !== null && opacity !== void 0 ? opacity : 1})`;
}
static getStyleFromHsl(color, opacity) {
return `hsla(${color.h}, ${color.s}%, ${color.l}%, ${opacity !== null && opacity !== void 0 ? opacity : 1})`;
}
static mix(color1, color2, size1, size2) {
let rgb1 = color1;
let rgb2 = color2;
if (rgb1.r === undefined) {
rgb1 = this.hslToRgb(color1);
}
if (rgb2.r === undefined) {
rgb2 = this.hslToRgb(color2);
}
return {
b: Utils_Utils.mix(rgb1.b, rgb2.b, size1, size2),
g: Utils_Utils.mix(rgb1.g, rgb2.g, size1, size2),
r: Utils_Utils.mix(rgb1.r, rgb2.r, size1, size2)
};
}
static replaceColorSvg(image, color, opacity) {
if (!image.svgData) {
return "";
}
const svgXml = image.svgData;
const rgbHex = /#([0-9A-F]{3,6})/gi;
return svgXml.replace(rgbHex, () => ColorUtils_ColorUtils.getStyleFromHsl(color, opacity));
}
static hue2rgb(p, q, t) {
let tCalc = t;
if (tCalc < 0) {
tCalc += 1;
}
if (tCalc > 1) {
tCalc -= 1;
}
if (tCalc < 1 / 6) {
return p + (q - p) * 6 * tCalc;
}
if (tCalc < 1 / 2) {
return q;
}
if (tCalc < 2 / 3) {
return p + (q - p) * (2 / 3 - tCalc) * 6;
}
return p;
}
static stringToRgba(input) {
if (input.startsWith("rgb")) {
const regex = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([\d.]+)\s*)?\)/i;
const result = regex.exec(input);
return result ? {
a: result.length > 4 ? parseFloat(result[5]) : 1,
b: parseInt(result[3], 10),
g: parseInt(result[2], 10),
r: parseInt(result[1], 10)
} : undefined;
} else if (input.startsWith("hsl")) {
const regex = /hsla?\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*(,\s*([\d.]+)\s*)?\)/i;
const result = regex.exec(input);
return result ? ColorUtils_ColorUtils.hslaToRgba({
a: result.length > 4 ? parseFloat(result[5]) : 1,
h: parseInt(result[1], 10),
l: parseInt(result[3], 10),
s: parseInt(result[2], 10)
}) : undefined;
} else {
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])([a-f\d])?$/i;
const hexFixed = input.replace(shorthandRegex, (_m, r, g, b, a) => {
return r + r + g + g + b + b + (a !== undefined ? a + a : "");
});
const regex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i;
const result = regex.exec(hexFixed);
return result ? {
a: result[4] !== undefined ? parseInt(result[4], 16) / 0xff : 1,
b: parseInt(result[3], 16),
g: parseInt(result[2], 16),
r: parseInt(result[1], 16)
} : undefined;
}
}
}
// CONCATENATED MODULE: ./dist/Utils/CanvasUtils.js
class CanvasUtils_CanvasUtils {
static paintBase(context, dimension, baseColor) {
context.save();
context.fillStyle = baseColor !== null && baseColor !== void 0 ? baseColor : "rgba(0,0,0,0)";
context.fillRect(0, 0, dimension.width, dimension.height);
context.restore();
}
static clear(context, dimension) {
context.clearRect(0, 0, dimension.width, dimension.height);
}
static drawLinkLine(context, width, begin, end, maxDistance, canvasSize, warp, backgroundMask, colorLine, opacity, shadow) {
let drawn = false;
if (Utils_Utils.getDistance(begin, end) <= maxDistance) {
this.drawLine(context, begin, end);
drawn = true;
} else if (warp) {
let pi1;
let pi2;
const endNE = {
x: end.x - canvasSize.width,
y: end.y
};
const {
dx,
dy,
distance
} = Utils_Utils.getDistances(begin, endNE);
if (distance <= maxDistance) {
const yi = begin.y - dy / dx * begin.x;
pi1 = {
x: 0,
y: yi
};
pi2 = {
x: canvasSize.width,
y: yi
};
} else {
const endSW = {
x: end.x,
y: end.y - canvasSize.height
};
const {
dx,
dy,
distance
} = Utils_Utils.getDistances(begin, endSW);
if (distance <= maxDistance) {
const yi = begin.y - dy / dx * begin.x;
const xi = -yi / (dy / dx);
pi1 = {
x: xi,
y: 0
};
pi2 = {
x: xi,
y: canvasSize.height
};
} else {
const endSE = {
x: end.x - canvasSize.width,
y: end.y - canvasSize.height
};
const {
dx,
dy,
distance
} = Utils_Utils.getDistances(begin, endSE);
if (distance <= maxDistance) {
const yi = begin.y - dy / dx * begin.x;
const xi = -yi / (dy / dx);
pi1 = {
x: xi,
y: yi
};
pi2 = {
x: pi1.x + canvasSize.width,
y: pi1.y + canvasSize.height
};
}
}
}
if (pi1 && pi2) {
this.drawLine(context, begin, pi1);
this.drawLine(context, end, pi2);
drawn = true;
}
}
if (!drawn) {
return;
}
context.lineWidth = width;
if (backgroundMask) {
context.globalCompositeOperation = "destination-out";
}
context.strokeStyle = ColorUtils_ColorUtils.getStyleFromRgb(colorLine, opacity);
if (shadow.enable) {
const shadowColor = ColorUtils_ColorUtils.colorToRgb(shadow.color);
if (shadowColor) {
context.shadowBlur = shadow.blur;
context.shadowColor = ColorUtils_ColorUtils.getStyleFromRgb(shadowColor);
}
}
context.stroke();
}
static drawLinkTriangle(context, width, pos1, pos2, pos3, backgroundMask, colorTriangle, opacityTriangle) {
this.drawTriangle(context, pos1, pos2, pos3);
context.lineWidth = width;
if (backgroundMask) {
context.globalCompositeOperation = "destination-out";
}
context.fillStyle = ColorUtils_ColorUtils.getStyleFromRgb(colorTriangle, opacityTriangle);
context.fill();
}
static drawConnectLine(context, width, lineStyle, begin, end) {
context.save();
this.drawLine(context, begin, end);
context.lineWidth = width;
context.strokeStyle = lineStyle;
context.stroke();
context.restore();
}
static gradient(context, p1, p2, opacity) {
const gradStop = Math.floor(p2.size.value / p1.size.value);
const color1 = p1.getFillColor();
const color2 = p2.getFillColor();
if (!color1 || !color2) {
return;
}
const sourcePos = p1.getPosition();
const destPos = p2.getPosition();
const midRgb = ColorUtils_ColorUtils.mix(color1, color2, p1.size.value, p2.size.value);
const grad = context.createLinearGradient(sourcePos.x, sourcePos.y, destPos.x, destPos.y);
grad.addColorStop(0, ColorUtils_ColorUtils.getStyleFromHsl(color1, opacity));
grad.addColorStop(gradStop > 1 ? 1 : gradStop, ColorUtils_ColorUtils.getStyleFromRgb(midRgb, opacity));
grad.addColorStop(1, ColorUtils_ColorUtils.getStyleFromHsl(color2, opacity));
return grad;
}
static drawGrabLine(context, width, begin, end, colorLine, opacity) {
context.save();
this.drawLine(context, begin, end);
context.strokeStyle = ColorUtils_ColorUtils.getStyleFromRgb(colorLine, opacity);
context.lineWidth = width;
context.stroke();
context.restore();
}
static drawParticle(container, context, particle, delta, fillColorValue, strokeColorValue, backgroundMask, radius, opacity, shadow) {
const pos = particle.getPosition();
context.save();
context.translate(pos.x, pos.y);
context.beginPath();
if (particle.angle !== 0) {
if (particle.particlesOptions.rotate.path) {
context.rotate(particle.angle + particle.pathAngle);
} else {
context.rotate(particle.angle);
}
}
if (backgroundMask) {
context.globalCompositeOperation = "destination-out";
}
const shadowColor = particle.shadowColor;
if (shadow.enable && shadowColor) {
context.shadowBlur = shadow.blur;
context.shadowColor = ColorUtils_ColorUtils.getStyleFromRgb(shadowColor);
context.shadowOffsetX = shadow.offset.x;
context.shadowOffsetY = shadow.offset.y;
}
context.fillStyle = fillColorValue;
const stroke = particle.stroke;
context.lineWidth = particle.strokeWidth;
context.strokeStyle = strokeColorValue;
if (particle.close) {
context.closePath();
}
this.drawShape(container, context, particle, radius, opacity, delta);
if (stroke.width > 0) {
context.stroke();
}
if (particle.fill) {
context.fill();
}
context.restore();
context.save();
context.translate(pos.x, pos.y);
if (particle.angle !== 0) {
context.rotate(particle.angle);
}
if (backgroundMask) {
context.globalCompositeOperation = "destination-out";
}
this.drawShapeAfterEffect(container, context, particle, radius, opacity, delta);
context.restore();
}
static drawShape(container, context, particle, radius, opacity, delta) {
if (!particle.shape) {
return;
}
const drawer = container.drawers.get(particle.shape);
if (!drawer) {
return;
}
drawer.draw(context, particle, radius, opacity, delta.value, container.retina.pixelRatio);
}
static drawShapeAfterEffect(container, context, particle, radius, opacity, delta) {
if (!particle.shape) {
return;
}
const drawer = container.drawers.get(particle.shape);
if (!(drawer === null || drawer === void 0 ? void 0 : drawer.afterEffect)) {
return;
}
drawer.afterEffect(context, particle, radius, opacity, delta.value, container.retina.pixelRatio);
}
static drawPlugin(context, plugin, delta) {
if (plugin.draw !== undefined) {
context.save();
plugin.draw(context, delta);
context.restore();
}
}
static drawLine(context, begin, end) {
context.beginPath();
context.moveTo(begin.x, begin.y);
context.lineTo(end.x, end.y);
context.closePath();
}
static drawTriangle(context, p1, p2, p3) {
context.beginPath();
context.moveTo(p1.x, p1.y);
context.lineTo(p2.x, p2.y);
context.lineTo(p3.x, p3.y);
context.closePath();
}
}
// CONCATENATED MODULE: ./dist/Core/Canvas.js
class Canvas_Canvas {
constructor(container) {
this.container = container;
this.size = {
height: 0,
width: 0
};
this.context = null;
this.generatedCanvas = false;
}
init() {
this.resize();
const options = this.container.options;
const cover = options.backgroundMask.cover;
const color = cover.color;
const trail = options.particles.move.trail;
this.coverColor = ColorUtils_ColorUtils.colorToRgb(color);
this.trailFillColor = ColorUtils_ColorUtils.colorToRgb(trail.fillColor);
this.initBackground();
this.paint();
}
loadCanvas(canvas, generatedCanvas) {
var _a;
if (!canvas.className) {
canvas.className = Constants.canvasClass;
}
if (this.generatedCanvas) {
(_a = this.element) === null || _a === void 0 ? void 0 : _a.remove();
}
this.generatedCanvas = generatedCanvas !== null && generatedCanvas !== void 0 ? generatedCanvas : false;
this.element = canvas;
this.size.height = canvas.offsetHeight;
this.size.width = canvas.offsetWidth;
this.context = this.element.getContext("2d");
this.container.retina.init();
this.initBackground();
}
destroy() {
var _a;
if (this.generatedCanvas) {
(_a = this.element) === null || _a === void 0 ? void 0 : _a.remove();
}
if (this.context) {
CanvasUtils_CanvasUtils.clear(this.context, this.size);
}
}
resize() {
if (!this.element) {
return;
}
this.element.width = this.size.width;
this.element.height = this.size.height;
}
paint() {
const options = this.container.options;
if (this.context) {
if (options.backgroundMask.enable && options.backgroundMask.cover && this.coverColor) {
this.paintBase(ColorUtils_ColorUtils.getStyleFromRgb(this.coverColor));
} else {
this.paintBase();
}
}
}
clear() {
const options = this.container.options;
const trail = options.particles.move.trail;
if (options.backgroundMask.enable) {
this.paint();
} else if (trail.enable && trail.length > 0 && this.trailFillColor) {
this.paintBase(ColorUtils_ColorUtils.getStyleFromRgb(this.trailFillColor, 1 / trail.length));
} else if (this.context) {
CanvasUtils_CanvasUtils.clear(this.context, this.size);
}
}
drawLinkTriangle(p1, link1, link2) {
var _a, _b;
const container = this.container;
const options = container.options;
const p2 = link1.destination;
const p3 = link2.destination;
const triangleOptions = p1.particlesOptions.links.triangles;
const opacityTriangle = (_a = triangleOptions.opacity) !== null && _a !== void 0 ? _a : (link1.opacity + link2.opacity) / 2;
const pos1 = p1.getPosition();
const pos2 = p2.getPosition();
const pos3 = p3.getPosition();
const ctx = this.context;
if (!ctx) {
return;
}
let colorTriangle = ColorUtils_ColorUtils.colorToRgb(triangleOptions.color);
if (!colorTriangle) {
const linksOptions = p1.particlesOptions.links;
const linkColor = linksOptions.id !== undefined ? container.particles.linksColors.get(linksOptions.id) : container.particles.linksColor;
if (linkColor === Constants.randomColorValue) {
colorTriangle = ColorUtils_ColorUtils.getRandomRgbColor();
} else if (linkColor === "mid") {
const sourceColor = p1.getFillColor();
const destColor = p2.getFillColor();
if (sourceColor && destColor) {
colorTriangle = ColorUtils_ColorUtils.mix(sourceColor, destColor, p1.size.value, p2.size.value);
} else {
const hslColor = sourceColor !== null && sourceColor !== void 0 ? sourceColor : destColor;
if (!hslColor) {
return;
}
colorTriangle = ColorUtils_ColorUtils.hslToRgb(hslColor);
}
} else {
colorTriangle = linkColor;
}
}
const width = (_b = p1.linksWidth) !== null && _b !== void 0 ? _b : container.retina.linksWidth;
CanvasUtils_CanvasUtils.drawLinkTriangle(ctx, width, pos1, pos2, pos3, options.backgroundMask.enable, colorTriangle, opacityTriangle);
}
drawLinkLine(p1, link) {
var _a;
const container = this.container;
const options = container.options;
const p2 = link.destination;
let opacity = link.opacity;
const pos1 = p1.getPosition();
const pos2 = p2.getPosition();
const ctx = this.context;
if (!ctx) {
return;
}
let colorLine;
const twinkle = p1.particlesOptions.twinkle.lines;
if (twinkle.enable) {
const twinkleFreq = twinkle.frequency;
const twinkleRgb = ColorUtils_ColorUtils.colorToRgb(twinkle.color);
const twinkling = Math.random() < twinkleFreq;
if (twinkling && twinkleRgb !== undefined) {
colorLine = twinkleRgb;
opacity = twinkle.opacity;
}
}
if (!colorLine) {
const linksOptions = p1.particlesOptions.links;
const linkColor = linksOptions.id !== undefined ? container.particles.linksColors.get(linksOptions.id) : container.particles.linksColor;
if (linkColor === Constants.randomColorValue) {
colorLine = ColorUtils_ColorUtils.getRandomRgbColor();
} else if (linkColor === "mid") {
const sourceColor = p1.getFillColor();
const destColor = p2.getFillColor();
if (sourceColor && destColor) {
colorLine = ColorUtils_ColorUtils.mix(sourceColor, destColor, p1.size.value, p2.size.value);
} else {
const hslColor = sourceColor !== null && sourceColor !== void 0 ? sourceColor : destColor;
if (!hslColor) {
return;
}
colorLine = ColorUtils_ColorUtils.hslToRgb(hslColor);
}
} else {
colorLine = linkColor;
}
}
const width = (_a = p1.linksWidth) !== null && _a !== void 0 ? _a : container.retina.linksWidth;
CanvasUtils_CanvasUtils.drawLinkLine(ctx, width, pos1, pos2, p1.particlesOptions.links.distance, container.canvas.size, p1.particlesOptions.links.warp, options.backgroundMask.enable, colorLine, opacity, p1.particlesOptions.links.shadow);
}
drawConnectLine(p1, p2) {
var _a;
const lineStyle = this.lineStyle(p1, p2);
if (!lineStyle) {
return;
}
const ctx = this.context;
if (!ctx) {
return;
}
const pos1 = p1.getPosition();
const pos2 = p2.getPosition();
CanvasUtils_CanvasUtils.drawConnectLine(ctx, (_a = p1.linksWidth) !== null && _a !== void 0 ? _a : this.container.retina.linksWidth, lineStyle, pos1, pos2);
}
drawGrabLine(particle, lineColor, opacity, mousePos) {
var _a;
const container = this.container;
const ctx = container.canvas.context;
if (!ctx) {
return;
}
const beginPos = particle.getPosition();
CanvasUtils_CanvasUtils.drawGrabLine(ctx, (_a = particle.linksWidth) !== null && _a !== void 0 ? _a : container.retina.linksWidth, beginPos, mousePos, lineColor, opacity);
}
drawParticle(particle, delta) {
var _a, _b, _c, _d, _e;
if (((_a = particle.image) === null || _a === void 0 ? void 0 : _a.loaded) === false) {
return;
}
const pfColor = particle.getFillColor();
if (pfColor === undefined) {
return;
}
const psColor = (_b = particle.getStrokeColor()) !== null && _b !== void 0 ? _b : pfColor;
const options = this.container.options;
const twinkle = particle.particlesOptions.twinkle.particles;
const twinkleFreq = twinkle.frequency;
const twinkleRgb = ColorUtils_ColorUtils.colorToRgb(twinkle.color);
const twinkling = twinkle.enable && Math.random() < twinkleFreq;
const radius = (_c = particle.bubble.radius) !== null && _c !== void 0 ? _c : particle.size.value;
const opacity = twinkling ? twinkle.opacity : (_d = particle.bubble.opacity) !== null && _d !== void 0 ? _d : particle.opacity.value;
const infectionStage = particle.infecter.infectionStage;
const infection = options.infection;
const infectionStages = infection.stages;
const infectionColor = infectionStage !== undefined ? infectionStages[infectionStage].color : undefined;
const infectionRgb = ColorUtils_ColorUtils.colorToRgb(infectionColor);
const fColor = twinkling && twinkleRgb !== undefined ? twinkleRgb : infectionRgb !== null && infectionRgb !== void 0 ? infectionRgb : ColorUtils_ColorUtils.hslToRgb(pfColor);
const sColor = twinkling && twinkleRgb !== undefined ? twinkleRgb : infectionRgb !== null && infectionRgb !== void 0 ? infectionRgb : ColorUtils_ColorUtils.hslToRgb(psColor);
const fillColorValue = fColor !== undefined ? ColorUtils_ColorUtils.getStyleFromRgb(fColor, opacity) : undefined;
if (!this.context || !fillColorValue) {
return;
}
const strokeColorValue = sColor !== undefined ? ColorUtils_ColorUtils.getStyleFromRgb(sColor, (_e = particle.stroke.opacity) !== null && _e !== void 0 ? _e : opacity) : fillColorValue;
if (particle.links.length > 0) {
this.context.save();
for (const link of particle.links) {
if (particle.particlesOptions.links.triangles.enable) {
const links = particle.links.map(l => l.destination);
const vertices = link.destination.links.filter(t => links.indexOf(t.destination) >= 0);
if (vertices.length) {
for (const vertice of vertices) {
this.drawLinkTriangle(particle, link, vertice);
}
}
}
this.drawLinkLine(particle, link);
}
this.context.restore();
}
CanvasUtils_CanvasUtils.drawParticle(this.container, this.context, particle, delta, fillColorValue, strokeColorValue, options.backgroundMask.enable, radius, opacity, particle.particlesOptions.shadow);
}
drawPlugin(plugin, delta) {
if (!this.context) {
return;
}
CanvasUtils_CanvasUtils.drawPlugin(this.context, plugin, delta);
}
paintBase(baseColor) {
if (this.context) {
CanvasUtils_CanvasUtils.paintBase(this.context, this.size, baseColor);
}
}
lineStyle(p1, p2) {
const options = this.container.options;
const connectOptions = options.interactivity.modes.connect;
if (this.context) {
return CanvasUtils_CanvasUtils.gradient(this.context, p1, p2, connectOptions.links.opacity);
}
}
initBackground() {
const options = this.container.options;
const background = options.background;
const element = this.element;
if (!element) {
return;
}
const elementStyle = element.style;
if (background.color) {
const color = ColorUtils_ColorUtils.colorToRgb(background.color);
if (color) {
elementStyle.backgroundColor = ColorUtils_ColorUtils.getStyleFromRgb(color, background.opacity);
}
}
if (background.image) {
elementStyle.backgroundImage = background.image;
}
if (background.position) {
elementStyle.backgroundPosition = background.position;
}
if (background.repeat) {
elementStyle.backgroundRepeat = background.repeat;
}
if (background.size) {
elementStyle.backgroundSize = background.size;
}
}
}
// CONCATENATED MODULE: ./dist/Enums/Statuses/OpacityAnimationStatus.js
var OpacityAnimationStatus;
(function (OpacityAnimationStatus) {
OpacityAnimationStatus[OpacityAnimationStatus["increasing"] = 0] = "increasing";
OpacityAnimationStatus[OpacityAnimationStatus["decreasing"] = 1] = "decreasing";
})(OpacityAnimationStatus || (OpacityAnimationStatus = {}));
// CONCATENATED MODULE: ./dist/Enums/Statuses/SizeAnimationStatus.js
var SizeAnimationStatus;
(function (SizeAnimationStatus) {
SizeAnimationStatus[SizeAnimationStatus["increasing"] = 0] = "increasing";
SizeAnimationStatus[SizeAnimationStatus["decreasing"] = 1] = "decreasing";
})(SizeAnimationStatus || (SizeAnimationStatus = {}));
// CONCATENATED MODULE: ./dist/Enums/Types/DestroyType.js
var DestroyType;
(function (DestroyType) {
DestroyType["none"] = "none";
DestroyType["max"] = "max";
DestroyType["min"] = "min";
})(DestroyType || (DestroyType = {}));
// CONCATENATED MODULE: ./dist/Enums/Directions/RotateDirection.js
var RotateDirection;
(function (RotateDirection) {
RotateDirection["clockwise"] = "clockwise";
RotateDirection["counterClockwise"] = "counter-clockwise";
RotateDirection["random"] = "random";
})(RotateDirection || (RotateDirection = {}));
// CONCATENATED MODULE: ./dist/Enums/Modes/OutMode.js
var OutMode;
(function (OutMode) {
OutMode["bounce"] = "bounce";
OutMode["bounceHorizontal"] = "bounce-horizontal";
OutMode["bounceVertical"] = "bounce-vertical";
OutMode["out"] = "out";
OutMode["destroy"] = "destroy";
})(OutMode || (OutMode = {}));
// CONCATENATED MODULE: ./dist/Core/Particle/Updater.js
class Updater_Updater {
constructor(container, particle) {
this.container = container;
this.particle = particle;
}
update(delta) {
if (this.particle.destroyed) {
return;
}
this.updateOpacity(delta);
this.updateSize(delta);
this.updateAngle(delta);
this.updateColor(delta);
this.updateStrokeColor(delta);
this.updateOutMode(delta);
}
updateOpacity(delta) {
const particle = this.particle;
if (particle.particlesOptions.opacity.animation.enable) {
switch (particle.opacity.status) {
case OpacityAnimationStatus.increasing:
if (particle.opacity.value >= particle.particlesOptions.opacity.value) {
particle.opacity.status = OpacityAnimationStatus.decreasing;
} else {
particle.opacity.value += (particle.opacity.velocity || 0) * delta.factor;
}
break;
case OpacityAnimationStatus.decreasing:
if (particle.opacity.value <= particle.particlesOptions.opacity.animation.minimumValue) {
particle.opacity.status = OpacityAnimationStatus.increasing;
} else {
particle.opacity.value -= (particle.opacity.velocity || 0) * delta.factor;
}
break;
}
if (particle.opacity.value < 0) {
particle.opacity.value = 0;
}
}
}
updateSize(delta) {
var _a;
const container = this.container;
const particle = this.particle;
const sizeOpt = particle.particlesOptions.size;
const sizeAnim = sizeOpt.animation;
if (sizeAnim.enable) {
switch (particle.size.status) {
case SizeAnimationStatus.increasing:
if (particle.size.value >= ((_a = particle.sizeValue) !== null && _a !== void 0 ? _a : container.retina.sizeValue)) {
particle.size.status = SizeAnimationStatus.decreasing;
} else {
particle.size.value += (particle.size.velocity || 0) * delta.factor;
}
break;
case SizeAnimationStatus.decreasing:
if (particle.size.value <= sizeAnim.minimumValue) {
particle.size.status = SizeAnimationStatus.increasing;
} else {
particle.size.value -= (particle.size.velocity || 0) * delta.factor;
}
}
switch (sizeAnim.destroy) {
case DestroyType.max:
if (particle.size.value >= sizeOpt.value * container.retina.pixelRatio) {
particle.destroy();
}
break;
case DestroyType.min:
if (particle.size.value <= sizeAnim.minimumValue * container.retina.pixelRatio) {
particle.destroy();
}
break;
}
if (particle.size.value < 0 && !particle.destroyed) {
particle.size.value = 0;
}
}
}
updateAngle(delta) {
const particle = this.particle;
const rotate = particle.particlesOptions.rotate;
const rotateAnimation = rotate.animation;
const speed = rotateAnimation.speed / 360 * delta.factor;
const max = 2 * Math.PI;
if (rotate.path) {
particle.pathAngle = Math.atan2(particle.velocity.vertical, particle.velocity.horizontal);
} else {
if (rotateAnimation.enable) {
switch (particle.rotateDirection) {
case RotateDirection.clockwise:
particle.angle += speed;
if (particle.angle > max) {
particle.angle -= max;
}
break;
case RotateDirection.counterClockwise:
default:
particle.angle -= speed;
if (particle.angle < 0) {
particle.angle += max;
}
break;
}
}
}
}
updateColor(delta) {
const particle = this.particle;
if (particle.color === undefined) {
return;
}
if (particle.particlesOptions.color.animation.enable) {
particle.color.h += (particle.colorVelocity || 0) * delta.factor;
if (particle.color.h > 360) {
particle.color.h -= 360;
}
}
}
updateStrokeColor(delta) {
const particle = this.particle;
const color = particle.stroke.color;
if (typeof color === "string" || color === undefined) {
return;
}
if (particle.strokeColor === undefined) {
return;
}
if (color.animation.enable) {
particle.strokeColor.h += (particle.colorVelocity || 0) * delta.factor;
if (particle.strokeColor.h > 360) {
particle.strokeColor.h -= 360;
}
}
}
fixOutOfCanvasPosition() {
const container = this.container;
const particle = this.particle;
const wrap = particle.particlesOptions.move.warp;
const canvasSize = container.canvas.size;
const newPos = {
bottom: canvasSize.height + particle.size.value - particle.offset.y,
left: -particle.size.value - particle.offset.x,
right: canvasSize.width + particle.size.value + particle.offset.x,
top: -particle.size.value - particle.offset.y
};
const sizeValue = particle.size.value;
const nextBounds = Utils_Utils.calculateBounds(particle.position, sizeValue);
if (nextBounds.left > canvasSize.width - particle.offset.x) {
particle.position.x = newPos.left;
if (!wrap) {
particle.position.y = Math.random() * canvasSize.height;
}
} else if (nextBounds.right < -particle.offset.x) {
particle.position.x = newPos.right;
if (!wrap) {
particle.position.y = Math.random() * canvasSize.height;
}
}
if (nextBounds.top > canvasSize.height - particle.offset.y) {
if (!wrap) {
particle.position.x = Math.random() * canvasSize.width;
}
particle.position.y = newPos.top;
} else if (nextBounds.bottom < -particle.offset.y) {
if (!wrap) {
particle.position.x = Math.random() * canvasSize.width;
}
particle.position.y = newPos.bottom;
}
}
updateOutMode(delta) {
const container = this.container;
const particle = this.particle;
switch (particle.particlesOptions.move.outMode) {
case OutMode.bounce:
case OutMode.bounceVertical:
case OutMode.bounceHorizontal:
this.updateBounce(delta);
break;
case OutMode.destroy:
if (!Utils_Utils.isPointInside(particle.position, container.canvas.size, particle.size.value)) {
particle.destroy();
container.particles.remove(particle);
return;
}
break;
case OutMode.out:
if (!Utils_Utils.isPointInside(particle.position, container.canvas.size, particle.size.value)) {
this.fixOutOfCanvasPosition();
}
}
}
updateBounce(delta) {
const container = this.container;
const particle = this.particle;
let handled = false;
for (const [, plugin] of container.plugins) {
if (plugin.particleBounce !== undefined) {
handled = plugin.particleBounce(particle, delta);
}
if (handled) {
break;
}
}
if (handled) {
return;
}
const outMode = particle.particlesOptions.move.outMode,
pos = particle.getPosition(),
offset = particle.offset,
size = particle.size.value,
bounds = Utils_Utils.calculateBounds(pos, size),
canvasSize = container.canvas.size;
if (outMode === OutMode.bounce || outMode === OutMode.bounceHorizontal) {
const velocity = particle.velocity.horizontal;
if (bounds.right >= canvasSize.width && velocity > 0 || bounds.left <= 0 && velocity < 0) {
particle.velocity.horizontal *= -1;
}
const minPos = offset.x + size;
if (bounds.right >= canvasSize.width) {
particle.position.x = canvasSize.width - minPos;
} else if (bounds.left <= 0) {
particle.position.x = minPos;
}
}
if (outMode === OutMode.bounce || outMode === OutMode.bounceVertical) {
const velocity = particle.velocity.vertical;
if (bounds.bottom >= container.canvas.size.height && velocity > 0 || bounds.top <= 0 && velocity < 0) {
particle.velocity.vertical *= -1;
}
const minPos = offset.y + size;
if (bounds.bottom >= canvasSize.height) {
particle.position.y = canvasSize.height - minPos;
} else if (bounds.top <= 0) {
particle.position.y = minPos;
}
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/OptionsColor.js
class OptionsColor {
constructor() {
this.value = "#fff";
}
static create(source, data) {
const color = source !== null && source !== void 0 ? source : new OptionsColor();
if (data !== undefined) {
color.load(typeof data === "string" ? {
value: data
} : data);
}
return color;
}
load(data) {
if ((data === null || data === void 0 ? void 0 : data.value) === undefined) {
return;
}
this.value = data.value;
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Links/LinksShadow.js
class LinksShadow_LinksShadow {
constructor() {
this.blur = 5;
this.color = new OptionsColor();
this.enable = false;
this.color.value = "#00ff00";
}
load(data) {
if (data === undefined) {
return;
}
if (data.blur !== undefined) {
this.blur = data.blur;
}
this.color = OptionsColor.create(this.color, data.color);
if (data.enable !== undefined) {
this.enable = data.enable;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Links/LinksTriangle.js
class LinksTriangle_LinksTriangle {
constructor() {
this.enable = false;
}
load(data) {
if (data === undefined) {
return;
}
if (data.color !== undefined) {
this.color = OptionsColor.create(this.color, data.color);
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.opacity !== undefined) {
this.opacity = data.opacity;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Links/Links.js
class Links_Links {
constructor() {
this.blink = false;
this.color = new OptionsColor();
this.consent = false;
this.distance = 100;
this.enable = false;
this.opacity = 1;
this.shadow = new LinksShadow_LinksShadow();
this.triangles = new LinksTriangle_LinksTriangle();
this.width = 1;
this.warp = false;
}
load(data) {
if (data === undefined) {
return;
}
if (data.id !== undefined) {
this.id = data.id;
}
if (data.blink !== undefined) {
this.blink = data.blink;
}
this.color = OptionsColor.create(this.color, data.color);
if (data.consent !== undefined) {
this.consent = data.consent;
}
if (data.distance !== undefined) {
this.distance = data.distance;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.opacity !== undefined) {
this.opacity = data.opacity;
}
this.shadow.load(data.shadow);
this.triangles.load(data.triangles);
if (data.width !== undefined) {
this.width = data.width;
}
if (data.warp !== undefined) {
this.warp = data.warp;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Attract.js
class Attract {
constructor() {
this.enable = false;
this.rotate = {
x: 3000,
y: 3000
};
}
get rotateX() {
return this.rotate.x;
}
set rotateX(value) {
this.rotate.x = value;
}
get rotateY() {
return this.rotate.y;
}
set rotateY(value) {
this.rotate.y = value;
}
load(data) {
var _a, _b, _c, _d;
if (data === undefined) {
return;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
const rotateX = (_b = (_a = data.rotate) === null || _a === void 0 ? void 0 : _a.x) !== null && _b !== void 0 ? _b : data.rotateX;
if (rotateX !== undefined) {
this.rotate.x = rotateX;
}
const rotateY = (_d = (_c = data.rotate) === null || _c === void 0 ? void 0 : _c.y) !== null && _d !== void 0 ? _d : data.rotateY;
if (rotateY !== undefined) {
this.rotate.y = rotateY;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Trail.js
class Trail_Trail {
constructor() {
this.enable = false;
this.length = 10;
this.fillColor = new OptionsColor();
this.fillColor.value = "#000000";
}
load(data) {
if (data === undefined) {
return;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
this.fillColor = OptionsColor.create(this.fillColor, data.fillColor);
if (data.length !== undefined) {
this.length = data.length;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Noise/NoiseRandom.js
class NoiseRandom {
constructor() {
this.enable = false;
this.minimumValue = 0;
}
load(data) {
if (data === undefined) {
return;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.minimumValue !== undefined) {
this.minimumValue = data.minimumValue;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Noise/NoiseDelay.js
class NoiseDelay_NoiseDelay {
constructor() {
this.random = new NoiseRandom();
this.value = 0;
}
load(data) {
var _a;
if (data === undefined) {
return;
}
(_a = this.random) === null || _a === void 0 ? void 0 : _a.load(data.random);
if (data.value !== undefined) {
this.value = data.value;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Noise/Noise.js
class Noise_Noise {
constructor() {
this.delay = new NoiseDelay_NoiseDelay();
this.enable = false;
}
load(data) {
if (data === undefined) {
return;
}
this.delay.load(data.delay);
if (data.enable !== undefined) {
this.enable = data.enable;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Move/MoveAngle.js
class MoveAngle {
constructor() {
this.offset = 45;
this.value = 90;
}
load(data) {
if (data === undefined) {
return;
}
if (data.offset !== undefined) {
this.offset = data.offset;
}
if (data.value !== undefined) {
this.value = data.value;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Move/Move.js
class Move_Move {
constructor() {
this.angle = new MoveAngle();
this.attract = new Attract();
this.direction = MoveDirection.none;
this.enable = false;
this.noise = new Noise_Noise();
this.outMode = OutMode.out;
this.random = false;
this.speed = 2;
this.straight = false;
this.trail = new Trail_Trail();
this.vibrate = false;
this.warp = false;
}
get collisions() {
return false;
}
set collisions(value) {}
get bounce() {
return this.collisions;
}
set bounce(value) {
this.collisions = value;
}
get out_mode() {
return this.outMode;
}
set out_mode(value) {
this.outMode = value;
}
load(data) {
var _a;
if (data === undefined) {
return;
}
if (data.angle !== undefined) {
if (typeof data.angle === "number") {
this.angle.value = data.angle;
} else {
this.angle.load(data.angle);
}
}
this.attract.load(data.attract);
if (data.direction !== undefined) {
this.direction = data.direction;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
this.noise.load(data.noise);
const outMode = (_a = data.outMode) !== null && _a !== void 0 ? _a : data.out_mode;
if (outMode !== undefined) {
this.outMode = outMode;
}
if (data.random !== undefined) {
this.random = data.random;
}
if (data.speed !== undefined) {
this.speed = data.speed;
}
if (data.straight !== undefined) {
this.straight = data.straight;
}
this.trail.load(data.trail);
if (data.vibrate !== undefined) {
this.vibrate = data.vibrate;
}
if (data.warp !== undefined) {
this.warp = data.warp;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Density.js
class Density {
constructor() {
this.enable = false;
this.area = 800;
this.factor = 1000;
}
get value_area() {
return this.area;
}
set value_area(value) {
this.area = value;
}
load(data) {
var _a;
if (data === undefined) {
return;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
const area = (_a = data.area) !== null && _a !== void 0 ? _a : data.value_area;
if (area !== undefined) {
this.area = area;
}
if (data.factor !== undefined) {
this.factor = data.factor;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/ParticlesNumber.js
class ParticlesNumber_ParticlesNumber {
constructor() {
this.density = new Density();
this.limit = 0;
this.value = 100;
}
get max() {
return this.limit;
}
set max(value) {
this.limit = value;
}
load(data) {
var _a;
if (data === undefined) {
return;
}
this.density.load(data.density);
const limit = (_a = data.limit) !== null && _a !== void 0 ? _a : data.max;
if (limit !== undefined) {
this.limit = limit;
}
if (data.value !== undefined) {
this.value = data.value;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Opacity/OpacityAnimation.js
class OpacityAnimation {
constructor() {
this.enable = false;
this.minimumValue = 0;
this.speed = 2;
this.sync = false;
}
get opacity_min() {
return this.minimumValue;
}
set opacity_min(value) {
this.minimumValue = value;
}
load(data) {
var _a;
if (data === undefined) {
return;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
const minimumValue = (_a = data.minimumValue) !== null && _a !== void 0 ? _a : data.opacity_min;
if (minimumValue !== undefined) {
this.minimumValue = minimumValue;
}
if (data.speed !== undefined) {
this.speed = data.speed;
}
if (data.sync !== undefined) {
this.sync = data.sync;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Opacity/OpacityRandom.js
class OpacityRandom {
constructor() {
this.enable = false;
this.minimumValue = 1;
}
load(data) {
if (data === undefined) {
return;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.minimumValue !== undefined) {
this.minimumValue = data.minimumValue;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Opacity/Opacity.js
class Opacity_Opacity {
constructor() {
this.animation = new OpacityAnimation();
this.random = new OpacityRandom();
this.value = 1;
}
get anim() {
return this.animation;
}
set anim(value) {
this.animation = value;
}
load(data) {
var _a;
if (data === undefined) {
return;
}
this.animation.load((_a = data.animation) !== null && _a !== void 0 ? _a : data.anim);
if (data.random !== undefined) {
if (typeof data.random === "boolean") {
this.random.enable = data.random;
} else {
this.random.load(data.random);
}
}
if (data.value !== undefined) {
this.value = data.value;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Shape/Shape.js
class Shape_Shape {
constructor() {
this.options = {};
this.type = ShapeType.circle;
}
get image() {
var _a;
return (_a = this.options[ShapeType.image]) !== null && _a !== void 0 ? _a : this.options[ShapeType.images];
}
set image(value) {
this.options[ShapeType.image] = value;
this.options[ShapeType.images] = value;
}
get custom() {
return this.options;
}
set custom(value) {
this.options = value;
}
get images() {
return this.image instanceof Array ? this.image : [this.image];
}
set images(value) {
this.image = value;
}
get stroke() {
return [];
}
set stroke(_value) {}
get character() {
var _a;
return (_a = this.options[ShapeType.character]) !== null && _a !== void 0 ? _a : this.options[ShapeType.char];
}
set character(value) {
this.options[ShapeType.character] = value;
this.options[ShapeType.char] = value;
}
get polygon() {
var _a;
return (_a = this.options[ShapeType.polygon]) !== null && _a !== void 0 ? _a : this.options[ShapeType.star];
}
set polygon(value) {
this.options[ShapeType.polygon] = value;
this.options[ShapeType.star] = value;
}
load(data) {
var _a, _b, _c;
if (data === undefined) {
return;
}
const options = (_a = data.options) !== null && _a !== void 0 ? _a : data.custom;
if (options !== undefined) {
for (const shape in options) {
const item = options[shape];
if (item !== undefined) {
this.options[shape] = Utils_Utils.deepExtend((_b = this.options[shape]) !== null && _b !== void 0 ? _b : {}, item);
}
}
}
this.loadShape(data.character, ShapeType.character, ShapeType.char, true);
this.loadShape(data.polygon, ShapeType.polygon, ShapeType.star, false);
this.loadShape((_c = data.image) !== null && _c !== void 0 ? _c : data.images, ShapeType.image, ShapeType.images, true);
if (data.type !== undefined) {
this.type = data.type;
}
}
loadShape(item, mainKey, altKey, altOverride) {
var _a, _b, _c, _d;
if (item === undefined) {
return;
}
if (item instanceof Array) {
if (!(this.options[mainKey] instanceof Array)) {
this.options[mainKey] = [];
if (!this.options[altKey] || altOverride) {
this.options[altKey] = [];
}
}
this.options[mainKey] = Utils_Utils.deepExtend((_a = this.options[mainKey]) !== null && _a !== void 0 ? _a : [], item);
if (!this.options[altKey] || altOverride) {
this.options[altKey] = Utils_Utils.deepExtend((_b = this.options[altKey]) !== null && _b !== void 0 ? _b : [], item);
}
} else {
if (this.options[mainKey] instanceof Array) {
this.options[mainKey] = {};
if (!this.options[altKey] || altOverride) {
this.options[altKey] = {};
}
}
this.options[mainKey] = Utils_Utils.deepExtend((_c = this.options[mainKey]) !== null && _c !== void 0 ? _c : {}, item);
if (!this.options[altKey] || altOverride) {
this.options[altKey] = Utils_Utils.deepExtend((_d = this.options[altKey]) !== null && _d !== void 0 ? _d : {}, item);
}
}
}
}
// CONCATENATED MODULE: ./dist/Enums/Types/StartValueType.js
var StartValueType;
(function (StartValueType) {
StartValueType["max"] = "max";
StartValueType["min"] = "min";
})(StartValueType || (StartValueType = {}));
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Size/SizeAnimation.js
class SizeAnimation_SizeAnimation {
constructor() {
this.destroy = DestroyType.none;
this.enable = false;
this.minimumValue = 0;
this.speed = 5;
this.startValue = StartValueType.max;
this.sync = false;
}
get size_min() {
return this.minimumValue;
}
set size_min(value) {
this.minimumValue = value;
}
load(data) {
var _a;
if (data === undefined) {
return;
}
if (data.destroy !== undefined) {
this.destroy = data.destroy;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
const minimumValue = (_a = data.minimumValue) !== null && _a !== void 0 ? _a : data.size_min;
if (minimumValue !== undefined) {
this.minimumValue = minimumValue;
}
if (data.speed !== undefined) {
this.speed = data.speed;
}
if (data.startValue !== undefined) {
this.startValue = data.startValue;
}
if (data.sync !== undefined) {
this.sync = data.sync;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Size/SizeRandom.js
class SizeRandom {
constructor() {
this.enable = false;
this.minimumValue = 1;
}
load(data) {
if (data === undefined) {
return;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.minimumValue !== undefined) {
this.minimumValue = data.minimumValue;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Size/Size.js
class Size_Size {
constructor() {
this.animation = new SizeAnimation_SizeAnimation();
this.random = new SizeRandom();
this.value = 3;
}
get anim() {
return this.animation;
}
set anim(value) {
this.animation = value;
}
load(data) {
var _a;
if (data === undefined) {
return;
}
const animation = (_a = data.animation) !== null && _a !== void 0 ? _a : data.anim;
if (animation !== undefined) {
this.animation.load(animation);
}
if (data.random !== undefined) {
if (typeof data.random === "boolean") {
this.random.enable = data.random;
} else {
this.random.load(data.random);
}
}
if (data.value !== undefined) {
this.value = data.value;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Rotate/RotateAnimation.js
class RotateAnimation {
constructor() {
this.enable = false;
this.speed = 0;
this.sync = false;
}
load(data) {
if (data === undefined) {
return;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.speed !== undefined) {
this.speed = data.speed;
}
if (data.sync !== undefined) {
this.sync = data.sync;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Rotate/Rotate.js
class Rotate_Rotate {
constructor() {
this.animation = new RotateAnimation();
this.direction = RotateDirection.clockwise;
this.path = false;
this.random = false;
this.value = 0;
}
load(data) {
if (data === undefined) {
return;
}
if (data.direction !== undefined) {
this.direction = data.direction;
}
this.animation.load(data.animation);
if (data.path !== undefined) {
this.path = data.path;
}
if (data.random !== undefined) {
this.random = data.random;
}
if (data.value !== undefined) {
this.value = data.value;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Shadow.js
class Shadow_Shadow {
constructor() {
this.blur = 0;
this.color = new OptionsColor();
this.enable = false;
this.offset = {
x: 0,
y: 0
};
this.color.value = "#000000";
}
load(data) {
if (data === undefined) {
return;
}
if (data.blur !== undefined) {
this.blur = data.blur;
}
this.color = OptionsColor.create(this.color, data.color);
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.offset === undefined) {
return;
}
if (data.offset.x !== undefined) {
this.offset.x = data.offset.x;
}
if (data.offset.y !== undefined) {
this.offset.y = data.offset.y;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/ColorAnimation.js
class ColorAnimation {
constructor() {
this.enable = false;
this.speed = 1;
this.sync = true;
}
load(data) {
if (data === undefined) {
return;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.speed !== undefined) {
this.speed = data.speed;
}
if (data.sync !== undefined) {
this.sync = data.sync;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/AnimatableColor.js
class AnimatableColor_AnimatableColor extends OptionsColor {
constructor() {
super();
this.animation = new ColorAnimation();
}
static create(source, data) {
const color = source !== null && source !== void 0 ? source : new AnimatableColor_AnimatableColor();
if (data !== undefined) {
color.load(typeof data === "string" ? {
value: data
} : data);
}
return color;
}
load(data) {
super.load(data);
this.animation.load(data === null || data === void 0 ? void 0 : data.animation);
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Stroke.js
class Stroke_Stroke {
constructor() {
this.width = 0;
}
load(data) {
if (data === undefined) {
return;
}
if (data.color !== undefined) {
this.color = AnimatableColor_AnimatableColor.create(this.color, data.color);
}
if (data.width !== undefined) {
this.width = data.width;
}
if (data.opacity !== undefined) {
this.opacity = data.opacity;
}
}
}
// CONCATENATED MODULE: ./dist/Enums/Modes/CollisionMode.js
var CollisionMode;
(function (CollisionMode) {
CollisionMode["absorb"] = "absorb";
CollisionMode["bounce"] = "bounce";
CollisionMode["destroy"] = "destroy";
})(CollisionMode || (CollisionMode = {}));
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Collisions.js
class Collisions_Collisions {
constructor() {
this.enable = false;
this.mode = CollisionMode.bounce;
}
load(data) {
if (data === undefined) {
return;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.mode !== undefined) {
this.mode = data.mode;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Twinkle/TwinkleValues.js
class TwinkleValues_TwinkleValues {
constructor() {
this.enable = false;
this.frequency = 0.05;
this.opacity = 1;
}
load(data) {
if (data === undefined) {
return;
}
if (data.color !== undefined) {
this.color = OptionsColor.create(this.color, data.color);
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.frequency !== undefined) {
this.frequency = data.frequency;
}
if (data.opacity !== undefined) {
this.opacity = data.opacity;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Twinkle/Twinkle.js
class Twinkle_Twinkle {
constructor() {
this.lines = new TwinkleValues_TwinkleValues();
this.particles = new TwinkleValues_TwinkleValues();
}
load(data) {
if (data === undefined) {
return;
}
this.lines.load(data.lines);
this.particles.load(data.particles);
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Particles/Particles.js
class Particles_Particles {
constructor() {
this.collisions = new Collisions_Collisions();
this.color = new AnimatableColor_AnimatableColor();
this.links = new Links_Links();
this.move = new Move_Move();
this.number = new ParticlesNumber_ParticlesNumber();
this.opacity = new Opacity_Opacity();
this.rotate = new Rotate_Rotate();
this.shadow = new Shadow_Shadow();
this.shape = new Shape_Shape();
this.size = new Size_Size();
this.stroke = new Stroke_Stroke();
this.twinkle = new Twinkle_Twinkle();
}
get line_linked() {
return this.links;
}
set line_linked(value) {
this.links = value;
}
get lineLinked() {
return this.links;
}
set lineLinked(value) {
this.links = value;
}
load(data) {
var _a, _b, _c, _d, _e, _f, _g;
if (data === undefined) {
return;
}
if (data.color !== undefined) {
this.color = AnimatableColor_AnimatableColor.create(this.color, data.color);
}
const links = (_b = (_a = data.links) !== null && _a !== void 0 ? _a : data.lineLinked) !== null && _b !== void 0 ? _b : data.line_linked;
if (links !== undefined) {
this.links.load(links);
}
this.move.load(data.move);
this.number.load(data.number);
this.opacity.load(data.opacity);
this.rotate.load(data.rotate);
this.shape.load(data.shape);
this.size.load(data.size);
this.shadow.load(data.shadow);
this.twinkle.load(data.twinkle);
const collisions = (_d = (_c = data.move) === null || _c === void 0 ? void 0 : _c.collisions) !== null && _d !== void 0 ? _d : (_e = data.move) === null || _e === void 0 ? void 0 : _e.bounce;
if (collisions !== undefined) {
this.collisions.enable = collisions;
}
this.collisions.load(data.collisions);
const strokeToLoad = (_f = data.stroke) !== null && _f !== void 0 ? _f : (_g = data.shape) === null || _g === void 0 ? void 0 : _g.stroke;
if (strokeToLoad === undefined) {
return;
}
if (strokeToLoad instanceof Array) {
this.stroke = strokeToLoad.map(s => {
const tmp = new Stroke_Stroke();
tmp.load(s);
return tmp;
});
} else {
if (this.stroke instanceof Array) {
this.stroke = new Stroke_Stroke();
}
this.stroke.load(strokeToLoad);
}
}
}
// CONCATENATED MODULE: ./dist/Core/Particle/Infecter.js
class Infecter_Infecter {
constructor(container, particle) {
this.container = container;
this.particle = particle;
}
startInfection(stage) {
const container = this.container;
const options = container.options;
const stages = options.infection.stages;
const stagesCount = stages.length;
if (stage > stagesCount || stage < 0) {
return;
}
this.infectionDelay = 0;
this.infectionDelayStage = stage;
}
updateInfectionStage(stage) {
const container = this.container;
const options = container.options;
const stagesCount = options.infection.stages.length;
if (stage > stagesCount || stage < 0 || this.infectionStage !== undefined && this.infectionStage > stage) {
return;
}
this.infectionStage = stage;
this.infectionTime = 0;
}
updateInfection(delta) {
const options = this.container.options;
const infection = options.infection;
const stages = options.infection.stages;
const stagesCount = stages.length;
if (this.infectionDelay !== undefined && this.infectionDelayStage !== undefined) {
const stage = this.infectionDelayStage;
if (stage > stagesCount || stage < 0) {
return;
}
if (this.infectionDelay > infection.delay * 1000) {
this.infectionStage = stage;
this.infectionTime = 0;
delete this.infectionDelay;
delete this.infectionDelayStage;
} else {
this.infectionDelay += delta;
}
} else {
delete this.infectionDelay;
delete this.infectionDelayStage;
}
if (this.infectionStage !== undefined && this.infectionTime !== undefined) {
const infectionStage = stages[this.infectionStage];
if (infectionStage.duration !== undefined && infectionStage.duration >= 0) {
if (this.infectionTime > infectionStage.duration * 1000) {
this.nextInfectionStage();
} else {
this.infectionTime += delta;
}
} else {
this.infectionTime += delta;
}
} else {
delete this.infectionStage;
delete this.infectionTime;
}
}
nextInfectionStage() {
const options = this.container.options;
const stagesCount = options.infection.stages.length;
if (stagesCount <= 0 || this.infectionStage === undefined) {
return;
}
this.infectionTime = 0;
if (stagesCount <= ++this.infectionStage) {
if (options.infection.cure) {
delete this.infectionStage;
delete this.infectionTime;
return;
} else {
this.infectionStage = 0;
this.infectionTime = 0;
}
}
}
}
// CONCATENATED MODULE: ./dist/Enums/Modes/HoverMode.js
var HoverMode;
(function (HoverMode) {
HoverMode["attract"] = "attract";
HoverMode["bubble"] = "bubble";
HoverMode["connect"] = "connect";
HoverMode["grab"] = "grab";
HoverMode["repulse"] = "repulse";
HoverMode["slow"] = "slow";
HoverMode["trail"] = "trail";
})(HoverMode || (HoverMode = {}));
// CONCATENATED MODULE: ./dist/Core/Particle/Mover.js
class Mover_Mover {
constructor(container, particle) {
this.container = container;
this.particle = particle;
}
move(delta) {
const particle = this.particle;
particle.bubble.inRange = false;
particle.links = [];
for (const [, plugin] of this.container.plugins) {
if (particle.destroyed) {
break;
}
if (plugin.particleUpdate) {
plugin.particleUpdate(particle, delta);
}
}
if (particle.destroyed) {
return;
}
this.moveParticle(delta);
this.moveParallax();
}
moveParticle(delta) {
var _a;
const particle = this.particle;
const particlesOptions = particle.particlesOptions;
if (!particlesOptions.move.enable) {
return;
}
const container = this.container;
const slowFactor = this.getProximitySpeedFactor();
const baseSpeed = (_a = particle.moveSpeed) !== null && _a !== void 0 ? _a : container.retina.moveSpeed;
const moveSpeed = baseSpeed / 2 * slowFactor * delta.factor;
this.applyNoise(delta);
particle.position.x += particle.velocity.horizontal * moveSpeed;
particle.position.y += particle.velocity.vertical * moveSpeed;
if (particlesOptions.move.vibrate) {
particle.position.x += Math.sin(particle.position.x * Math.cos(particle.position.y));
particle.position.y += Math.cos(particle.position.y * Math.sin(particle.position.x));
}
}
applyNoise(delta) {
const particle = this.particle;
const particlesOptions = particle.particlesOptions;
const noiseOptions = particlesOptions.move.noise;
const noiseEnabled = noiseOptions.enable;
if (!noiseEnabled) {
return;
}
const container = this.container;
if (particle.lastNoiseTime <= particle.noiseDelay) {
particle.lastNoiseTime += delta.value;
return;
}
const noise = container.noise.generate(particle);
particle.velocity.horizontal += Math.cos(noise.angle) * noise.length;
particle.velocity.horizontal = Utils_Utils.clamp(particle.velocity.horizontal, -1, 1);
particle.velocity.vertical += Math.sin(noise.angle) * noise.length;
particle.velocity.vertical = Utils_Utils.clamp(particle.velocity.vertical, -1, 1);
particle.lastNoiseTime -= particle.noiseDelay;
}
moveParallax() {
const container = this.container;
const options = container.options;
if (!options.interactivity.events.onHover.parallax.enable) {
return;
}
const particle = this.particle;
const parallaxForce = options.interactivity.events.onHover.parallax.force;
const mousePos = container.interactivity.mouse.position;
if (!mousePos) {
return;
}
const windowDimension = {
height: window.innerHeight / 2,
width: window.innerWidth / 2
};
const parallaxSmooth = options.interactivity.events.onHover.parallax.smooth;
const tmp = {
x: (mousePos.x - windowDimension.width) * (particle.size.value / parallaxForce),
y: (mousePos.y - windowDimension.height) * (particle.size.value / parallaxForce)
};
particle.offset.x += (tmp.x - particle.offset.x) / parallaxSmooth;
particle.offset.y += (tmp.y - particle.offset.y) / parallaxSmooth;
}
getProximitySpeedFactor() {
const container = this.container;
const options = container.options;
const active = Utils_Utils.isInArray(HoverMode.slow, options.interactivity.events.onHover.mode);
if (!active) {
return 1;
}
const mousePos = this.container.interactivity.mouse.position;
if (!mousePos) {
return 1;
}
const particlePos = this.particle.getPosition();
const dist = Utils_Utils.getDistance(mousePos, particlePos);
const radius = container.retina.slowModeRadius;
if (dist > radius) {
return 1;
}
const proximityFactor = dist / radius || 0;
const slowFactor = options.interactivity.modes.slow.factor;
return proximityFactor / slowFactor;
}
}
// CONCATENATED MODULE: ./dist/Core/Particle.js
class Particle_Particle {
constructor(container, position, overrideOptions) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
this.container = container;
this.fill = true;
this.close = true;
this.links = [];
this.lastNoiseTime = 0;
this.destroyed = false;
const options = container.options;
const particlesOptions = new Particles_Particles();
particlesOptions.load(options.particles);
const shapeType = particlesOptions.shape.type;
this.shape = shapeType instanceof Array ? Utils_Utils.itemFromArray(shapeType) : shapeType;
if (overrideOptions === null || overrideOptions === void 0 ? void 0 : overrideOptions.shape) {
if (overrideOptions.shape.type) {
const overrideShapeType = overrideOptions.shape.type;
this.shape = overrideShapeType instanceof Array ? Utils_Utils.itemFromArray(overrideShapeType) : overrideShapeType;
}
const shapeOptions = new Shape_Shape();
shapeOptions.load(overrideOptions.shape);
if (this.shape) {
const shapeData = shapeOptions.options[this.shape];
if (shapeData) {
this.shapeData = Utils_Utils.deepExtend({}, shapeData instanceof Array ? Utils_Utils.itemFromArray(shapeData) : shapeData);
}
}
} else {
const shapeData = particlesOptions.shape.options[this.shape];
if (shapeData) {
this.shapeData = Utils_Utils.deepExtend({}, shapeData instanceof Array ? Utils_Utils.itemFromArray(shapeData) : shapeData);
}
}
if (overrideOptions !== undefined) {
particlesOptions.load(overrideOptions);
}
if (((_a = this.shapeData) === null || _a === void 0 ? void 0 : _a.particles) !== undefined) {
particlesOptions.load((_b = this.shapeData) === null || _b === void 0 ? void 0 : _b.particles);
}
this.fill = (_d = (_c = this.shapeData) === null || _c === void 0 ? void 0 : _c.fill) !== null && _d !== void 0 ? _d : this.fill;
this.close = (_f = (_e = this.shapeData) === null || _e === void 0 ? void 0 : _e.close) !== null && _f !== void 0 ? _f : this.close;
this.particlesOptions = particlesOptions;
const noiseDelay = this.particlesOptions.move.noise.delay;
this.noiseDelay = (noiseDelay.random.enable ? Utils_Utils.randomInRange(noiseDelay.random.minimumValue, noiseDelay.value) : noiseDelay.value) * 1000;
container.retina.initParticle(this);
const color = this.particlesOptions.color;
const sizeValue = (_g = this.sizeValue) !== null && _g !== void 0 ? _g : container.retina.sizeValue;
const randomSize = typeof this.particlesOptions.size.random === "boolean" ? this.particlesOptions.size.random : this.particlesOptions.size.random.enable;
this.size = {
value: randomSize && this.randomMinimumSize !== undefined ? Utils_Utils.randomInRange(this.randomMinimumSize, sizeValue) : sizeValue
};
this.direction = this.particlesOptions.move.direction;
this.bubble = {
inRange: false
};
this.initialVelocity = this.calculateVelocity();
this.velocity = {
horizontal: this.initialVelocity.horizontal,
vertical: this.initialVelocity.vertical
};
const rotateOptions = this.particlesOptions.rotate;
const degAngle = rotateOptions.random ? Math.random() * 360 : rotateOptions.value;
this.angle = degAngle * Math.PI / 180;
this.pathAngle = Math.atan2(this.initialVelocity.vertical, this.initialVelocity.horizontal);
this.rotateDirection = rotateOptions.direction;
if (this.rotateDirection === RotateDirection.random) {
const index = Math.floor(Math.random() * 2);
this.rotateDirection = index > 0 ? RotateDirection.counterClockwise : RotateDirection.clockwise;
}
const sizeAnimation = this.particlesOptions.size.animation;
if (sizeAnimation.enable) {
switch (sizeAnimation.startValue) {
case StartValueType.min:
if (!randomSize) {
const pxRatio = container.retina.pixelRatio;
this.size.value = sizeAnimation.minimumValue * pxRatio;
}
break;
}
this.size.status = SizeAnimationStatus.increasing;
this.size.velocity = ((_h = this.sizeAnimationSpeed) !== null && _h !== void 0 ? _h : container.retina.sizeAnimationSpeed) / 100;
if (!sizeAnimation.sync) {
this.size.velocity *= Math.random();
}
}
this.color = ColorUtils_ColorUtils.colorToHsl(color);
const colorAnimation = this.particlesOptions.color.animation;
if (colorAnimation.enable) {
this.colorVelocity = colorAnimation.speed / 100;
if (!colorAnimation.sync) {
this.colorVelocity = this.colorVelocity * Math.random();
}
} else {
this.colorVelocity = 0;
}
if (colorAnimation.enable && !colorAnimation.sync && this.color) {
this.color.h = Math.random() * 360;
}
this.position = this.calcPosition(this.container, position);
this.offset = {
x: 0,
y: 0
};
if (this.particlesOptions.collisions.enable && !this.checkOverlap(position)) {
throw new Error();
}
const opacityOptions = this.particlesOptions.opacity;
const randomOpacity = opacityOptions.random;
const opacityValue = opacityOptions.value;
this.opacity = {
value: randomOpacity.enable ? Utils_Utils.randomInRange(randomOpacity.minimumValue, opacityValue) : opacityValue
};
const opacityAnimation = opacityOptions.animation;
if (opacityAnimation.enable) {
this.opacity.status = OpacityAnimationStatus.increasing;
this.opacity.velocity = opacityAnimation.speed / 100;
if (!opacityAnimation.sync) {
this.opacity.velocity *= Math.random();
}
}
let drawer = container.drawers.get(this.shape);
if (!drawer) {
drawer = Plugins.getShapeDrawer(this.shape);
if (drawer) {
container.drawers.set(this.shape, drawer);
}
}
const imageShape = this.loadImageShape(container, drawer);
if (imageShape) {
this.image = imageShape.image;
this.fill = imageShape.fill;
this.close = imageShape.close;
}
this.stroke = this.particlesOptions.stroke instanceof Array ? Utils_Utils.itemFromArray(this.particlesOptions.stroke) : this.particlesOptions.stroke;
this.strokeWidth = this.stroke.width * container.retina.pixelRatio;
this.strokeColor = ColorUtils_ColorUtils.colorToHsl(this.stroke.color);
if (typeof this.stroke.color !== "string") {
const strokeColorAnimation = (_j = this.stroke.color) === null || _j === void 0 ? void 0 : _j.animation;
if (strokeColorAnimation && this.strokeColor) {
if (strokeColorAnimation.enable) {
this.strokeColorVelocity = colorAnimation.speed / 100;
if (!strokeColorAnimation.sync) {
this.strokeColorVelocity = this.strokeColorVelocity * Math.random();
}
} else {
this.strokeColorVelocity = 0;
}
if (strokeColorAnimation.enable && !strokeColorAnimation.sync && this.color) {
this.strokeColor.h = Math.random() * 360;
}
}
}
this.shadowColor = ColorUtils_ColorUtils.colorToRgb(this.particlesOptions.shadow.color);
this.updater = new Updater_Updater(container, this);
this.infecter = new Infecter_Infecter(container, this);
this.mover = new Mover_Mover(container, this);
}
move(delta) {
this.mover.move(delta);
}
update(delta) {
this.updater.update(delta);
}
draw(delta) {
this.container.canvas.drawParticle(this, delta);
}
isOverlapping() {
const container = this.container;
let collisionFound = false;
const pos1 = this.getPosition();
for (const p2 of container.particles.array.filter(t => t != this)) {
const pos2 = p2.getPosition();
const dist = Utils_Utils.getDistance(pos1, pos2);
if (dist <= this.size.value + p2.size.value) {
collisionFound = true;
break;
}
}
return collisionFound;
}
getPosition() {
return {
x: this.position.x + this.offset.x,
y: this.position.y + this.offset.y
};
}
getFillColor() {
var _a;
return (_a = this.bubble.color) !== null && _a !== void 0 ? _a : this.color;
}
getStrokeColor() {
var _a, _b;
return (_b = (_a = this.bubble.color) !== null && _a !== void 0 ? _a : this.strokeColor) !== null && _b !== void 0 ? _b : this.color;
}
destroy() {
this.destroyed = true;
}
checkOverlap(position, iterations = 0) {
const container = this.container;
if (!container.particles.count) {
return true;
}
if (iterations >= container.particles.count) {
return false;
}
const overlapping = this.isOverlapping();
if (overlapping) {
this.position.x = position ? position.x : Math.random() * container.canvas.size.width;
this.position.y = position ? position.y : Math.random() * container.canvas.size.height;
return this.checkOverlap(undefined, iterations + 1);
}
return true;
}
calcPosition(container, position) {
var _a, _b;
for (const [, plugin] of container.plugins) {
const pluginPos = plugin.particlePosition !== undefined ? plugin.particlePosition(position, this) : undefined;
if (pluginPos !== undefined) {
return Utils_Utils.deepExtend({}, pluginPos);
}
}
const pos = {
x: (_a = position === null || position === void 0 ? void 0 : position.x) !== null && _a !== void 0 ? _a : Math.random() * container.canvas.size.width,
y: (_b = position === null || position === void 0 ? void 0 : position.y) !== null && _b !== void 0 ? _b : Math.random() * container.canvas.size.height
};
const outMode = this.particlesOptions.move.outMode;
if (Utils_Utils.isInArray(outMode, OutMode.bounce) || Utils_Utils.isInArray(outMode, OutMode.bounceHorizontal)) {
if (pos.x > container.canvas.size.width - this.size.value * 2) {
pos.x -= this.size.value;
} else if (pos.x < this.size.value * 2) {
pos.x += this.size.value;
}
}
if (Utils_Utils.isInArray(outMode, OutMode.bounce) || Utils_Utils.isInArray(outMode, OutMode.bounceVertical)) {
if (pos.y > container.canvas.size.height - this.size.value * 2) {
pos.y -= this.size.value;
} else if (pos.y < this.size.value * 2) {
pos.y += this.size.value;
}
}
return pos;
}
calculateVelocity() {
const baseVelocity = Utils_Utils.getParticleBaseVelocity(this);
const res = {
horizontal: 0,
vertical: 0
};
const moveOptions = this.particlesOptions.move;
let rad;
let radOffset = Math.PI / 4;
if (typeof moveOptions.angle === "number") {
rad = Math.PI / 180 * moveOptions.angle;
} else {
rad = Math.PI / 180 * moveOptions.angle.value;
radOffset = Math.PI / 180 * moveOptions.angle.offset;
}
const range = {
left: Math.sin(radOffset + rad / 2) - Math.sin(radOffset - rad / 2),
right: Math.cos(radOffset + rad / 2) - Math.cos(radOffset - rad / 2)
};
if (moveOptions.straight) {
res.horizontal = baseVelocity.x;
res.vertical = baseVelocity.y;
if (moveOptions.random) {
res.horizontal += Utils_Utils.randomInRange(range.left, range.right) / 2;
res.vertical += Utils_Utils.randomInRange(range.left, range.right) / 2;
}
} else {
res.horizontal = baseVelocity.x + Utils_Utils.randomInRange(range.left, range.right) / 2;
res.vertical = baseVelocity.y + Utils_Utils.randomInRange(range.left, range.right) / 2;
}
return res;
}
loadImageShape(container, drawer) {
var _a, _b, _c, _d;
if (!(this.shape === ShapeType.image || this.shape === ShapeType.images)) {
return;
}
const shape = this.particlesOptions.shape;
const imageDrawer = drawer;
const imagesOptions = shape.options[this.shape];
const images = imageDrawer.getImages(container).images;
const image = Utils_Utils.itemFromArray(images);
const optionsImage = imagesOptions instanceof Array ? imagesOptions.find(t => t.src === image.source) : imagesOptions;
const color = this.getFillColor();
let imageRes;
if ((image === null || image === void 0 ? void 0 : image.svgData) !== undefined && optionsImage.replaceColor && color) {
const svgColoredData = ColorUtils_ColorUtils.replaceColorSvg(image, color, this.opacity.value);
const svg = new Blob([svgColoredData], {
type: "image/svg+xml"
});
const domUrl = window.URL || window.webkitURL || window;
const url = domUrl.createObjectURL(svg);
const img = new Image();
imageRes = {
data: image,
loaded: false,
ratio: optionsImage.width / optionsImage.height,
replaceColor: (_a = optionsImage.replaceColor) !== null && _a !== void 0 ? _a : optionsImage.replace_color,
source: optionsImage.src
};
img.addEventListener("load", () => {
if (this.image) {
this.image.loaded = true;
image.element = img;
}
domUrl.revokeObjectURL(url);
});
img.addEventListener("error", () => {
domUrl.revokeObjectURL(url);
Utils_Utils.loadImage(optionsImage.src).then(img2 => {
if (this.image) {
image.element = img2.element;
this.image.loaded = true;
}
});
});
img.src = url;
} else {
imageRes = {
data: image,
loaded: true,
ratio: optionsImage.width / optionsImage.height,
replaceColor: (_b = optionsImage.replaceColor) !== null && _b !== void 0 ? _b : optionsImage.replace_color,
source: optionsImage.src
};
}
if (!imageRes.ratio) {
imageRes.ratio = 1;
}
const fill = (_c = optionsImage.fill) !== null && _c !== void 0 ? _c : this.fill;
const close = (_d = optionsImage.close) !== null && _d !== void 0 ? _d : this.close;
return {
image: imageRes,
fill,
close
};
}
}
// CONCATENATED MODULE: ./dist/Utils/Range.js
class Range {
constructor(x, y) {
this.position = {
x: x,
y: y
};
}
}
// CONCATENATED MODULE: ./dist/Utils/Rectangle.js
class Rectangle_Rectangle extends Range {
constructor(x, y, width, height) {
super(x, y);
this.size = {
height: height,
width: width
};
}
contains(point) {
const w = this.size.width;
const h = this.size.height;
const pos = this.position;
return point.x >= pos.x && point.x <= pos.x + w && point.y >= pos.y && point.y <= pos.y + h;
}
intersects(range) {
const rect = range;
const circle = range;
const w = this.size.width;
const h = this.size.height;
const pos1 = this.position;
const pos2 = range.position;
if (circle.radius !== undefined) {
return circle.intersects(this);
} else if (rect.size !== undefined) {
const size2 = rect.size;
const w2 = size2.width;
const h2 = size2.height;
return pos2.x < pos1.x + w && pos2.x + w2 > pos1.x && pos2.y < pos1.y + h && pos2.y + h2 > pos1.y;
}
return false;
}
}
// CONCATENATED MODULE: ./dist/Utils/QuadTree.js
class QuadTree_QuadTree {
constructor(rectangle, capacity) {
this.rectangle = rectangle;
this.capacity = capacity;
this.points = [];
this.divided = false;
}
subdivide() {
const x = this.rectangle.position.x;
const y = this.rectangle.position.y;
const w = this.rectangle.size.width;
const h = this.rectangle.size.height;
const capacity = this.capacity;
this.northEast = new QuadTree_QuadTree(new Rectangle_Rectangle(x, y, w / 2, h / 2), capacity);
this.northWest = new QuadTree_QuadTree(new Rectangle_Rectangle(x + w / 2, y, w / 2, h / 2), capacity);
this.southEast = new QuadTree_QuadTree(new Rectangle_Rectangle(x, y + h / 2, w / 2, h / 2), capacity);
this.southWest = new QuadTree_QuadTree(new Rectangle_Rectangle(x + w / 2, y + h / 2, w / 2, h / 2), capacity);
this.divided = true;
}
insert(point) {
var _a, _b, _c, _d, _e;
if (!this.rectangle.contains(point.position)) {
return false;
}
if (this.points.length < this.capacity) {
this.points.push(point);
return true;
}
if (!this.divided) {
this.subdivide();
}
return (_e = ((_a = this.northEast) === null || _a === void 0 ? void 0 : _a.insert(point)) || ((_b = this.northWest) === null || _b === void 0 ? void 0 : _b.insert(point)) || ((_c = this.southEast) === null || _c === void 0 ? void 0 : _c.insert(point)) || ((_d = this.southWest) === null || _d === void 0 ? void 0 : _d.insert(point))) !== null && _e !== void 0 ? _e : false;
}
query(range, found) {
var _a, _b, _c, _d;
const res = found !== null && found !== void 0 ? found : [];
if (!range.intersects(this.rectangle)) {
return [];
} else {
for (const p of this.points.filter(p => range.contains(p.position))) {
res.push(p.particle);
}
if (this.divided) {
(_a = this.northEast) === null || _a === void 0 ? void 0 : _a.query(range, res);
(_b = this.northWest) === null || _b === void 0 ? void 0 : _b.query(range, res);
(_c = this.southEast) === null || _c === void 0 ? void 0 : _c.query(range, res);
(_d = this.southWest) === null || _d === void 0 ? void 0 : _d.query(range, res);
}
}
return res;
}
}
// CONCATENATED MODULE: ./dist/Utils/Point.js
class Point {
constructor(position, particle) {
this.position = position;
this.particle = particle;
}
}
// CONCATENATED MODULE: ./dist/Utils/Circle.js
class Circle_Circle extends Range {
constructor(x, y, radius) {
super(x, y);
this.radius = radius;
}
contains(point) {
const d = Math.pow(point.x - this.position.x, 2) + Math.pow(point.y - this.position.y, 2);
return d <= this.radius * this.radius;
}
intersects(range) {
const rect = range;
const circle = range;
const pos1 = this.position;
const pos2 = range.position;
const xDist = Math.abs(pos2.x - pos1.x);
const yDist = Math.abs(pos2.y - pos1.y);
const r = this.radius;
if (circle.radius !== undefined) {
const rSum = r + circle.radius;
const dist = Math.sqrt(xDist * xDist + yDist + yDist);
return rSum > dist;
} else if (rect.size !== undefined) {
const w = rect.size.width;
const h = rect.size.height;
const edges = Math.pow(xDist - w, 2) + Math.pow(yDist - h, 2);
if (xDist > r + w || yDist > r + h) {
return false;
}
if (xDist <= w || yDist <= h) {
return true;
}
return edges <= r * r;
}
return false;
}
}
// CONCATENATED MODULE: ./dist/Core/Particle/Interactions/Mouse/Grabber.js
class Grabber_Grabber {
constructor(container) {
this.container = container;
}
isEnabled() {
const container = this.container;
const mouse = container.interactivity.mouse;
const events = container.options.interactivity.events;
if (!(events.onHover.enable && mouse.position)) {
return false;
}
const hoverMode = events.onHover.mode;
return Utils_Utils.isInArray(HoverMode.grab, hoverMode);
}
reset() {}
interact() {
var _a, _b;
const container = this.container;
const options = container.options;
const interactivity = options.interactivity;
if (interactivity.events.onHover.enable && container.interactivity.status === Constants.mouseMoveEvent) {
const mousePos = container.interactivity.mouse.position;
if (mousePos === undefined) {
return;
}
const distance = container.retina.grabModeDistance;
const query = container.particles.quadTree.query(new Circle_Circle(mousePos.x, mousePos.y, distance));
for (const particle of query) {
const pos = particle.getPosition();
const distance = Utils_Utils.getDistance(pos, mousePos);
if (distance <= container.retina.grabModeDistance) {
const grabLineOptions = interactivity.modes.grab.links;
const lineOpacity = grabLineOptions.opacity;
const grabDistance = container.retina.grabModeDistance;
const opacityLine = lineOpacity - distance * lineOpacity / grabDistance;
if (opacityLine > 0) {
const optColor = (_a = grabLineOptions.color) !== null && _a !== void 0 ? _a : particle.particlesOptions.links.color;
if (!container.particles.grabLineColor) {
container.particles.grabLineColor = optColor === Constants.randomColorValue || ((_b = optColor) === null || _b === void 0 ? void 0 : _b.value) === Constants.randomColorValue ? Constants.randomColorValue : ColorUtils_ColorUtils.colorToRgb(optColor);
}
let colorLine;
if (container.particles.grabLineColor === Constants.randomColorValue) {
colorLine = ColorUtils_ColorUtils.getRandomRgbColor();
} else {
colorLine = container.particles.grabLineColor;
}
if (colorLine === undefined) {
return;
}
container.canvas.drawGrabLine(particle, colorLine, opacityLine, mousePos);
}
}
}
}
}
}
// CONCATENATED MODULE: ./dist/Enums/Modes/DivMode.js
var DivMode;
(function (DivMode) {
DivMode["bubble"] = "bubble";
DivMode["repulse"] = "repulse";
})(DivMode || (DivMode = {}));
// CONCATENATED MODULE: ./dist/Enums/Modes/ClickMode.js
var ClickMode;
(function (ClickMode) {
ClickMode["attract"] = "attract";
ClickMode["bubble"] = "bubble";
ClickMode["push"] = "push";
ClickMode["remove"] = "remove";
ClickMode["repulse"] = "repulse";
ClickMode["pause"] = "pause";
ClickMode["trail"] = "trail";
})(ClickMode || (ClickMode = {}));
// CONCATENATED MODULE: ./dist/Enums/Types/DivType.js
var DivType;
(function (DivType) {
DivType["circle"] = "circle";
DivType["rectangle"] = "rectangle";
})(DivType || (DivType = {}));
// CONCATENATED MODULE: ./dist/Core/Particle/Interactions/Mouse/Repulser.js
class Repulser_Repulser {
constructor(container) {
this.container = container;
}
isEnabled() {
const container = this.container;
const options = container.options;
const mouse = container.interactivity.mouse;
const events = options.interactivity.events;
const divs = events.onDiv;
const divRepulse = Utils_Utils.isDivModeEnabled(DivMode.repulse, divs);
if (!(divRepulse || events.onHover.enable && mouse.position || events.onClick.enable && mouse.clickPosition)) {
return false;
}
const hoverMode = events.onHover.mode;
const clickMode = events.onClick.mode;
return Utils_Utils.isInArray(HoverMode.repulse, hoverMode) || Utils_Utils.isInArray(ClickMode.repulse, clickMode) || divRepulse;
}
reset() {}
interact() {
const container = this.container;
const options = container.options;
const mouseMoveStatus = container.interactivity.status === Constants.mouseMoveEvent;
const events = options.interactivity.events;
const hoverEnabled = events.onHover.enable;
const hoverMode = events.onHover.mode;
const clickEnabled = events.onClick.enable;
const clickMode = events.onClick.mode;
const divs = events.onDiv;
if (mouseMoveStatus && hoverEnabled && Utils_Utils.isInArray(HoverMode.repulse, hoverMode)) {
this.hoverRepulse();
} else if (clickEnabled && Utils_Utils.isInArray(ClickMode.repulse, clickMode)) {
this.clickRepulse();
} else {
Utils_Utils.divModeExecute(DivMode.repulse, divs, (id, div) => this.singleDivRepulse(id, div));
}
}
singleDivRepulse(id, div) {
const container = this.container;
const elem = document.getElementById(id);
if (!elem) {
return;
}
const pxRatio = container.retina.pixelRatio;
const pos = {
x: (elem.offsetLeft + elem.offsetWidth / 2) * pxRatio,
y: (elem.offsetTop + elem.offsetHeight / 2) * pxRatio
};
const repulseRadius = elem.offsetWidth / 2 * pxRatio;
const area = div.type === DivType.circle ? new Circle_Circle(pos.x, pos.y, repulseRadius) : new Rectangle_Rectangle(elem.offsetLeft * pxRatio, elem.offsetTop * pxRatio, elem.offsetWidth * pxRatio, elem.offsetHeight * pxRatio);
const divs = container.options.interactivity.modes.repulse.divs;
const divRepulse = Utils_Utils.divMode(divs, id);
this.processRepulse(pos, repulseRadius, area, divRepulse);
}
hoverRepulse() {
const container = this.container;
const mousePos = container.interactivity.mouse.position;
if (!mousePos) {
return;
}
const repulseRadius = container.retina.repulseModeDistance;
this.processRepulse(mousePos, repulseRadius, new Circle_Circle(mousePos.x, mousePos.y, repulseRadius));
}
processRepulse(position, repulseRadius, area, divRepulse) {
var _a;
const container = this.container;
const query = container.particles.quadTree.query(area);
for (const particle of query) {
const {
dx,
dy,
distance
} = Utils_Utils.getDistances(particle.position, position);
const normVec = {
x: dx / distance,
y: dy / distance
};
const velocity = ((_a = divRepulse === null || divRepulse === void 0 ? void 0 : divRepulse.speed) !== null && _a !== void 0 ? _a : container.options.interactivity.modes.repulse.speed) * 100;
const repulseFactor = Utils_Utils.clamp((1 - Math.pow(distance / repulseRadius, 2)) * velocity, 0, 50);
particle.position.x = particle.position.x + normVec.x * repulseFactor;
particle.position.y = particle.position.y + normVec.y * repulseFactor;
}
}
clickRepulse() {
const container = this.container;
if (!container.repulse.finish) {
if (!container.repulse.count) {
container.repulse.count = 0;
}
container.repulse.count++;
if (container.repulse.count === container.particles.count) {
container.repulse.finish = true;
}
}
if (container.repulse.clicking) {
const repulseDistance = container.retina.repulseModeDistance;
const repulseRadius = Math.pow(repulseDistance / 6, 3);
const mouseClickPos = container.interactivity.mouse.clickPosition;
if (mouseClickPos === undefined) {
return;
}
const range = new Circle_Circle(mouseClickPos.x, mouseClickPos.y, repulseRadius);
const query = container.particles.quadTree.query(range);
for (const particle of query) {
const {
dx,
dy,
distance
} = Utils_Utils.getDistances(mouseClickPos, particle.position);
const d = distance * distance;
const velocity = container.options.interactivity.modes.repulse.speed;
const force = -repulseRadius * velocity / d;
if (d <= repulseRadius) {
container.repulse.particles.push(particle);
const angle = Math.atan2(dy, dx);
particle.velocity.horizontal = force * Math.cos(angle);
particle.velocity.vertical = force * Math.sin(angle);
}
}
} else if (container.repulse.clicking === false) {
for (const particle of container.repulse.particles) {
particle.velocity.horizontal = particle.initialVelocity.horizontal;
particle.velocity.vertical = particle.initialVelocity.vertical;
}
container.repulse.particles = [];
}
}
}
// CONCATENATED MODULE: ./dist/Enums/Types/ProcessBubbleType.js
var ProcessBubbleType;
(function (ProcessBubbleType) {
ProcessBubbleType["color"] = "color";
ProcessBubbleType["opacity"] = "opacity";
ProcessBubbleType["size"] = "size";
})(ProcessBubbleType || (ProcessBubbleType = {}));
// CONCATENATED MODULE: ./dist/Core/Particle/Interactions/Mouse/Bubbler.js
class Bubbler_Bubbler {
constructor(container) {
this.container = container;
}
static calculateBubbleValue(particleValue, modeValue, optionsValue, ratio) {
if (modeValue > optionsValue) {
const size = particleValue + (modeValue - optionsValue) * ratio;
return Utils_Utils.clamp(size, particleValue, modeValue);
} else if (modeValue < optionsValue) {
const size = particleValue - (optionsValue - modeValue) * ratio;
return Utils_Utils.clamp(size, modeValue, particleValue);
}
}
isEnabled() {
const container = this.container;
const options = container.options;
const mouse = container.interactivity.mouse;
const events = options.interactivity.events;
const divs = events.onDiv;
const divBubble = Utils_Utils.isDivModeEnabled(DivMode.bubble, divs);
if (!(divBubble || events.onHover.enable && mouse.position || events.onClick.enable && mouse.clickPosition)) {
return false;
}
const hoverMode = events.onHover.mode;
const clickMode = events.onClick.mode;
return Utils_Utils.isInArray(HoverMode.bubble, hoverMode) || Utils_Utils.isInArray(ClickMode.bubble, clickMode) || divBubble;
}
reset(particle, force) {
if (!particle.bubble.inRange || force) {
delete particle.bubble.divId;
delete particle.bubble.opacity;
delete particle.bubble.radius;
delete particle.bubble.color;
}
}
interact() {
const options = this.container.options;
const events = options.interactivity.events;
const onHover = events.onHover;
const onClick = events.onClick;
const hoverEnabled = onHover.enable;
const hoverMode = onHover.mode;
const clickEnabled = onClick.enable;
const clickMode = onClick.mode;
const divs = events.onDiv;
if (hoverEnabled && Utils_Utils.isInArray(HoverMode.bubble, hoverMode)) {
this.hoverBubble();
} else if (clickEnabled && Utils_Utils.isInArray(ClickMode.bubble, clickMode)) {
this.clickBubble();
} else {
Utils_Utils.divModeExecute(DivMode.bubble, divs, (id, div) => this.singleDivHover(id, div));
}
}
singleDivHover(id, div) {
const container = this.container;
const elem = document.getElementById(id);
if (!elem) {
return;
}
const pxRatio = container.retina.pixelRatio;
const pos = {
x: (elem.offsetLeft + elem.offsetWidth / 2) * pxRatio,
y: (elem.offsetTop + elem.offsetHeight / 2) * pxRatio
};
const repulseRadius = elem.offsetWidth / 2 * pxRatio;
const area = div.type === DivType.circle ? new Circle_Circle(pos.x, pos.y, repulseRadius) : new Rectangle_Rectangle(elem.offsetLeft * pxRatio, elem.offsetTop * pxRatio, elem.offsetWidth * pxRatio, elem.offsetHeight * pxRatio);
const query = container.particles.quadTree.query(area);
for (const particle of query.filter(t => area.contains(t.getPosition()))) {
particle.bubble.inRange = true;
const divs = container.options.interactivity.modes.bubble.divs;
const divBubble = Utils_Utils.divMode(divs, id);
if (!particle.bubble.divId || particle.bubble.divId !== id) {
this.reset(particle, true);
particle.bubble.divId = id;
}
this.hoverBubbleSize(particle, 1, divBubble);
this.hoverBubbleOpacity(particle, 1, divBubble);
this.hoverBubbleColor(particle, divBubble);
}
}
process(particle, distMouse, timeSpent, data) {
const container = this.container;
const bubbleParam = data.bubbleObj.optValue;
if (bubbleParam === undefined) {
return;
}
const options = container.options;
const bubbleDuration = options.interactivity.modes.bubble.duration;
const bubbleDistance = container.retina.bubbleModeDistance;
const particlesParam = data.particlesObj.optValue;
const pObjBubble = data.bubbleObj.value;
const pObj = data.particlesObj.value || 0;
const type = data.type;
if (bubbleParam !== particlesParam) {
if (!container.bubble.durationEnd) {
if (distMouse <= bubbleDistance) {
const obj = pObjBubble !== null && pObjBubble !== void 0 ? pObjBubble : pObj;
if (obj !== bubbleParam) {
const value = pObj - timeSpent * (pObj - bubbleParam) / bubbleDuration;
if (type === ProcessBubbleType.size) {
particle.bubble.radius = value;
}
if (type === ProcessBubbleType.opacity) {
particle.bubble.opacity = value;
}
}
} else {
if (type === ProcessBubbleType.size) {
delete particle.bubble.radius;
}
if (type === ProcessBubbleType.opacity) {
delete particle.bubble.opacity;
}
}
} else if (pObjBubble) {
if (type === ProcessBubbleType.size) {
delete particle.bubble.radius;
}
if (type === ProcessBubbleType.opacity) {
delete particle.bubble.opacity;
}
}
}
}
clickBubble() {
var _a;
const container = this.container;
const options = container.options;
const mouseClickPos = container.interactivity.mouse.clickPosition;
if (mouseClickPos === undefined) {
return;
}
const distance = container.retina.bubbleModeDistance;
const query = container.particles.quadTree.query(new Circle_Circle(mouseClickPos.x, mouseClickPos.y, distance));
for (const particle of query) {
particle.bubble.inRange = true;
const pos = particle.getPosition();
const distMouse = Utils_Utils.getDistance(pos, mouseClickPos);
const timeSpent = (new Date().getTime() - (container.interactivity.mouse.clickTime || 0)) / 1000;
if (container.bubble.clicking) {
if (timeSpent > options.interactivity.modes.bubble.duration) {
container.bubble.durationEnd = true;
}
if (timeSpent > options.interactivity.modes.bubble.duration * 2) {
container.bubble.clicking = false;
container.bubble.durationEnd = false;
}
const sizeData = {
bubbleObj: {
optValue: container.retina.bubbleModeSize,
value: particle.bubble.radius
},
particlesObj: {
optValue: (_a = particle.sizeValue) !== null && _a !== void 0 ? _a : container.retina.sizeValue,
value: particle.size.value
},
type: ProcessBubbleType.size
};
this.process(particle, distMouse, timeSpent, sizeData);
const opacityData = {
bubbleObj: {
optValue: options.interactivity.modes.bubble.opacity,
value: particle.bubble.opacity
},
particlesObj: {
optValue: particle.particlesOptions.opacity.value,
value: particle.opacity.value
},
type: ProcessBubbleType.opacity
};
this.process(particle, distMouse, timeSpent, opacityData);
if (!container.bubble.durationEnd) {
if (distMouse <= container.retina.bubbleModeDistance) {
this.hoverBubbleColor(particle);
} else {
delete particle.bubble.color;
}
} else {
delete particle.bubble.color;
}
}
}
}
hoverBubble() {
const container = this.container;
const mousePos = container.interactivity.mouse.position;
if (mousePos === undefined) {
return;
}
const distance = container.retina.bubbleModeDistance;
const query = container.particles.quadTree.query(new Circle_Circle(mousePos.x, mousePos.y, distance));
for (const particle of query) {
particle.bubble.inRange = true;
const pos = particle.getPosition();
const distance = Utils_Utils.getDistance(pos, mousePos);
const ratio = 1 - distance / container.retina.bubbleModeDistance;
if (distance <= container.retina.bubbleModeDistance) {
if (ratio >= 0 && container.interactivity.status === Constants.mouseMoveEvent) {
this.hoverBubbleSize(particle, ratio);
this.hoverBubbleOpacity(particle, ratio);
this.hoverBubbleColor(particle);
}
} else {
this.reset(particle);
}
if (container.interactivity.status === Constants.mouseLeaveEvent) {
this.reset(particle);
}
}
}
hoverBubbleSize(particle, ratio, divBubble) {
var _a;
const container = this.container;
const modeSize = (divBubble === null || divBubble === void 0 ? void 0 : divBubble.size) ? divBubble.size * container.retina.pixelRatio : container.retina.bubbleModeSize;
if (modeSize === undefined) {
return;
}
const optSize = (_a = particle.sizeValue) !== null && _a !== void 0 ? _a : container.retina.sizeValue;
const pSize = particle.size.value;
const size = Bubbler_Bubbler.calculateBubbleValue(pSize, modeSize, optSize, ratio);
if (size !== undefined) {
particle.bubble.radius = size;
}
}
hoverBubbleOpacity(particle, ratio, divBubble) {
var _a;
const options = this.container.options;
const modeOpacity = (_a = divBubble === null || divBubble === void 0 ? void 0 : divBubble.opacity) !== null && _a !== void 0 ? _a : options.interactivity.modes.bubble.opacity;
if (modeOpacity === undefined) {
return;
}
const optOpacity = particle.particlesOptions.opacity.value;
const pOpacity = particle.opacity.value;
const opacity = Bubbler_Bubbler.calculateBubbleValue(pOpacity, modeOpacity, optOpacity, ratio);
if (opacity !== undefined) {
particle.bubble.opacity = opacity;
}
}
hoverBubbleColor(particle, divBubble) {
var _a;
const options = this.container.options;
if (particle.bubble.color === undefined) {
const modeColor = (_a = divBubble === null || divBubble === void 0 ? void 0 : divBubble.color) !== null && _a !== void 0 ? _a : options.interactivity.modes.bubble.color;
if (modeColor === undefined) {
return;
}
const bubbleColor = modeColor instanceof Array ? Utils_Utils.itemFromArray(modeColor) : modeColor;
particle.bubble.color = ColorUtils_ColorUtils.colorToHsl(bubbleColor);
}
}
}
// CONCATENATED MODULE: ./dist/Core/Particle/Interactions/Mouse/Connector.js
class Connector_Connector {
constructor(container) {
this.container = container;
}
isEnabled() {
const container = this.container;
const mouse = container.interactivity.mouse;
const events = container.options.interactivity.events;
if (!(events.onHover.enable && mouse.position)) {
return false;
}
const hoverMode = events.onHover.mode;
return Utils_Utils.isInArray(HoverMode.connect, hoverMode);
}
reset() {}
interact() {
const container = this.container;
const options = container.options;
if (options.interactivity.events.onHover.enable && container.interactivity.status === "mousemove") {
const mousePos = container.interactivity.mouse.position;
if (!mousePos) {
return;
}
const distance = Math.abs(container.retina.connectModeRadius);
const query = container.particles.quadTree.query(new Circle_Circle(mousePos.x, mousePos.y, distance));
let i = 0;
for (const p1 of query) {
const pos1 = p1.getPosition();
for (const p2 of query.slice(i + 1)) {
const pos2 = p2.getPosition();
const distMax = Math.abs(container.retina.connectModeDistance);
const xDiff = Math.abs(pos1.x - pos2.x);
const yDiff = Math.abs(pos1.y - pos2.y);
if (xDiff < distMax && yDiff < distMax) {
container.canvas.drawConnectLine(p1, p2);
}
}
++i;
}
}
}
}
// CONCATENATED MODULE: ./dist/Utils/CircleWarp.js
class CircleWarp_CircleWarp extends Circle_Circle {
constructor(x, y, radius, canvasSize) {
super(x, y, radius);
this.canvasSize = canvasSize;
this.canvasSize = {
height: canvasSize.height,
width: canvasSize.width
};
}
contains(point) {
if (super.contains(point)) {
return true;
}
const posNE = {
x: point.x - this.canvasSize.width,
y: point.y
};
if (super.contains(posNE)) {
return true;
}
const posSE = {
x: point.x - this.canvasSize.width,
y: point.y - this.canvasSize.height
};
if (super.contains(posSE)) {
return true;
}
const posSW = {
x: point.x,
y: point.y - this.canvasSize.height
};
return super.contains(posSW);
}
intersects(range) {
if (super.intersects(range)) {
return true;
}
const rect = range;
const circle = range;
const newPos = {
x: range.position.x - this.canvasSize.width,
y: range.position.y - this.canvasSize.height
};
if (circle.radius !== undefined) {
const biggerCircle = new Circle_Circle(newPos.x, newPos.y, circle.radius * 2);
return super.intersects(biggerCircle);
} else if (rect.size !== undefined) {
const rectSW = new Rectangle_Rectangle(newPos.x, newPos.y, rect.size.width * 2, rect.size.height * 2);
return super.intersects(rectSW);
}
return false;
}
}
// CONCATENATED MODULE: ./dist/Core/Particle/Interactions/Particles/Linker.js
class Linker_Linker {
constructor(container) {
this.container = container;
}
isEnabled(particle) {
return particle.particlesOptions.links.enable;
}
reset() {}
interact(p1) {
var _a;
const container = this.container;
const linkOpt1 = p1.particlesOptions.links;
const optOpacity = linkOpt1.opacity;
const optDistance = (_a = p1.linksDistance) !== null && _a !== void 0 ? _a : container.retina.linksDistance;
const canvasSize = container.canvas.size;
const warp = linkOpt1.warp;
const pos1 = p1.getPosition();
const range = warp ? new CircleWarp_CircleWarp(pos1.x, pos1.y, optDistance, canvasSize) : new Circle_Circle(pos1.x, pos1.y, optDistance);
const query = container.particles.quadTree.query(range);
for (const p2 of query) {
const linkOpt2 = p2.particlesOptions.links;
if (p1 === p2 || !linkOpt2.enable || linkOpt1.id !== linkOpt2.id) {
continue;
}
const pos2 = p2.getPosition();
let distance = Utils_Utils.getDistance(pos1, pos2);
if (warp) {
if (distance > optDistance) {
const pos2NE = {
x: pos2.x - canvasSize.width,
y: pos2.y
};
distance = Utils_Utils.getDistance(pos1, pos2NE);
if (distance > optDistance) {
const pos2SE = {
x: pos2.x - canvasSize.width,
y: pos2.y - canvasSize.height
};
distance = Utils_Utils.getDistance(pos1, pos2SE);
if (distance > optDistance) {
const pos2SW = {
x: pos2.x,
y: pos2.y - canvasSize.height
};
distance = Utils_Utils.getDistance(pos1, pos2SW);
}
}
}
}
if (distance > optDistance) {
return;
}
const opacityLine = optOpacity - distance * optOpacity / optDistance;
if (opacityLine > 0) {
const linksOptions = p1.particlesOptions.links;
let linkColor = linksOptions.id !== undefined ? container.particles.linksColors.get(linksOptions.id) : container.particles.linksColor;
if (!linkColor) {
const optColor = linksOptions.color;
const color = typeof optColor === "string" ? optColor : optColor.value;
if (color === Constants.randomColorValue) {
if (linksOptions.consent) {
linkColor = ColorUtils_ColorUtils.colorToRgb({
value: color
});
} else if (linksOptions.blink) {
linkColor = Constants.randomColorValue;
} else {
linkColor = Constants.midColorValue;
}
} else {
linkColor = ColorUtils_ColorUtils.colorToRgb({
value: color
});
}
if (linksOptions.id !== undefined) {
container.particles.linksColors.set(linksOptions.id, linkColor);
} else {
container.particles.linksColor = linkColor;
}
}
if (p2.links.map(t => t.destination).indexOf(p1) === -1 && p1.links.map(t => t.destination).indexOf(p2) === -1) {
p1.links.push({
destination: p2,
opacity: opacityLine
});
}
}
}
}
}
// CONCATENATED MODULE: ./dist/Core/Particle/Interactions/Particles/Attractor.js
class Attractor_Attractor {
constructor(container) {
this.container = container;
}
interact(p1) {
var _a;
const container = this.container;
const options = container.options;
const distance = (_a = p1.linksDistance) !== null && _a !== void 0 ? _a : container.retina.linksDistance;
const pos1 = p1.getPosition();
const query = container.particles.quadTree.query(new Circle_Circle(pos1.x, pos1.y, distance));
for (const p2 of query) {
if (p1 === p2 || p2.particlesOptions.move.attract.enable) {
continue;
}
const pos2 = p2.getPosition();
const {
dx,
dy
} = Utils_Utils.getDistances(pos1, pos2);
const rotate = options.particles.move.attract.rotate;
const ax = dx / (rotate.x * 1000);
const ay = dy / (rotate.y * 1000);
p1.velocity.horizontal -= ax;
p1.velocity.vertical -= ay;
p2.velocity.horizontal += ax;
p2.velocity.vertical += ay;
}
}
isEnabled(particle) {
return particle.particlesOptions.move.attract.enable;
}
reset() {}
}
// CONCATENATED MODULE: ./dist/Core/Particle/Interactions/Particles/Collider.js
class Collider_Collider {
constructor(container) {
this.container = container;
}
static rotate(velocity, angle) {
return {
horizontal: velocity.horizontal * Math.cos(angle) - velocity.vertical * Math.sin(angle),
vertical: velocity.horizontal * Math.sin(angle) + velocity.vertical * Math.cos(angle)
};
}
static collisionVelocity(v1, v2, m1, m2) {
return {
horizontal: v1.horizontal * (m1 - m2) / (m1 + m2) + v2.horizontal * 2 * m2 / (m1 + m2),
vertical: v1.vertical
};
}
static bounce(p1, p2) {
const pos1 = p1.getPosition();
const pos2 = p2.getPosition();
const xVelocityDiff = p1.velocity.horizontal - p2.velocity.horizontal;
const yVelocityDiff = p1.velocity.vertical - p2.velocity.vertical;
const xDist = pos2.x - pos1.x;
const yDist = pos2.y - pos1.y;
if (xVelocityDiff * xDist + yVelocityDiff * yDist >= 0) {
const angle = -Math.atan2(pos2.y - pos1.y, pos2.x - pos1.x);
const m1 = p1.size.value;
const m2 = p2.size.value;
const u1 = Collider_Collider.rotate(p1.velocity, angle);
const u2 = Collider_Collider.rotate(p2.velocity, angle);
const v1 = Collider_Collider.collisionVelocity(u1, u2, m1, m2);
const v2 = Collider_Collider.collisionVelocity(u2, u1, m1, m2);
const vFinal1 = Collider_Collider.rotate(v1, -angle);
const vFinal2 = Collider_Collider.rotate(v2, -angle);
p1.velocity.horizontal = vFinal1.horizontal;
p1.velocity.vertical = vFinal1.vertical;
p2.velocity.horizontal = vFinal2.horizontal;
p2.velocity.vertical = vFinal2.vertical;
}
}
static destroy(p1, p2) {
if (p1.size.value === undefined && p2.size.value !== undefined) {
p1.destroy();
} else if (p1.size.value !== undefined && p2.size.value === undefined) {
p2.destroy();
} else if (p1.size.value !== undefined && p2.size.value !== undefined) {
if (p1.size.value >= p2.size.value) {
p2.destroy();
} else {
p1.destroy();
}
}
}
static getRadius(particle, fallback) {
return particle.bubble.radius || particle.size.value || fallback;
}
isEnabled(particle) {
return particle.particlesOptions.collisions.enable;
}
reset() {}
interact(p1) {
const container = this.container;
const pos1 = p1.getPosition();
const query = container.particles.quadTree.query(new Circle_Circle(pos1.x, pos1.y, p1.size.value * 2));
for (const p2 of query) {
if (p1 === p2 || !p2.particlesOptions.collisions.enable || p1.particlesOptions.collisions.mode !== p2.particlesOptions.collisions.mode) {
continue;
}
const pos2 = p2.getPosition();
const dist = Utils_Utils.getDistance(pos1, pos2);
const defaultSize = container.retina.sizeValue;
const radius1 = Collider_Collider.getRadius(p1, defaultSize);
const radius2 = Collider_Collider.getRadius(p2, defaultSize);
const distP = radius1 + radius2;
if (dist <= distP) {
this.resolveCollision(p1, p2);
}
}
}
resolveCollision(p1, p2) {
switch (p1.particlesOptions.collisions.mode) {
case CollisionMode.absorb:
{
this.absorb(p1, p2);
break;
}
case CollisionMode.bounce:
{
Collider_Collider.bounce(p1, p2);
break;
}
case CollisionMode.destroy:
{
Collider_Collider.destroy(p1, p2);
break;
}
}
}
absorb(p1, p2) {
const container = this.container;
const fps = container.options.fpsLimit / 1000;
if (p1.size.value === undefined && p2.size.value !== undefined) {
p1.destroy();
} else if (p1.size.value !== undefined && p2.size.value === undefined) {
p2.destroy();
} else if (p1.size.value !== undefined && p2.size.value !== undefined) {
if (p1.size.value >= p2.size.value) {
const factor = Utils_Utils.clamp(p1.size.value / p2.size.value, 0, p2.size.value) * fps;
p1.size.value += factor;
p2.size.value -= factor;
if (p2.size.value <= container.retina.pixelRatio) {
p2.size.value = 0;
p2.destroy();
}
} else {
const factor = Utils_Utils.clamp(p2.size.value / p1.size.value, 0, p1.size.value) * fps;
p1.size.value -= factor;
p2.size.value += factor;
if (p1.size.value <= container.retina.pixelRatio) {
p1.size.value = 0;
p1.destroy();
}
}
}
}
}
// CONCATENATED MODULE: ./dist/Core/Particle/Interactions/Particles/Infecter.js
class Particles_Infecter_Infecter {
constructor(container) {
this.container = container;
}
isEnabled() {
return this.container.options.infection.enable;
}
reset() {}
interact(p1, delta) {
var _a, _b;
const infecter1 = p1.infecter;
infecter1.updateInfection(delta.value);
if (infecter1.infectionStage === undefined) {
return;
}
const container = this.container;
const options = container.options;
const infectionOptions = options.infection;
if (!infectionOptions.enable || infectionOptions.stages.length < 1) {
return;
}
const infectionStage1 = infectionOptions.stages[infecter1.infectionStage];
const pxRatio = container.retina.pixelRatio;
const radius = p1.size.value * 2 + infectionStage1.radius * pxRatio;
const pos = p1.getPosition();
const infectedStage1 = (_a = infectionStage1.infectedStage) !== null && _a !== void 0 ? _a : infecter1.infectionStage;
const query = container.particles.quadTree.query(new Circle_Circle(pos.x, pos.y, radius)).filter(p => p.infecter.infectionStage === undefined || p.infecter.infectionStage !== infecter1.infectionStage);
const infections = infectionStage1.rate;
const neighbors = query.length;
for (const p2 of query) {
const infecter2 = p2.infecter;
if (Math.random() < infections / neighbors) {
if (infecter2.infectionStage === undefined) {
infecter2.startInfection(infectedStage1);
} else if (infecter2.infectionStage < infecter1.infectionStage) {
infecter2.updateInfectionStage(infectedStage1);
} else if (infecter2.infectionStage > infecter1.infectionStage) {
const infectionStage2 = infectionOptions.stages[infecter2.infectionStage];
const infectedStage2 = (_b = infectionStage2 === null || infectionStage2 === void 0 ? void 0 : infectionStage2.infectedStage) !== null && _b !== void 0 ? _b : infecter2.infectionStage;
infecter1.updateInfectionStage(infectedStage2);
}
}
}
}
}
// CONCATENATED MODULE: ./dist/Core/Particle/Interactions/Mouse/TrailMaker.js
class TrailMaker_TrailMaker {
constructor(container) {
this.container = container;
this.delay = 0;
}
interact(delta) {
const container = this.container;
const options = container.options;
const trailOptions = options.interactivity.modes.trail;
const optDelay = trailOptions.delay * 1000;
if (this.delay < optDelay) {
this.delay += delta.value;
}
if (this.delay >= optDelay) {
container.particles.push(trailOptions.quantity, container.interactivity.mouse, trailOptions.particles);
this.delay -= optDelay;
}
}
isEnabled() {
const container = this.container;
const options = container.options;
const mouse = container.interactivity.mouse;
const events = options.interactivity.events;
return mouse.clicking && mouse.inside && !!mouse.position && Utils_Utils.isInArray(ClickMode.trail, events.onClick.mode) || mouse.inside && !!mouse.position && Utils_Utils.isInArray(HoverMode.trail, events.onHover.mode);
}
reset() {}
}
// CONCATENATED MODULE: ./dist/Core/Particle/Interactions/Mouse/Attractor.js
class Mouse_Attractor_Attractor {
constructor(container) {
this.container = container;
}
isEnabled() {
const container = this.container;
const options = container.options;
const mouse = container.interactivity.mouse;
const events = options.interactivity.events;
if (!(events.onHover.enable && mouse.position || events.onClick.enable && mouse.clickPosition)) {
return false;
}
const hoverMode = events.onHover.mode;
const clickMode = events.onClick.mode;
return Utils_Utils.isInArray(HoverMode.attract, hoverMode) || Utils_Utils.isInArray(ClickMode.attract, clickMode);
}
reset() {}
interact() {
const container = this.container;
const options = container.options;
const mouseMoveStatus = container.interactivity.status === Constants.mouseMoveEvent;
const events = options.interactivity.events;
const hoverEnabled = events.onHover.enable;
const hoverMode = events.onHover.mode;
const clickEnabled = events.onClick.enable;
const clickMode = events.onClick.mode;
if (mouseMoveStatus && hoverEnabled && Utils_Utils.isInArray(HoverMode.attract, hoverMode)) {
this.hoverAttract();
} else if (clickEnabled && Utils_Utils.isInArray(ClickMode.attract, clickMode)) {
this.clickAttract();
}
}
hoverAttract() {
const container = this.container;
const mousePos = container.interactivity.mouse.position;
if (!mousePos) {
return;
}
const attractRadius = container.retina.attractModeDistance;
this.processAttract(mousePos, attractRadius, new Circle_Circle(mousePos.x, mousePos.y, attractRadius));
}
processAttract(position, attractRadius, area) {
const container = this.container;
const query = container.particles.quadTree.query(area);
for (const particle of query) {
const {
dx,
dy,
distance
} = Utils_Utils.getDistances(particle.position, position);
const normVec = {
x: dx / distance,
y: dy / distance
};
const velocity = container.options.interactivity.modes.attract.speed;
const attractFactor = Utils_Utils.clamp((1 - Math.pow(distance / attractRadius, 2)) * velocity, 0, 50);
particle.position.x = particle.position.x - normVec.x * attractFactor;
particle.position.y = particle.position.y - normVec.y * attractFactor;
}
}
clickAttract() {
const container = this.container;
if (!container.attract.finish) {
if (!container.attract.count) {
container.attract.count = 0;
}
container.attract.count++;
if (container.attract.count === container.particles.count) {
container.attract.finish = true;
}
}
if (container.attract.clicking) {
const mousePos = container.interactivity.mouse.clickPosition;
if (!mousePos) {
return;
}
const attractRadius = container.retina.attractModeDistance;
this.processAttract(mousePos, attractRadius, new Circle_Circle(mousePos.x, mousePos.y, attractRadius));
} else if (container.attract.clicking === false) {
container.attract.particles = [];
}
return;
}
}
// CONCATENATED MODULE: ./dist/Core/Particle/InteractionManager.js
class InteractionManager_InteractionManager {
constructor(container) {
this.container = container;
this.externalInteractors = [new Mouse_Attractor_Attractor(container), new Bubbler_Bubbler(container), new Connector_Connector(container), new Grabber_Grabber(container), new Repulser_Repulser(container), new TrailMaker_TrailMaker(container)];
this.particleInteractors = [new Attractor_Attractor(container), new Collider_Collider(container), new Particles_Infecter_Infecter(container), new Linker_Linker(container)];
}
init() {}
externalInteract(delta) {
for (const interactor of this.externalInteractors) {
if (interactor.isEnabled()) {
interactor.interact(delta);
}
}
}
particlesInteract(particle, delta) {
for (const interactor of this.externalInteractors) {
interactor.reset(particle);
}
for (const interactor of this.particleInteractors) {
if (interactor.isEnabled(particle)) {
interactor.interact(particle, delta);
}
}
}
}
// CONCATENATED MODULE: ./dist/Core/Particles.js
class Core_Particles_Particles {
constructor(container) {
this.container = container;
this.array = [];
this.interactionManager = new InteractionManager_InteractionManager(container);
const canvasSize = this.container.canvas.size;
this.linksColors = new Map();
this.quadTree = new QuadTree_QuadTree(new Rectangle_Rectangle(0, 0, canvasSize.width, canvasSize.height), 4);
}
get count() {
return this.array.length;
}
init() {
const container = this.container;
const options = container.options;
let handled = false;
for (const [, plugin] of container.plugins) {
if (plugin.particlesInitialization !== undefined) {
handled = plugin.particlesInitialization();
}
if (handled) {
break;
}
}
if (!handled) {
for (let i = this.count; i < options.particles.number.value; i++) {
this.addParticle();
}
}
if (options.infection.enable) {
for (let i = 0; i < options.infection.infections; i++) {
const notInfected = this.array.map(p => p.infecter).filter(p => p.infectionStage === undefined);
const infected = Utils_Utils.itemFromArray(notInfected);
infected.startInfection(0);
}
}
this.interactionManager.init();
container.noise.init();
}
redraw() {
this.clear();
this.init();
this.draw({
value: 0,
factor: 0
});
}
removeAt(index, quantity) {
if (index >= 0 && index <= this.count) {
for (const particle of this.array.splice(index, quantity !== null && quantity !== void 0 ? quantity : 1)) {
particle.destroy();
}
}
}
remove(particle) {
this.removeAt(this.array.indexOf(particle));
}
update(delta) {
const container = this.container;
const particlesToDelete = [];
container.noise.update();
for (const particle of this.array) {
particle.move(delta);
if (particle.destroyed) {
particlesToDelete.push(particle);
continue;
}
this.quadTree.insert(new Point(particle.getPosition(), particle));
}
for (const particle of particlesToDelete) {
this.remove(particle);
}
this.interactionManager.externalInteract(delta);
for (const particle of this.container.particles.array) {
particle.update(delta);
this.interactionManager.particlesInteract(particle, delta);
}
}
draw(delta) {
const container = this.container;
container.canvas.clear();
const canvasSize = this.container.canvas.size;
this.quadTree = new QuadTree_QuadTree(new Rectangle_Rectangle(0, 0, canvasSize.width, canvasSize.height), 4);
this.update(delta);
for (const [, plugin] of container.plugins) {
container.canvas.drawPlugin(plugin, delta);
}
for (const p of this.array) {
p.draw(delta);
}
}
clear() {
this.array = [];
}
push(nb, mouse, overrideOptions) {
const container = this.container;
const options = container.options;
const limit = options.particles.number.limit * container.density;
this.pushing = true;
if (limit > 0) {
const countToRemove = this.count + nb - limit;
if (countToRemove > 0) {
this.removeQuantity(countToRemove);
}
}
for (let i = 0; i < nb; i++) {
this.addParticle(mouse === null || mouse === void 0 ? void 0 : mouse.position, overrideOptions);
}
if (!options.particles.move.enable) {
this.container.play();
}
this.pushing = false;
}
addParticle(position, overrideOptions) {
try {
const particle = new Particle_Particle(this.container, position, overrideOptions);
this.array.push(particle);
return particle;
} catch (_a) {
console.log("error adding particle");
return;
}
}
removeQuantity(quantity) {
const options = this.container.options;
this.removeAt(0, quantity);
if (!options.particles.move.enable) {
this.container.play();
}
}
}
// CONCATENATED MODULE: ./dist/Core/Retina.js
class Retina_Retina {
constructor(container) {
this.container = container;
}
init() {
const container = this.container;
const options = container.options;
if (options.detectRetina) {
this.pixelRatio = Utils_Utils.isSsr() ? 1 : window.devicePixelRatio;
} else {
this.pixelRatio = 1;
}
const ratio = this.pixelRatio;
if (container.canvas.element) {
const element = container.canvas.element;
container.canvas.size.width = element.offsetWidth * ratio;
container.canvas.size.height = element.offsetHeight * ratio;
}
const particles = options.particles;
this.linksDistance = particles.links.distance * ratio;
this.linksWidth = particles.links.width * ratio;
this.moveSpeed = particles.move.speed * ratio;
this.sizeValue = particles.size.value * ratio;
this.sizeAnimationSpeed = particles.size.animation.speed * ratio;
const modes = options.interactivity.modes;
this.connectModeDistance = modes.connect.distance * ratio;
this.connectModeRadius = modes.connect.radius * ratio;
this.grabModeDistance = modes.grab.distance * ratio;
this.repulseModeDistance = modes.repulse.distance * ratio;
this.attractModeDistance = modes.attract.distance * ratio;
this.slowModeRadius = modes.slow.radius * ratio;
this.bubbleModeDistance = modes.bubble.distance * ratio;
if (modes.bubble.size) {
this.bubbleModeSize = modes.bubble.size * ratio;
}
}
initParticle(particle) {
const particlesOptions = particle.particlesOptions;
const ratio = this.pixelRatio;
particle.linksDistance = particlesOptions.links.distance * ratio;
particle.linksWidth = particlesOptions.links.width * ratio;
particle.moveSpeed = particlesOptions.move.speed * ratio;
particle.sizeValue = particlesOptions.size.value * ratio;
if (typeof particlesOptions.size.random !== "boolean") {
particle.randomMinimumSize = particlesOptions.size.random.minimumValue * ratio;
}
particle.sizeAnimationSpeed = particlesOptions.size.animation.speed * ratio;
}
}
// CONCATENATED MODULE: ./dist/Core/FrameManager.js
class FrameManager {
constructor(container) {
this.container = container;
}
nextFrame(timestamp) {
const container = this.container;
const options = container.options;
const fpsLimit = options.fpsLimit > 0 ? options.fpsLimit : 60;
if (container.lastFrameTime !== undefined && timestamp < container.lastFrameTime + 1000 / fpsLimit) {
container.draw();
return;
}
const deltaValue = timestamp - container.lastFrameTime;
const delta = {
value: deltaValue,
factor: options.fpsLimit > 0 ? 60 * deltaValue / 1000 : 3.6
};
container.lastFrameTime = timestamp;
container.particles.draw(delta);
if (options.particles.move.enable && container.getAnimationStatus()) {
container.draw();
}
}
}
// CONCATENATED MODULE: ./dist/Enums/InteractivityDetect.js
var InteractivityDetect;
(function (InteractivityDetect) {
InteractivityDetect["canvas"] = "canvas";
InteractivityDetect["parent"] = "parent";
InteractivityDetect["window"] = "window";
})(InteractivityDetect || (InteractivityDetect = {}));
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Events/ClickEvent.js
class ClickEvent {
constructor() {
this.enable = false;
this.mode = [];
}
load(data) {
if (data === undefined) {
return;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.mode !== undefined) {
this.mode = data.mode;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Events/DivEvent.js
class DivEvent_DivEvent {
constructor() {
this.ids = [];
this.enable = false;
this.mode = [];
this.type = DivType.circle;
}
get elementId() {
return this.ids;
}
set elementId(value) {
this.ids = value;
}
get el() {
return this.elementId;
}
set el(value) {
this.elementId = value;
}
load(data) {
var _a, _b;
if (data === undefined) {
return;
}
const ids = (_b = (_a = data.ids) !== null && _a !== void 0 ? _a : data.elementId) !== null && _b !== void 0 ? _b : data.el;
if (ids !== undefined) {
this.ids = ids;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.mode !== undefined) {
this.mode = data.mode;
}
if (data.type !== undefined) {
this.type = data.type;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Events/Parallax.js
class Parallax {
constructor() {
this.enable = false;
this.force = 2;
this.smooth = 10;
}
load(data) {
if (data === undefined) {
return;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.force !== undefined) {
this.force = data.force;
}
if (data.smooth !== undefined) {
this.smooth = data.smooth;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Events/HoverEvent.js
class HoverEvent_HoverEvent {
constructor() {
this.enable = false;
this.mode = [];
this.parallax = new Parallax();
}
load(data) {
if (data === undefined) {
return;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.mode !== undefined) {
this.mode = data.mode;
}
this.parallax.load(data.parallax);
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Events/Events.js
class Events_Events {
constructor() {
this.onClick = new ClickEvent();
this.onDiv = new DivEvent_DivEvent();
this.onHover = new HoverEvent_HoverEvent();
this.resize = true;
}
get onclick() {
return this.onClick;
}
set onclick(value) {
this.onClick = value;
}
get ondiv() {
return this.onDiv;
}
set ondiv(value) {
this.onDiv = value;
}
get onhover() {
return this.onHover;
}
set onhover(value) {
this.onHover = value;
}
load(data) {
var _a, _b, _c;
if (data === undefined) {
return;
}
this.onClick.load((_a = data.onClick) !== null && _a !== void 0 ? _a : data.onclick);
const onDiv = (_b = data.onDiv) !== null && _b !== void 0 ? _b : data.ondiv;
if (onDiv !== undefined) {
if (onDiv instanceof Array) {
this.onDiv = onDiv.map(div => {
const tmp = new DivEvent_DivEvent();
tmp.load(div);
return tmp;
});
} else {
this.onDiv = new DivEvent_DivEvent();
this.onDiv.load(onDiv);
}
}
this.onHover.load((_c = data.onHover) !== null && _c !== void 0 ? _c : data.onhover);
if (data.resize !== undefined) {
this.resize = data.resize;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Modes/BubbleBase.js
class BubbleBase_BubbleBase {
constructor() {
this.distance = 200;
this.duration = 0.4;
}
load(data) {
if (data === undefined) {
return;
}
if (data.distance !== undefined) {
this.distance = data.distance;
}
if (data.duration !== undefined) {
this.duration = data.duration;
}
if (data.opacity !== undefined) {
this.opacity = data.opacity;
}
if (data.color !== undefined) {
if (data.color instanceof Array) {
this.color = data.color.map(s => OptionsColor.create(undefined, s));
} else {
if (this.color instanceof Array) {
this.color = new OptionsColor();
}
this.color = OptionsColor.create(this.color, data.color);
}
}
if (data.size !== undefined) {
this.size = data.size;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Modes/BubbleDiv.js
class BubbleDiv_BubbleDiv extends BubbleBase_BubbleBase {
constructor() {
super();
this.ids = [];
}
load(data) {
super.load(data);
if (!(data !== undefined && data.ids !== undefined)) {
return;
}
this.ids = data.ids;
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Modes/Bubble.js
class Bubble_Bubble extends BubbleBase_BubbleBase {
load(data) {
super.load(data);
if (!(data !== undefined && data.divs !== undefined)) {
return;
}
if (data.divs instanceof Array) {
this.divs = data.divs.map(s => {
const tmp = new BubbleDiv_BubbleDiv();
tmp.load(s);
return tmp;
});
} else {
if (this.divs instanceof Array || !this.divs) {
this.divs = new BubbleDiv_BubbleDiv();
}
this.divs.load(data.divs);
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Modes/ConnectLinks.js
class ConnectLinks {
constructor() {
this.opacity = 0.5;
}
load(data) {
if (!(data !== undefined && data.opacity !== undefined)) {
return;
}
this.opacity = data.opacity;
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Modes/Connect.js
class Connect_Connect {
constructor() {
this.distance = 80;
this.links = new ConnectLinks();
this.radius = 60;
}
get line_linked() {
return this.links;
}
set line_linked(value) {
this.links = value;
}
get lineLinked() {
return this.links;
}
set lineLinked(value) {
this.links = value;
}
load(data) {
var _a, _b;
if (data === undefined) {
return;
}
if (data.distance !== undefined) {
this.distance = data.distance;
}
this.links.load((_b = (_a = data.links) !== null && _a !== void 0 ? _a : data.lineLinked) !== null && _b !== void 0 ? _b : data.line_linked);
if (data.radius !== undefined) {
this.radius = data.radius;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Modes/GrabLinks.js
class GrabLinks_GrabLinks {
constructor() {
this.opacity = 1;
}
load(data) {
if (data === undefined) {
return;
}
if (data.opacity !== undefined) {
this.opacity = data.opacity;
}
if (data.color !== undefined) {
this.color = OptionsColor.create(this.color, data.color);
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Modes/Grab.js
class Grab_Grab {
constructor() {
this.distance = 100;
this.links = new GrabLinks_GrabLinks();
}
get line_linked() {
return this.links;
}
set line_linked(value) {
this.links = value;
}
get lineLinked() {
return this.links;
}
set lineLinked(value) {
this.links = value;
}
load(data) {
var _a, _b;
if (data === undefined) {
return;
}
if (data.distance !== undefined) {
this.distance = data.distance;
}
this.links.load((_b = (_a = data.links) !== null && _a !== void 0 ? _a : data.lineLinked) !== null && _b !== void 0 ? _b : data.line_linked);
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Modes/Remove.js
class Remove {
constructor() {
this.quantity = 2;
}
get particles_nb() {
return this.quantity;
}
set particles_nb(value) {
this.quantity = value;
}
load(data) {
var _a;
if (data === undefined) {
return;
}
const quantity = (_a = data.quantity) !== null && _a !== void 0 ? _a : data.particles_nb;
if (quantity !== undefined) {
this.quantity = quantity;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Modes/Push.js
class Push {
constructor() {
this.quantity = 4;
}
get particles_nb() {
return this.quantity;
}
set particles_nb(value) {
this.quantity = value;
}
load(data) {
var _a;
if (data === undefined) {
return;
}
const quantity = (_a = data.quantity) !== null && _a !== void 0 ? _a : data.particles_nb;
if (quantity !== undefined) {
this.quantity = quantity;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Modes/RepulseBase.js
class RepulseBase {
constructor() {
this.distance = 200;
this.duration = 0.4;
this.speed = 1;
}
load(data) {
if (data === undefined) {
return;
}
if (data.distance !== undefined) {
this.distance = data.distance;
}
if (data.duration !== undefined) {
this.duration = data.duration;
}
if (data.speed !== undefined) {
this.speed = data.speed;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Modes/RepulseDiv.js
class RepulseDiv_RepulseDiv extends RepulseBase {
constructor() {
super();
this.ids = [];
}
load(data) {
super.load(data);
if (data === undefined) {
return;
}
if (data.ids === undefined) {
return;
}
this.ids = data.ids;
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Modes/Repulse.js
class Repulse_Repulse extends RepulseBase {
load(data) {
super.load(data);
if ((data === null || data === void 0 ? void 0 : data.divs) === undefined) {
return;
}
if (data.divs instanceof Array) {
this.divs = data.divs.map(s => {
const tmp = new RepulseDiv_RepulseDiv();
tmp.load(s);
return tmp;
});
} else {
if (this.divs instanceof Array || !this.divs) {
this.divs = new RepulseDiv_RepulseDiv();
}
this.divs.load(data.divs);
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Modes/Slow.js
class Slow {
constructor() {
this.factor = 3;
this.radius = 200;
}
get active() {
return false;
}
set active(_value) {}
load(data) {
if (data === undefined) {
return;
}
if (data.factor !== undefined) {
this.factor = data.factor;
}
if (data.radius !== undefined) {
this.radius = data.radius;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Modes/Trail.js
class Modes_Trail_Trail {
constructor() {
this.delay = 1;
this.quantity = 1;
}
load(data) {
if (data === undefined) {
return;
}
if (data.delay !== undefined) {
this.delay = data.delay;
}
if (data.quantity !== undefined) {
this.quantity = data.quantity;
}
if (data.particles !== undefined) {
this.particles = Utils_Utils.deepExtend({}, data.particles);
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Modes/Attract.js
class Attract_Attract {
constructor() {
this.distance = 200;
this.duration = 0.4;
this.speed = 1;
}
load(data) {
if (data === undefined) {
return;
}
if (data.distance !== undefined) {
this.distance = data.distance;
}
if (data.duration !== undefined) {
this.duration = data.duration;
}
if (data.speed !== undefined) {
this.speed = data.speed;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Modes/Modes.js
class Modes_Modes {
constructor() {
this.attract = new Attract_Attract();
this.bubble = new Bubble_Bubble();
this.connect = new Connect_Connect();
this.grab = new Grab_Grab();
this.push = new Push();
this.remove = new Remove();
this.repulse = new Repulse_Repulse();
this.slow = new Slow();
this.trail = new Modes_Trail_Trail();
}
load(data) {
if (data === undefined) {
return;
}
this.attract.load(data.attract);
this.bubble.load(data.bubble);
this.connect.load(data.connect);
this.grab.load(data.grab);
this.push.load(data.push);
this.remove.load(data.remove);
this.repulse.load(data.repulse);
this.slow.load(data.slow);
this.trail.load(data.trail);
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Interactivity/Interactivity.js
class Interactivity_Interactivity {
constructor() {
this.detectsOn = InteractivityDetect.canvas;
this.events = new Events_Events();
this.modes = new Modes_Modes();
}
get detect_on() {
return this.detectsOn;
}
set detect_on(value) {
this.detectsOn = value;
}
load(data) {
var _a, _b, _c;
if (data === undefined) {
return;
}
const detectsOn = (_a = data.detectsOn) !== null && _a !== void 0 ? _a : data.detect_on;
if (detectsOn !== undefined) {
this.detectsOn = detectsOn;
}
this.events.load(data.events);
this.modes.load(data.modes);
if (((_c = (_b = data.modes) === null || _b === void 0 ? void 0 : _b.slow) === null || _c === void 0 ? void 0 : _c.active) === true) {
if (this.events.onHover.mode instanceof Array) {
if (this.events.onHover.mode.indexOf(HoverMode.slow) < 0) {
this.events.onHover.mode.push(HoverMode.slow);
}
} else if (this.events.onHover.mode !== HoverMode.slow) {
this.events.onHover.mode = [this.events.onHover.mode, HoverMode.slow];
}
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/BackgroundMask/BackgroundMaskCover.js
class BackgroundMaskCover_BackgroundMaskCover {
constructor() {
this.color = new OptionsColor();
this.opacity = 1;
}
load(data) {
if (data === undefined) {
return;
}
if (data.color !== undefined) {
this.color = OptionsColor.create(this.color, data.color);
}
if (data.opacity !== undefined) {
this.opacity = data.opacity;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/BackgroundMask/BackgroundMask.js
class BackgroundMask_BackgroundMask {
constructor() {
this.cover = new BackgroundMaskCover_BackgroundMaskCover();
this.enable = false;
}
load(data) {
if (data === undefined) {
return;
}
if (data.cover !== undefined) {
const cover = data.cover;
const color = typeof data.cover === "string" ? {
color: data.cover
} : data.cover;
this.cover.load(cover.color !== undefined ? cover : {
color: color
});
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Background/Background.js
class Background_Background {
constructor() {
this.color = new OptionsColor();
this.color.value = "";
this.image = "";
this.position = "";
this.repeat = "";
this.size = "";
this.opacity = 1;
}
load(data) {
if (data === undefined) {
return;
}
if (data.color !== undefined) {
this.color = OptionsColor.create(this.color, data.color);
}
if (data.image !== undefined) {
this.image = data.image;
}
if (data.position !== undefined) {
this.position = data.position;
}
if (data.repeat !== undefined) {
this.repeat = data.repeat;
}
if (data.size !== undefined) {
this.size = data.size;
}
if (data.opacity !== undefined) {
this.opacity = data.opacity;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Infection/InfectionStage.js
class InfectionStage_InfectionStage {
constructor() {
this.color = new OptionsColor();
this.color.value = "#ff0000";
this.radius = 0;
this.rate = 1;
}
load(data) {
if (data === undefined) {
return;
}
if (data.color !== undefined) {
this.color = OptionsColor.create(this.color, data.color);
}
this.duration = data.duration;
this.infectedStage = data.infectedStage;
if (data.radius !== undefined) {
this.radius = data.radius;
}
if (data.rate !== undefined) {
this.rate = data.rate;
}
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Infection/Infection.js
class Infection_Infection {
constructor() {
this.cure = false;
this.delay = 0;
this.enable = false;
this.infections = 0;
this.stages = [];
}
load(data) {
if (data === undefined) {
return;
}
if (data.cure !== undefined) {
this.cure = data.cure;
}
if (data.delay !== undefined) {
this.delay = data.delay;
}
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.infections !== undefined) {
this.infections = data.infections;
}
if (data.stages === undefined) {
return;
}
this.stages = data.stages.map(t => {
const s = new InfectionStage_InfectionStage();
s.load(t);
return s;
});
}
}
// CONCATENATED MODULE: ./dist/Options/Classes/Options.js
class Options_Options {
constructor() {
this.background = new Background_Background();
this.backgroundMask = new BackgroundMask_BackgroundMask();
this.detectRetina = true;
this.fpsLimit = 30;
this.infection = new Infection_Infection();
this.interactivity = new Interactivity_Interactivity();
this.particles = new Particles_Particles();
this.pauseOnBlur = true;
}
get fps_limit() {
return this.fpsLimit;
}
set fps_limit(value) {
this.fpsLimit = value;
}
get retina_detect() {
return this.detectRetina;
}
set retina_detect(value) {
this.detectRetina = value;
}
load(data) {
var _a, _b;
if (data === undefined) {
return;
}
if (data.preset !== undefined) {
if (data.preset instanceof Array) {
for (const preset of data.preset) {
this.importPreset(preset);
}
} else {
this.importPreset(data.preset);
}
}
const detectRetina = (_a = data.detectRetina) !== null && _a !== void 0 ? _a : data.retina_detect;
if (detectRetina !== undefined) {
this.detectRetina = detectRetina;
}
const fpsLimit = (_b = data.fpsLimit) !== null && _b !== void 0 ? _b : data.fps_limit;
if (fpsLimit !== undefined) {
this.fpsLimit = fpsLimit;
}
if (data.pauseOnBlur !== undefined) {
this.pauseOnBlur = data.pauseOnBlur;
}
this.background.load(data.background);
this.particles.load(data.particles);
this.infection.load(data.infection);
this.interactivity.load(data.interactivity);
this.backgroundMask.load(data.backgroundMask);
Plugins.loadOptions(this, data);
}
importPreset(preset) {
this.load(Plugins.getPreset(preset));
}
}
// CONCATENATED MODULE: ./dist/Utils/EventListeners.js
class EventListeners_EventListeners {
constructor(container) {
this.container = container;
this.canPush = true;
this.mouseMoveHandler = e => this.mouseTouchMove(e);
this.touchStartHandler = e => this.mouseTouchMove(e);
this.touchMoveHandler = e => this.mouseTouchMove(e);
this.touchEndHandler = () => this.mouseTouchFinish();
this.mouseLeaveHandler = () => this.mouseTouchFinish();
this.touchCancelHandler = () => this.mouseTouchFinish();
this.touchEndClickHandler = e => this.mouseTouchClick(e);
this.mouseUpHandler = e => this.mouseTouchClick(e);
this.mouseDownHandler = () => this.mouseDown();
this.visibilityChangeHandler = () => this.handleVisibilityChange();
this.resizeHandler = () => this.handleWindowResize();
}
static manageListener(element, event, handler, add, options) {
if (add) {
let addOptions = {
passive: true
};
if (typeof options === "boolean") {
addOptions.capture = options;
} else if (options !== undefined) {
addOptions = options;
}
element.addEventListener(event, handler, addOptions);
} else {
const removeOptions = options;
element.removeEventListener(event, handler, removeOptions);
}
}
addListeners() {
this.manageListeners(true);
}
removeListeners() {
this.manageListeners(false);
}
manageListeners(add) {
const container = this.container;
const options = container.options;
const detectType = options.interactivity.detectsOn;
let mouseLeaveEvent = Constants.mouseLeaveEvent;
if (detectType === InteractivityDetect.window) {
container.interactivity.element = window;
mouseLeaveEvent = Constants.mouseOutEvent;
} else if (detectType === InteractivityDetect.parent && container.canvas.element) {
container.interactivity.element = container.canvas.element.parentNode;
} else {
container.interactivity.element = container.canvas.element;
}
const interactivityEl = container.interactivity.element;
if (interactivityEl && (options.interactivity.events.onHover.enable || options.interactivity.events.onClick.enable)) {
EventListeners_EventListeners.manageListener(interactivityEl, Constants.mouseMoveEvent, this.mouseMoveHandler, add);
EventListeners_EventListeners.manageListener(interactivityEl, Constants.touchStartEvent, this.touchStartHandler, add);
EventListeners_EventListeners.manageListener(interactivityEl, Constants.touchMoveEvent, this.touchMoveHandler, add);
if (!options.interactivity.events.onClick.enable) {
EventListeners_EventListeners.manageListener(interactivityEl, Constants.touchEndEvent, this.touchEndHandler, add);
}
EventListeners_EventListeners.manageListener(interactivityEl, mouseLeaveEvent, this.mouseLeaveHandler, add);
EventListeners_EventListeners.manageListener(interactivityEl, Constants.touchCancelEvent, this.touchCancelHandler, add);
}
if (options.interactivity.events.onClick.enable && interactivityEl) {
EventListeners_EventListeners.manageListener(interactivityEl, Constants.touchEndEvent, this.touchEndClickHandler, add);
EventListeners_EventListeners.manageListener(interactivityEl, Constants.mouseUpEvent, this.mouseUpHandler, add);
EventListeners_EventListeners.manageListener(interactivityEl, Constants.mouseDownEvent, this.mouseDownHandler, add);
}
if (options.interactivity.events.resize) {
EventListeners_EventListeners.manageListener(window, Constants.resizeEvent, this.resizeHandler, add);
}
if (document) {
EventListeners_EventListeners.manageListener(document, Constants.visibilityChangeEvent, this.visibilityChangeHandler, add, false);
}
}
handleWindowResize() {
const container = this.container;
const options = container.options;
const canvas = container.canvas.element;
if (!canvas) {
return;
}
const pxRatio = container.retina.pixelRatio;
container.canvas.size.width = canvas.offsetWidth * pxRatio;
container.canvas.size.height = canvas.offsetHeight * pxRatio;
canvas.width = container.canvas.size.width;
canvas.height = container.canvas.size.height;
if (!options.particles.move.enable) {
container.particles.redraw();
}
container.densityAutoParticles();
for (const [, plugin] of container.plugins) {
if (plugin.resize !== undefined) {
plugin.resize();
}
}
}
handleVisibilityChange() {
const container = this.container;
const options = container.options;
this.mouseTouchFinish();
if (!options.pauseOnBlur) {
return;
}
if (document === null || document === void 0 ? void 0 : document.hidden) {
container.pageHidden = true;
container.pause();
} else {
container.pageHidden = false;
if (container.getAnimationStatus()) {
container.play(true);
} else {
container.draw();
}
}
}
mouseDown() {
const interactivity = this.container.interactivity;
if (interactivity) {
const mouse = interactivity.mouse;
mouse.clicking = true;
mouse.downPosition = mouse.position;
}
}
mouseTouchMove(e) {
var _a, _b, _c;
const container = this.container;
const options = container.options;
if (((_a = container.interactivity) === null || _a === void 0 ? void 0 : _a.element) === undefined) {
return;
}
container.interactivity.mouse.inside = true;
let pos;
const canvas = container.canvas.element;
if (e.type.startsWith("mouse")) {
this.canPush = true;
const mouseEvent = e;
if (container.interactivity.element === window) {
if (canvas) {
const clientRect = canvas.getBoundingClientRect();
pos = {
x: mouseEvent.clientX - clientRect.left,
y: mouseEvent.clientY - clientRect.top
};
}
} else if (options.interactivity.detectsOn === InteractivityDetect.parent) {
const source = mouseEvent.target;
const target = mouseEvent.currentTarget;
if (source && target) {
const sourceRect = source.getBoundingClientRect();
const targetRect = target.getBoundingClientRect();
pos = {
x: mouseEvent.offsetX + sourceRect.left - targetRect.left,
y: mouseEvent.offsetY + sourceRect.top - targetRect.top
};
} else {
pos = {
x: mouseEvent.offsetX || mouseEvent.clientX,
y: mouseEvent.offsetY || mouseEvent.clientY
};
}
} else {
if (mouseEvent.target === container.canvas.element) {
pos = {
x: mouseEvent.offsetX || mouseEvent.clientX,
y: mouseEvent.offsetY || mouseEvent.clientY
};
}
}
} else {
this.canPush = e.type !== "touchmove";
const touchEvent = e;
const lastTouch = touchEvent.touches[touchEvent.touches.length - 1];
const canvasRect = canvas === null || canvas === void 0 ? void 0 : canvas.getBoundingClientRect();
pos = {
x: lastTouch.clientX - ((_b = canvasRect === null || canvasRect === void 0 ? void 0 : canvasRect.left) !== null && _b !== void 0 ? _b : 0),
y: lastTouch.clientY - ((_c = canvasRect === null || canvasRect === void 0 ? void 0 : canvasRect.top) !== null && _c !== void 0 ? _c : 0)
};
}
const pxRatio = container.retina.pixelRatio;
if (pos) {
pos.x *= pxRatio;
pos.y *= pxRatio;
}
container.interactivity.mouse.position = pos;
container.interactivity.status = Constants.mouseMoveEvent;
}
mouseTouchFinish() {
const container = this.container;
const interactivity = container.interactivity;
const mouse = interactivity.mouse;
delete mouse.position;
delete mouse.clickPosition;
delete mouse.downPosition;
interactivity.status = Constants.mouseLeaveEvent;
mouse.inside = false;
mouse.clicking = false;
}
mouseTouchClick(e) {
const container = this.container;
const options = container.options;
const mouse = container.interactivity.mouse;
mouse.inside = true;
let handled = false;
const mousePosition = mouse.position;
if (mousePosition === undefined || !options.interactivity.events.onClick.enable) {
return;
}
for (const [, plugin] of container.plugins) {
if (plugin.clickPositionValid !== undefined) {
handled = plugin.clickPositionValid(mousePosition);
if (handled) {
break;
}
}
}
if (!handled) {
this.doMouseTouchClick(e);
}
mouse.clicking = false;
}
doMouseTouchClick(e) {
const container = this.container;
const options = container.options;
if (this.canPush) {
const mousePos = container.interactivity.mouse.position;
if (mousePos) {
container.interactivity.mouse.clickPosition = {
x: mousePos.x,
y: mousePos.y
};
} else {
return;
}
container.interactivity.mouse.clickTime = new Date().getTime();
const onClick = options.interactivity.events.onClick;
if (onClick.mode instanceof Array) {
for (const mode of onClick.mode) {
this.handleClickMode(mode);
}
} else {
this.handleClickMode(onClick.mode);
}
}
if (e.type === "touchend") {
setTimeout(() => this.mouseTouchFinish(), 500);
}
}
handleClickMode(mode) {
const container = this.container;
const options = container.options;
const pushNb = options.interactivity.modes.push.quantity;
const removeNb = options.interactivity.modes.remove.quantity;
switch (mode) {
case ClickMode.push:
{
if (pushNb > 0) {
if (options.particles.move.enable) {
container.particles.push(pushNb, container.interactivity.mouse);
} else {
if (pushNb === 1) {
container.particles.push(pushNb, container.interactivity.mouse);
} else if (pushNb > 1) {
container.particles.push(pushNb);
}
}
}
break;
}
case ClickMode.remove:
container.particles.removeQuantity(removeNb);
break;
case ClickMode.bubble:
container.bubble.clicking = true;
break;
case ClickMode.repulse:
container.repulse.clicking = true;
container.repulse.count = 0;
for (const particle of container.repulse.particles) {
particle.velocity.horizontal = particle.initialVelocity.horizontal;
particle.velocity.vertical = particle.initialVelocity.vertical;
}
container.repulse.particles = [];
container.repulse.finish = false;
setTimeout(() => {
if (!container.destroyed) {
container.repulse.clicking = false;
}
}, options.interactivity.modes.repulse.duration * 1000);
break;
case ClickMode.attract:
container.attract.clicking = true;
container.attract.count = 0;
for (const particle of container.attract.particles) {
particle.velocity.horizontal = particle.initialVelocity.horizontal;
particle.velocity.vertical = particle.initialVelocity.vertical;
}
container.attract.particles = [];
container.attract.finish = false;
setTimeout(() => {
if (!container.destroyed) {
container.attract.clicking = false;
}
}, options.interactivity.modes.attract.duration * 1000);
break;
case ClickMode.pause:
if (container.getAnimationStatus()) {
container.pause();
} else {
container.play();
}
break;
}
for (const [, plugin] of container.plugins) {
if (plugin.handleClickMode) {
plugin.handleClickMode(mode);
}
}
}
}
// CONCATENATED MODULE: ./dist/Core/Container.js
class Container_Container {
constructor(id, sourceOptions, ...presets) {
this.id = id;
this.sourceOptions = sourceOptions;
this.started = false;
this.destroyed = false;
this.paused = true;
this.lastFrameTime = 0;
this.pageHidden = false;
this.retina = new Retina_Retina(this);
this.canvas = new Canvas_Canvas(this);
this.particles = new Core_Particles_Particles(this);
this.drawer = new FrameManager(this);
this.noise = {
generate: () => {
return {
angle: Math.random() * Math.PI * 2,
length: Math.random()
};
},
init: () => {},
update: () => {}
};
this.interactivity = {
mouse: {
clicking: false,
inside: false
}
};
this.bubble = {};
this.repulse = {
particles: []
};
this.attract = {
particles: []
};
this.plugins = new Map();
this.drawers = new Map();
this.density = 1;
this.options = new Options_Options();
for (const preset of presets) {
this.options.load(Plugins.getPreset(preset));
}
const shapes = Plugins.getSupportedShapes();
for (const type of shapes) {
const drawer = Plugins.getShapeDrawer(type);
if (drawer) {
this.drawers.set(type, drawer);
}
}
if (this.sourceOptions) {
this.options.load(this.sourceOptions);
}
this.eventListeners = new EventListeners_EventListeners(this);
}
play(force) {
const needsUpdate = this.paused || force;
if (this.paused) {
this.paused = false;
}
if (needsUpdate) {
for (const [, plugin] of this.plugins) {
if (plugin.play) {
plugin.play();
}
}
this.lastFrameTime = performance.now();
}
this.draw();
}
pause() {
if (this.drawAnimationFrame !== undefined) {
Utils_Utils.cancelAnimation(this.drawAnimationFrame);
delete this.drawAnimationFrame;
}
if (this.paused) {
return;
}
for (const [, plugin] of this.plugins) {
if (plugin.pause) {
plugin.pause();
}
}
if (!this.pageHidden) {
this.paused = true;
}
}
draw() {
this.drawAnimationFrame = Utils_Utils.animate(t => {
var _a;
return (_a = this.drawer) === null || _a === void 0 ? void 0 : _a.nextFrame(t);
});
}
getAnimationStatus() {
return !this.paused;
}
setNoise(noiseOrGenerator, init, update) {
if (!noiseOrGenerator) {
return;
}
if (typeof noiseOrGenerator === "function") {
this.noise.generate = noiseOrGenerator;
if (init) {
this.noise.init = init;
}
if (update) {
this.noise.update = update;
}
} else {
if (noiseOrGenerator.generate) {
this.noise.generate = noiseOrGenerator.generate;
}
if (noiseOrGenerator.init) {
this.noise.init = noiseOrGenerator.init;
}
if (noiseOrGenerator.update) {
this.noise.update = noiseOrGenerator.update;
}
}
}
densityAutoParticles() {
this.initDensityFactor();
const numberOptions = this.options.particles.number;
const optParticlesNumber = numberOptions.value;
const optParticlesLimit = numberOptions.limit > 0 ? numberOptions.limit : optParticlesNumber;
const particlesNumber = Math.min(optParticlesNumber, optParticlesLimit) * this.density;
const particlesCount = this.particles.count;
if (particlesCount < particlesNumber) {
this.particles.push(Math.abs(particlesNumber - particlesCount));
} else if (particlesCount > particlesNumber) {
this.particles.removeQuantity(particlesCount - particlesNumber);
}
}
destroy() {
this.stop();
this.canvas.destroy();
delete this.interactivity;
delete this.options;
delete this.retina;
delete this.canvas;
delete this.particles;
delete this.bubble;
delete this.repulse;
delete this.attract;
delete this.drawer;
delete this.eventListeners;
for (const [, drawer] of this.drawers) {
if (drawer.destroy) {
drawer.destroy(this);
}
}
this.drawers = new Map();
this.destroyed = true;
}
exportImg(callback) {
this.exportImage(callback);
}
exportImage(callback, type, quality) {
var _a;
return (_a = this.canvas.element) === null || _a === void 0 ? void 0 : _a.toBlob(callback, type !== null && type !== void 0 ? type : "image/png", quality);
}
exportConfiguration() {
return JSON.stringify(this.options, undefined, 2);
}
refresh() {
return __awaiter(this, void 0, void 0, function* () {
this.stop();
yield this.start();
});
}
stop() {
if (!this.started) {
return;
}
this.started = false;
this.eventListeners.removeListeners();
this.pause();
this.particles.clear();
this.canvas.clear();
for (const [, plugin] of this.plugins) {
if (plugin.stop) {
plugin.stop();
}
}
this.plugins = new Map();
this.particles.linksColors = new Map();
delete this.particles.linksColor;
}
start() {
return __awaiter(this, void 0, void 0, function* () {
if (this.started) {
return;
}
yield this.init();
this.started = true;
this.eventListeners.addListeners();
for (const [, plugin] of this.plugins) {
if (plugin.startAsync !== undefined) {
yield plugin.startAsync();
} else if (plugin.start !== undefined) {
plugin.start();
}
}
this.play();
});
}
init() {
return __awaiter(this, void 0, void 0, function* () {
this.retina.init();
this.canvas.init();
const availablePlugins = Plugins.getAvailablePlugins(this);
for (const [id, plugin] of availablePlugins) {
this.plugins.set(id, plugin);
}
for (const [, drawer] of this.drawers) {
if (drawer.init) {
yield drawer.init(this);
}
}
for (const [, plugin] of this.plugins) {
if (plugin.init) {
plugin.init(this.options);
} else if (plugin.initAsync !== undefined) {
yield plugin.initAsync(this.options);
}
}
this.particles.init();
this.densityAutoParticles();
});
}
initDensityFactor() {
const densityOptions = this.options.particles.number.density;
if (!this.canvas.element || !densityOptions.enable) {
return;
}
const canvas = this.canvas.element;
const pxRatio = this.retina.pixelRatio;
this.density = canvas.width * canvas.height / (densityOptions.factor * pxRatio * densityOptions.area);
}
}
// CONCATENATED MODULE: ./dist/Core/Loader.js
const tsParticlesDom = [];
class Loader_Loader {
static dom() {
return tsParticlesDom;
}
static domItem(index) {
const dom = Loader_Loader.dom();
const item = dom[index];
if (item && !item.destroyed) {
return item;
}
dom.splice(index, 1);
}
static loadFromArray(tagId, options, index) {
return __awaiter(this, void 0, void 0, function* () {
return Loader_Loader.load(tagId, Utils_Utils.itemFromArray(options, index));
});
}
static setFromArray(id, domContainer, options, index) {
return __awaiter(this, void 0, void 0, function* () {
return Loader_Loader.set(id, domContainer, Utils_Utils.itemFromArray(options, index));
});
}
static load(tagId, options) {
return __awaiter(this, void 0, void 0, function* () {
const domContainer = document.getElementById(tagId);
if (!domContainer) {
return;
}
return Loader_Loader.set(tagId, domContainer, options);
});
}
static set(id, domContainer, options) {
return __awaiter(this, void 0, void 0, function* () {
const dom = Loader_Loader.dom();
const oldIndex = dom.findIndex(v => v.id === id);
if (oldIndex >= 0) {
const old = Loader_Loader.domItem(oldIndex);
if (old && !old.destroyed) {
old.destroy();
dom.splice(oldIndex, 1);
}
}
let canvasEl;
let generatedCanvas;
if (domContainer.tagName.toLowerCase() === "canvas") {
canvasEl = domContainer;
generatedCanvas = false;
} else {
const existingCanvases = domContainer.getElementsByTagName("canvas");
if (existingCanvases.length) {
canvasEl = existingCanvases[0];
if (!canvasEl.className) {
canvasEl.className = Constants.canvasClass;
}
generatedCanvas = false;
} else {
generatedCanvas = true;
canvasEl = document.createElement("canvas");
canvasEl.className = Constants.canvasClass;
canvasEl.style.width = "100%";
canvasEl.style.height = "100%";
domContainer.appendChild(canvasEl);
}
}
const newItem = new Container_Container(id, options);
if (oldIndex >= 0) {
dom.splice(oldIndex, 0, newItem);
} else {
dom.push(newItem);
}
newItem.canvas.loadCanvas(canvasEl, generatedCanvas);
yield newItem.start();
return newItem;
});
}
static loadJSON(tagId, jsonUrl) {
return __awaiter(this, void 0, void 0, function* () {
const response = yield fetch(jsonUrl);
if (response.ok) {
const options = yield response.json();
if (options instanceof Array) {
return Loader_Loader.loadFromArray(tagId, options);
} else {
return Loader_Loader.load(tagId, options);
}
} else {
Loader_Loader.fetchError(response.status);
}
});
}
static setJSON(id, domContainer, jsonUrl) {
return __awaiter(this, void 0, void 0, function* () {
const response = yield fetch(jsonUrl);
if (response.ok) {
const options = yield response.json();
if (options instanceof Array) {
return Loader_Loader.setFromArray(id, domContainer, options);
} else {
return Loader_Loader.set(id, domContainer, options);
}
} else {
Loader_Loader.fetchError(response.status);
}
});
}
static setOnClickHandler(callback) {
const dom = Loader_Loader.dom();
if (dom.length === 0) {
throw new Error("Can only set click handlers after calling tsParticles.load() or tsParticles.loadJSON()");
}
for (const domItem of dom) {
const el = domItem.interactivity.element;
if (!el) {
continue;
}
const clickOrTouchHandler = (e, pos) => {
if (domItem.destroyed) {
return;
}
const pxRatio = domItem.retina.pixelRatio;
const particles = domItem.particles.quadTree.query(new Circle_Circle(pos.x * pxRatio, pos.y * pxRatio, domItem.retina.sizeValue));
callback(e, particles);
};
const clickHandler = e => {
if (domItem.destroyed) {
return;
}
const mouseEvent = e;
const pos = {
x: mouseEvent.offsetX || mouseEvent.clientX,
y: mouseEvent.offsetY || mouseEvent.clientY
};
clickOrTouchHandler(e, pos);
};
const touchStartHandler = () => {
if (domItem.destroyed) {
return;
}
touched = true;
touchMoved = false;
};
const touchMoveHandler = () => {
if (domItem.destroyed) {
return;
}
touchMoved = true;
};
const touchEndHandler = e => {
var _a, _b, _c;
if (domItem.destroyed) {
return;
}
if (touched && !touchMoved) {
const touchEvent = e;
const lastTouch = touchEvent.touches[touchEvent.touches.length - 1];
const canvasRect = (_a = domItem.canvas.element) === null || _a === void 0 ? void 0 : _a.getBoundingClientRect();
const pos = {
x: lastTouch.clientX - ((_b = canvasRect === null || canvasRect === void 0 ? void 0 : canvasRect.left) !== null && _b !== void 0 ? _b : 0),
y: lastTouch.clientY - ((_c = canvasRect === null || canvasRect === void 0 ? void 0 : canvasRect.top) !== null && _c !== void 0 ? _c : 0)
};
clickOrTouchHandler(e, pos);
}
touched = false;
touchMoved = false;
};
const touchCancelHandler = () => {
if (domItem.destroyed) {
return;
}
touched = false;
touchMoved = false;
};
let touched = false;
let touchMoved = false;
el.addEventListener("click", clickHandler);
el.addEventListener("touchstart", touchStartHandler);
el.addEventListener("touchmove", touchMoveHandler);
el.addEventListener("touchend", touchEndHandler);
el.addEventListener("touchcancel", touchCancelHandler);
}
}
static fetchError(statusCode) {
console.error(`Error tsParticles - fetch status: ${statusCode}`);
console.error("Error tsParticles - File config not found");
}
}
// CONCATENATED MODULE: ./dist/main.slim.js
class main_slim_MainSlim {
constructor() {
this.initialized = false;
const squareDrawer = new SquareDrawer();
const textDrawer = new TextDrawer_TextDrawer();
const imageDrawer = new ImageDrawer_ImageDrawer();
Plugins.addShapeDrawer(ShapeType.line, new LineDrawer());
Plugins.addShapeDrawer(ShapeType.circle, new CircleDrawer());
Plugins.addShapeDrawer(ShapeType.edge, squareDrawer);
Plugins.addShapeDrawer(ShapeType.square, squareDrawer);
Plugins.addShapeDrawer(ShapeType.triangle, new TriangleDrawer_TriangleDrawer());
Plugins.addShapeDrawer(ShapeType.star, new StarDrawer());
Plugins.addShapeDrawer(ShapeType.polygon, new PolygonDrawer_PolygonDrawer());
Plugins.addShapeDrawer(ShapeType.char, textDrawer);
Plugins.addShapeDrawer(ShapeType.character, textDrawer);
Plugins.addShapeDrawer(ShapeType.image, imageDrawer);
Plugins.addShapeDrawer(ShapeType.images, imageDrawer);
}
init() {
if (!this.initialized) {
this.initialized = true;
}
}
loadFromArray(tagId, options, index) {
return __awaiter(this, void 0, void 0, function* () {
return Loader_Loader.loadFromArray(tagId, options, index);
});
}
load(tagId, options) {
return __awaiter(this, void 0, void 0, function* () {
return Loader_Loader.load(tagId, options);
});
}
set(id, element, options) {
return __awaiter(this, void 0, void 0, function* () {
return Loader_Loader.set(id, element, options);
});
}
loadJSON(tagId, pathConfigJson) {
return Loader_Loader.loadJSON(tagId, pathConfigJson);
}
setOnClickHandler(callback) {
Loader_Loader.setOnClickHandler(callback);
}
dom() {
return Loader_Loader.dom();
}
domItem(index) {
return Loader_Loader.domItem(index);
}
addShape(shape, drawer, init, afterEffect, destroy) {
let customDrawer;
if (typeof drawer === "function") {
customDrawer = {
afterEffect: afterEffect,
destroy: destroy,
draw: drawer,
init: init
};
} else {
customDrawer = drawer;
}
Plugins.addShapeDrawer(shape, customDrawer);
}
addPreset(preset, options) {
Plugins.addPreset(preset, options);
}
addPlugin(plugin) {
Plugins.addPlugin(plugin);
}
}
// CONCATENATED MODULE: ./dist/Plugins/Absorbers/AbsorberInstance.js
class AbsorberInstance_AbsorberInstance {
constructor(absorbers, container, options, position) {
var _a, _b;
this.absorbers = absorbers;
this.container = container;
this.initialPosition = position;
this.options = options;
this.dragging = false;
let size = options.size.value * container.retina.pixelRatio;
const random = typeof options.size.random === "boolean" ? options.size.random : options.size.random.enable;
const minSize = typeof options.size.random === "boolean" ? 1 : options.size.random.minimumValue;
if (random) {
size = Utils_Utils.randomInRange(minSize, size);
}
this.opacity = this.options.opacity;
this.size = size * container.retina.pixelRatio;
this.mass = this.size * options.size.density;
const limit = options.size.limit;
this.limit = limit !== undefined ? limit * container.retina.pixelRatio : limit;
const color = typeof options.color === "string" ? {
value: options.color
} : options.color;
this.color = (_a = ColorUtils_ColorUtils.colorToRgb(color)) !== null && _a !== void 0 ? _a : {
b: 0,
g: 0,
r: 0
};
this.position = (_b = this.initialPosition) !== null && _b !== void 0 ? _b : this.calcPosition();
}
attract(particle) {
const options = this.options;
if (options.draggable) {
const mouse = this.container.interactivity.mouse;
if (mouse.clicking && mouse.downPosition) {
const mouseDist = Utils_Utils.getDistance(this.position, mouse.downPosition);
if (mouseDist <= this.size) {
this.dragging = true;
}
} else {
this.dragging = false;
}
if (this.dragging && mouse.position) {
this.position.x = mouse.position.x;
this.position.y = mouse.position.y;
}
}
const pos = particle.getPosition();
const {
dx,
dy,
distance
} = Utils_Utils.getDistances(this.position, pos);
const angle = Math.atan2(dx, dy);
const acceleration = this.mass / Math.pow(distance, 2);
if (distance < this.size + particle.size.value) {
const sizeFactor = particle.size.value * 0.033 * this.container.retina.pixelRatio;
if (this.size > particle.size.value && distance < this.size - particle.size.value) {
if (options.destroy) {
particle.destroy();
} else {
particle.needsNewPosition = true;
this.updateParticlePosition(particle, angle, acceleration);
}
} else {
if (options.destroy) {
particle.size.value -= sizeFactor;
}
this.updateParticlePosition(particle, angle, acceleration);
}
if (this.limit === undefined || this.size < this.limit) {
this.size += sizeFactor;
}
this.mass += sizeFactor * this.options.size.density;
} else {
this.updateParticlePosition(particle, angle, acceleration);
}
}
resize() {
const initialPosition = this.initialPosition;
this.position = initialPosition && Utils_Utils.isPointInside(initialPosition, this.container.canvas.size) ? initialPosition : this.calcPosition();
}
draw(context) {
context.translate(this.position.x, this.position.y);
context.beginPath();
context.arc(0, 0, this.size, 0, Math.PI * 2, false);
context.closePath();
context.fillStyle = ColorUtils_ColorUtils.getStyleFromRgb(this.color, this.opacity);
context.fill();
}
calcPosition() {
var _a;
const container = this.container;
const percentPosition = (_a = this.options.position) !== null && _a !== void 0 ? _a : {
x: Math.random() * 100,
y: Math.random() * 100
};
return {
x: percentPosition.x / 100 * container.canvas.size.width,
y: percentPosition.y / 100 * container.canvas.size.height
};
}
updateParticlePosition(particle, angle, acceleration) {
var _a;
if (particle.destroyed) {
return;
}
const canvasSize = this.container.canvas.size;
if (particle.needsNewPosition) {
const pSize = particle.size.value;
particle.position.x = Math.random() * (canvasSize.width - pSize * 2) + pSize;
particle.position.y = Math.random() * (canvasSize.height - pSize * 2) + pSize;
particle.needsNewPosition = false;
}
if (this.options.orbits) {
if (particle.orbitRadius === undefined) {
particle.orbitRadius = Utils_Utils.getDistance(particle.getPosition(), this.position);
}
if (particle.orbitRadius <= this.size && !this.options.destroy) {
particle.orbitRadius = Math.random() * Math.max(canvasSize.width, canvasSize.height);
}
if (particle.orbitAngle === undefined) {
particle.orbitAngle = Math.random() * Math.PI * 2;
}
const orbitRadius = particle.orbitRadius;
const orbitAngle = particle.orbitAngle;
particle.velocity.horizontal = 0;
particle.velocity.vertical = 0;
particle.position.x = this.position.x + orbitRadius * Math.cos(orbitAngle);
particle.position.y = this.position.y + orbitRadius * Math.sin(orbitAngle);
particle.orbitRadius -= acceleration;
particle.orbitAngle += ((_a = particle.moveSpeed) !== null && _a !== void 0 ? _a : this.container.retina.moveSpeed) / 100;
} else {
particle.velocity.horizontal += Math.sin(angle) * acceleration;
particle.velocity.vertical += Math.cos(angle) * acceleration;
}
}
}
// CONCATENATED MODULE: ./dist/Plugins/Absorbers/Options/Classes/AbsorberRandomSize.js
class AbsorberRandomSize {
constructor() {
this.enable = false;
this.minimumValue = 1;
}
load(data) {
if (data !== undefined) {
if (data.enable !== undefined) {
this.enable = data.enable;
}
if (data.minimumValue !== undefined) {
this.minimumValue = data.minimumValue;
}
}
}
}
// CONCATENATED MODULE: ./dist/Plugins/Absorbers/Options/Classes/AbsorberSize.js
class AbsorberSize_AbsorberSize {
constructor() {
this.density = 5;
this.random = new AbsorberRandomSize();
this.value = 50;
}
load(data) {
if (data !== undefined) {
if (data.density !== undefined) {
this.density = data.density;
}
if (data.value !== undefined) {
this.value = data.value;
}
if (data.random !== undefined) {
if (typeof data.random === "boolean") {
this.random.load({
enable: data.random
});
} else {
this.random.load(data.random);
}
}
if (data.limit !== undefined) {
this.limit = data.limit;
}
}
}
}
// CONCATENATED MODULE: ./dist/Plugins/Absorbers/Options/Classes/Absorber.js
class Absorber_Absorber {
constructor() {
this.color = new OptionsColor();
this.color.value = "#000000";
this.draggable = false;
this.opacity = 1;
this.destroy = true;
this.orbits = false;
this.size = new AbsorberSize_AbsorberSize();
}
load(data) {
if (data !== undefined) {
if (data.color !== undefined) {
this.color = OptionsColor.create(this.color, data.color);
}
if (data.draggable !== undefined) {
this.draggable = data.draggable;
}
if (data.opacity !== undefined) {
this.opacity = data.opacity;
}
if (data.position !== undefined) {
this.position = {
x: data.position.x,
y: data.position.y
};
}
if (data.size !== undefined) {
this.size.load(data.size);
}
if (data.destroy !== undefined) {
this.destroy = data.destroy;
}
if (data.orbits !== undefined) {
this.orbits = data.orbits;
}
}
}
}
// CONCATENATED MODULE: ./dist/Plugins/Absorbers/Enums/AbsorberClickMode.js
var AbsorberClickMode;
(function (AbsorberClickMode) {
AbsorberClickMode["absorber"] = "absorber";
})(AbsorberClickMode || (AbsorberClickMode = {}));
// CONCATENATED MODULE: ./dist/Plugins/Absorbers/Absorbers.js
class Absorbers_Absorbers {
constructor(container) {
this.container = container;
this.array = [];
this.absorbers = [];
this.interactivityAbsorbers = [];
}
init(options) {
var _a, _b;
if (!options) {
return;
}
if (options.absorbers) {
if (options.absorbers instanceof Array) {
this.absorbers = options.absorbers.map(s => {
const tmp = new Absorber_Absorber();
tmp.load(s);
return tmp;
});
} else {
if (this.absorbers instanceof Array) {
this.absorbers = new Absorber_Absorber();
}
this.absorbers.load(options.absorbers);
}
}
const interactivityAbsorbers = (_b = (_a = options.interactivity) === null || _a === void 0 ? void 0 : _a.modes) === null || _b === void 0 ? void 0 : _b.absorbers;
if (interactivityAbsorbers) {
if (interactivityAbsorbers instanceof Array) {
this.interactivityAbsorbers = interactivityAbsorbers.map(s => {
const tmp = new Absorber_Absorber();
tmp.load(s);
return tmp;
});
} else {
if (this.interactivityAbsorbers instanceof Array) {
this.interactivityAbsorbers = new Absorber_Absorber();
}
this.interactivityAbsorbers.load(interactivityAbsorbers);
}
}
if (this.absorbers instanceof Array) {
for (const absorberOptions of this.absorbers) {
const absorber = new AbsorberInstance_AbsorberInstance(this, this.container, absorberOptions);
this.addAbsorber(absorber);
}
} else {
const absorberOptions = this.absorbers;
const absorber = new AbsorberInstance_AbsorberInstance(this, this.container, absorberOptions);
this.addAbsorber(absorber);
}
}
particleUpdate(particle) {
for (const absorber of this.array) {
absorber.attract(particle);
if (particle.destroyed) {
break;
}
}
}
draw(context) {
for (const absorber of this.array) {
context.save();
absorber.draw(context);
context.restore();
}
}
stop() {
this.array = [];
}
resize() {
for (const absorber of this.array) {
absorber.resize();
}
}
handleClickMode(mode) {
const container = this.container;
const absorberOptions = this.absorbers;
const modeAbsorbers = this.interactivityAbsorbers;
if (mode === AbsorberClickMode.absorber) {
let absorbersModeOptions;
if (modeAbsorbers instanceof Array) {
if (modeAbsorbers.length > 0) {
absorbersModeOptions = Utils_Utils.itemFromArray(modeAbsorbers);
}
} else {
absorbersModeOptions = modeAbsorbers;
}
const absorbersOptions = absorbersModeOptions !== null && absorbersModeOptions !== void 0 ? absorbersModeOptions : absorberOptions instanceof Array ? Utils_Utils.itemFromArray(absorberOptions) : absorberOptions;
const aPosition = container.interactivity.mouse.clickPosition;
const absorber = new AbsorberInstance_AbsorberInstance(this, this.container, absorbersOptions, aPosition);
this.addAbsorber(absorber);
}
}
addAbsorber(absorber) {
this.array.push(absorber);
}
removeAbsorber(absorber) {
const index = this.array.indexOf(absorber);
if (index >= 0) {
this.array.splice(index, 1);
}
}
}
// CONCATENATED MODULE: ./dist/Plugins/Absorbers/AbsorbersPlugin.js
class AbsorbersPlugin_AbsorbersPlugin {
constructor() {
this.id = "absorbers";
}
getPlugin(container) {
return new Absorbers_Absorbers(container);
}
needsPlugin(options) {
var _a, _b, _c;
if (options === undefined) {
return false;
}
const absorbers = options.absorbers;
let loadAbsorbers = false;
if (absorbers instanceof Array) {
if (absorbers.length) {
loadAbsorbers = true;
}
} else if (absorbers !== undefined) {
loadAbsorbers = true;
} else if (((_c = (_b = (_a = options.interactivity) === null || _a === void 0 ? void 0 : _a.events) === null || _b === void 0 ? void 0 : _b.onClick) === null || _c === void 0 ? void 0 : _c.mode) && Utils_Utils.isInArray(AbsorberClickMode.absorber, options.interactivity.events.onClick.mode)) {
loadAbsorbers = true;
}
return loadAbsorbers;
}
loadOptions(options, source) {
var _a, _b;
if (!this.needsPlugin(options) && !this.needsPlugin(source)) {
return;
}
const optionsCast = options;
if (source === null || source === void 0 ? void 0 : source.absorbers) {
if ((source === null || source === void 0 ? void 0 : source.absorbers) instanceof Array) {
optionsCast.absorbers = source === null || source === void 0 ? void 0 : source.absorbers.map(s => {
const tmp = new Absorber_Absorber();
tmp.load(s);
return tmp;
});
} else {
let absorberOptions = optionsCast.absorbers;
if ((absorberOptions === null || absorberOptions === void 0 ? void 0 : absorberOptions.load) === undefined) {
optionsCast.absorbers = absorberOptions = new Absorber_Absorber();
}
absorberOptions.load(source === null || source === void 0 ? void 0 : source.absorbers);
}
}
const interactivityAbsorbers = (_b = (_a = source === null || source === void 0 ? void 0 : source.interactivity) === null || _a === void 0 ? void 0 : _a.modes) === null || _b === void 0 ? void 0 : _b.absorbers;
if (interactivityAbsorbers) {
if (interactivityAbsorbers instanceof Array) {
optionsCast.interactivity.modes.absorbers = interactivityAbsorbers.map(s => {
const tmp = new Absorber_Absorber();
tmp.load(s);
return tmp;
});
} else {
let absorberOptions = optionsCast.interactivity.modes.absorbers;
if ((absorberOptions === null || absorberOptions === void 0 ? void 0 : absorberOptions.load) === undefined) {
optionsCast.interactivity.modes.absorbers = absorberOptions = new Absorber_Absorber();
}
absorberOptions.load(interactivityAbsorbers);
}
}
}
}
const AbsorbersPlugin_plugin = new AbsorbersPlugin_AbsorbersPlugin();
// CONCATENATED MODULE: ./dist/Enums/Modes/SizeMode.js
var SizeMode;
(function (SizeMode) {
SizeMode["precise"] = "precise";
SizeMode["percent"] = "percent";
})(SizeMode || (SizeMode = {}));
// CONCATENATED MODULE: ./dist/Plugins/Emitters/Options/Classes/EmitterSize.js
class EmitterSize_EmitterSize {
constructor() {
this.mode = SizeMode.percent;
this.height = 0;
this.width = 0;
}
load(data) {
if (data !== undefined) {
if (data.mode !== undefined) {
this.mode = data.mode;
}
if (data.height !== undefined) {
this.height = data.height;
}
if (data.width !== undefined) {
this.width = data.width;
}
}
}
}
// CONCATENATED MODULE: ./dist/Plugins/Emitters/EmitterInstance.js
class EmitterInstance_EmitterInstance {
constructor(emitters, container, emitterOptions, position) {
var _a, _b, _c;
this.emitters = emitters;
this.container = container;
this.initialPosition = position;
this.emitterOptions = Utils_Utils.deepExtend({}, emitterOptions);
this.position = (_a = this.initialPosition) !== null && _a !== void 0 ? _a : this.calcPosition();
let particlesOptions = Utils_Utils.deepExtend({}, this.emitterOptions.particles);
if (particlesOptions === undefined) {
particlesOptions = {};
}
if (particlesOptions.move === undefined) {
particlesOptions.move = {};
}
if (particlesOptions.move.direction === undefined) {
particlesOptions.move.direction = this.emitterOptions.direction;
}
this.particlesOptions = particlesOptions;
this.size = (_b = this.emitterOptions.size) !== null && _b !== void 0 ? _b : (() => {
const size = new EmitterSize_EmitterSize();
size.load({
height: 0,
mode: SizeMode.percent,
width: 0
});
return size;
})();
this.lifeCount = (_c = this.emitterOptions.life.count) !== null && _c !== void 0 ? _c : -1;
this.immortal = this.lifeCount <= 0;
this.play();
}
play() {
if (this.lifeCount > 0 || this.immortal || !this.emitterOptions.life.count) {
if (this.startInterval === undefined) {
this.startInterval = window.setInterval(() => {
this.emit();
}, 1000 * this.emitterOptions.rate.delay);
}
if (this.lifeCount > 0 || this.immortal) {
this.prepareToDie();
}
}
}
pause() {
const interval = this.startInterval;
if (interval !== undefined) {
clearInterval(interval);
delete this.startInterval;
}
}
resize() {
const initialPosition = this.initialPosition;
this.position = initialPosition && Utils_Utils.isPointInside(initialPosition, this.container.canvas.size) ? initialPosition : this.calcPosition();
}
prepareToDie() {
var _a;
const duration = (_a = this.emitterOptions.life) === null || _a === void 0 ? void 0 : _a.duration;
if ((this.lifeCount > 0 || this.immortal) && duration !== undefined && duration > 0) {
window.setTimeout(() => {
var _a;
this.pause();
if (!this.immortal) {
this.lifeCount--;
}
if (this.lifeCount > 0 || this.immortal) {
this.position = this.calcPosition();
window.setTimeout(() => {
this.play();
}, ((_a = this.emitterOptions.life.delay) !== null && _a !== void 0 ? _a : 0) * 1000);
} else {
this.destroy();
}
}, duration * 1000);
}
}
destroy() {
this.emitters.removeEmitter(this);
}
calcPosition() {
var _a;
const container = this.container;
const percentPosition = (_a = this.emitterOptions.position) !== null && _a !== void 0 ? _a : {
x: Math.random() * 100,
y: Math.random() * 100
};
return {
x: percentPosition.x / 100 * container.canvas.size.width,
y: percentPosition.y / 100 * container.canvas.size.height
};
}
emit() {
const container = this.container;
const position = this.position;
const offset = {
x: this.size.mode === SizeMode.percent ? container.canvas.size.width * this.size.width / 100 : this.size.width,
y: this.size.mode === SizeMode.percent ? container.canvas.size.height * this.size.height / 100 : this.size.height
};
for (let i = 0; i < this.emitterOptions.rate.quantity; i++) {
container.particles.addParticle({
x: position.x + offset.x * (Math.random() - 0.5),
y: position.y + offset.y * (Math.random() - 0.5)
}, this.particlesOptions);
}
}
}
// CONCATENATED MODULE: ./dist/Plugins/Emitters/Options/Classes/EmitterRate.js
class EmitterRate {
constructor() {
this.quantity = 1;
this.delay = 0.1;
}
load(data) {
if (data !== undefined) {
if (data.quantity !== undefined) {
this.quantity = data.quantity;
}
if (data.delay !== undefined) {
this.delay = data.delay;
}
}
}
}
// CONCATENATED MODULE: ./dist/Plugins/Emitters/Options/Classes/EmitterLife.js
class EmitterLife {
load(data) {
if (data !== undefined) {
if (data.count !== undefined) {
this.count = data.count;
}
if (data.delay !== undefined) {
this.delay = data.delay;
}
if (data.duration !== undefined) {
this.duration = data.duration;
}
}
}
}
// CONCATENATED MODULE: ./dist/Plugins/Emitters/Options/Classes/Emitter.js
class Emitter_Emitter {
constructor() {
this.direction = MoveDirection.none;
this.life = new EmitterLife();
this.rate = new EmitterRate();
}
load(data) {
if (data !== undefined) {
if (data.size !== undefined) {
if (this.size === undefined) {
this.size = new EmitterSize_EmitterSize();
}
this.size.load(data.size);
}
if (data.direction !== undefined) {
this.direction = data.direction;
}
this.life.load(data.life);
if (data.particles !== undefined) {
this.particles = Utils_Utils.deepExtend({}, data.particles);
}
this.rate.load(data.rate);
if (data.position !== undefined) {
this.position = {
x: data.position.x,
y: data.position.y
};
}
}
}
}
// CONCATENATED MODULE: ./dist/Plugins/Emitters/Enums/EmitterClickMode.js
var EmitterClickMode;
(function (EmitterClickMode) {
EmitterClickMode["emitter"] = "emitter";
})(EmitterClickMode || (EmitterClickMode = {}));
// CONCATENATED MODULE: ./dist/Plugins/Emitters/Emitters.js
class Emitters_Emitters {
constructor(container) {
this.container = container;
this.array = [];
this.emitters = [];
this.interactivityEmitters = [];
}
init(options) {
var _a, _b;
if (!options) {
return;
}
if (options.emitters) {
if (options.emitters instanceof Array) {
this.emitters = options.emitters.map(s => {
const tmp = new Emitter_Emitter();
tmp.load(s);
return tmp;
});
} else {
if (this.emitters instanceof Array) {
this.emitters = new Emitter_Emitter();
}
this.emitters.load(options.emitters);
}
}
const interactivityEmitters = (_b = (_a = options.interactivity) === null || _a === void 0 ? void 0 : _a.modes) === null || _b === void 0 ? void 0 : _b.emitters;
if (interactivityEmitters) {
if (interactivityEmitters instanceof Array) {
this.interactivityEmitters = interactivityEmitters.map(s => {
const tmp = new Emitter_Emitter();
tmp.load(s);
return tmp;
});
} else {
if (this.interactivityEmitters instanceof Array) {
this.interactivityEmitters = new Emitter_Emitter();
}
this.interactivityEmitters.load(interactivityEmitters);
}
}
if (this.emitters instanceof Array) {
for (const emitterOptions of this.emitters) {
const emitter = new EmitterInstance_EmitterInstance(this, this.container, emitterOptions);
this.addEmitter(emitter);
}
} else {
const emitterOptions = this.emitters;
const emitter = new EmitterInstance_EmitterInstance(this, this.container, emitterOptions);
this.addEmitter(emitter);
}
}
play() {
for (const emitter of this.array) {
emitter.play();
}
}
pause() {
for (const emitter of this.array) {
emitter.pause();
}
}
stop() {
this.array = [];
}
handleClickMode(mode) {
const container = this.container;
const emitterOptions = this.emitters;
const modeEmitters = this.interactivityEmitters;
if (mode === EmitterClickMode.emitter) {
let emitterModeOptions;
if (modeEmitters instanceof Array) {
if (modeEmitters.length > 0) {
emitterModeOptions = Utils_Utils.itemFromArray(modeEmitters);
}
} else {
emitterModeOptions = modeEmitters;
}
const emittersOptions = emitterModeOptions !== null && emitterModeOptions !== void 0 ? emitterModeOptions : emitterOptions instanceof Array ? Utils_Utils.itemFromArray(emitterOptions) : emitterOptions;
const ePosition = container.interactivity.mouse.clickPosition;
const emitter = new EmitterInstance_EmitterInstance(this, this.container, Utils_Utils.deepExtend({}, emittersOptions), ePosition);
this.addEmitter(emitter);
}
}
resize() {
for (const emitter of this.array) {
emitter.resize();
}
}
addEmitter(emitter) {
this.array.push(emitter);
}
removeEmitter(emitter) {
const index = this.array.indexOf(emitter);
if (index >= 0) {
this.array.splice(index, 1);
}
}
}
// CONCATENATED MODULE: ./dist/Plugins/Emitters/EmittersPlugin.js
class EmittersPlugin_EmittersPlugin {
constructor() {
this.id = "emitters";
}
getPlugin(container) {
return new Emitters_Emitters(container);
}
needsPlugin(options) {
var _a, _b, _c;
if (options === undefined) {
return false;
}
const emitters = options.emitters;
let loadEmitters = false;
if (emitters instanceof Array) {
if (emitters.length) {
loadEmitters = true;
}
} else if (emitters !== undefined) {
loadEmitters = true;
} else if (((_c = (_b = (_a = options.interactivity) === null || _a === void 0 ? void 0 : _a.events) === null || _b === void 0 ? void 0 : _b.onClick) === null || _c === void 0 ? void 0 : _c.mode) && Utils_Utils.isInArray(EmitterClickMode.emitter, options.interactivity.events.onClick.mode)) {
loadEmitters = true;
}
return loadEmitters;
}
loadOptions(options, source) {
var _a, _b;
if (!this.needsPlugin(options) && !this.needsPlugin(source)) {
return;
}
const optionsCast = options;
if (source === null || source === void 0 ? void 0 : source.emitters) {
if ((source === null || source === void 0 ? void 0 : source.emitters) instanceof Array) {
optionsCast.emitters = source === null || source === void 0 ? void 0 : source.emitters.map(s => {
const tmp = new Emitter_Emitter();
tmp.load(s);
return tmp;
});
} else {
let emitterOptions = optionsCast.emitters;
if ((emitterOptions === null || emitterOptions === void 0 ? void 0 : emitterOptions.load) === undefined) {
optionsCast.emitters = emitterOptions = new Emitter_Emitter();
}
emitterOptions.load(source === null || source === void 0 ? void 0 : source.emitters);
}
}
const interactivityEmitters = (_b = (_a = source === null || source === void 0 ? void 0 : source.interactivity) === null || _a === void 0 ? void 0 : _a.modes) === null || _b === void 0 ? void 0 : _b.emitters;
if (interactivityEmitters) {
if (interactivityEmitters instanceof Array) {
optionsCast.interactivity.modes.emitters = interactivityEmitters.map(s => {
const tmp = new Emitter_Emitter();
tmp.load(s);
return tmp;
});
} else {
let emitterOptions = optionsCast.interactivity.modes.emitters;
if ((emitterOptions === null || emitterOptions === void 0 ? void 0 : emitterOptions.load) === undefined) {
optionsCast.interactivity.modes.emitters = emitterOptions = new Emitter_Emitter();
}
emitterOptions.load(interactivityEmitters);
}
}
}
}
const EmittersPlugin_plugin = new EmittersPlugin_EmittersPlugin();
// CONCATENATED MODULE: ./dist/Plugins/PolygonMask/Enums/Type.js
var Type;
(function (Type) {
Type["inline"] = "inline";
Type["inside"] = "inside";
Type["outside"] = "outside";
Type["none"] = "none";
})(Type || (Type = {}));
// CONCATENATED MODULE: ./dist/Plugins/PolygonMask/Enums/InlineArrangement.js
var InlineArrangement;
(function (InlineArrangement) {
InlineArrangement["equidistant"] = "equidistant";
InlineArrangement["onePerPoint"] = "one-per-point";
InlineArrangement["perPoint"] = "per-point";
InlineArrangement["randomLength"] = "random-length";
InlineArrangement["randomPoint"] = "random-point";
})(InlineArrangement || (InlineArrangement = {}));
// CONCATENATED MODULE: ./dist/Plugins/PolygonMask/Options/Classes/DrawStroke.js
class DrawStroke_DrawStroke {
constructor() {
this.color = new OptionsColor();
this.width = 0.5;
this.opacity = 1;
}
load(data) {
var _a;
if (data !== undefined) {
this.color = OptionsColor.create(this.color, data.color);
if (typeof this.color.value === "string") {
this.opacity = (_a = ColorUtils_ColorUtils.stringToAlpha(this.color.value)) !== null && _a !== void 0 ? _a : this.opacity;
}
if (data.opacity !== undefined) {
this.opacity = data.opacity;
}
if (data.width !== undefined) {
this.width = data.width;
}
}
}
}
// CONCATENATED MODULE: ./dist/Plugins/PolygonMask/Options/Classes/Draw.js
class Draw_Draw {
constructor() {
this.enable = false;
this.stroke = new DrawStroke_DrawStroke();
}
get lineWidth() {
return this.stroke.width;
}
set lineWidth(value) {
this.stroke.width = value;
}
get lineColor() {
return this.stroke.color;
}
set lineColor(value) {
this.stroke.color = OptionsColor.create(this.stroke.color, value);
}
load(data) {
var _a;
if (data !== undefined) {
if (data.enable !== undefined) {
this.enable = data.enable;
}
const stroke = (_a = data.stroke) !== null && _a !== void 0 ? _a : {
color: data.lineColor,
width: data.lineWidth
};
this.stroke.load(stroke);
}
}
}
// CONCATENATED MODULE: ./dist/Plugins/PolygonMask/Enums/MoveType.js
var MoveType;
(function (MoveType) {
MoveType["path"] = "path";
MoveType["radius"] = "radius";
})(MoveType || (MoveType = {}));
// CONCATENATED MODULE: ./dist/Plugins/PolygonMask/Options/Classes/Move.js
class Classes_Move_Move {
constructor() {
this.radius = 10;
this.type = MoveType.path;
}
load(data) {
if (data !== undefined) {
if (data.radius !== undefined) {
this.radius = data.radius;
}
if (data.type !== undefined) {
this.type = data.type;
}
}
}
}
// CONCATENATED MODULE: ./dist/Plugins/PolygonMask/Options/Classes/Inline.js
class Inline_Inline {
constructor() {
this.arrangement = InlineArrangement.onePerPoint;
}
load(data) {
if (data !== undefined) {
if (data.arrangement !== undefined) {
this.arrangement = data.arrangement;
}
}
}
}
// CONCATENATED MODULE: ./dist/Plugins/PolygonMask/Options/Classes/LocalSvg.js
class LocalSvg {
constructor() {
this.path = [];
this.size = {
height: 0,
width: 0
};
}
load(data) {
if (data !== undefined) {
if (data.path !== undefined) {
this.path = data.path;
}
if (data.size !== undefined) {
if (data.size.width !== undefined) {
this.size.width = data.size.width;
}
if (data.size.height !== undefined) {
this.size.height = data.size.height;
}
}
}
}
}
// CONCATENATED MODULE: ./dist/Plugins/PolygonMask/Options/Classes/PolygonMask.js
class PolygonMask_PolygonMask {
constructor() {
this.draw = new Draw_Draw();
this.enable = false;
this.inline = new Inline_Inline();
this.move = new Classes_Move_Move();
this.scale = 1;
this.type = Type.none;
}
get inlineArrangement() {
return this.inline.arrangement;
}
set inlineArrangement(value) {
this.inline.arrangement = value;
}
load(data) {
var _a;
if (data !== undefined) {
this.draw.load(data.draw);
const inline = (_a = data.inline) !== null && _a !== void 0 ? _a : {
arrangement: data.inlineArrangement
};
if (inline !== undefined) {
this.inline.load(inline);
}
this.move.load(data.move);
if (data.scale !== undefined) {
this.scale = data.scale;
}
if (data.type !== undefined) {
this.type = data.type;
}
if (data.enable !== undefined) {
this.enable = data.enable;
} else {
this.enable = this.type !== Type.none;
}
if (data.url !== undefined) {
this.url = data.url;
}
if (data.data !== undefined) {
if (typeof data.data === "string") {
this.data = data.data;
} else {
this.data = new LocalSvg();
this.data.load(data.data);
}
}
if (data.position !== undefined) {
this.position = {
x: data.position.x,
y: data.position.y
};
}
}
}
}
// CONCATENATED MODULE: ./dist/Plugins/PolygonMask/PolygonMaskInstance.js
class PolygonMaskInstance_PolygonMaskInstance {
constructor(container) {
this.container = container;
this.dimension = {
height: 0,
width: 0
};
this.path2DSupported = !!window.Path2D;
this.options = new PolygonMask_PolygonMask();
this.polygonMaskMoveRadius = this.options.move.radius * container.retina.pixelRatio;
}
static polygonBounce(particle) {
particle.velocity.horizontal = particle.velocity.vertical / 2 - particle.velocity.horizontal;
particle.velocity.vertical = particle.velocity.horizontal / 2 - particle.velocity.vertical;
}
static drawPolygonMask(context, rawData, stroke) {
const color = ColorUtils_ColorUtils.colorToRgb(stroke.color);
if (!color) {
return;
}
context.beginPath();
context.moveTo(rawData[0].x, rawData[0].y);
for (const item of rawData) {
context.lineTo(item.x, item.y);
}
context.closePath();
context.strokeStyle = ColorUtils_ColorUtils.getStyleFromRgb(color);
context.lineWidth = stroke.width;
context.stroke();
}
static drawPolygonMaskPath(context, path, stroke, position) {
context.translate(position.x, position.y);
const color = ColorUtils_ColorUtils.colorToRgb(stroke.color);
if (!color) {
return;
}
context.strokeStyle = ColorUtils_ColorUtils.getStyleFromRgb(color, stroke.opacity);
context.lineWidth = stroke.width;
context.stroke(path);
}
static parsePaths(paths, scale, offset) {
const res = [];
for (const path of paths) {
const segments = path.element.pathSegList;
const len = segments.numberOfItems;
const p = {
x: 0,
y: 0
};
for (let i = 0; i < len; i++) {
const segment = segments.getItem(i);
const svgPathSeg = window.SVGPathSeg;
switch (segment.pathSegType) {
case svgPathSeg.PATHSEG_MOVETO_ABS:
case svgPathSeg.PATHSEG_LINETO_ABS:
case svgPathSeg.PATHSEG_CURVETO_CUBIC_ABS:
case svgPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS:
case svgPathSeg.PATHSEG_ARC_ABS:
case svgPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS:
case svgPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS:
{
const absSeg = segment;
p.x = absSeg.x;
p.y = absSeg.y;
break;
}
case svgPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS:
p.x = segment.x;
break;
case svgPathSeg.PATHSEG_LINETO_VERTICAL_ABS:
p.y = segment.y;
break;
case svgPathSeg.PATHSEG_LINETO_REL:
case svgPathSeg.PATHSEG_MOVETO_REL:
case svgPathSeg.PATHSEG_CURVETO_CUBIC_REL:
case svgPathSeg.PATHSEG_CURVETO_QUADRATIC_REL:
case svgPathSeg.PATHSEG_ARC_REL:
case svgPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL:
case svgPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL:
{
const relSeg = segment;
p.x += relSeg.x;
p.y += relSeg.y;
break;
}
case svgPathSeg.PATHSEG_LINETO_HORIZONTAL_REL:
p.x += segment.x;
break;
case svgPathSeg.PATHSEG_LINETO_VERTICAL_REL:
p.y += segment.y;
break;
case svgPathSeg.PATHSEG_UNKNOWN:
case svgPathSeg.PATHSEG_CLOSEPATH:
continue;
}
res.push({
x: p.x * scale + offset.x,
y: p.y * scale + offset.y
});
}
}
return res;
}
initAsync(options) {
return __awaiter(this, void 0, void 0, function* () {
this.options.load(options === null || options === void 0 ? void 0 : options.polygon);
const polygonMaskOptions = this.options;
this.polygonMaskMoveRadius = polygonMaskOptions.move.radius * this.container.retina.pixelRatio;
if (polygonMaskOptions.enable) {
yield this.initRawData();
}
});
}
resize() {
const container = this.container;
const options = this.options;
if (!(options.enable && options.type !== Type.none)) {
return;
}
if (this.redrawTimeout) {
clearTimeout(this.redrawTimeout);
}
this.redrawTimeout = window.setTimeout(() => __awaiter(this, void 0, void 0, function* () {
yield this.initRawData(true);
container.particles.redraw();
}), 250);
}
stop() {
delete this.raw;
delete this.paths;
}
particlesInitialization() {
const options = this.options;
if (options.enable && options.type === Type.inline && (options.inline.arrangement === InlineArrangement.onePerPoint || options.inline.arrangement === InlineArrangement.perPoint)) {
this.drawPoints();
return true;
}
return false;
}
particlePosition(position, particle) {
var _a, _b;
const options = this.options;
if (!(options.enable && ((_b = (_a = this.raw) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0)) {
return;
}
const pos = Utils_Utils.deepExtend({}, position ? position : this.randomPoint());
if (options.type === Type.inline && particle) {
particle.initialPosition = pos;
}
return pos;
}
particleBounce(particle) {
const options = this.options;
if (options.enable && options.type !== Type.none && options.type !== Type.inline) {
if (!this.checkInsidePolygon(particle.getPosition())) {
PolygonMaskInstance_PolygonMaskInstance.polygonBounce(particle);
return true;
}
} else if (options.enable && options.type === Type.inline && particle.initialPosition) {
const dist = Utils_Utils.getDistance(particle.initialPosition, particle.getPosition());
if (dist > this.polygonMaskMoveRadius) {
PolygonMaskInstance_PolygonMaskInstance.polygonBounce(particle);
return true;
}
}
return false;
}
clickPositionValid(position) {
const options = this.options;
return options.enable && options.type !== Type.none && options.type !== Type.inline && this.checkInsidePolygon(position);
}
draw(context) {
var _a;
if (!((_a = this.paths) === null || _a === void 0 ? void 0 : _a.length)) {
return;
}
const options = this.options;
const polygonDraw = options.draw;
if (!(options.enable && polygonDraw.enable)) {
return;
}
const rawData = this.raw;
for (const path of this.paths) {
const path2d = path.path2d;
const path2dSupported = this.path2DSupported;
if (!context) {
continue;
}
if (path2dSupported && path2d && this.offset) {
PolygonMaskInstance_PolygonMaskInstance.drawPolygonMaskPath(context, path2d, polygonDraw.stroke, this.offset);
} else if (rawData) {
PolygonMaskInstance_PolygonMaskInstance.drawPolygonMask(context, rawData, polygonDraw.stroke);
}
}
}
checkInsidePolygon(position) {
var _a, _b;
const container = this.container;
const options = this.options;
if (!options.enable || options.type === Type.none || options.type === Type.inline) {
return true;
}
if (!this.raw) {
throw new Error(Constants.noPolygonFound);
}
const canvasSize = container.canvas.size;
const x = (_a = position === null || position === void 0 ? void 0 : position.x) !== null && _a !== void 0 ? _a : Math.random() * canvasSize.width;
const y = (_b = position === null || position === void 0 ? void 0 : position.y) !== null && _b !== void 0 ? _b : Math.random() * canvasSize.height;
let inside = false;
for (let i = 0, j = this.raw.length - 1; i < this.raw.length; j = i++) {
const pi = this.raw[i];
const pj = this.raw[j];
const intersect = pi.y > y !== pj.y > y && x < (pj.x - pi.x) * (y - pi.y) / (pj.y - pi.y) + pi.x;
if (intersect) {
inside = !inside;
}
}
return options.type === Type.inside ? inside : options.type === Type.outside ? !inside : false;
}
parseSvgPath(xml, force) {
var _a, _b, _c;
const forceDownload = force !== null && force !== void 0 ? force : false;
if (this.paths !== undefined && !forceDownload) {
return this.raw;
}
const container = this.container;
const options = this.options;
const parser = new DOMParser();
const doc = parser.parseFromString(xml, "image/svg+xml");
const svg = doc.getElementsByTagName("svg")[0];
let svgPaths = svg.getElementsByTagName("path");
if (!svgPaths.length) {
svgPaths = doc.getElementsByTagName("path");
}
this.paths = [];
for (let i = 0; i < svgPaths.length; i++) {
const path = svgPaths.item(i);
if (path) {
this.paths.push({
element: path,
length: path.getTotalLength()
});
}
}
const pxRatio = container.retina.pixelRatio;
const scale = options.scale / pxRatio;
this.dimension.width = parseFloat((_a = svg.getAttribute("width")) !== null && _a !== void 0 ? _a : "0") * scale;
this.dimension.height = parseFloat((_b = svg.getAttribute("height")) !== null && _b !== void 0 ? _b : "0") * scale;
const position = (_c = options.position) !== null && _c !== void 0 ? _c : {
x: 50,
y: 50
};
this.offset = {
x: container.canvas.size.width * position.x / (100 * pxRatio) - this.dimension.width / 2,
y: container.canvas.size.height * position.y / (100 * pxRatio) - this.dimension.height / 2
};
return PolygonMaskInstance_PolygonMaskInstance.parsePaths(this.paths, scale, this.offset);
}
downloadSvgPath(svgUrl, force) {
return __awaiter(this, void 0, void 0, function* () {
const options = this.options;
const url = svgUrl || options.url;
const forceDownload = force !== null && force !== void 0 ? force : false;
if (!url || this.paths !== undefined && !forceDownload) {
return this.raw;
}
const req = yield fetch(url);
if (!req.ok) {
throw new Error("tsParticles Error - Error occurred during polygon mask download");
}
return this.parseSvgPath(yield req.text(), force);
});
}
drawPoints() {
if (!this.raw) {
return;
}
for (const item of this.raw) {
this.container.particles.addParticle({
x: item.x,
y: item.y
});
}
}
randomPoint() {
const container = this.container;
const options = this.options;
let position;
if (options.type === Type.inline) {
switch (options.inline.arrangement) {
case InlineArrangement.randomPoint:
position = this.getRandomPoint();
break;
case InlineArrangement.randomLength:
position = this.getRandomPointByLength();
break;
case InlineArrangement.equidistant:
position = this.getEquidistantPointByIndex(container.particles.count);
break;
case InlineArrangement.onePerPoint:
case InlineArrangement.perPoint:
default:
position = this.getPointByIndex(container.particles.count);
}
} else {
position = {
x: Math.random() * container.canvas.size.width,
y: Math.random() * container.canvas.size.height
};
}
if (this.checkInsidePolygon(position)) {
return position;
} else {
return this.randomPoint();
}
}
getRandomPoint() {
if (!this.raw || !this.raw.length) {
throw new Error(Constants.noPolygonDataLoaded);
}
const coords = Utils_Utils.itemFromArray(this.raw);
return {
x: coords.x,
y: coords.y
};
}
getRandomPointByLength() {
var _a, _b, _c;
const options = this.options;
if (!this.raw || !this.raw.length || !((_a = this.paths) === null || _a === void 0 ? void 0 : _a.length)) {
throw new Error(Constants.noPolygonDataLoaded);
}
const path = Utils_Utils.itemFromArray(this.paths);
const distance = Math.floor(Math.random() * path.length) + 1;
const point = path.element.getPointAtLength(distance);
return {
x: point.x * options.scale + (((_b = this.offset) === null || _b === void 0 ? void 0 : _b.x) || 0),
y: point.y * options.scale + (((_c = this.offset) === null || _c === void 0 ? void 0 : _c.y) || 0)
};
}
getEquidistantPointByIndex(index) {
var _a, _b, _c, _d, _e, _f, _g;
const options = this.container.options;
const polygonMaskOptions = this.options;
if (!this.raw || !this.raw.length || !((_a = this.paths) === null || _a === void 0 ? void 0 : _a.length)) throw new Error(Constants.noPolygonDataLoaded);
let offset = 0;
let point;
const totalLength = this.paths.reduce((tot, path) => tot + path.length, 0);
const distance = totalLength / options.particles.number.value;
for (const path of this.paths) {
const pathDistance = distance * index - offset;
if (pathDistance <= path.length) {
point = path.element.getPointAtLength(pathDistance);
break;
} else {
offset += path.length;
}
}
return {
x: ((_b = point === null || point === void 0 ? void 0 : point.x) !== null && _b !== void 0 ? _b : 0) * polygonMaskOptions.scale + ((_d = (_c = this.offset) === null || _c === void 0 ? void 0 : _c.x) !== null && _d !== void 0 ? _d : 0),
y: ((_e = point === null || point === void 0 ? void 0 : point.y) !== null && _e !== void 0 ? _e : 0) * polygonMaskOptions.scale + ((_g = (_f = this.offset) === null || _f === void 0 ? void 0 : _f.y) !== null && _g !== void 0 ? _g : 0)
};
}
getPointByIndex(index) {
if (!this.raw || !this.raw.length) {
throw new Error(Constants.noPolygonDataLoaded);
}
const coords = this.raw[index % this.raw.length];
return {
x: coords.x,
y: coords.y
};
}
createPath2D() {
var _a, _b;
const options = this.options;
if (!this.path2DSupported || !((_a = this.paths) === null || _a === void 0 ? void 0 : _a.length)) {
return;
}
for (const path of this.paths) {
const pathData = (_b = path.element) === null || _b === void 0 ? void 0 : _b.getAttribute("d");
if (pathData) {
const path2d = new Path2D(pathData);
const matrix = document.createElementNS("http://www.w3.org/2000/svg", "svg").createSVGMatrix();
const finalPath = new Path2D();
const transform = matrix.scale(options.scale);
if (finalPath.addPath) {
finalPath.addPath(path2d, transform);
path.path2d = finalPath;
} else {
delete path.path2d;
}
} else {
delete path.path2d;
}
if (path.path2d || !this.raw) {
continue;
}
path.path2d = new Path2D();
path.path2d.moveTo(this.raw[0].x, this.raw[0].y);
this.raw.forEach((pos, i) => {
var _a;
if (i > 0) {
(_a = path.path2d) === null || _a === void 0 ? void 0 : _a.lineTo(pos.x, pos.y);
}
});
path.path2d.closePath();
}
}
initRawData(force) {
return __awaiter(this, void 0, void 0, function* () {
const options = this.options;
if (options.url) {
this.raw = yield this.downloadSvgPath(options.url, force);
} else if (options.data) {
const data = options.data;
let svg;
if (typeof data !== "string") {
const path = data.path instanceof Array ? data.path.map(t => `<path d="${t}" />`).join("") : `<path d="${data.path}" />`;
const namespaces = 'xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"';
svg = `<svg ${namespaces} width="${data.size.width}" height="${data.size.height}">${path}</svg>`;
} else {
svg = data;
}
this.raw = this.parseSvgPath(svg, force);
}
this.createPath2D();
});
}
}
// CONCATENATED MODULE: ./dist/Plugins/PolygonMask/PolygonMaskPlugin.js
class PolygonMaskPlugin_PolygonMaskPlugin {
constructor() {
this.id = "polygonMask";
}
getPlugin(container) {
return new PolygonMaskInstance_PolygonMaskInstance(container);
}
needsPlugin(options) {
var _a, _b, _c;
return (_b = (_a = options === null || options === void 0 ? void 0 : options.polygon) === null || _a === void 0 ? void 0 : _a.enable) !== null && _b !== void 0 ? _b : ((_c = options === null || options === void 0 ? void 0 : options.polygon) === null || _c === void 0 ? void 0 : _c.type) !== undefined && options.polygon.type !== Type.none;
}
loadOptions(options, source) {
if (!this.needsPlugin(source)) {
return;
}
const optionsCast = options;
let polygonOptions = optionsCast.polygon;
if ((polygonOptions === null || polygonOptions === void 0 ? void 0 : polygonOptions.load) === undefined) {
optionsCast.polygon = polygonOptions = new PolygonMask_PolygonMask();
}
polygonOptions.load(source === null || source === void 0 ? void 0 : source.polygon);
}
}
const PolygonMaskPlugin_plugin = new PolygonMaskPlugin_PolygonMaskPlugin();
// CONCATENATED MODULE: ./dist/main.js
class main_Main extends main_slim_MainSlim {
constructor() {
super();
this.addPlugin(AbsorbersPlugin_plugin);
this.addPlugin(EmittersPlugin_plugin);
this.addPlugin(PolygonMaskPlugin_plugin);
}
}
// CONCATENATED MODULE: ./dist/Enums/Directions/index.js
// CONCATENATED MODULE: ./dist/Enums/Modes/index.js
// CONCATENATED MODULE: ./dist/Enums/Statuses/index.js
// CONCATENATED MODULE: ./dist/Enums/Types/index.js
// CONCATENATED MODULE: ./dist/Enums/index.js
// CONCATENATED MODULE: ./dist/index.js
const tsParticles = new main_Main();
tsParticles.init();
const {
particlesJS,
pJSDom
} = initPjs(tsParticles);
/***/ })
/******/ }))); |
import React from 'react';
import classNames from 'classnames';
import RankingBadgeBackground from 'components/ranking-badge-background';
import RankingBadgeLabel from 'components/ranking-badge-label';
import getRadius from 'decorators/get-radius';
import setStateFromProps from 'decorators/set-state-from-props';
@getRadius
@setStateFromProps
export default class RankingBadge extends React.Component {
static propTypes = {
className: React.PropTypes.string.isRequired,
height: React.PropTypes.number.isRequired,
index: React.PropTypes.number.isRequired,
}
static defaultProps = {
className: '',
height: 0,
index: 0,
}
state = {
labelText: '',
radius: 0,
}
getLabelText(index) {
return (index + 1).toString();
}
setStateFromProps(props) {
this.setState({
labelText: this.getLabelText(props.index),
radius: this.getRadius(props.height),
});
}
render() {
return (
<g className={classNames(
'ranking-badge',
this.props.className
)}>
<RankingBadgeBackground
index={this.props.index}
radius={this.state.radius} />
<RankingBadgeLabel
radius={this.state.radius}
text={this.state.labelText} />
</g>
);
}
}
|
FollowUp.widgets = {
lbxMain: ["wm.Layout", {"horizontalAlign":"left","verticalAlign":"top"}, {}]
} |
// Load modules
var Url = require('url');
var Hoek = require('hoek');
var Cryptiles = require('cryptiles');
var Crypto = require('./crypto');
var Utils = require('./utils');
// Declare internals
var internals = {};
// Generate an Authorization header for a given request
/*
uri: 'http://example.com/resource?a=b' or object from Url.parse()
method: HTTP verb (e.g. 'GET', 'POST')
options: {
// Required
credentials: {
id: 'dh37fgj492je',
key: 'aoijedoaijsdlaksjdl',
algorithm: 'sha256' // 'sha1', 'sha256'
},
// Optional
ext: 'application-specific', // Application specific data sent via the ext attribute
timestamp: Date.now(), // A pre-calculated timestamp
nonce: '2334f34f', // A pre-generated nonce
localtimeOffsetMsec: 400, // Time offset to sync with server time (ignored if timestamp provided)
payload: '{"some":"payload"}', // UTF-8 encoded string for body hash generation (ignored if hash provided)
contentType: 'application/json', // Payload content-type (ignored if hash provided)
hash: 'U4MKKSmiVxk37JCCrAVIjV=', // Pre-calculated payload hash
app: '24s23423f34dx', // Oz application id
dlg: '234sz34tww3sd' // Oz delegated-by application id
}
*/
exports.header = function (uri, method, options) {
var result = {
field: '',
artifacts: {}
};
// Validate inputs
if (!uri || (typeof uri !== 'string' && typeof uri !== 'object') ||
!method || typeof method !== 'string' ||
!options || typeof options !== 'object') {
result.err = 'Invalid argument type';
return result;
}
// Application time
var timestamp = options.timestamp || Math.floor((Utils.now() + (options.localtimeOffsetMsec || 0)) / 1000)
// Validate credentials
var credentials = options.credentials;
if (!credentials ||
!credentials.id ||
!credentials.key ||
!credentials.algorithm) {
result.err = 'Invalid credential object';
return result;
}
if (Crypto.algorithms.indexOf(credentials.algorithm) === -1) {
result.err = 'Unknown algorithm';
return result;
}
// Parse URI
if (typeof uri === 'string') {
uri = Url.parse(uri);
}
// Calculate signature
var artifacts = {
ts: timestamp,
nonce: options.nonce || Cryptiles.randomString(6),
method: method,
resource: uri.pathname + (uri.search || ''), // Maintain trailing '?'
host: uri.hostname,
port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
hash: options.hash,
ext: options.ext,
app: options.app,
dlg: options.dlg
};
result.artifacts = artifacts;
// Calculate payload hash
if (!artifacts.hash &&
options.hasOwnProperty('payload')) {
artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
}
var mac = Crypto.calculateMac('header', credentials, artifacts);
// Construct header
var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== ''; // Other falsey values allowed
var header |
/**
* jQuery UI DataList Widget for "lists of data cards"
*
* @copyright 2013-2016 (c) Sahana Software Foundation
* @license MIT
*
* requires jQuery 1.9.1+
* requires jQuery UI 1.10 widget factory
*
*/
(function($, undefined) {
"use strict";
var datalistID = 0;
/**
* DataList widget, pagination and Ajax-Refresh for data lists
*/
$.widget('s3.datalist', {
/**
* Default options
*/
options: {
},
/**
* Create the widget
*/
_create: function() {
this.id = datalistID;
datalistID += 1;
},
/**
* Update widget options
*/
_init: function() {
this.hasInfiniteScroll = false;
// Render all initial contents
this.refresh();
},
/**
* Remove generated elements & reset other changes
*/
_destroy: function() {
$.Widget.prototype.destroy.call(this);
},
/**
* Re-draw contents
*/
refresh: function() {
// Unbind global events
//this._unbindEvents();
// Initialize infinite scroll
this._infiniteScroll();
// (Re-)bind item events
this._bindItemEvents();
// Bind global events
//this._bindEvents();
// Fire initial update event
$(this.element).trigger('listUpdate');
},
/**
* Initialize infinite scroll for this data list
*/
_infiniteScroll: function() {
var $datalist = $(this.element);
var pagination = $datalist.find('input.dl-pagination');
if (!pagination.length) {
// No pagination
return;
}
// Read pagination data
var dlData = JSON.parse($(pagination[0]).val());
var startIndex = dlData.startindex,
maxItems = dlData.maxitems,
totalItems = dlData.totalitems,
pageSize = dlData.pagesize,
ajaxURL = dlData.ajaxurl;
if (!pagination.hasClass('dl-scroll')) {
// No infiniteScroll
if (pageSize > totalItems) {
// Hide the 'more' button if we can see all items
pagination.closest('.dl-navigation').css({display: 'none'});
}
return;
}
if (pageSize === null) {
// No pagination
pagination.closest('.dl-navigation').css({display: 'none'});
return;
}
// Cannot retrieve more items than there are totally available
maxItems = Math.min(maxItems, totalItems - startIndex);
// Compute bounds
var maxIndex = startIndex + maxItems,
initialItems = $datalist.find('.dl-item').length;
// Compute maxPage
var maxPage = 1,
ajaxItems = (maxItems - initialItems);
if (ajaxItems > 0) {
maxPage += Math.ceil(ajaxItems / pageSize);
} else {
if (pagination.length) {
pagination.closest('.dl-navigation').css({display: 'none'});
}
return;
}
if (pagination.length) {
var dl = this;
$datalist.infinitescroll({
debug: false,
loading: {
// @ToDo: i18n
finishedMsg: 'no more items to load',
msgText: 'loading...',
img: S3.Ap.concat('/static/img/indicator.gif')
},
navSelector: 'div.dl-navigation',
nextSelector: 'div.dl-navigation a:first',
itemSelector: 'div.dl-row',
path: function(page) {
// Compute start+limit
var start = initialItems + (page - 2) * pageSize;
var limit = Math.min(pageSize, maxIndex - start);
// Construct Ajax URL
var url = dl._urlAppend(ajaxURL, 'start=' + start + '&limit=' + limit);
return url;
},
maxPage: maxPage
},
// Function to be called after Ajax-loading new data
function(data) {
$datalist.find('.dl-row:last:in-viewport').each(function() {
// Last item is within the viewport, so try to
// load more items to fill the viewport
$this = $(this);
if (!$this.hasClass('autoretrieve')) {
// prevent further auto-retrieve attempts if this
// one doesn't produce any items:
$this.addClass('autoretrieve');
dl._autoRetrieve();
}
});
dl._bindItemEvents();
});
this.hasInfiniteScroll = true;
$datalist.find('.dl-row:last:in-viewport').each(function() {
$(this).addClass('autoretrieve');
dl._autoRetrieve();
});
}
return;
},
/**
* Reload a single item (e.g. when updated in a modal)
*
* @param {integer} recordID - the record ID
*/
ajaxReloadItem: function(recordID) {
var $datalist = $(this.element);
var listID = $datalist.attr('id'),
pagination = $datalist.find('input.dl-pagination');
if (!pagination.length) {
// No pagination data
return;
}
// Do we have an Ajax-URL?
var dlData = JSON.parse($(pagination[0]).val()),
ajaxURL = dlData.ajaxurl;
if (ajaxURL === null) {
return;
}
// Is the item currently loaded?
var itemID = '#' + listID + '-' + recordID,
item = $(itemID);
if (!item.length) {
return;
}
// Ajax-load the item
var dl = this;
$.ajax({
'url': dl._urlAppend(ajaxURL, 'record=' + recordID),
'success': function(data) {
var itemData = $(data.slice(data.indexOf('<'))).find(itemID);
if (itemData.length) {
item.replaceWith(itemData);
} else {
// Updated item does not match the filter anymore
dl._removeItem(item, dlData);
}
// Bind item events
dl._bindItemEvents();
// Fire update event
$datalist.trigger('listUpdate');
},
'error': function(request, status, error) {
if (error == 'UNAUTHORIZED') {
msg = i18n.gis_requires_login;
} else {
msg = request.responseText;
}
console.log(msg);
},
'dataType': 'html'
});
},
/**
* Ajax-reload this datalist
*
* @param {Array} filters - the current filters
*/
ajaxReload: function(filters) {
var $datalist = $(this.element);
var pagination = $datalist.find('input.dl-pagination');
if (!pagination.length) {
// No pagination data
return;
}
// Read dlData
var $pagination0 = $(pagination[0]);
var dlData = JSON.parse($pagination0.val());
var startIndex = dlData.startindex,
pageSize = dlData.pagesize,
totalItems = dlData.totalitems,
ajaxURL = dlData.ajaxurl;
if (pageSize === null) {
// No pagination
return;
}
// Handle filters
if (typeof filters == 'undefined') {
// Find a filter form that has the current datalist as target
var listID = $datalist.attr('id'),
filterTargets = $('form.filter-form input.filter-submit-target'),
len = filterTargets.length,
targets,
targetList;
if (listID && len) {
for (var i = 0; i < len; i++) {
targets = $(filterTargets[i]);
targetList = targets.val().split(' ');
if ($.inArray(listID, targetList) != -1) {
filters = S3.search.getCurrentFilters(targets.closest('form.filter-form'));
break;
}
}
}
}
if (filters) {
// Update the Ajax URL
try {
ajaxURL = S3.search.filterURL(ajaxURL, filters);
dlData.ajaxurl = ajaxURL;
$pagination0.val(JSON.stringify(dlData));
} catch(e) {}
}
var start = startIndex,
limit = pageSize;
// Ajax-load the list
var dl = this;
$.ajax({
'url': dl._urlAppend(ajaxURL, 'start=' + startIndex + '&limit=' + pageSize),
'success': function(data) {
// Update the list
// Remove the infinite scroll
$datalist.infinitescroll('destroy');
$datalist.data('infinitescroll', null);
var newlist = $(data.slice(data.indexOf('<'))).find('.dl');
if (newlist.length) {
// Insert new items, update status
var paginationNew = $(newlist).find('input.dl-pagination');
if (paginationNew.length) {
var dlDataNew = JSON.parse($(paginationNew[0]).val());
dlData.totalitems = dlDataNew.totalitems;
dlData.maxitems = dlDataNew.maxitems;
$pagination0.val(JSON.stringify(dlData));
}
var modalMore = $datalist.find('div.dl-navigation a.dl-more'),
modalMoreLength = modalMore.length,
popup_url,
popup_title;
if (modalMoreLength) {
// Read attributes
popup_url = $(modalMore[0]).attr('href');
popup_title = $(modalMore[0]).attr('title');
}
$datalist.empty().html(newlist.html());
$datalist.find('input.dl-pagination').replaceWith(pagination);
if (modalMoreLength) {
// Restore attributes
if (filters) {
popup_url = S3.search.filterURL(popup_url, filters);
}
$($datalist.find('.dl-navigation a')[0]).addClass('s3_modal')
.attr('href', popup_url)
.attr('title', popup_title);
}
} else {
// List is empty: hide navigation, show empty section
var nav = $datalist.find('.dl-navigation').css({display: 'none'});
newlist = $(data.slice(data.indexOf('<'))).find('.empty');
$datalist.empty().append(newlist);
$datalist.append(nav);
}
// Re-activate infinite scroll
dl._infiniteScroll();
$datalist.find('.dl-item:last:in-viewport').each(function() {
$(this).addClass('autoretrieve');
dl._autoRetrieve();
});
// Bind item events
dl._bindItemEvents();
// Fire update event
$datalist.trigger('listUpdate');
},
'error': function(request, status, error) {
if (error == 'UNAUTHORIZED') {
msg = i18n.gis_requires_login;
} else {
msg = request.responseText;
}
console.log(msg);
},
'dataType': 'html'
});
return;
},
/**
* Ajax-delete an item from this list
*
* @param {jQuery} anchor - the card element that triggered the action
*/
_ajaxDeleteItem: function(anchor) {
var $datalist = $(this.element);
var item = $(anchor).closest('.dl-item');
if (!item.length) {
return;
}
var pagination = $datalist.find('input.dl-pagination').first();
if (!pagination.length) {
// No such datalist or no pagination data
return;
}
var dlData = JSON.parse($(pagination).val());
// Do we have an Ajax-URL?
var ajaxURL = dlData.ajaxurl;
if (ajaxURL === null) {
return;
}
var recordID = item.attr('id').split('-').pop();
// Ajax-delete the item
var dl = this;
$.ajax({
'url': this._urlAppend(ajaxURL, 'delete=' + recordID),
'success': function(data) {
// Remove the card
dl._removeItem(item, dlData);
},
'error': function(request, status, error) {
var msg;
if (error == 'UNAUTHORIZED') {
msg = i18n.gis_requires_login;
} else {
msg = request.responseText;
}
console.log(msg);
},
'type': 'POST',
'dataType': 'json'
});
// Trigger auto-retrieve
$datalist.find('.dl-item:last:in-viewport').each(function() {
$(this).addClass('autoretrieve');
dl._autoRetrieve(this);
});
},
/**
* Remove an item from the list
*
* @param {jQuery} item - the list item (card)
* @param {object} dlData - the pagination data
*/
_removeItem: function(item, dlData) {
var $datalist = $(this.element),
pagination = $datalist.find('input.dl-pagination').first(),
rowSize = dlData.rowsize,
ajaxURL = dlData.ajaxurl;
var rowIndex = item.index(),
row = item.closest('.dl-row'),
idTokens = item.attr('id').split('-'),
i,
prev,
next;
// 1. Remove the item
item.remove();
// 2. Move all following items in the row 1 position to the left
var $row = $(row);
if (rowIndex < rowSize - 1) {
for (i = rowIndex + 1; i < rowSize; i++) {
prev = 'dl-col-' + (i - 1);
next = 'dl-col-' + i;
$row.find('.' + next).removeClass(next).addClass(prev);
}
}
// 3. Move all first items of all following rows to the end of the previous row
var prevRow = row;
$row.nextAll('.dl-row').each(function() {
$(this).find('.dl-col-0').first()
.appendTo(prevRow)
.removeClass('dl-col-0')
.addClass('dl-col-' + (rowSize - 1));
if (rowSize > 1) {
for (i = 1; i < rowSize; i++) {
prev = 'dl-col-' + (i - 1);
next = 'dl-col-' + i;
$(this).find('.' + next).removeClass(next).addClass(prev);
}
}
prevRow = this;
});
// 4. Load 1 more item to fill up the last row
var lastRow = $row.closest('.dl').find('.dl-row').last(),
numItems = $row.closest('.dl').find('.dl-item').length;
var dl = this;
$.ajax({
'url': dl._urlAppend(ajaxURL, 'start=' + numItems + '&limit=1'),
'success': function(data) {
// @todo: reduce counters (total items, max items)
// and update header accordingly
$(data.slice(data.indexOf('<')))
.find('.dl-item')
.first()
.removeClass('dl-col-0')
.addClass('dl-col-' + (rowSize - 1))
.appendTo(lastRow);
dl._bindItemEvents();
},
'error': function(request, status, error) {
if (error == 'UNAUTHORIZED') {
msg = i18n.gis_requires_login;
} else {
msg = request.responseText;
}
console.log(msg);
},
'dataType': 'html'
});
// 5. Update dl-data totalitems/maxitems
dlData.totalitems--;
if (dlData.maxitems > dlData.totalitems) {
dlData.maxitems = dlData.totalitems;
}
$(pagination).val(JSON.stringify(dlData));
// 6. Show the empty-section if there are no more records
if (dlData.totalitems === 0) {
$datalist.find('.dl-empty').css({display: 'block'});
}
// 7. Also update the layer on the Map (if any)
// @ToDo: Which Map?
if (typeof map != 'undefined') {
var layers = map.layers,
needle = idTokens.join('_');
Ext.iterate(layers, function(key, val, obj) {
if (key.s3_layer_id == needle) {
var layer = layers[val],
found = false,
uuid = data['uuid']; // The Record UUID
Ext.iterate(layer.feaures, function(key, val, obj) {
if (key.properties.id == uuid) {
// Remove the feature
layer.removeFeatures([key]);
found = true;
}
});
if (!found) {
// Feature was in a Cluster: refresh the layer
Ext.iterate(layer.strategies, function(key, val, obj) {
if (key.CLASS_NAME == 'OpenLayers.Strategy.Refresh') {
// Reload the layer
layer.strategies[val].refresh();
}
});
}
}
});
}
// 8. Fire update event
$datalist.trigger('listUpdate');
},
/**
* Force page retrieval
*/
_autoRetrieve: function() {
if (this.hasInfiniteScroll) {
$(this.element).infinitescroll('retrieve');
}
},
/**
* Append extra query elements to a URL
*
* @param {string} url - the URL
* @param {string} query - the additional query
*/
_urlAppend: function(url, query) {
var parts = url.split('?'),
q = '';
var newurl = parts[0];
if (parts.length > 1) {
if (query) {
q = '&' + query;
}
return (newurl + '?' + parts[1] + q);
} else {
if (query) {
q = '?' + query;
}
return (newurl + q);
}
},
/**
* Get the total number of items (from the data dict)
*/
getTotalItems: function() {
var pagination = $(this.element).find('input.dl-pagination');
if (!pagination.length) {
// No pagination = all items in the list, so just count them
return $datalist.find('.dl-item').length;
}
return JSON.parse($(pagination[0]).val())['totalitems'];
},
/**
* Bind events in list items
*
* @todo: call from _bindEvents?
*/
_bindItemEvents: function() {
// Bind events in list items
var $datalist = $(this.element);
// Click-event for dl-item-delete
var dl = this;
$datalist.find('.dl-item-delete')
.css({cursor: 'pointer'})
.unbind('click.dl')
.on('click.dl', function(event) {
if (confirm(i18n.delete_confirmation)) {
dl._ajaxDeleteItem(this);
return true;
} else {
event.preventDefault();
return false;
}
});
// Add Event Handlers to new page elements
S3.redraw();
// Other callbacks
return;
},
/**
* Bind events to generated elements (after refresh)
*/
_bindEvents: function() {
return true;
},
/**
* Unbind events (before refresh)
*/
_unbindEvents: function() {
return true;
}
});
/**
* DataLists document-ready script - attach to all .dl
*/
$(document).ready(function() {
// Initialize infinite scroll
$('.dl').each(function() {
$(this).datalist();
});
});
})(jQuery);
// END ========================================================================
|
// # Api Route tests
// As it stands, these tests depend on the database, and as such are integration tests.
// Mocking out the models to not touch the DB would turn these into unit tests, and should probably be done in future,
// But then again testing real code, rather than mock code, might be more useful...
var should = require('should'),
supertest = require('supertest'),
testUtils = require('../../../utils/index'),
localUtils = require('./utils'),
config = require('../../../../server/config/index'),
ghost = testUtils.startGhost,
request;
require('should-http');
describe('Unauthorized', function () {
var ghostServer;
before(function () {
return ghost()
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('url'));
});
});
it('returns 401 error for known endpoint', function (done) {
request.get(localUtils.API.getApiQuery('posts/'))
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(401)
.end(function firstRequest(err, res) {
if (err) {
return done(err);
}
should.not.exist(res.headers['x-cache-invalidate']);
should.not.exist(res.headers['x-cache-invalidate']);
res.should.be.json();
should.exist(res.body);
res.body.should.be.a.JSONErrorResponse();
done();
});
});
it('returns 404 error for unknown endpoint', function (done) {
request.get(localUtils.API.getApiQuery('unknown/'))
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.end(function firstRequest(err, res) {
if (err) {
return done(err);
}
should.not.exist(res.headers['x-cache-invalidate']);
res.should.be.json();
should.exist(res.body);
res.body.should.be.a.JSONErrorResponse();
done();
});
});
});
describe('Authorized API', function () {
var accesstoken, ghostServer;
before(function () {
return ghost()
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('url'));
})
.then(function () {
return localUtils.doAuth(request);
})
.then(function (token) {
accesstoken = token;
});
});
it('serves a JSON 404 for an unknown endpoint', function (done) {
request.get(localUtils.API.getApiQuery('unknown/'))
.set('Authorization', 'Bearer ' + accesstoken)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(404)
.end(function firstRequest(err, res) {
if (err) {
return done(err);
}
should.not.exist(res.headers['x-cache-invalidate']);
res.should.be.json();
should.exist(res.body);
res.body.should.be.a.JSONErrorResponse();
done();
});
});
});
|
/// <reference path="RoadsLib.d.ts" />
window.onload = function () {
runGame();
};
function runGame() {
var cvs = document.getElementById('cvs');
var gl = cvs.getContext('webgl') || cvs.getContext('experimental-webgl');
if (!gl) {
document.getElementById('error_webgl').style.display = '';
return;
}
var actx = null;
try {
actx = new webkitAudioContext();
} catch (e) {
}
try {
actx = new AudioContext();
} catch (e) {
}
if (!actx) {
document.getElementById('error_webaudio').style.display = '';
}
var isXMas = window.location.search.indexOf('xmas=1') >= 0;
var manager = new Managers.StreamManager(new Stores.AJAXFileProvider(), isXMas ? 'Data.XMas/' : 'Data/'), shaderManager = new Managers.ShaderManager(manager);
var managers = new Managers.ManagerSet(manager, shaderManager);
managers.Sounds = new Managers.SoundManager(managers);
var src = new Controls.CombinedControlSource();
src.addSource(new Controls.KeyboardControlSource(new Engine.KeyboardManager(document.body)));
src.addSource(new Controls.JoystickControlSource(new Controls.NavigatorJoystick(navigator)));
managers.Controls = src;
managers.Settings = new Managers.SettingsManager(new Stores.LocalStorageStore(isXMas ? 'xmas' : 'classic'));
managers.Graphics = new Shaders.ClassicShaderProvider();
managers.Textures = new Managers.TextureManager(managers);
managers.Canvas = new Drawing.HTMLCanvasProvider();
managers.VR = null;
managers.SnapshotProvider = managers.Settings.UseInterpolation ? new Game.InterpolatingSnapshoptProvider() : new Game.FixedRateSnapshotProvider();
//managers.Graphics = new Shaders.VRShaderProvider();
manager.loadMultiple([
"Shaders/basic_2d.fs", "Shaders/basic_2d.vs", 'Shaders/title_2d.fs', 'Shaders/title_2d.vs', 'Shaders/color_3d.vs', 'Shaders/color_3d.fs',
"Data/SKYROADS.EXE",
"Data/ANIM.LZS",
"Data/CARS.LZS",
"Data/DASHBRD.LZS",
"Data/DEMO.REC",
"Data/FUL_DISP.DAT",
"Data/GOMENU.LZS",
"Data/HELPMENU.LZS",
"Data/INTRO.LZS",
"Data/INTRO.SND",
"Data/MAINMENU.LZS",
"Data/MUZAX.LZS",
"Data/OXY_DISP.DAT",
"Data/ROADS.LZS",
"Data/SETMENU.LZS",
"Data/SFX.SND",
"Data/SPEED.DAT",
"Data/TREKDAT.LZS",
"Data/WORLD0.LZS",
"Data/WORLD1.LZS",
"Data/WORLD2.LZS",
"Data/WORLD3.LZS",
"Data/WORLD4.LZS",
"Data/WORLD5.LZS",
"Data/WORLD6.LZS",
"Data/WORLD7.LZS",
"Data/WORLD8.LZS",
"Data/WORLD9.LZS"
]).done(function () {
var exe = new ExeData.ExeDataLoader(managers);
exe.load();
var audioProvider = new Sounds.WebAPIAudioProvider(actx);
var opl = new Music.OPL(audioProvider);
var player = new Music.Player(opl, managers);
opl.setSource(player);
managers.Audio = new Sounds.InThreadAudioProvider(audioProvider, player);
document.getElementById('loading').style.display = 'none';
cvs.style.display = 'block';
var demoCon = new Game.DemoController(manager.getRawArray('DEMO.REC'));
var state = new States.Intro(managers);
//var state = new States.GoMenu(managers);
//var state = new States.MainMenu(managers);
managers.Frames = new Engine.FrameManager(new Engine.BrowserDocumentProvider(), cvs, managers, state, new Engine.Clock());
});
}
//# sourceMappingURL=GameMain.js.map
|
/*!
* find-telegram-bot <https://github.com/alopatindev/find-telegram-bot>
*
* Copyright (c) 2017 Alexander Lopatin
* Licensed under the MIT License
*/
'use strict'
module.exports = function() {
const botUrlPrefix = this.baseUrl + '/bot/'
function htmlDecode(value) {
return $('<div/>')
.html(value)
.text()
}
function script() {
const botItems = $('.botitem').find('.info')
const urls = botItems.find('a')
const descriptions = botItems.find('.description')
return urls
.toArray()
.map(function(url, index) {
const name = url
.href
.replace(botUrlPrefix, '')
const description = htmlDecode(descriptions[index]
.innerText
.trim())
return [name, description]
})
}
var results = []
try {
console.debug('storebotScript')
results = script()
console.debug('storebotScript end results.length=' + results.length)
} catch (e) {
console.error(e)
}
return results
}
|
"use strict";
const path = require("path");
const {
executeTests,
prepareForTests,
utilityFunctions
} = require(path.resolve("tests/unit-tests.js"));
const m = prepareForTests(__filename);
executeTests("Service starter", [{
name: "addMiddlewares()",
assertions: [{
when: "there is an error",
should: "return a rejected Promise",
test: (test) => test((t) =>
m({
middlewares: {
loadMiddlewares: utilityFunctions.rejectFn
}
})
.addMiddlewares()
.catch(() => t.pass(""))
)
}, {
when: "there are no error",
should: "return a resolved Promise",
test: (test) => test((t) =>
m({
middlewares: {
loadMiddlewares: utilityFunctions.resolveFn
}
})
.addMiddlewares()
.then(() => t.pass(""))
)
}]
}, {
name: "createService()",
assertions: [{
when: "there is an error",
should: "return a rejected Promise",
test: (test) => test(function(t) {
const testModule = m({
express: utilityFunctions.nullFn
});
utilityFunctions.stub(testModule, "addMiddlewares", utilityFunctions.rejectFn);
return testModule
.createService()
.catch(() => t.pass(""));
})
}, {
when: "there are no errors",
should: "return a resolved Promise",
test: (test) => test(function(t) {
const testModule = m({
express: utilityFunctions.nullFn
});
utilityFunctions.stub(testModule, "addMiddlewares", utilityFunctions.resolveFn);
return testModule
.createService()
.then(() => t.pass(""));
})
}]
}, {
name: "startService()",
assertions: [{
when: "the service cannot be started",
should: "return a rejected Promise",
test: (test) => test((t) =>
m({})
.startService({
service: {
port: 0
}
}, {
listen: utilityFunctions.throwFn
})
.catch(() => t.pass(""))
)
}, {
when: "the service starts successfully",
should: "return a resolved Promise",
test: (test) => test((t) =>
m({})
.startService({
service: {
port: 0
}
}, {
listen: utilityFunctions.nullFn
})
.then(() => t.pass(""))
)
}]
}, {
name: "bootstrap()",
assertions: [{
when: "there is an error",
should: "return a rejected Promise",
test: (test) => test(function(t) {
const testModule = m({});
utilityFunctions.stub(testModule, "createService", utilityFunctions.rejectFn);
return testModule
.bootstrap()
.catch(() => t.pass(""));
})
}, {
when: "there are no error",
should: "return a resolved Promise",
test: (test) => test(function(t) {
const testModule = m({});
utilityFunctions.stub(testModule, "createService", utilityFunctions.resolveFn);
utilityFunctions.stub(testModule, "startService", utilityFunctions.resolveFn);
return testModule
.bootstrap()
.then(() => t.pass(""));
})
}]
}, {
name: "start()",
assertions: [{
when: "there is an error",
should: "return a rejected promise",
test: (test) => test((t) =>
m({})
.start()
.catch(() => t.pass(""))
)
}, {
when: "there are no error",
should: "return a resolved Promise",
test: (test) => test(function(t) {
const testModule = m({
state: {
get: utilityFunctions.nullFn,
set: utilityFunctions.nullFnHO
},
models: {
loadModels: utilityFunctions.resolveFn
}
});
utilityFunctions.stub(testModule, "bootstrap", utilityFunctions.resolveFn);
return testModule
.start()
.then(() => t.pass(""));
})
}]
}, {
name: "stop()",
assertions: [{
when: "...everytime",
should: "call the close method of given input",
test: (test) => test((t) =>
m({})
.stop({
close: utilityFunctions.resolveFnHO(true)
})
.then(() => t.pass(""))
)
}]
}]);
|
/**
* Configuration file manager
* @todo refactor this, make async
*/
(function(require, m)
{
'use strict';
var fs = require('fs');
var module = function(config_path)
{
var path = config_path;
/**
* Updates the needed backup
* @param data
* @param callback
*/
this.updateSync = function(data, callback)
{
try
{
var dir_path = path.substring(0, path.lastIndexOf('/'));
try
{
var stats = fs.statSync(dir_path);
if (!stats.isDirectory())
{
callback('Settings directory is not a directory.');
return;
}
}
catch (error)
{
try
{
fs.mkdirSync(dir_path);
}
catch (error)
{
callback('Settings directory could not be created.');
return;
}
}
fs.writeFileSync(path, JSON.stringify(data, null, 4), {encoding: 'utf8'});
callback(false);
return;
}
catch (error)
{
}
callback('Settings could not be written.');
};
/**
* Deletes a backup
* @param callback
*/
this.deleteSync = function(callback)
{
try
{
fs.readFileSync(path, {encoding: 'utf8'});
}
catch (error)
{
callback(false);
}
try
{
fs.unlinkSync(path);
callback(false);
return;
}
catch (error)
{
}
callback('Settings could not be deleted.');
};
/**
* Loads a configuration file
* Throws an error if the JSON could not be loaded
*/
this.loadSync = function()
{
var raw_data;
try
{
raw_data = fs.readFileSync(path, {encoding: 'utf8'});
}
catch (error)
{
raw_data = '{}';
}
var data;
try
{
data = JSON.parse(raw_data);
}
catch (error)
{
data = false;
}
return data;
};
};
m.exports = module;
})(require, module);
|
const runAPI = require("../../runCompiler");
runAPI.run(); |
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
export class Hero extends React.Component {
static propTypes = {
// No prop types required
keyword: PropTypes.string.isRequired,
location: PropTypes.string.isRequired,
onChangeSearchInput: PropTypes.func.isRequired,
onChangeLocationInput: PropTypes.func.isRequired,
onKeyDownCheckForEnter: PropTypes.func.isRequired,
onClickSearchButton: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
// To detect changed in the autocomplete
this.handlePlaceChanged = this.handlePlaceChanged.bind(this);
// To detect if the dropdown is open when user presses enter
this.onKeyDownLocationInput = this.onKeyDownLocationInput.bind(this);
this.state = {
changingLocation: false,
};
}
componentDidMount() {
// Sets up Google Autocomplete
const locationInputElement = document.getElementById('location-input');
const options = {
types: ['(cities)'],
componentRestrictions: {
country: 'us',
},
};
const autocomplete = new google.maps.places.Autocomplete(locationInputElement, options);
google.maps.event.addListener(autocomplete, 'place_changed', this.handlePlaceChanged);
}
handlePlaceChanged() {
const {
onChangeLocationInput,
} = this.props;
onChangeLocationInput(undefined, true);
this.setState({
changingLocation: false,
});
}
onKeyDownLocationInput(event) {
const {
onKeyDownCheckForEnter,
} = this.props;
if (event.keyCode === 13 && !this.state.changingLocation) {
onKeyDownCheckForEnter(event);
} else {
this.setState({
changingLocation: true,
});
}
}
render() {
const {
keyword,
location,
onChangeSearchInput,
onChangeLocationInput,
onKeyDownCheckForEnter,
onClickSearchButton,
} = this.props;
return (
<div className="home-hero">
<div className="hero-background">
</div>
<div className="hero-content-container">
<div className="hero-content">
<div className="hero-content-text-container">
<div className="hero-content-welcome">
Welcome
</div>
<div className="hero-content-subtext">
Search local shops for the product you need now
</div>
</div>
</div>
<div className="hero-footer">
<div className="hero-searchbar">
<form className="search-form">
<input
className="search-item-input"
type="text"
placeholder="What are you looking to buy?"
value={ keyword }
onChange={ onChangeSearchInput }
onKeyDown={ onKeyDownCheckForEnter }
/>
<input
id="location-input"
className="search-location-input"
type="text"
placeholder="Where are you at?"
value={ location }
onChange={ onChangeLocationInput }
onKeyDown={ this.onKeyDownLocationInput }
/>
<input
className="search-button"
type="button"
value="Search"
onClick={ onClickSearchButton }
/>
</form>
</div>
</div>
</div>
</div>
);
}
}
export default Hero;
|
import LinearGradient from 'canvas/graphics/LinearGradient.js';
import RadialGradient from 'canvas/graphics/RadialGradient.js';
export const SOLID = 0;
export const PATTERN = 1;
export const LINEAR_HORIZONTAL = 2;
export const LINEAR_VERTICAL = 3;
export const LINEAR_DIAGONAL = 4;
export const RADIAL = 5;
export default class ShapeFill {
constructor (shape, type = SOLID) {
this.shape = shape;
this.type = type;
this.angle = 0;
this.colors = null;
this.pattern = null;
this.gradient = null;
this.colorString = '';
this.style = 'rgba(0,0,0,1)';
this.dirty = false;
}
setSolid (colorString) {
this.type = SOLID;
this.colorString = colorString;
this.style = colorString;
return this;
}
setSolidFromRGB (r, g, b, a = 1) {
this.type = SOLID;
this.colorString = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
this.style = this.colorString;
return this;
}
setPattern (pattern) {
this.type = PATTERN;
this.pattern = pattern;
this.style = pattern;
return this;
}
setLinearGradientHorizontal (...colors) {
this.type = LINEAR_HORIZONTAL;
return this.setColors(colors);
}
setLinearGradientVertical (...colors) {
this.type = LINEAR_VERTICAL;
return this.setColors(colors);
}
setLinearGradientDiagonal (...colors) {
this.type = LINEAR_DIAGONAL;
return this.setColors(colors);
}
setRadialGradient (...colors) {
this.type = RADIAL;
return this.setColors(colors);
}
setColors (...colors) {
if (colors.length === 1 && Array.isArray(colors[0]))
{
this.colors = colors[0];
}
else
{
this.colors = colors;
}
this.dirty = true;
return this;
}
updateGradient (context) {
this.gradient = null;
context.save();
context.translate(0, 0);
if (this.type === LINEAR_HORIZONTAL)
{
this.gradient = context.createLinearGradient(0, 0, this.shape.width, 0);
}
else if (this.type === LINEAR_VERTICAL)
{
this.gradient = context.createLinearGradient(0, 0, 0, this.shape.height);
}
else if (this.type === LINEAR_DIAGONAL)
{
this.gradient = context.createLinearGradient(0, 0, this.shape.width, this.shape.height);
}
else if (this.type === RADIAL)
{
// TODO
}
if (this.gradient)
{
let c = 0;
for (let i = 0; i < this.colors.length / 2; i++)
{
this.gradient.addColorStop(this.colors[c], this.colors[c + 1]);
c += 2;
}
this.style = this.gradient;
}
context.restore();
this.dirty = false;
return this;
}
draw (context) {
if (this.dirty)
{
this.updateGradient(context);
}
context.fillStyle = this.style;
context.fill();
}
}
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2014-2022 Mickael Jeanroy
*
* 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.
*/
import {isNumber} from '../../util/is-number.js';
/**
* Check that the tested object is a number strictly less than zero.
*
* @message Expect [actual] (not) to be a negative number
* @example
* expect(-1).toBeNegative();
* expect(0).not.toBeNegative();
* expect(1).not.toBeNegative();
*
* @param {Object} ctx Test context.
* @return {Object} Test result.
* @since 0.1.0
*/
export function toBeNegative({actual, pp}) {
return {
pass: isNumber(actual) && actual < 0,
message() {
return `Expect ${pp(actual)} {{not}} to be a negative number`;
},
};
}
|
const { removeExcept } = require('./util'),
INVALID_ARGUMENT_ERROR = 'INVALID_ARGUMENT_ERROR',
DELETE_ERROR = 'DELETE_ERROR',
CLEAR_COMPLETED = 'CLEAR_COMPLETED';
/**
* Defines the basic properties needed for clearing a directory.
* @typedef {object} clearInputData
*
* @property {String} eID the unique id generated with the combination of packagename and timestamp.
* @property {String} directory the directory to clean
*
* @example
* {
* eID: 'somePackage-xxxxxxxxxxxxx',
* appName: 'somePackage',
* directory: 'User/PathForExtractDirectory'
* }
*
*/
/**
* @typedef {String} clearStatus
* It holds the value of either one of
* 'INVALID_ARGUMENT_ERROR', 'FILE_ACCESS_ERROR', 'CLEAR_COMPLETED'
*/
/**
* @typedef clearInfo
* The below object holds key properties defining the information for clearing process
*
* @property {clearStatus} status
* @property {?Error} [error]
*
* @example
* {
* status: 'CLEAR_COMPLETED',
* error: null
* }
*/
/**
* @typedef clearOutputData
* All the properties present in the return value
*
* @extends clearInputData
* @property {clearInfo} clearInfo
*
* @example
* {
* eID: 'somePackage-xxxxxxxxxxxxx',
* appName: 'somePackage',
* directory: 'User/PathForExtractDirectory',
* clearInfo: {
* status: 'CLEAR_COMPLETED',
* error: null
* }
* }
*
*/
/**
* @callback clearResponseCallback
* @param {?Error} error
* @param {clearOutputData} data
*
*/
/**
* @method clear
* @description This will clear the given directory
* leaving only the `app` and `${eID}-old` directories
* @param {clearInputData} clearInputData
* @param {clearResponseCallback} callback
* @throws {InvalidParamsException}
*/
function clear(clearInputData, callback) {
if (!callback) {
throw new Error('InvalidArgumentException: Hermes~clear - callback is a required parameter');
}
if (typeof callback !== 'function') {
throw new Error('InvalidArgumentException: Hermes~clear - callback should be of type function');
}
const clearOutputData = Object.assign({}, clearInputData, {
clearInfo: {
status: null,
error: null,
},
});
if (!clearInputData) {
const err = new Error('InvalidArgumentException: Hermes~clear - clearInputData is a required parameter');
clearOutputData.clearInfo = { status: INVALID_ARGUMENT_ERROR, error: err };
return callback(err, clearOutputData);
}
if (typeof clearInputData !== 'object' || Array.isArray(clearInputData)) {
const err = new Error('InvalidArgumentException: Hermes~clear - clearInputData should be of type object');
clearOutputData.clearInfo = { status: INVALID_ARGUMENT_ERROR, error: err };
return callback(err, clearOutputData);
}
if (!clearInputData.eID) {
const err = new Error('InvalidArgumentException: Hermes~clear - clearInputData.eID is a required field');
clearOutputData.clearInfo = { status: INVALID_ARGUMENT_ERROR, error: err };
return callback(err, clearOutputData);
}
if (typeof clearInputData.eID !== 'string') {
const err = new Error('InvalidArgumentException: Hermes~clear - clearInputData.eID should be of type string');
clearOutputData.clearInfo = { status: INVALID_ARGUMENT_ERROR, error: err };
return callback(err, clearOutputData);
}
if (!clearInputData.directory) {
const err = new Error('InvalidArgumentException: Hermes~clear - clearInputData.directory is a required field');
clearOutputData.clearInfo = { status: INVALID_ARGUMENT_ERROR, error: err };
return callback(err, clearOutputData);
}
if (typeof clearInputData.directory !== 'string') {
const err = new Error('InvalidArgumentException: Hermes~clear - clearInputData.directory should be of type string');
clearOutputData.clearInfo = { status: INVALID_ARGUMENT_ERROR, error: err };
return callback(err, clearOutputData);
}
if (!clearInputData.appName) {
const err = new Error('InvalidArgumentException: Hermes~clear - clearInputData.appName is a required field');
clearOutputData.clearInfo = { status: INVALID_ARGUMENT_ERROR, error: err };
return callback(err, clearOutputData);
}
if (typeof clearInputData.appName !== 'string') {
const err = new Error('InvalidArgumentException: Hermes~clear - clearInputData.appName should be of type string');
clearOutputData.clearInfo = { status: INVALID_ARGUMENT_ERROR, error: err };
return callback(err, clearOutputData);
}
const directoryToClean = clearInputData.directory,
{ eID, appName } = clearInputData;
return removeExcept(directoryToClean, ['app', eID, appName, `${eID}-old`], (err) => {
if (err) {
clearOutputData.clearInfo = { status: DELETE_ERROR, error: err };
return callback(err, clearOutputData);
}
clearOutputData.clearInfo = { status: CLEAR_COMPLETED, error: null };
return callback(null, clearOutputData);
});
}
module.exports = clear;
|
// Spectrum Colorpicker v1.3.1
// https://github.com/bgrins/spectrum
// Author: Brian Grinstead
// License: MIT
(function (window, $, undefined) {
var defaultOpts = {
// Callbacks
beforeShow: noop,
move: noop,
change: noop,
show: noop,
hide: noop,
// Options
color: false,
flat: false,
showInput: false,
allowEmpty: false,
showButtons: true,
clickoutFiresChange: false,
showInitial: false,
showPalette: false,
showPaletteOnly: false,
showSelectionPalette: true,
localStorageKey: false,
appendTo: "body",
maxSelectionSize: 7,
cancelText: "cancel",
chooseText: "choose",
clearText: "Clear Color Selection",
preferredFormat: false,
className: "",
showAlpha: false,
theme: "sp-light",
palette: ['fff', '000'],
selectionPalette: [],
disabled: false
},
spectrums = [],
IE = !!/msie/i.exec( window.navigator.userAgent ),
rgbaSupport = (function() {
function contains( str, substr ) {
return !!~('' + str).indexOf(substr);
}
var elem = document.createElement('div');
var style = elem.style;
style.cssText = 'background-color:rgba(0,0,0,.5)';
return contains(style.backgroundColor, 'rgba') || contains(style.backgroundColor, 'hsla');
})(),
inputTypeColorSupport = (function() {
var colorInput = $("<input type='color' value='!' />")[0];
return colorInput.type === "color" && colorInput.value !== "!";
})(),
replaceInput = [
"<div class='sp-replacer'>",
"<div class='sp-preview'><div class='sp-preview-inner'></div></div>",
"<div class='sp-dd'>▼</div>",
"</div>"
].join(''),
markup = (function () {
// IE does not support gradients with multiple stops, so we need to simulate
// that for the rainbow slider with 8 divs that each have a single gradient
var gradientFix = "";
if (IE) {
for (var i = 1; i <= 6; i++) {
gradientFix += "<div class='sp-" + i + "'></div>";
}
}
return [
"<div class='sp-container sp-hidden'>",
"<div class='sp-palette-container'>",
"<div class='sp-palette sp-thumb sp-cf'></div>",
"</div>",
"<div class='sp-picker-container'>",
"<div class='sp-top sp-cf'>",
"<div class='sp-fill'></div>",
"<div class='sp-top-inner'>",
"<div class='sp-color'>",
"<div class='sp-sat'>",
"<div class='sp-val'>",
"<div class='sp-dragger'></div>",
"</div>",
"</div>",
"</div>",
"<div class='sp-clear sp-clear-display'>",
"</div>",
"<div class='sp-hue'>",
"<div class='sp-slider'></div>",
gradientFix,
"</div>",
"</div>",
"<div class='sp-alpha'><div class='sp-alpha-inner'><div class='sp-alpha-handle'></div></div></div>",
"</div>",
"<div class='sp-input-container sp-cf'>",
"<input class='sp-input' type='text' spellcheck='false' />",
"</div>",
"<div class='sp-initial sp-thumb sp-cf'></div>",
"<div class='sp-button-container sp-cf'>",
"<a class='sp-cancel' href='#'></a>",
"<button class='sp-choose'></button>",
"</div>",
"</div>",
"</div>"
].join("");
})();
function paletteTemplate (p, color, className) {
var html = [];
for (var i = 0; i < p.length; i++) {
var current = p[i];
if(current) {
var tiny = tinycolor(current);
var c = tiny.toHsl().l < 0.5 ? "sp-thumb-el sp-thumb-dark" : "sp-thumb-el sp-thumb-light";
c += (tinycolor.equals(color, current)) ? " sp-thumb-active" : "";
var swatchStyle = rgbaSupport ? ("background-color:" + tiny.toRgbString()) : "filter:" + tiny.toFilter();
html.push('<span title="' + tiny.toRgbString() + '" data-color="' + tiny.toRgbString() + '" class="' + c + '"><span class="sp-thumb-inner" style="' + swatchStyle + ';" /></span>');
} else {
var cls = 'sp-clear-display';
html.push('<span title="No Color Selected" data-color="" style="background-color:transparent;" class="' + cls + '"></span>');
}
}
return "<div class='sp-cf " + className + "'>" + html.join('') + "</div>";
}
function hideAll() {
for (var i = 0; i < spectrums.length; i++) {
if (spectrums[i]) {
spectrums[i].hide();
}
}
}
function instanceOptions(o, callbackContext) {
var opts = $.extend({}, defaultOpts, o);
opts.callbacks = {
'move': bind(opts.move, callbackContext),
'change': bind(opts.change, callbackContext),
'show': bind(opts.show, callbackContext),
'hide': bind(opts.hide, callbackContext),
'beforeShow': bind(opts.beforeShow, callbackContext)
};
return opts;
}
function spectrum(element, o) {
var opts = instanceOptions(o, element),
flat = opts.flat,
showSelectionPalette = opts.showSelectionPalette,
localStorageKey = opts.localStorageKey,
theme = opts.theme,
callbacks = opts.callbacks,
resize = throttle(reflow, 10),
visible = false,
dragWidth = 0,
dragHeight = 0,
dragHelperHeight = 0,
slideHeight = 0,
slideWidth = 0,
alphaWidth = 0,
alphaSlideHelperWidth = 0,
slideHelperHeight = 0,
currentHue = 0,
currentSaturation = 0,
currentValue = 0,
currentAlpha = 1,
palette = [],
paletteArray = [],
selectionPalette = opts.selectionPalette.slice(0),
maxSelectionSize = opts.maxSelectionSize,
draggingClass = "sp-dragging",
shiftMovementDirection = null;
var doc = element.ownerDocument,
body = doc.body,
boundElement = $(element),
disabled = false,
container = $(markup, doc).addClass(theme),
dragger = container.find(".sp-color"),
dragHelper = container.find(".sp-dragger"),
slider = container.find(".sp-hue"),
slideHelper = container.find(".sp-slider"),
alphaSliderInner = container.find(".sp-alpha-inner"),
alphaSlider = container.find(".sp-alpha"),
alphaSlideHelper = container.find(".sp-alpha-handle"),
textInput = container.find(".sp-input"),
paletteContainer = container.find(".sp-palette"),
initialColorContainer = container.find(".sp-initial"),
cancelButton = container.find(".sp-cancel"),
clearButton = container.find(".sp-clear"),
chooseButton = container.find(".sp-choose"),
isInput = boundElement.is("input"),
isInputTypeColor = isInput && inputTypeColorSupport && boundElement.attr("type") === "color",
shouldReplace = isInput && !flat,
replacer = (shouldReplace) ? $(replaceInput).addClass(theme).addClass(opts.className) : $([]),
offsetElement = (shouldReplace) ? replacer : boundElement,
previewElement = replacer.find(".sp-preview-inner"),
initialColor = opts.color || (isInput && boundElement.val()),
colorOnShow = false,
preferredFormat = opts.preferredFormat,
currentPreferredFormat = preferredFormat,
clickoutFiresChange = !opts.showButtons || opts.clickoutFiresChange,
isEmpty = !initialColor,
allowEmpty = opts.allowEmpty && !isInputTypeColor;
function applyOptions() {
if (opts.showPaletteOnly) {
opts.showPalette = true;
}
if (opts.palette) {
palette = opts.palette.slice(0);
paletteArray = $.isArray(palette[0]) ? palette : [palette];
}
container.toggleClass("sp-flat", flat);
container.toggleClass("sp-input-disabled", !opts.showInput);
container.toggleClass("sp-alpha-enabled", opts.showAlpha);
container.toggleClass("sp-clear-enabled", allowEmpty);
container.toggleClass("sp-buttons-disabled", !opts.showButtons);
container.toggleClass("sp-palette-disabled", !opts.showPalette);
container.toggleClass("sp-palette-only", opts.showPaletteOnly);
container.toggleClass("sp-initial-disabled", !opts.showInitial);
container.addClass(opts.className);
reflow();
}
function initialize() {
if (IE) {
container.find("*:not(input)").attr("unselectable", "on");
}
applyOptions();
if (shouldReplace) {
boundElement.after(replacer).hide();
}
if (!allowEmpty) {
clearButton.hide();
}
if (flat) {
boundElement.after(container).hide();
}
else {
var appendTo = opts.appendTo === "parent" ? boundElement.parent() : $(opts.appendTo);
if (appendTo.length !== 1) {
appendTo = $("body");
}
appendTo.append(container);
}
if (localStorageKey && window.localStorage) {
// Migrate old palettes over to new format. May want to remove this eventually.
try {
var oldPalette = window.localStorage[localStorageKey].split(",#");
if (oldPalette.length > 1) {
delete window.localStorage[localStorageKey];
$.each(oldPalette, function(i, c) {
addColorToSelectionPalette(c);
});
}
}
catch(e) { }
try {
selectionPalette = window.localStorage[localStorageKey].split(";");
}
catch (e) { }
}
offsetElement.bind("click.spectrum touchstart.spectrum", function (e) {
if (!disabled) {
toggle();
}
e.stopPropagation();
if (!$(e.target).is("input")) {
e.preventDefault();
}
});
if(boundElement.is(":disabled") || (opts.disabled === true)) {
disable();
}
// Prevent clicks from bubbling up to document. This would cause it to be hidden.
container.click(stopPropagation);
// Handle user typed input
textInput.change(setFromTextInput);
textInput.bind("paste", function () {
setTimeout(setFromTextInput, 1);
});
textInput.keydown(function (e) { if (e.keyCode == 13) { setFromTextInput(); } });
cancelButton.text(opts.cancelText);
cancelButton.bind("click.spectrum", function (e) {
e.stopPropagation();
e.preventDefault();
hide("cancel");
});
clearButton.attr("title", opts.clearText);
clearButton.bind("click.spectrum", function (e) {
e.stopPropagation();
e.preventDefault();
isEmpty = true;
move();
if(flat) {
//for the flat style, this is a change event
updateOriginalInput(true);
}
});
chooseButton.text(opts.chooseText);
chooseButton.bind("click.spectrum", function (e) {
e.stopPropagation();
e.preventDefault();
if (isValid()) {
updateOriginalInput(true);
hide();
}
});
draggable(alphaSlider, function (dragX, dragY, e) {
currentAlpha = (dragX / alphaWidth);
isEmpty = false;
if (e.shiftKey) {
currentAlpha = Math.round(currentAlpha * 10) / 10;
}
move();
}, dragStart, dragStop);
draggable(slider, function (dragX, dragY) {
currentHue = parseFloat(dragY / slideHeight);
isEmpty = false;
if (!opts.showAlpha) {
currentAlpha = 1;
}
move();
}, dragStart, dragStop);
draggable(dragger, function (dragX, dragY, e) {
// shift+drag should snap the movement to either the x or y axis.
if (!e.shiftKey) {
shiftMovementDirection = null;
}
else if (!shiftMovementDirection) {
var oldDragX = currentSaturation * dragWidth;
var oldDragY = dragHeight - (currentValue * dragHeight);
var furtherFromX = Math.abs(dragX - oldDragX) > Math.abs(dragY - oldDragY);
shiftMovementDirection = furtherFromX ? "x" : "y";
}
var setSaturation = !shiftMovementDirection || shiftMovementDirection === "x";
var setValue = !shiftMovementDirection || shiftMovementDirection === "y";
if (setSaturation) {
currentSaturation = parseFloat(dragX / dragWidth);
}
if (setValue) {
currentValue = parseFloat((dragHeight - dragY) / dragHeight);
}
isEmpty = false;
if (!opts.showAlpha) {
currentAlpha = 1;
}
move();
}, dragStart, dragStop);
if (!!initialColor) {
set(initialColor);
// In case color was black - update the preview UI and set the format
// since the set function will not run (default color is black).
updateUI();
currentPreferredFormat = preferredFormat || tinycolor(initialColor).format;
addColorToSelectionPalette(initialColor);
}
else {
updateUI();
}
if (flat) {
show();
}
function palletElementClick(e) {
if (e.data && e.data.ignore) {
set($(this).data("color"));
move();
}
else {
set($(this).data("color"));
move();
updateOriginalInput(true);
hide();
}
return false;
}
var paletteEvent = IE ? "mousedown.spectrum" : "click.spectrum touchstart.spectrum";
paletteContainer.delegate(".sp-thumb-el", paletteEvent, palletElementClick);
initialColorContainer.delegate(".sp-thumb-el:nth-child(1)", paletteEvent, { ignore: true }, palletElementClick);
}
function addColorToSelectionPalette(color) {
if (showSelectionPalette) {
var colorRgb = tinycolor(color).toRgbString();
if ($.inArray(colorRgb, selectionPalette) === -1) {
selectionPalette.push(colorRgb);
while(selectionPalette.length > maxSelectionSize) {
selectionPalette.shift();
}
}
if (localStorageKey && window.localStorage) {
try {
window.localStorage[localStorageKey] = selectionPalette.join(";");
}
catch(e) { }
}
}
}
function getUniqueSelectionPalette() {
var unique = [];
var p = selectionPalette;
var paletteLookup = {};
var rgb;
if (opts.showPalette) {
for (var i = 0; i < paletteArray.length; i++) {
for (var j = 0; j < paletteArray[i].length; j++) {
rgb = tinycolor(paletteArray[i][j]).toRgbString();
paletteLookup[rgb] = true;
}
}
for (i = 0; i < p.length; i++) {
rgb = tinycolor(p[i]).toRgbString();
if (!paletteLookup.hasOwnProperty(rgb)) {
unique.push(p[i]);
paletteLookup[rgb] = true;
}
}
}
return unique.reverse().slice(0, opts.maxSelectionSize);
}
function drawPalette() {
var currentColor = get();
var html = $.map(paletteArray, function (palette, i) {
return paletteTemplate(palette, currentColor, "sp-palette-row sp-palette-row-" + i);
});
if (selectionPalette) {
html.push(paletteTemplate(getUniqueSelectionPalette(), currentColor, "sp-palette-row sp-palette-row-selection"));
}
paletteContainer.html(html.join(""));
}
function drawInitial() {
if (opts.showInitial) {
var initial = colorOnShow;
var current = get();
initialColorContainer.html(paletteTemplate([initial, current], current, "sp-palette-row-initial"));
}
}
function dragStart() {
if (dragHeight <= 0 || dragWidth <= 0 || slideHeight <= 0) {
reflow();
}
container.addClass(draggingClass);
shiftMovementDirection = null;
boundElement.trigger('dragstart.spectrum', [ get() ]);
}
function dragStop() {
container.removeClass(draggingClass);
boundElement.trigger('dragstop.spectrum', [ get() ]);
}
function setFromTextInput() {
var value = textInput.val();
if ((value === null || value === "") && allowEmpty) {
set(null);
updateOriginalInput(true);
}
else {
var tiny = tinycolor(value);
if (tiny.ok) {
set(tiny);
updateOriginalInput(true);
}
else {
textInput.addClass("sp-validation-error");
}
}
}
function toggle() {
if (visible) {
hide();
}
else {
show();
}
}
function show() {
var event = $.Event('beforeShow.spectrum');
if (visible) {
reflow();
return;
}
boundElement.trigger(event, [ get() ]);
if (callbacks.beforeShow(get()) === false || event.isDefaultPrevented()) {
return;
}
hideAll();
visible = true;
$(doc).bind("click.spectrum", hide);
$(window).bind("resize.spectrum", resize);
replacer.addClass("sp-active");
container.removeClass("sp-hidden");
reflow();
updateUI();
colorOnShow = get();
drawInitial();
callbacks.show(colorOnShow);
boundElement.trigger('show.spectrum', [ colorOnShow ]);
}
function hide(e) {
// Return on right click
if (e && e.type == "click" && e.button == 2) { return; }
// Return if hiding is unnecessary
if (!visible || flat) { return; }
visible = false;
$(doc).unbind("click.spectrum", hide);
$(window).unbind("resize.spectrum", resize);
replacer.removeClass("sp-active");
container.addClass("sp-hidden");
var colorHasChanged = !tinycolor.equals(get(), colorOnShow);
if (colorHasChanged) {
if (clickoutFiresChange && e !== "cancel") {
updateOriginalInput(true);
}
else {
revert();
}
}
callbacks.hide(get());
boundElement.trigger('hide.spectrum', [ get() ]);
}
function revert() {
set(colorOnShow, true);
}
function set(color, ignoreFormatChange) {
if (tinycolor.equals(color, get())) {
// Update UI just in case a validation error needs
// to be cleared.
updateUI();
return;
}
var newColor, newHsv;
if (!color && allowEmpty) {
isEmpty = true;
} else {
isEmpty = false;
newColor = tinycolor(color);
newHsv = newColor.toHsv();
currentHue = (newHsv.h % 360) / 360;
currentSaturation = newHsv.s;
currentValue = newHsv.v;
currentAlpha = newHsv.a;
}
updateUI();
if (newColor && newColor.ok && !ignoreFormatChange) {
currentPreferredFormat = preferredFormat || newColor.format;
}
}
function get(opts) {
opts = opts || { };
if (allowEmpty && isEmpty) {
return null;
}
return tinycolor.fromRatio({
h: currentHue,
s: currentSaturation,
v: currentValue,
a: Math.round(currentAlpha * 100) / 100
}, { format: opts.format || currentPreferredFormat });
}
function isValid() {
return !textInput.hasClass("sp-validation-error");
}
function move() {
updateUI();
callbacks.move(get());
boundElement.trigger('move.spectrum', [ get() ]);
}
function updateUI() {
textInput.removeClass("sp-validation-error");
updateHelperLocations();
// Update dragger background color (gradients take care of saturation and value).
var flatColor = tinycolor.fromRatio({ h: currentHue, s: 1, v: 1 });
dragger.css("background-color", flatColor.toHexString());
// Get a format that alpha will be included in (hex and names ignore alpha)
var format = currentPreferredFormat;
if (currentAlpha < 1 && !(currentAlpha === 0 && format === "name")) {
if (format === "hex" || format === "hex3" || format === "hex6" || format === "name") {
format = "rgb";
}
}
var realColor = get({ format: format }),
displayColor = '';
//reset background info for preview element
previewElement.removeClass("sp-clear-display");
previewElement.css('background-color', 'transparent');
if (!realColor && allowEmpty) {
// Update the replaced elements background with icon indicating no color selection
previewElement.addClass("sp-clear-display");
}
else {
var realHex = realColor.toHexString(),
realRgb = realColor.toRgbString();
// Update the replaced elements background color (with actual selected color)
if (rgbaSupport || realColor.alpha === 1) {
previewElement.css("background-color", realRgb);
}
else {
previewElement.css("background-color", "transparent");
previewElement.css("filter", realColor.toFilter());
}
if (opts.showAlpha) {
var rgb = realColor.toRgb();
rgb.a = 0;
var realAlpha = tinycolor(rgb).toRgbString();
var gradient = "linear-gradient(left, " + realAlpha + ", " + realHex + ")";
if (IE) {
alphaSliderInner.css("filter", tinycolor(realAlpha).toFilter({ gradientType: 1 }, realHex));
}
else {
alphaSliderInner.css("background", "-webkit-" + gradient);
alphaSliderInner.css("background", "-moz-" + gradient);
alphaSliderInner.css("background", "-ms-" + gradient);
// Use current syntax gradient on unprefixed property.
alphaSliderInner.css("background",
"linear-gradient(to right, " + realAlpha + ", " + realHex + ")");
}
}
displayColor = realColor.toString(format);
}
// Update the text entry input as it changes happen
if (opts.showInput) {
textInput.val(displayColor);
}
if (opts.showPalette) {
drawPalette();
}
drawInitial();
}
function updateHelperLocations() {
var s = currentSaturation;
var v = currentValue;
if(allowEmpty && isEmpty) {
//if selected color is empty, hide the helpers
alphaSlideHelper.hide();
slideHelper.hide();
dragHelper.hide();
}
else {
//make sure helpers are visible
alphaSlideHelper.show();
slideHelper.show();
dragHelper.show();
// Where to show the little circle in that displays your current selected color
var dragX = s * dragWidth;
var dragY = dragHeight - (v * dragHeight);
dragX = Math.max(
-dragHelperHeight,
Math.min(dragWidth - dragHelperHeight, dragX - dragHelperHeight)
);
dragY = Math.max(
-dragHelperHeight,
Math.min(dragHeight - dragHelperHeight, dragY - dragHelperHeight)
);
dragHelper.css({
"top": dragY + "px",
"left": dragX + "px"
});
var alphaX = currentAlpha * alphaWidth;
alphaSlideHelper.css({
"left": (alphaX - (alphaSlideHelperWidth / 2)) + "px"
});
// Where to show the bar that displays your current selected hue
var slideY = (currentHue) * slideHeight;
slideHelper.css({
"top": (slideY - slideHelperHeight) + "px"
});
}
}
function updateOriginalInput(fireCallback) {
var color = get(),
displayColor = '',
hasChanged = !tinycolor.equals(color, colorOnShow);
if (color) {
displayColor = color.toString(currentPreferredFormat);
// Update the selection palette with the current color
addColorToSelectionPalette(color);
}
if (isInput) {
boundElement.val(displayColor);
}
colorOnShow = color;
if (fireCallback && hasChanged) {
callbacks.change(color);
boundElement.trigger('change', [ color ]);
}
}
function reflow() {
dragWidth = dragger.width();
dragHeight = dragger.height();
dragHelperHeight = dragHelper.height();
slideWidth = slider.width();
slideHeight = slider.height();
slideHelperHeight = slideHelper.height();
alphaWidth = alphaSlider.width();
alphaSlideHelperWidth = alphaSlideHelper.width();
if (!flat) {
container.css("position", "absolute");
container.offset(getOffset(container, offsetElement));
}
updateHelperLocations();
if (opts.showPalette) {
drawPalette();
}
boundElement.trigger('reflow.spectrum');
}
function destroy() {
boundElement.show();
offsetElement.unbind("click.spectrum touchstart.spectrum");
container.remove();
replacer.remove();
spectrums[spect.id] = null;
}
function option(optionName, optionValue) {
if (optionName === undefined) {
return $.extend({}, opts);
}
if (optionValue === undefined) {
return opts[optionName];
}
opts[optionName] = optionValue;
applyOptions();
}
function enable() {
disabled = false;
boundElement.attr("disabled", false);
offsetElement.removeClass("sp-disabled");
}
function disable() {
hide();
disabled = true;
boundElement.attr("disabled", true);
offsetElement.addClass("sp-disabled");
}
initialize();
var spect = {
show: show,
hide: hide,
toggle: toggle,
reflow: reflow,
option: option,
enable: enable,
disable: disable,
set: function (c) {
set(c);
updateOriginalInput();
},
get: get,
destroy: destroy,
container: container
};
spect.id = spectrums.push(spect) - 1;
return spect;
}
/**
* checkOffset - get the offset below/above and left/right element depending on screen position
* Thanks https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js
*/
function getOffset(picker, input) {
var extraY = 0;
var dpWidth = picker.outerWidth();
var dpHeight = picker.outerHeight();
var inputHeight = input.outerHeight();
var doc = picker[0].ownerDocument;
var docElem = doc.documentElement;
var viewWidth = docElem.clientWidth + $(doc).scrollLeft();
var viewHeight = docElem.clientHeight + $(doc).scrollTop();
var offset = input.offset();
offset.top += inputHeight;
offset.left -=
Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
Math.abs(offset.left + dpWidth - viewWidth) : 0);
offset.top -=
Math.min(offset.top, ((offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
Math.abs(dpHeight + inputHeight - extraY) : extraY));
return offset;
}
/**
* noop - do nothing
*/
function noop() {
}
/**
* stopPropagation - makes the code only doing this a little easier to read in line
*/
function stopPropagation(e) {
e.stopPropagation();
}
/**
* Create a function bound to a given object
* Thanks to underscore.js
*/
function bind(func, obj) {
var slice = Array.prototype.slice;
var args = slice.call(arguments, 2);
return function () {
return func.apply(obj, args.concat(slice.call(arguments)));
};
}
/**
* Lightweight drag helper. Handles containment within the element, so that
* when dragging, the x is within [0,element.width] and y is within [0,element.height]
*/
function draggable(element, onmove, onstart, onstop) {
onmove = onmove || function () { };
onstart = onstart || function () { };
onstop = onstop || function () { };
var doc = element.ownerDocument || document;
var dragging = false;
var offset = {};
var maxHeight = 0;
var maxWidth = 0;
var hasTouch = ('ontouchstart' in window);
var duringDragEvents = {};
duringDragEvents["selectstart"] = prevent;
duringDragEvents["dragstart"] = prevent;
duringDragEvents["touchmove mousemove"] = move;
duringDragEvents["touchend mouseup"] = stop;
function prevent(e) {
if (e.stopPropagation) {
e.stopPropagation();
}
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
}
function move(e) {
if (dragging) {
// Mouseup happened outside of window
if (IE && document.documentMode < 9 && !e.button) {
return stop();
}
var touches = e.originalEvent.touches;
var pageX = touches ? touches[0].pageX : e.pageX;
var pageY = touches ? touches[0].pageY : e.pageY;
var dragX = Math.max(0, Math.min(pageX - offset.left, maxWidth));
var dragY = Math.max(0, Math.min(pageY - offset.top, maxHeight));
if (hasTouch) {
// Stop scrolling in iOS
prevent(e);
}
onmove.apply(element, [dragX, dragY, e]);
}
}
function start(e) {
var rightclick = (e.which) ? (e.which == 3) : (e.button == 2);
var touches = e.originalEvent.touches;
if (!rightclick && !dragging) {
if (onstart.apply(element, arguments) !== false) {
dragging = true;
maxHeight = $(element).height();
maxWidth = $(element).width();
offset = $(element).offset();
$(doc).bind(duringDragEvents);
$(doc.body).addClass("sp-dragging");
if (!hasTouch) {
move(e);
}
prevent(e);
}
}
}
function stop() {
if (dragging) {
$(doc).unbind(duringDragEvents);
$(doc.body).removeClass("sp-dragging");
onstop.apply(element, arguments);
}
dragging = false;
}
$(element).bind("touchstart mousedown", start);
}
function throttle(func, wait, debounce) {
var timeout;
return function () {
var context = this, args = arguments;
var throttler = function () {
timeout = null;
func.apply(context, args);
};
if (debounce) clearTimeout(timeout);
if (debounce || !timeout) timeout = setTimeout(throttler, wait);
};
}
function log(){/* jshint -W021 */if(window.console){if(Function.prototype.bind)log=Function.prototype.bind.call(console.log,console);else log=function(){Function.prototype.apply.call(console.log,console,arguments);};log.apply(this,arguments);}}
/**
* Define a jQuery plugin
*/
var dataID = "spectrum.id";
$.fn.spectrum = function (opts, extra) {
if (typeof opts == "string") {
var returnValue = this;
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function () {
var spect = spectrums[$(this).data(dataID)];
if (spect) {
var method = spect[opts];
if (!method) {
throw new Error( "Spectrum: no such method: '" + opts + "'" );
}
if (opts == "get") {
returnValue = spect.get();
}
else if (opts == "container") {
returnValue = spect.container;
}
else if (opts == "option") {
returnValue = spect.option.apply(spect, args);
}
else if (opts == "destroy") {
spect.destroy();
$(this).removeData(dataID);
}
else {
method.apply(spect, args);
}
}
});
return returnValue;
}
// Initializing a new instance of spectrum
return this.spectrum("destroy").each(function () {
var options = $.extend({}, opts, $(this).data());
var spect = spectrum(this, options);
$(this).data(dataID, spect.id);
});
};
$.fn.spectrum.load = true;
$.fn.spectrum.loadOpts = {};
$.fn.spectrum.draggable = draggable;
$.fn.spectrum.defaults = defaultOpts;
$.spectrum = { };
$.spectrum.localization = { };
$.spectrum.palettes = { };
$.fn.spectrum.processNativeColorInputs = function () {
if (!inputTypeColorSupport) {
$("input[type=color]").spectrum({
preferredFormat: "hex6"
});
}
};
// TinyColor v0.9.17
// https://github.com/bgrins/TinyColor
// 2013-08-10, Brian Grinstead, MIT License
(function() {
var trimLeft = /^[\s,#]+/,
trimRight = /\s+$/,
tinyCounter = 0,
math = Math,
mathRound = math.round,
mathMin = math.min,
mathMax = math.max,
mathRandom = math.random;
function tinycolor (color, opts) {
color = (color) ? color : '';
opts = opts || { };
// If input is already a tinycolor, return itself
if (typeof color == "object" && color.hasOwnProperty("_tc_id")) {
return color;
}
var rgb = inputToRGB(color);
var r = rgb.r,
g = rgb.g,
b = rgb.b,
a = rgb.a,
roundA = mathRound(100*a) / 100,
format = opts.format || rgb.format;
// Don't let the range of [0,255] come back in [0,1].
// Potentially lose a little bit of precision here, but will fix issues where
// .5 gets interpreted as half of the total, instead of half of 1
// If it was supposed to be 128, this was already taken care of by `inputToRgb`
if (r < 1) { r = mathRound(r); }
if (g < 1) { g = mathRound(g); }
if (b < 1) { b = mathRound(b); }
return {
ok: rgb.ok,
format: format,
_tc_id: tinyCounter++,
alpha: a,
getAlpha: function() {
return a;
},
setAlpha: function(value) {
a = boundAlpha(value);
roundA = mathRound(100*a) / 100;
},
toHsv: function() {
var hsv = rgbToHsv(r, g, b);
return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: a };
},
toHsvString: function() {
var hsv = rgbToHsv(r, g, b);
var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
return (a == 1) ?
"hsv(" + h + ", " + s + "%, " + v + "%)" :
"hsva(" + h + ", " + s + "%, " + v + "%, "+ roundA + ")";
},
toHsl: function() {
var hsl = rgbToHsl(r, g, b);
return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: a };
},
toHslString: function() {
var hsl = rgbToHsl(r, g, b);
var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
return (a == 1) ?
"hsl(" + h + ", " + s + "%, " + l + "%)" :
"hsla(" + h + ", " + s + "%, " + l + "%, "+ roundA + ")";
},
toHex: function(allow3Char) {
return rgbToHex(r, g, b, allow3Char);
},
toHexString: function(allow3Char) {
return '#' + this.toHex(allow3Char);
},
toHex8: function() {
return rgbaToHex(r, g, b, a);
},
toHex8String: function() {
return '#' + this.toHex8();
},
toRgb: function() {
return { r: mathRound(r), g: mathRound(g), b: mathRound(b), a: a };
},
toRgbString: function() {
return (a == 1) ?
"rgb(" + mathRound(r) + ", " + mathRound(g) + ", " + mathRound(b) + ")" :
"rgba(" + mathRound(r) + ", " + mathRound(g) + ", " + mathRound(b) + ", " + roundA + ")";
},
toPercentageRgb: function() {
return { r: mathRound(bound01(r, 255) * 100) + "%", g: mathRound(bound01(g, 255) * 100) + "%", b: mathRound(bound01(b, 255) * 100) + "%", a: a };
},
toPercentageRgbString: function() {
return (a == 1) ?
"rgb(" + mathRound(bound01(r, 255) * 100) + "%, " + mathRound(bound01(g, 255) * 100) + "%, " + mathRound(bound01(b, 255) * 100) + "%)" :
"rgba(" + mathRound(bound01(r, 255) * 100) + "%, " + mathRound(bound01(g, 255) * 100) + "%, " + mathRound(bound01(b, 255) * 100) + "%, " + roundA + ")";
},
toName: function() {
if (a === 0) {
return "transparent";
}
return hexNames[rgbToHex(r, g, b, true)] || false;
},
toFilter: function(secondColor) {
var hex8String = '#' + rgbaToHex(r, g, b, a);
var secondHex8String = hex8String;
var gradientType = opts && opts.gradientType ? "GradientType = 1, " : "";
if (secondColor) {
var s = tinycolor(secondColor);
secondHex8String = s.toHex8String();
}
return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")";
},
toString: function(format) {
var formatSet = !!format;
format = format || this.format;
var formattedString = false;
var hasAlphaAndFormatNotSet = !formatSet && a < 1 && a > 0;
var formatWithAlpha = hasAlphaAndFormatNotSet && (format === "hex" || format === "hex6" || format === "hex3" || format === "name");
if (format === "rgb") {
formattedString = this.toRgbString();
}
if (format === "prgb") {
formattedString = this.toPercentageRgbString();
}
if (format === "hex" || format === "hex6") {
formattedString = this.toHexString();
}
if (format === "hex3") {
formattedString = this.toHexString(true);
}
if (format === "hex8") {
formattedString = this.toHex8String();
}
if (format === "name") {
formattedString = this.toName();
}
if (format === "hsl") {
formattedString = this.toHslString();
}
if (format === "hsv") {
formattedString = this.toHsvString();
}
if (formatWithAlpha) {
return this.toRgbString();
}
return formattedString || this.toHexString();
}
};
}
// If input is an object, force 1 into "1.0" to handle ratios properly
// String input requires "1.0" as input, so 1 will be treated as 1
tinycolor.fromRatio = function(color, opts) {
if (typeof color == "object") {
var newColor = {};
for (var i in color) {
if (color.hasOwnProperty(i)) {
if (i === "a") {
newColor[i] = color[i];
}
else {
newColor[i] = convertToPercentage(color[i]);
}
}
}
color = newColor;
}
return tinycolor(color, opts);
};
// Given a string or object, convert that input to RGB
// Possible string inputs:
//
// "red"
// "#f00" or "f00"
// "#ff0000" or "ff0000"
// "#ff000000" or "ff000000"
// "rgb 255 0 0" or "rgb (255, 0, 0)"
// "rgb 1.0 0 0" or "rgb (1, 0, 0)"
// "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
// "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
// "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
// "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
// "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
//
function inputToRGB(color) {
var rgb = { r: 0, g: 0, b: 0 };
var a = 1;
var ok = false;
var format = false;
if (typeof color == "string") {
color = stringInputToObject(color);
}
if (typeof color == "object") {
if (color.hasOwnProperty("r") && color.hasOwnProperty("g") && color.hasOwnProperty("b")) {
rgb = rgbToRgb(color.r, color.g, color.b);
ok = true;
format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
}
else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("v")) {
color.s = convertToPercentage(color.s);
color.v = convertToPercentage(color.v);
rgb = hsvToRgb(color.h, color.s, color.v);
ok = true;
format = "hsv";
}
else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("l")) {
color.s = convertToPercentage(color.s);
color.l = convertToPercentage(color.l);
rgb = hslToRgb(color.h, color.s, color.l);
ok = true;
format = "hsl";
}
if (color.hasOwnProperty("a")) {
a = color.a;
}
}
a = boundAlpha(a);
return {
ok: ok,
format: color.format || format,
r: mathMin(255, mathMax(rgb.r, 0)),
g: mathMin(255, mathMax(rgb.g, 0)),
b: mathMin(255, mathMax(rgb.b, 0)),
a: a
};
}
// Conversion Functions
// --------------------
// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
// <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>
// `rgbToRgb`
// Handle bounds / percentage checking to conform to CSS color spec
// <http://www.w3.org/TR/css3-color/>
// *Assumes:* r, g, b in [0, 255] or [0, 1]
// *Returns:* { r, g, b } in [0, 255]
function rgbToRgb(r, g, b){
return {
r: bound01(r, 255) * 255,
g: bound01(g, 255) * 255,
b: bound01(b, 255) * 255
};
}
// `rgbToHsl`
// Converts an RGB color value to HSL.
// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
// *Returns:* { h, s, l } in [0,1]
function rgbToHsl(r, g, b) {
r = bound01(r, 255);
g = bound01(g, 255);
b = bound01(b, 255);
var max = mathMax(r, g, b), min = mathMin(r, g, b);
var h, s, l = (max + min) / 2;
if(max == min) {
h = s = 0; // achromatic
}
else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return { h: h, s: s, l: l };
}
// `hslToRgb`
// Converts an HSL color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
function hslToRgb(h, s, l) {
var r, g, b;
h = bound01(h, 360);
s = bound01(s, 100);
l = bound01(l, 100);
function hue2rgb(p, q, t) {
if(t < 0) t += 1;
if(t > 1) t -= 1;
if(t < 1/6) return p + (q - p) * 6 * t;
if(t < 1/2) return q;
if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
if(s === 0) {
r = g = b = l; // achromatic
}
else {
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return { r: r * 255, g: g * 255, b: b * 255 };
}
// `rgbToHsv`
// Converts an RGB color value to HSV
// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
// *Returns:* { h, s, v } in [0,1]
function rgbToHsv(r, g, b) {
r = bound01(r, 255);
g = bound01(g, 255);
b = bound01(b, 255);
var max = mathMax(r, g, b), min = mathMin(r, g, b);
var h, s, v = max;
var d = max - min;
s = max === 0 ? 0 : d / max;
if(max == min) {
h = 0; // achromatic
}
else {
switch(max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return { h: h, s: s, v: v };
}
// `hsvToRgb`
// Converts an HSV color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
function hsvToRgb(h, s, v) {
h = bound01(h, 360) * 6;
s = bound01(s, 100);
v = bound01(v, 100);
var i = math.floor(h),
f = h - i,
p = v * (1 - s),
q = v * (1 - f * s),
t = v * (1 - (1 - f) * s),
mod = i % 6,
r = [v, q, p, p, t, v][mod],
g = [t, v, v, q, p, p][mod],
b = [p, p, t, v, v, q][mod];
return { r: r * 255, g: g * 255, b: b * 255 };
}
// `rgbToHex`
// Converts an RGB color to hex
// Assumes r, g, and b are contained in the set [0, 255]
// Returns a 3 or 6 character hex
function rgbToHex(r, g, b, allow3Char) {
var hex = [
pad2(mathRound(r).toString(16)),
pad2(mathRound(g).toString(16)),
pad2(mathRound(b).toString(16))
];
// Return a 3 character hex if possible
if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
}
return hex.join("");
}
// `rgbaToHex`
// Converts an RGBA color plus alpha transparency to hex
// Assumes r, g, b and a are contained in the set [0, 255]
// Returns an 8 character hex
function rgbaToHex(r, g, b, a) {
var hex = [
pad2(convertDecimalToHex(a)),
pad2(mathRound(r).toString(16)),
pad2(mathRound(g).toString(16)),
pad2(mathRound(b).toString(16))
];
return hex.join("");
}
// `equals`
// Can be called with any tinycolor input
tinycolor.equals = function (color1, color2) {
if (!color1 || !color2) { return false; }
return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
};
tinycolor.random = function() {
return tinycolor.fromRatio({
r: mathRandom(),
g: mathRandom(),
b: mathRandom()
});
};
// Modification Functions
// ----------------------
// Thanks to less.js for some of the basics here
// <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>
tinycolor.desaturate = function (color, amount) {
amount = (amount === 0) ? 0 : (amount || 10);
var hsl = tinycolor(color).toHsl();
hsl.s -= amount / 100;
hsl.s = clamp01(hsl.s);
return tinycolor(hsl);
};
tinycolor.saturate = function (color, amount) {
amount = (amount === 0) ? 0 : (amount || 10);
var hsl = tinycolor(color).toHsl();
hsl.s += amount / 100;
hsl.s = clamp01(hsl.s);
return tinycolor(hsl);
};
tinycolor.greyscale = function(color) {
return tinycolor.desaturate(color, 100);
};
tinycolor.lighten = function(color, amount) {
amount = (amount === 0) ? 0 : (amount || 10);
var hsl = tinycolor(color).toHsl();
hsl.l += amount / 100;
hsl.l = clamp01(hsl.l);
return tinycolor(hsl);
};
tinycolor.darken = function (color, amount) {
amount = (amount === 0) ? 0 : (amount || 10);
var hsl = tinycolor(color).toHsl();
hsl.l -= amount / 100;
hsl.l = clamp01(hsl.l);
return tinycolor(hsl);
};
tinycolor.complement = function(color) {
var hsl = tinycolor(color).toHsl();
hsl.h = (hsl.h + 180) % 360;
return tinycolor(hsl);
};
// Combination Functions
// ---------------------
// Thanks to jQuery xColor for some of the ideas behind these
// <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>
tinycolor.triad = function(color) {
var hsl = tinycolor(color).toHsl();
var h = hsl.h;
return [
tinycolor(color),
tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
];
};
tinycolor.tetrad = function(color) {
var hsl = tinycolor(color).toHsl();
var h = hsl.h;
return [
tinycolor(color),
tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
];
};
tinycolor.splitcomplement = function(color) {
var hsl = tinycolor(color).toHsl();
var h = hsl.h;
return [
tinycolor(color),
tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
];
};
tinycolor.analogous = function(color, results, slices) {
results = results || 6;
slices = slices || 30;
var hsl = tinycolor(color).toHsl();
var part = 360 / slices;
var ret = [tinycolor(color)];
for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
hsl.h = (hsl.h + part) % 360;
ret.push(tinycolor(hsl));
}
return ret;
};
tinycolor.monochromatic = function(color, results) {
results = results || 6;
var hsv = tinycolor(color).toHsv();
var h = hsv.h, s = hsv.s, v = hsv.v;
var ret = [];
var modification = 1 / results;
while (results--) {
ret.push(tinycolor({ h: h, s: s, v: v}));
v = (v + modification) % 1;
}
return ret;
};
// Readability Functions
// ---------------------
// <http://www.w3.org/TR/AERT#color-contrast>
// `readability`
// Analyze the 2 colors and returns an object with the following properties:
// `brightness`: difference in brightness between the two colors
// `color`: difference in color/hue between the two colors
tinycolor.readability = function(color1, color2) {
var a = tinycolor(color1).toRgb();
var b = tinycolor(color2).toRgb();
var brightnessA = (a.r * 299 + a.g * 587 + a.b * 114) / 1000;
var brightnessB = (b.r * 299 + b.g * 587 + b.b * 114) / 1000;
var colorDiff = (
Math.max(a.r, b.r) - Math.min(a.r, b.r) +
Math.max(a.g, b.g) - Math.min(a.g, b.g) +
Math.max(a.b, b.b) - Math.min(a.b, b.b)
);
return {
brightness: Math.abs(brightnessA - brightnessB),
color: colorDiff
};
};
// `readable`
// http://www.w3.org/TR/AERT#color-contrast
// Ensure that foreground and background color combinations provide sufficient contrast.
// *Example*
// tinycolor.readable("#000", "#111") => false
tinycolor.readable = function(color1, color2) {
var readability = tinycolor.readability(color1, color2);
return readability.brightness > 125 && readability.color > 500;
};
// `mostReadable`
// Given a base color and a list of possible foreground or background
// colors for that base, returns the most readable color.
// *Example*
// tinycolor.mostReadable("#123", ["#fff", "#000"]) => "#000"
tinycolor.mostReadable = function(baseColor, colorList) {
var bestColor = null;
var bestScore = 0;
var bestIsReadable = false;
for (var i=0; i < colorList.length; i++) {
// We normalize both around the "acceptable" breaking point,
// but rank brightness constrast higher than hue.
var readability = tinycolor.readability(baseColor, colorList[i]);
var readable = readability.brightness > 125 && readability.color > 500;
var score = 3 * (readability.brightness / 125) + (readability.color / 500);
if ((readable && ! bestIsReadable) ||
(readable && bestIsReadable && score > bestScore) ||
((! readable) && (! bestIsReadable) && score > bestScore)) {
bestIsReadable = readable;
bestScore = score;
bestColor = tinycolor(colorList[i]);
}
}
return bestColor;
};
// Big List of Colors
// ------------------
// <http://www.w3.org/TR/css3-color/#svg-color>
var names = tinycolor.names = {
aliceblue: "f0f8ff",
antiquewhite: "faebd7",
aqua: "0ff",
aquamarine: "7fffd4",
azure: "f0ffff",
beige: "f5f5dc",
bisque: "ffe4c4",
black: "000",
blanchedalmond: "ffebcd",
blue: "00f",
blueviolet: "8a2be2",
brown: "a52a2a",
burlywood: "deb887",
burntsienna: "ea7e5d",
cadetblue: "5f9ea0",
chartreuse: "7fff00",
chocolate: "d2691e",
coral: "ff7f50",
cornflowerblue: "6495ed",
cornsilk: "fff8dc",
crimson: "dc143c",
cyan: "0ff",
darkblue: "00008b",
darkcyan: "008b8b",
darkgoldenrod: "b8860b",
darkgray: "a9a9a9",
darkgreen: "006400",
darkgrey: "a9a9a9",
darkkhaki: "bdb76b",
darkmagenta: "8b008b",
darkolivegreen: "556b2f",
darkorange: "ff8c00",
darkorchid: "9932cc",
darkred: "8b0000",
darksalmon: "e9967a",
darkseagreen: "8fbc8f",
darkslateblue: "483d8b",
darkslategray: "2f4f4f",
darkslategrey: "2f4f4f",
darkturquoise: "00ced1",
darkviolet: "9400d3",
deeppink: "ff1493",
deepskyblue: "00bfff",
dimgray: "696969",
dimgrey: "696969",
dodgerblue: "1e90ff",
firebrick: "b22222",
floralwhite: "fffaf0",
forestgreen: "228b22",
fuchsia: "f0f",
gainsboro: "dcdcdc",
ghostwhite: "f8f8ff",
gold: "ffd700",
goldenrod: "daa520",
gray: "808080",
green: "008000",
greenyellow: "adff2f",
grey: "808080",
honeydew: "f0fff0",
hotpink: "ff69b4",
indianred: "cd5c5c",
indigo: "4b0082",
ivory: "fffff0",
khaki: "f0e68c",
lavender: "e6e6fa",
lavenderblush: "fff0f5",
lawngreen: "7cfc00",
lemonchiffon: "fffacd",
lightblue: "add8e6",
lightcoral: "f08080",
lightcyan: "e0ffff",
lightgoldenrodyellow: "fafad2",
lightgray: "d3d3d3",
lightgreen: "90ee90",
lightgrey: "d3d3d3",
lightpink: "ffb6c1",
lightsalmon: "ffa07a",
lightseagreen: "20b2aa",
lightskyblue: "87cefa",
lightslategray: "789",
lightslategrey: "789",
lightsteelblue: "b0c4de",
lightyellow: "ffffe0",
lime: "0f0",
limegreen: "32cd32",
linen: "faf0e6",
magenta: "f0f",
maroon: "800000",
mediumaquamarine: "66cdaa",
mediumblue: "0000cd",
mediumorchid: "ba55d3",
mediumpurple: "9370db",
mediumseagreen: "3cb371",
mediumslateblue: "7b68ee",
mediumspringgreen: "00fa9a",
mediumturquoise: "48d1cc",
mediumvioletred: "c71585",
midnightblue: "191970",
mintcream: "f5fffa",
mistyrose: "ffe4e1",
moccasin: "ffe4b5",
navajowhite: "ffdead",
navy: "000080",
oldlace: "fdf5e6",
olive: "808000",
olivedrab: "6b8e23",
orange: "ffa500",
orangered: "ff4500",
orchid: "da70d6",
palegoldenrod: "eee8aa",
palegreen: "98fb98",
paleturquoise: "afeeee",
palevioletred: "db7093",
papayawhip: "ffefd5",
peachpuff: "ffdab9",
peru: "cd853f",
pink: "ffc0cb",
plum: "dda0dd",
powderblue: "b0e0e6",
purple: "800080",
red: "f00",
rosybrown: "bc8f8f",
royalblue: "4169e1",
saddlebrown: "8b4513",
salmon: "fa8072",
sandybrown: "f4a460",
seagreen: "2e8b57",
seashell: "fff5ee",
sienna: "a0522d",
silver: "c0c0c0",
skyblue: "87ceeb",
slateblue: "6a5acd",
slategray: "708090",
slategrey: "708090",
snow: "fffafa",
springgreen: "00ff7f",
steelblue: "4682b4",
tan: "d2b48c",
teal: "008080",
thistle: "d8bfd8",
tomato: "ff6347",
turquoise: "40e0d0",
violet: "ee82ee",
wheat: "f5deb3",
white: "fff",
whitesmoke: "f5f5f5",
yellow: "ff0",
yellowgreen: "9acd32"
};
// Make it easy to access colors via `hexNames[hex]`
var hexNames = tinycolor.hexNames = flip(names);
// Utilities
// ---------
// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
function flip(o) {
var flipped = { };
for (var i in o) {
if (o.hasOwnProperty(i)) {
flipped[o[i]] = i;
}
}
return flipped;
}
// Return a valid alpha value [0,1] with all invalid values being set to 1
function boundAlpha(a) {
a = parseFloat(a);
if (isNaN(a) || a < 0 || a > 1) {
a = 1;
}
return a;
}
// Take input from [0, n] and return it as [0, 1]
function bound01(n, max) {
if (isOnePointZero(n)) { n = "100%"; }
var processPercent = isPercentage(n);
n = mathMin(max, mathMax(0, parseFloat(n)));
// Automatically convert percentage into number
if (processPercent) {
n = parseInt(n * max, 10) / 100;
}
// Handle floating point rounding errors
if ((math.abs(n - max) < 0.000001)) {
return 1;
}
// Convert into [0, 1] range if it isn't already
return (n % max) / parseFloat(max);
}
// Force a number between 0 and 1
function clamp01(val) {
return mathMin(1, mathMax(0, val));
}
// Parse a base-16 hex value into a base-10 integer
function parseIntFromHex(val) {
return parseInt(val, 16);
}
// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
// <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
function isOnePointZero(n) {
return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
}
// Check to see if string passed in is a percentage
function isPercentage(n) {
return typeof n === "string" && n.indexOf('%') != -1;
}
// Force a hex value to have 2 characters
function pad2(c) {
return c.length == 1 ? '0' + c : '' + c;
}
// Replace a decimal with it's percentage value
function convertToPercentage(n) {
if (n <= 1) {
n = (n * 100) + "%";
}
return n;
}
// Converts a decimal to a hex value
function convertDecimalToHex(d) {
return Math.round(parseFloat(d) * 255).toString(16);
}
// Converts a hex value to a decimal
function convertHexToDecimal(h) {
return (parseIntFromHex(h) / 255);
}
var matchers = (function() {
// <http://www.w3.org/TR/css3-values/#integers>
var CSS_INTEGER = "[-\\+]?\\d+%?";
// <http://www.w3.org/TR/css3-values/#number-value>
var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
// Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.
var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
// Actual matching.
// Parentheses and commas are optional, but not required.
// Whitespace can take the place of commas or opening paren
var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
return {
rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
hex3: /^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
hex6: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
hex8: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
};
})();
// `stringInputToObject`
// Permissive string parsing. Take in a number of formats, and output an object
// based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
function stringInputToObject(color) {
color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
var named = false;
if (names[color]) {
color = names[color];
named = true;
}
else if (color == 'transparent') {
return { r: 0, g: 0, b: 0, a: 0, format: "name" };
}
// Try to match string input using regular expressions.
// Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
// Just return an object and let the conversion functions handle that.
// This way the result will be the same whether the tinycolor is initialized with string or object.
var match;
if ((match = matchers.rgb.exec(color))) {
return { r: match[1], g: match[2], b: match[3] };
}
if ((match = matchers.rgba.exec(color))) {
return { r: match[1], g: match[2], b: match[3], a: match[4] };
}
if ((match = matchers.hsl.exec(color))) {
return { h: match[1], s: match[2], l: match[3] };
}
if ((match = matchers.hsla.exec(color))) {
return { h: match[1], s: match[2], l: match[3], a: match[4] };
}
if ((match = matchers.hsv.exec(color))) {
return { h: match[1], s: match[2], v: match[3] };
}
if ((match = matchers.hex8.exec(color))) {
return {
a: convertHexToDecimal(match[1]),
r: parseIntFromHex(match[2]),
g: parseIntFromHex(match[3]),
b: parseIntFromHex(match[4]),
format: named ? "name" : "hex8"
};
}
if ((match = matchers.hex6.exec(color))) {
return {
r: parseIntFromHex(match[1]),
g: parseIntFromHex(match[2]),
b: parseIntFromHex(match[3]),
format: named ? "name" : "hex"
};
}
if ((match = matchers.hex3.exec(color))) {
return {
r: parseIntFromHex(match[1] + '' + match[1]),
g: parseIntFromHex(match[2] + '' + match[2]),
b: parseIntFromHex(match[3] + '' + match[3]),
format: named ? "name" : "hex"
};
}
return false;
}
// Expose tinycolor to window, does not need to run in non-browser context.
window.tinycolor = tinycolor;
})();
$(function () {
if ($.fn.spectrum.load) {
$.fn.spectrum.processNativeColorInputs();
}
});
})(window, jQuery); |
// h3 セクションの見出し
module.exports = {
type: {
flow : true,
heading : true,
palpable: true
},
contents: {
phrasing: true
}
};
|
export const setUser = function($email, hasWeb3, lastUpdated, userEntryRoute) {
let user = {
$email,
hasWeb3,
lastUpdated,
userEntryRoute
}
return user
}
export const trackCollectionView = function(
sourceComponent,
sourcePath,
targetCollection
) {
let name = 'Collection - View'
let data = {
targetCollection
}
if (sourceComponent) {
data = { ...data, sourceComponent }
}
if (sourcePath) {
data = { ...data, sourcePath }
}
const action = {
name,
data
}
return action
}
export const trackContact = function(
sourceComponent,
sourcePageLocation,
sourcePath
) {
let name = 'Contact'
let data = {
sourceComponent,
sourcePageLocation,
sourcePath
}
const action = {
name,
data
}
return action
}
export const trackDappContract = function(address, dapp, network, platform) {
let name = 'DApp - Contract'
let data = {
address,
dapp,
network,
platform
}
const action = {
name,
data
}
return action
}
export const trackDappContractAudit = function(
contract,
slug,
auditorName,
learnMoreUrl
) {
let name = 'DApp - Contract Audit'
let data = {
contract,
dapp: slug,
auditorName,
learnMoreUrl
}
const action = {
name,
data
}
return action
}
export const trackDappContractCopy = function(
address,
dapp,
network,
platform
) {
let name = 'DApp - Contract Copy'
let data = {
address,
dapp,
network,
platform
}
const action = {
name,
data
}
return action
}
export const trackDappEdit = function(slug) {
let name = 'DApp - Suggest a change'
let data = {
slug
}
const action = {
name,
data
}
return action
}
export const trackDappEditSubmit = function(changes, email, slug) {
let name = 'DApp - Submit a change'
let data = {
changes,
email,
slug
}
const action = {
name,
data
}
return action
}
export const trackDappFeedback = function(dapp, feedback) {
let name = 'DApp - Feedback'
let data = {
dapp,
feedback
}
const action = {
name,
data
}
return action
}
export const trackDappFlag = function(slug) {
let name = 'DApp - Flag as inappropriate'
let data = {
slug
}
const action = {
name,
data
}
return action
}
export const trackDappPlatform = function(platform, slug) {
let name = 'DApp - Platform'
let data = {
platform,
dapp: slug
}
const action = {
name,
data
}
return action
}
export const trackDappPlatformSoftware = function(platform, slug) {
let name = 'DApp - Platform Software'
let data = {
platform,
dapp: slug
}
const action = {
name,
data
}
return action
}
export const trackDappRankingCategory = function(
sourceComponent,
sourcePath,
category
) {
let name = 'DApp Ranking - Category'
let data = {
sourceComponent,
sourcePath,
category
}
const action = {
name,
data
}
return action
}
export const trackDappPager = function(from, to) {
let name = 'DApp Ranking - Pager'
let data = {
from,
to
}
const action = {
name,
data
}
return action
}
export const trackDappRankingPager = function(from, to) {
let name = 'DApp Ranking - Pager'
let data = {
from,
to
}
const action = {
name,
data
}
return action
}
export const trackDappRankingPlatform = function(
sourceComponent,
sourcePath,
platform
) {
let name = 'DApp Ranking - Platform'
let data = {
sourceComponent,
sourcePath,
platform
}
const action = {
name,
data
}
return action
}
export const trackDappRankingSort = function(order, sort) {
let name = 'DApp Ranking - Sort'
let data = {
order,
sort
}
const action = {
name,
data
}
return action
}
export const trackDappShare = function(slug) {
let name = 'DApp - Share'
let data = {
slug
}
const action = {
name,
data
}
return action
}
export const trackDappSite = function(dapp, type, url) {
let name = 'DApp - Site'
let data = {
dapp,
type,
url
}
const action = {
name,
data
}
return action
}
export const trackDappSocial = function(dapp, platform, url) {
let name = 'DApp - Social'
let data = {
dapp,
platform,
url
}
const action = {
name,
data
}
return action
}
export const trackDappCategory = function(category, slug) {
let actionName = 'DApp - Category'
let data = {
category,
slug
}
const action = {
name: actionName,
data
}
return action
}
export const trackDappEditView = function(dapp) {
let actionName = 'DApp - Edit View'
let data = {
dapp
}
const action = {
name: actionName,
data
}
return action
}
export const trackDappImproveProfileClick = function(dapp) {
let name = 'DApp - Improve Profile Click'
let data = {
dapp
}
const action = {
name,
data
}
return action
}
export const trackDappImproveProfileView = function(dapp) {
let name = 'DApp - Improve Profile View'
let data = {
dapp
}
const action = {
name,
data
}
return action
}
export const trackDappMetaClick = function(dapp) {
let actionName = 'DApp - Meta Click'
let data = {
dapp
}
const action = {
name: actionName,
data
}
return action
}
export const trackDappMetaView = function(dapp) {
let actionName = 'DApp - Meta View'
let data = {
dapp
}
const action = {
name: actionName,
data
}
return action
}
export const trackDappTag = function(name, slug) {
let actionName = 'DApp - Site'
let data = {
name,
slug
}
const action = {
name: actionName,
data
}
return action
}
export const trackDappView = function(
sourceCollection,
sourceComponent,
sourcePath,
targetDapp
) {
let name = 'DApp - View'
let data = {
targetDapp
}
if (sourceCollection) {
data = { ...data, sourceCollection }
}
if (sourceComponent) {
data = { ...data, sourceComponent }
}
if (sourcePath) {
data = { ...data, sourcePath }
}
const action = {
name,
data
}
return action
}
export const trackDappsFilter = function(type, option) {
let name = 'DApps - Filter'
let data = {
type,
option
}
const action = {
name,
data
}
return action
}
export const trackDappsSort = function(option) {
let name = 'DApps - Sort'
let data = {
option
}
const action = {
name,
data
}
return action
}
export const trackFooterLink = function(sourcePath, link) {
let name = 'Footer - Logo Download'
let data = {
sourcePath,
link
}
const action = {
name,
data
}
return action
}
export const trackFooterLogoDownload = function(sourcePath) {
let name = 'Footer - Logo Download'
let data = {
sourcePath
}
const action = {
name,
data
}
return action
}
export const trackFooterAppAndroid = function(sourcePath) {
let name = 'Footer - App Android'
let data = {
sourcePath
}
const action = {
name,
data
}
return action
}
export const trackFooterSubmit = function(sourcePath) {
let name = 'Footer - Submit'
let data = {
sourcePath
}
const action = {
name,
data
}
return action
}
export const trackFeaturedCategory = function(category) {
let name = 'Featured Category'
let data = {
category
}
const action = {
name,
data
}
return action
}
export const trackHomeEventCta = function(targetCta) {
let name = 'Home Event CTA'
let data = {
targetCta
}
const action = {
name,
data
}
return action
}
export const trackHomeHeroCta = function(targetCta) {
let name = 'Home Hero CTA'
let data = {
targetCta
}
const action = {
name,
data
}
return action
}
export const trackHomeHeroDappIcon = function(targetIndex) {
let name = 'Home Hero DApp Icon'
let data = {
targetIndex
}
const action = {
name,
data
}
return action
}
export const trackListAdd = function(dapp) {
let name = 'My List - Add'
let data = {
dapp
}
const action = {
name,
data
}
return action
}
export const trackListRemove = function(dapp) {
let name = 'My List - Remove'
let data = {
dapp
}
const action = {
name,
data
}
return action
}
export const trackLogosDownload = function() {
let name = 'Logos Download'
let data = {}
const action = {
name,
data
}
return action
}
export const trackMenu = function(sourcePath, targetMenuItem) {
let name = 'Menu'
let data = {
sourcePath,
targetMenuItem
}
const action = {
name,
data
}
return action
}
export const trackMetamaskCta = function(sourceComponent, sourcePath) {
let name = 'Metamask CTA'
let data = {
sourceComponent,
sourcePath
}
const action = {
name,
data
}
return action
}
export const trackMetamaskHelp = function() {
let name = 'Metamask Help'
let data = {}
const action = {
name,
data
}
return action
}
export const trackMyListView = function(dapps) {
let name = 'My List - View'
let data = {
dapps
}
const action = {
name,
data
}
return action
}
export const trackMyListShare = function(dapps) {
let name = 'My List - Share'
let data = {
dapps
}
const action = {
name,
data
}
return action
}
export const trackNewsletterSubscribe = function(
email,
sourceComponent,
sourcePath
) {
let name = 'Newsletter - Subscribe'
let data = {
email,
sourceComponent,
sourcePath
}
const action = {
name,
data
}
return action
}
export const trackPageAbout = function(
sourceComponent,
sourcePageLocation,
sourcePath
) {
let name = 'About page'
let data = {
sourceComponent,
sourcePageLocation,
sourcePath
}
const action = {
name,
data
}
return action
}
export const trackPromotedDappsView = function(
sourceComponent,
sourcePath,
userEntryRoute
) {
let name = 'Promoted DApps - View'
let data = {
userEntryRoute
}
if (sourceComponent) {
data = { ...data, sourceComponent }
}
if (sourcePath) {
data = { ...data, sourcePath }
}
const action = {
name,
data
}
return action
}
export const trackPageTerms = function(
sourceComponent,
sourcePageLocation,
sourcePath
) {
let name = 'Terms page'
let data = {
sourceComponent,
sourcePageLocation,
sourcePath
}
const action = {
name,
data
}
return action
}
export const trackPromotedDappSubmit = function(dapp, email, hasSubmittedDapp) {
let name = 'Promoted DApp - Submit'
let data = {
dapp,
email,
hasSubmittedDapp
}
const action = {
name,
data
}
return action
}
export const trackPublicListCreate = function(listUrl, slug) {
let name = 'Public List - Create'
let data = {
listUrl,
slug
}
const action = {
name,
data
}
return action
}
export const trackScatterCta = function(sourceComponent, sourcePath) {
let name = 'Scatter CTA'
let data = {
sourceComponent,
sourcePath
}
const action = {
name,
data
}
return action
}
export const trackSearchSuggestion = function(sourcePath, suggestion) {
let name = 'Search - Suggestion'
let data = {
sourcePath,
suggestion
}
const action = {
name,
data
}
return action
}
export const trackSocial = function(
sourceComponent,
sourcePageLocation,
sourcePath,
targetPlatform
) {
let name = 'Social'
let data = {
sourceComponent,
sourcePageLocation,
sourcePath,
targetPlatform
}
const action = {
name,
data
}
return action
}
|
'use strict';
angular.module('srs.sales', ['ngRoute','srs.customer.services'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/sales', {
templateUrl: 'modules/sales/sales.html',
controller: 'srs.salesHome'
});
}])
.controller('srs.salesHome', salesHome);
salesHome.$inject = ['$scope','$q','Customer','$timeout'];
function salesHome ($scope, $q, Customer, $timeout) {
var self = this;
// list of `state` value/display objects
self.states = loadData();
self.selectedItem = null;
self.searchText = null;
self.querySearch = querySearch;
self.simulateQuery = false;
self.isDisabled = false;
// ******************************
// Internal methods
// ******************************
/**
* Search for states... use $timeout to simulate
* remote dataservice call.
*/
function loadData(){
var customers = Customer;
var len = customers.length;
var i;
for (i=0; i < len; i++) {
customers[i].name = angular.lowercase(customers[i].firstName) + " " + angular.lowercase(customers[i].lastName) ;
customers[i].displayName = customers[i].firstName + " " + customers[i].lastName;
}
return customers;
}
function querySearch (query) {
var results = query ? self.states.filter(createFilterFor(query)) : [], deferred;
if (self.simulateQuery) {
deferred = $q.defer();
$timeout(function () {
deferred.resolve(results);
}, Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
/**
* Create filter function for a query string
*/
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(customer) {
return (customer.name.indexOf(lowercaseQuery) >= 0);
};
}
} |
/**
* Created by zhengguo.chen on 17/4/24.
* Group routers
*/
var router = require('express').Router();
var groupModel = require('../models/group');
router.route('/')
// get group list
.get((req, res) => {
res.handleResult(groupModel.getGroupList());
})
// create group
.post((req, res) => {
res.handleResult(groupModel.createGroup(req.body));
});
router.route('/:groupId')
// update group
.put((req, res) => {
res.handleResult(groupModel.updateGroup(req.params.groupId, req.body));
})
// delete group
.delete((req, res) => {
res.handleResult(groupModel.deleteGroup(req.params.groupId));
});
module.exports = router;
|
$(document).ready(function() {
// Initialize Masonry
$('#content').masonry({
columnWidth: 205,
itemSelector: '.item',
isFitWidth: true,
isAnimated: !Modernizr.csstransitions
}).imagesLoaded(function() {
$(this).masonry('reload');
});
}); |
import Ember from 'ember';
export default Ember.Mixin.create({
queryParams: {
q: {
replace: true
}
},
model: function() {
return [];
},
setupController: function(controller, model) {
this._super.apply(this, arguments);
controller.filter();
}
});
|
/*
* ajaxify.js
* Ajaxify - The Ajax Plugin
* https://4nf.org/
*
* Copyright Arvind Gupta; MIT Licensed
*/
/* INTERFACE: See also https://4nf.org/interface/
Simplest plugin call:
let ajaxify = new Ajaxify({options});
Ajaxifies the whole site, dynamically replacing the elements specified in "elements" across pages
*/
// The main plugin - Ajaxify
// Is passed the global options
// Checks for necessary pre-conditions - otherwise gracefully degrades
// Initialises sub-plugins
// Calls Pronto
class Ajaxify { constructor(options) {
String.prototype.iO = function(s) { return this.toString().indexOf(s) + 1; }; //Intuitively better understandable shorthand for String.indexOf() - String.iO()
let $ = this;
//Options default values
$.s = {
// basic config parameters
elements: "body", //selector for element IDs that are going to be swapped (e.g. "#el1, #el2, #el3")
selector : "a:not(.no-ajaxy)", //selector for links to trigger swapping - not elements to be swapped - i.e. a selection of links
forms : "form:not(.no-ajaxy)", // selector for ajaxifying forms - set to "false" to disable
canonical : false, // Fetch current URL from "canonical" link if given, updating the History API. In case of a re-direct...
refresh : false, // Refresh the page even if link clicked is current page
// visual effects settings
requestDelay : 0, //in msec - Delay of Pronto request
scrolltop : "s", // Smart scroll, true = always scroll to top of page, false = no scroll
bodyClasses : false, // Copy body classes from target page, set to "true" to enable
// script and style handling settings, prefetch
deltas : true, // true = deltas loaded, false = all scripts loaded
asyncdef : true, // default async value for dynamically inserted external scripts, false = synchronous / true = asynchronous
alwayshints : false, // strings, - separated by ", " - if matched in any external script URL - these are always loaded on every page load
inline : true, // true = all inline scripts loaded, false = only specific inline scripts are loaded
inlinesync : true, // synchronise inline scripts loading by adding a central tiny delay to all of them
inlinehints : false, // strings - separated by ", " - if matched in any inline scripts - only these are executed - set "inline" to false beforehand
inlineskip : "adsbygoogle", // strings - separated by ", " - if matched in any inline scripts - these are NOT are executed - set "inline" to true beforehand
inlineappend : true, // append scripts to the main content element, instead of "eval"-ing them
intevents: true, // intercept events that are fired only on classic page load and simulate their trigger on ajax page load ("DOMContentLoaded", "load")
style : true, // true = all style tags in the head loaded, false = style tags on target page ignored
prefetchoff : false, // Plugin pre-fetches pages on hoverIntent - true = set off completely // strings - separated by ", " - hints to select out
// debugging & advanced settings
verbosity : 0, //Debugging level to console: default off. Can be set to 10 and higher (in case of logging enabled)
memoryoff : false, // strings - separated by ", " - if matched in any URLs - only these are NOT executed - set to "true" to disable memory completely
cb : 0, // callback handler on completion of each Ajax request - default 0
pluginon : true, // Plugin set "on" or "off" (==false) manually
passCount: false // Show number of pass for debugging
};
$.pass = 0; $.currentURL = ""; $.h = {};
$.parse = (s, pl) => (pl = document.createElement('div'), pl.insertAdjacentHTML('afterbegin', s), pl.firstElementChild); // HTML parser
$.trigger = (t, e) => { let ev = document.createEvent('HTMLEvents'); ev.initEvent("pronto." + t, true, false); ev.data = e ? e : $.Rq("e"); window.dispatchEvent(ev); document.dispatchEvent(ev); }
$.internal = (url) => { if (!url) return false; if (typeof(url) === "object") url = url.href; if (url==="") return true; return url.substring(0,rootUrl.length) === rootUrl || !url.iO(":"); }
$.intevents = () => {
let iFn = function (a, b, c = false) { if ((this === document || this === window) && a=="DOMContentLoaded") setTimeout(b); else this.ael(a,b,c);} // if "DOMContentLoaded" - execute function, else - add event listener
EventTarget.prototype.ael = EventTarget.prototype.addEventListener; // store original method
EventTarget.prototype.addEventListener = iFn; // start intercepting event listener addition
}
//Module global variables
let rootUrl = location.origin, api = window.history && window.history.pushState && window.history.replaceState,
//Regexes for escaping fetched HTML of a whole page - best of Baluptons Ajaxify
//Makes it possible to pre-fetch an entire page
docType = /<\!DOCTYPE[^>]*>/i,
tagso = /<(html|head|link)([\s\>])/gi,
tagsod = /<(body)([\s\>])/gi,
tagsc = /<\/(html|head|body|link)\>/gi,
//Helper strings
div12 = '<div class="ajy-$1"$2',
divid12 = '<div id="ajy-$1"$2',
linki = '<link rel="stylesheet" type="text/css" href="*" />',
linkr = 'link[href*="!"]',
scrr = 'script[src*="!"]',
inlineclass = "ajy-inline";
//Global helpers
let doc=document, bdy,
qa=(s,o=doc)=>o.querySelectorAll(s),
qs=(s,o=doc)=>o.querySelector(s);
function _copyAttributes(el, $S, flush) { //copy all attributes of element generically
if (flush) [...el.attributes].forEach(e => el.removeAttribute(e.name)); //delete all old attributes
[...$S.attributes].forEach(e => el.setAttribute(e.nodeName, e.nodeValue)); //low-level insertion
}
function _on(eventName, elementSelector, handler, el = document) { //e.currentTarget is document when the handler is called
el.addEventListener(eventName, function(e) {
// loop parent nodes from the target to the delegation node
for (var target = e.target; target && target != this; target = target.parentNode) {
if (target.matches(elementSelector)) {
handler(target, e);
break;
}
}
}, !!eventName.iO('mo'));
}
class Hints { constructor(h) { let _ = this;
_.list = (typeof h === 'string' && h.length > 0) ? h.split(", ") : false; //hints are passed as a comma separated string
_.find = (t) => (!t || !_.list) ? false : _.list.some(h => t.iO(h)); //iterate through hints within passed text (t)
}}
function lg(m){ $.s.verbosity && console && console.log(m); }
// The stateful Cache class
// Usage - parameter "o" values:
// none - returns currently cached page
// <URL> - returns page with specified URL
// <object> - saves the page in cache
// f - flushes the cache
class Cache { constructor() {
let d = false;
this.a = function (o) {
if (!o) return d;
if (typeof o === "string") { //URL or "f" passed
if(o === "f") { //"f" passed -> flush
$.pages("f"); //delegate flush to $.pages
lg("Cache flushed");
} else d = $.pages($.memory(o)); //URL passed -> look up page in memory
return d; //return cached page
}
if (typeof o === "object") {
d = o;
return d;
}
};
}}
// The stateful Memory class
// Usage: $.memory(<URL>) - returns the same URL if not turned off internally
class Memory { constructor(options) {
$.h.memoryoff = new Hints($.s.memoryoff);
this.a = function (h) {
if (!h || $.s.memoryoff === true) return false;
if ($.s.memoryoff === false) return h;
return $.h.memoryoff.find(h) ? false : h;
};
}}
// The stateful Pages class
// Usage - parameter "h" values:
// <URL> - returns page with specified URL from internal array
// <object> - saves the passed page in internal array
// false - returns false
class Pages { constructor() {
let d = [], i = -1;
this.a = function (h) {
if (typeof h === "string") {
if(h === "f") d = [];
else if((i=_iPage(h)) !== -1) return d[i][1];
}
if (typeof h === "object") {
if((i=_iPage(h[0])) === -1) d.push(h);
else d[i] = h;
}
if (typeof h === "boolean") return false;
};
let _iPage = h => d.findIndex(e => e[0] == h)
}}
// The GetPage class
// First parameter (o) is a switch:
// empty - returns cache
// <URL> - loads HTML via Ajax, second parameter "p" must be callback
// + - pre-fetches page, second parameter "p" must be URL, third parameter "p2" must be callback
// - - loads page into DOM and handle scripts, second parameter "p" must hold selection to load
// x - returns response
// otherwise - returns selection of current page to client
class GetPage { constructor() {
let rsp = 0, cb = 0, plus = 0, rt = "", ct = 0, rc = 0, ac = 0;
this.a = function (o, p, p2) {
if (!o) return $.cache();
if (o.iO("/")) {
cb = p;
if(plus == o) return;
return _lPage(o);
}
if (o === "+") {
plus = p;
cb = p2;
return _lPage(p, true);
}
if (o === "a") { if (rc > 0) {_cl(); ac.abort();} return; }
if (o === "s") return ((rc) ? 1 : 0) + rt;
if (o === "-") return _lSel(p);
if (o === "x") return rsp;
if (!$.cache()) return;
if (o === "body") return qs("#ajy-" + o, $.cache());
if (o === "script") return qa(o, $.cache());
return qs((o === "title") ? o : ".ajy-" + o, $.cache());
};
let _lSel = $t => (
$.pass++,
_lEls($t),
qa("body > script").forEach(e => (e.classList.contains(inlineclass)) ? e.parentNode.removeChild(e) : false),
$.scripts(true),
$.scripts("s"),
$.scripts("c")
),
_lPage = (h, pre) => {
if (h.iO("#")) h = h.split("#")[0];
if ($.Rq("is") || !$.cache(h)) return _lAjax(h, pre);
plus = 0;
if (cb) return cb();
},
_ld = ($t, $h) => {
if(!$h) {
lg("Inserting placeholder for ID: " + $t.getAttribute("id"));
var tagN = $t.tagName.toLowerCase();
$t.parentNode.replaceChild($.parse("<" + tagN + " id='" + $t.getAttribute("id") + "'></" + tagN + ">"), $t);
return;
}
var $c = $h.cloneNode(true); // clone element node (true = deep clone)
qa("script", $c).forEach(e => e.parentNode.removeChild(e));
_copyAttributes($t, $c, true);
$t.innerHTML = $c.innerHTML;
},
_lEls = $t =>
$.cache() && !_isBody($t) && $t.forEach(function($el) {
_ld($el, qs("#" + $el.getAttribute("id"), $.cache()));
}),
_isBody = $t => $t[0].tagName.toLowerCase() == "body" && (_ld(bdy, qs("#ajy-body", $.cache())), 1),
_lAjax = (hin, pre) => {
var ispost = $.Rq("is");
if (pre) rt="p"; else rt="c";
ac = new AbortController(); // set abort controller
rc++; // set active request counter
fetch(hin, {
method: ((ispost) ? "POST" : "GET"),
cache: "default",
mode: "same-origin",
headers: {"X-Requested-With": "XMLHttpRequest"},
body: (ispost) ? $.Rq("d") : null,
signal: ac.signal
}).then(r => {
if (!r.ok || !_isHtml(r)) {
if (!pre) {location.href = hin; _cl(); $.pronto(0, $.currentURL);}
return;
}
rsp = r; // store response
return r.text();
}).then(r => {
_cl(1); // clear only plus variable
if (!r) return; // ensure data
rsp.responseText = r; // store response text
return _cache(hin, r);
}).catch(err => {
if(err.name === "AbortError") return;
try {
$.trigger("error", err);
lg("Response text : " + err.message);
return _cache(hin, err.message, err);
} catch (e) {}
}).finally(() => rc--); // reset active request counter
},
_cl = c => (plus = 0, (!c) ? cb = 0 : 0), // clear plus AND/OR callback
_cache = (href, h, err) => $.cache($.parse(_parseHTML(h))) && ($.pages([href, $.cache()]), 1) && cb && cb(err),
_isHtml = x => (ct = x.headers.get("content-type")) && (ct.iO("html") || ct.iO("form-")),
_parseHTML = h => document.createElement("html").innerHTML = _replD(h).trim(),
_replD = h => String(h).replace(docType, "").replace(tagso, div12).replace(tagsod, divid12).replace(tagsc, "</div>")
}}
// The stateful Scripts plugin
// First parameter "o" is switch:
// i - initailise options
// c - fetch canonical URL
// <object> - handle one inline script
// otherwise - delta loading
class Scripts { constructor() {
let $s = false, txt = 0;
$.h.inlinehints = new Hints($.s.inlinehints);
$.h.inlineskip = new Hints($.s.inlineskip);
this.a = function (o) {
if (o === "i") {
if(!$s) $s = {};
return true;
}
if (o === "s") return _allstyle($s.y);
if (o === "1") {
$.detScripts($s);
return _addScripts($s);
}
if (o === "c") return $.s.canonical && $s.can ? $s.can.getAttribute("href") : false;
if (o === "d") return $.detScripts($s);
if (o && typeof o == "object") return _onetxt(o);
if ($.scripts("d")) return;
_addScripts($s);
};
let _allstyle = $s =>
!$.s.style || !$s || (
qa("style", qs("head")).forEach(e => e.parentNode.removeChild(e)),
$s.forEach(el => _addstyle(el.textContent))
),
_onetxt = $s =>
(!(txt = $s.textContent).iO(").ajaxify(") && (!txt.iO("new Ajaxify(")) &&
(($.s.inline && !$.h.inlineskip.find(txt)) || $s.classList.contains("ajaxy") ||
$.h.inlinehints.find(txt))
) && _addtxt($s),
_addtxt = $s => {
if(!txt || !txt.length) return;
if($.s.inlineappend || ($s.getAttribute("type") && !$s.getAttribute("type").iO("text/javascript"))) try { return _apptxt($s); } catch (e) { }
try { eval(txt); } catch (e1) {
lg("Error in inline script : " + txt + "\nError code : " + e1);
}
},
_apptxt = $s => { let sc = document.createElement("script"); _copyAttributes(sc, $s); sc.classList.add(inlineclass);
try {sc.appendChild(document.createTextNode($s.textContent))} catch(e) {sc.text = $s.textContent};
return qs("body").appendChild(sc);
},
_addstyle = t => qs("head").appendChild($.parse('<style>' + t + '</style>')),
_addScripts = $s => ( $.addAll($s.c, "href"), $.s.inlinesync ? setTimeout(() => $.addAll($s.j, "src")) : $.addAll($s.j, "src"))
}}
// The DetScripts plugin - stands for "detach scripts"
// Works on "$s" <object> that is passed in and fills it
// Fetches all stylesheets in the head
// Fetches the canonical URL
// Fetches all external scripts on the page
// Fetches all inline scripts on the page
class DetScripts { constructor() {
let head = 0, lk = 0, j = 0;
this.a = function ($s) {
head = $.pass ? $.fn("head") : qs("head"); //If "pass" is 0 -> fetch head from DOM, otherwise from target page
if (!head) return true;
lk = qa($.pass ? ".ajy-link" : "link", head); //If "pass" is 0 -> fetch links from DOM, otherwise from target page
j = $.pass ? $.fn("script") : qa("script"); //If "pass" is 0 -> fetch JSs from DOM, otherwise from target page
$s.c = _rel(lk, "stylesheet"); //Extract stylesheets
$s.y = qa("style", head); //Extract style tags
$s.can = _rel(lk, "canonical"); //Extract canonical tag
$s.j = j; //Assign JSs to internal selection
};
let _rel = (lk, v) => Array.prototype.filter.call(lk, e => e.getAttribute("rel").iO(v));
}}
// The AddAll plugin
// Works on a new selection of scripts to apply delta-loading to it
// pk parameter:
// href - operate on stylesheets in the new selection
// src - operate on JS scripts
class AddAll { constructor() {
let $scriptsO = [], $sCssO = [], $sO = [], PK = 0, url = 0;
$.h.alwayshints = new Hints($.s.alwayshints);
this.a = function ($this, pk) {
if(!$this.length) return; //ensure input
if($.s.deltas === "n") return true; //Delta-loading completely disabled
PK = pk; //Copy "primary key" into internal variable
if(!$.s.deltas) return _allScripts($this); //process all scripts
//deltas presumed to be "true" -> proceed with normal delta-loading
$scriptsO = PK == "href" ? $sCssO : $sO; //Copy old. Stylesheets or JS
if(!$.pass) _newArray($this); //Fill new array on initial load, nothing more
else $this.forEach(function(s) { //Iterate through selection
var $t = s;
url = $t.getAttribute(PK);
if(_classAlways($t)) { //Class always handling
_removeScript(); //remove from DOM
_iScript($t); //insert back single external script in the head
return;
}
if(url) { //URL?
if(!$scriptsO.some(e => e == url)) { // Test, whether new
$scriptsO.push(url); //If yes: Push to old array
_iScript($t);
}
//Otherwise nothing to do
return;
}
if(PK != "href" && !$t.classList.contains("no-ajaxy")) $.scripts($t); //Inline JS script? -> inject into DOM
});
};
let _allScripts = $t => $t.forEach(e => _iScript(e)),
_newArray = $t => $t.forEach(e => (url = e.getAttribute(PK)) ? $scriptsO.push(url) : 0),
_classAlways = $t => $t.getAttribute("data-class") == "always" || $.h.alwayshints.find(url),
_iScript = $S => {
url = $S.getAttribute(PK);
if(PK == "href") return qs("head").appendChild($.parse(linki.replace("*", url)));
if(!url) return $.scripts($S);
var sc = document.createElement("script");
sc.async = $.s.asyncdef;
_copyAttributes(sc, $S);
qs("head").appendChild(sc);
},
_removeScript = () => qa((PK == "href" ? linkr : scrr).replace("!", url)).forEach(e => e.parentNode.removeChild(e))
}}
// The Rq plugin - stands for request
// Stores all kinds of and manages data concerning the pending request
// Simplifies the Pronto plugin by managing request data separately, instead of passing it around...
// Second parameter (p) : data
// First parameter (o) values:
// = - check whether internally stored "href" ("h") variable is the same as the global currentURL
// ! - update last request ("l") variable with passed href
// ? - Edin's intelligent plausibility check - can spawn an external fetch abort
// v - validate value passed in "p", which is expected to be a click event value - also performs "i" afterwards
// i - initialise request defaults and return "c" (currentTarget)
// h - access internal href hard
// e - set / get internal "e" (event)
// p - set / get internal "p" (push flag)
// is - set / get internal "ispost" (flag whether request is a POST)
// d - set / get internal "d" (data for central $.ajax())
// C - set / get internal "can" ("href" of canonical URL)
// c - check whether simple canonical URL is given and return, otherwise return value passed in "p"
class RQ { constructor() {
let ispost = 0, data = 0, push = 0, can = 0, e = 0, c = 0, h = 0, l = false;
this.a = function (o, p, t) {
if(o === "=") {
if(p) return h === $.currentURL //check whether internally stored "href" ("h") variable is the same as the global currentURL
|| h === l; //or href of last request ("l")
return h === $.currentURL; //for click requests
}
if(o === "!") return l = h; //store href in "l" (last request)
if(o === "?") { //Edin previously called this "isOK" - powerful intelligent plausibility check
let xs=$.fn("s");
if (!xs.iO("0") && !p) $.fn("a"); //if fetch is not idle and new request is standard one, do ac.abort() to set it free
if (xs==="1c" && p) return false; //if fetch is processing standard request and new request is prefetch, cancel prefetch until fetch is finished
if (xs==="1p" && p) $.s.memoryoff ? $.fn("a") : 1; //if fetch is processing prefetch request and new request is prefetch do nothing (see [options] comment below)
//([semaphore options for requests] $.fn("a") -> abort previous, proceed with new | return false -> leave previous, stop new | return true -> proceed)
return true;
}
if(o === "v") { //validate value passed in "p", which is expected to be a click event value - also performs "i" afterwards
if(!p) return false; //ensure data
_setE(p, t); //Set event and href in one go
if(!$.internal(h)) return false; //if not internal -> report failure
o = "i"; //continue with "i"
}
if(o === "i") { //initialise request defaults and return "c" (currentTarget)
ispost = false; //GET assumed
data = null; //reset data
push = true; //assume we want to push URL to the History API
can = false; //reset can (canonical URL)
return h; //return "h" (href)
}
if(o === "h") { // Access href hard
if(p) {
if (typeof p === "string") e = 0; // Reset e -> default handler
h = (p.href) ? p.href : p; // Poke in href hard
}
return h; //href
}
if(o === "e") { //set / get internal "e" (event)
if(p) _setE(p, t); //Set event and href in one go
return e ? e : h; // Return "e" or if not given "h"
}
if(o === "p") { //set / get internal "p" (push flag)
if(p !== undefined) push = p;
return push;
}
if(o === "is") { //set / get internal "ispost" (flag whether request is a POST)
if(p !== undefined) ispost = p;
return ispost;
}
if(o === "d") { //set / get internal "d" (data for central $.ajax())
if(p) data = p;
return data;
}
if(o === "C") { //set internal "can" ("href" of canonical URL)
if(p !== undefined) can = p;
return can;
}
if(o === "c") return can && can !== p && !p.iO("#") && !p.iO("?") ? can : p; //get internal "can" ("href" of canonical URL)
};
let _setE = (p, t) => h = typeof (e = p) !== "string" ? (e.currentTarget && e.currentTarget.href) || (t && t.href) || e.currentTarget.action || e.originalEvent.state.url : e
}}
// The Frms plugin - stands for forms
// Ajaxify all forms in the specified divs
// Switch (o) values:
// d - set divs variable
// a - Ajaxify all forms in divs
class Frms { constructor() {
let fm = 0, divs = 0;
this.a = function (o, p) {
if (!$.s.forms || !o) return; //ensure data
if(o === "d") divs = p; //set divs variable
if(o === "a") divs.forEach(div => { //iterate through divs
Array.prototype.filter.call(qa($.s.forms, div), function(e) { //filter forms
let c = e.getAttribute("action");
return($.internal(c && c.length > 0 ? c : $.currentURL)); //ensure "action"
}).forEach(frm => { //iterate through forms
frm.addEventListener("submit", q => { //create event listener
fm = q.target; // fetch target
p = _k(); //Serialise data
var g = "get", //assume GET
m = fm.getAttribute("method"); //fetch method attribute
if (m.length > 0 && m.toLowerCase() == "post") g = "post"; //Override with "post"
var h, a = fm.getAttribute("action"); //fetch action attribute
if (a && a.length > 0) h = a; //found -> store
else h = $.currentURL; //not found -> select current URL
$.Rq("v", q); //validate request
if (g == "get") h = _b(h, p); //GET -> copy URL parameters
else {
$.Rq("is", true); //set is POST in request data
$.Rq("d", p); //save data in request data
}
$.trigger("submit", h); //raise pronto.submit event
$.pronto(0, { href: h }); //programmatically change page
q.preventDefault(); //prevent default form action
return(false); //success -> disable default behaviour
})
});
});
};
let _k = () => {
let o = new FormData(fm), n = qs("input[name][type=submit]", fm);
if (n) o.append(n.getAttribute("name"), n.value);
return o;
},
_b = (m, n) => {
let s = "";
if (m.iO("?")) m = m.substring(0, m.iO("?"));
for (var [k, v] of n.entries()) s += `${k}=${encodeURIComponent(v)}&`;
return `${m}?${s.slice(0,-1)}`;
}
}}
// The stateful Offsets plugin
// Usage:
// 1) $.offsets(<URL>) - returns offset of specified URL from internal array
// 2) $.offsets() - saves the current URL + offset in internal array
class Offsets { constructor() {
let d = [], i = -1;
this.a = function (h) {
if (typeof h === "string") { //Lookup page offset
h = h.iO("?") ? h.split("?")[0] : h; //Handle root URL only from dynamic pages
i = _iOffset(h); //Fetch offset
if(i === -1) return 0; // scrollTop if not found
return d[i][1]; //Return offset that was found
}
//Add page offset
var u = $.currentURL, us1 = u.iO("?") ? u.split("?")[0] : u, us = us1.iO("#") ? us1.split("#")[0] : us1, os = [us, (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop];
i = _iOffset(us); //get page index
if(i === -1) d.push(os); //doesn't exist -> push to array
else d[i] = os; //exists -> overwrite
};
let _iOffset = h => d.findIndex(e => e[0] == h)
}}
// The Scrolly plugin - manages scroll effects centrally
// scrolltop values: "s" - "smart" (default), true - always scroll to top, false - no scroll
// Switch (o) values:
// + - add current page to offsets
// ! - scroll to current page offset
class Scrolly { constructor() {
if ('scrollRestoration' in history) history.scrollRestoration = 'manual';
this.a = function (o) {
if(!o) return; //ensure operator
var op = o; //cache operator
if(o === "+" || o === "!") o = $.currentURL; //fetch currentURL for "+" and "-" operators
if(op !== "+" && o.iO("#") && (o.iO("#") < o.length - 1)) { //if hash in URL and not standalone hash
let $el = qs("#" + o.split("#")[1]); //fetch the element
if (!$el) return; //nothing found -> return quickly
let box = $el.getBoundingClientRect();
_scrll(box.top + window.pageYOffset - document.documentElement.clientTop); // ...animate to ID
return;
}
if($.s.scrolltop === "s") { //smart scroll enabled
if(op === "+") $.offsets(); //add page offset
if(op === "!") _scrll($.offsets(o)); //scroll to stored position of page
return;
}
if(op !== "+" && $.s.scrolltop) _scrll(0); //otherwise scroll to top of page
//default -> do nothing
};
let _scrll = o => setTimeout(() => window.scrollTo(0, o), 10) //delay of 10 milliseconds on all scroll effects
}}
// The hApi plugin - manages operations on the History API centrally
// Second parameter (p) - set global currentURL
// Switch (o) values:
// = - perform a replaceState, using currentURL
// otherwise - perform a pushState, using currentURL
class HApi { constructor() {
this.a = function (o, p) {
if(!o) return; //ensure operator
if(p) $.currentURL = p; //if p given -> update current URL
if(o === "=") history.replaceState({ url: $.currentURL }, "state-" + $.currentURL, $.currentURL); //perform replaceState
else if ($.currentURL !== window.location.href) history.pushState({ url: $.currentURL }, "state-" + $.currentURL, $.currentURL); //perform pushState
};
}}
// The Pronto plugin - Pronto variant of Ben Plum's Pronto plugin - low level event handling in general
// Works on a selection, passed to Pronto by the selection, which specifies, which elements to Ajaxify
// Switch (h) values:
// i - initialise Pronto
// <object> - fetch href part and continue with _request()
// <URL> - set "h" variable of Rq hard and continue with _request()
class Pronto { constructor() {
let $gthis = 0, requestTimer = 0, pd = 150, ptim = 0;
$.h.prefetchoff = new Hints($.s.prefetchoff);
this.a = function ($this, h) {
if(!h) return; //ensure data
if(h === "i") { //request to initialise
bdy = document.body;
if(!$this.length) $this = "body";
$gthis = qa($this); //copy selection to global selector
$.frms = new Frms().a; //initialise forms sub-plugin
if($.s.idleTime) $.slides = new classSlides($).a; //initialise optional slideshow sub-plugin
$.scrolly = new Scrolly().a; //initialise scroll effects sub-plugin
$.offsets = new Offsets().a;
$.hApi = new HApi().a;
_init_p(); //initialise Pronto sub-plugin
return $this; //return query selector for chaining
}
if(typeof(h) === "object") { //jump to internal page programmatically -> handler for forms sub-plugin
$.Rq("h", h);
_request();
return;
}
if(h.iO("/")) { //jump to internal page programmatically -> default handler
$.Rq("h", h);
_request(true);
}
};
let _init_p = () => {
$.hApi("=", window.location.href);
window.addEventListener("popstate", _onPop);
if ($.s.prefetchoff !== true) {
_on("mouseenter", $.s.selector, _preftime); // start prefetch timeout
_on("mouseleave", $.s.selector, _prefstop); // stop prefetch timeout
_on("touchstart", $.s.selector, _prefetch);
}
_on("click", $.s.selector, _click, bdy);
$.frms("d", qa("body"));
$.frms("a");
$.frms("d", $gthis);
if($.s.idleTime) $.slides("i");
},
_preftime = (t, e) => (_prefstop(), ptim = setTimeout(()=> _prefetch(t, e), pd)), // call prefetch if timeout expires without being cleared by _prefstop
_prefstop = () => clearTimeout(ptim),
_prefetch = (t, e) => {
if($.s.prefetchoff === true) return;
if (!$.Rq("?", true)) return;
var href = $.Rq("v", e, t);
if ($.Rq("=", true) || !href || $.h.prefetchoff.find(href)) return;
$.fn("+", href, () => false);
},
_stopBubbling = e => (
e.preventDefault(),
e.stopPropagation(),
e.stopImmediatePropagation()
),
_click = (t, e, notPush) => {
if(!$.Rq("?")) return;
var href = $.Rq("v", e, t);
if(!href || _exoticKey(t)) return;
if(href.substr(-1) ==="#") return true;
if(_hashChange()) {
$.hApi("=", href);
return true;
}
$.scrolly("+");
_stopBubbling(e);
if($.Rq("=")) $.hApi("=");
if($.s.refresh || !$.Rq("=")) _request(notPush);
},
_request = notPush => {
$.Rq("!");
if(notPush) $.Rq("p", false);
$.trigger("request");
$.fn($.Rq("h"), err => {
if (err) {
lg("Error in _request : " + err);
$.trigger("error", err);
}
_render();
});
},
_render = () => {
$.trigger("beforeload");
if($.s.requestDelay) {
if(requestTimer) clearTimeout(requestTimer);
requestTimer = setTimeout(_doRender, $.s.requestDelay);
} else _doRender();
},
_onPop = e => {
var url = window.location.href;
$.Rq("i");
$.Rq("h", url);
$.Rq("p", false);
$.scrolly("+");
if (!url || url === $.currentURL) return;
$.trigger("request");
$.fn(url, _render);
},
_doRender = () => {
$.trigger("load");
if($.s.bodyClasses) { var classes = $.fn("body").getAttribute("class"); bdy.setAttribute("class", classes ? classes : ""); }
var href = $.Rq("h"), title;
href = $.Rq("c", href);
$.hApi($.Rq("p") ? "+" : "=", href);
if(title = $.fn("title")) qs("title").innerHTML = title.innerHTML;
$.Rq("C", $.fn("-", $gthis));
$.frms("a");
$.scrolly("!");
_gaCaptureView(href);
$.trigger("render");
if($.s.passCount) qs("#" + $.s.passCount).innerHTML = "Pass: " + $.pass;
if($.s.cb) $.s.cb();
},
_gaCaptureView = href => {
href = "/" + href.replace(rootUrl,"");
if (typeof window.ga !== "undefined") window.ga("send", "pageview", href);
else if (typeof window._gaq !== "undefined") window._gaq.push(["_trackPageview", href]);
},
_exoticKey = (t) => {
var href = $.Rq("h"), e = $.Rq("e"), tgt = e.currentTarget.target || t.target;
return (e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || tgt === "_blank"
|| href.iO("wp-login") || href.iO("wp-admin"));
},
_hashChange = () => {
var e = $.Rq("e");
return (e.hash && e.href.replace(e.hash, "") === window.location.href.replace(location.hash, "") || e.href === window.location.href + "#");
}
}}
$.init = () => {
let o = options;
if (!o || typeof(o) !== "string") {
if (document.readyState === "complete" ||
(document.readyState !== "loading" && !document.documentElement.doScroll)) run();
else document.addEventListener('DOMContentLoaded', run);
return $;
}
else return $.pronto(0, o);
};
let run = () => {
$.s = Object.assign($.s, options);
$.pages = new Pages().a;
$.pronto = new Pronto().a;
if (load()) {
$.pronto($.s.elements, "i");
if ($.s.deltas) $.scripts("1");
}
},
load = () => {
if (!api || !$.s.pluginon) {
lg("Gracefully exiting...");
return false;
}
lg("Ajaxify loaded..."); //verbosity option steers, whether this initialisation message is output
if ($.s.intevents) $.intevents(); // intercept events
$.scripts = new Scripts().a;
$.scripts("i");
$.cache = new Cache().a;
$.memory = new Memory().a;
$.fn = $.getPage = new GetPage().a;
$.detScripts = new DetScripts().a;
$.addAll = new AddAll().a;
$.Rq = new RQ().a;
return true;
}
$.init(); // initialize Ajaxify on definition
}} |
var request = require('request');
module.exports = function (city) {
return new Promise(function (resolve,reject){
var url = 'http://api.openweathermap.org/data/2.5/weather?q='+ city
+'&APPID=5380693afcd9a8800c6c17856c7e92f5&units=metric';
request({
url: url,
json: true
}, function (error,response,body) {
if (error) {
console.log("unable to fetch data");
reject(error);
} else {
resolve({name: body.name, temp: body.main.temp})
}
});
})
}; |
/*
* Bristol
* Copyright 2014 Tom Frost
*/
const DEFAULT_SEVERITY_LEVELS = ['error', 'warn', 'info', 'debug', 'trace'];
const DEFAULT_FORMATTER = require('./formatters/json');
var logUtil = require('./Util'),
events = require('events'),
util = require('util');
/**
* The Bristol class defines a logger capable of simultaneous logging to
* different destinations called "targets", using a specified format for each,
* and parsing application-specific object types into meaningful attributes to
* be logged.
*
* New instances of Bristol can be created with the traditional "new Bristol()"
* style, however the object returned by require()ing this library is also
* an instance of Bristol, for the convenience of being able to require it,
* configure it, and have an immediately ready-to-use logger when requiring it
* in any other file.
* @constructor
*/
function Bristol() {
this._severities = {};
this._targets = [];
this._transforms = [];
this._globals = {};
this.setSeverities(DEFAULT_SEVERITY_LEVELS);
}
util.inherits(Bristol, events.EventEmitter);
/**
* Adds a logging target to Bristol. The options supplied apply only to the
* target module itself. A formatter can be set, and restrictions can be
* placed on the messages that this target receives by chaining this call with
* a series of calls on the returned configuration object.
*
* If no configuration options are set, the default formatter is 'json' and
* the target will receive all log messages.
* @param {string|function} target The name of a built-in target, or a
* function with the signature (options.<Object>, severity.<string>,
* date.<Date>, message.<String>). Note that the target is not responsible
* for doing anything with the severity and date, as those should be
* handled by the formatter. They are provided in the event that the
* target may change its behavior based on these values.
* @param {{}} [options] An optional set of arguments specific to the target
* being added
* @returns {{
* withFormatter,
* excluding,
* onlyIncluding,
* withLowestSeverity,
* withHighestSeverity
* }} A config chain object
*/
Bristol.prototype.addTarget = function(target, options) {
if (typeof target === 'string')
target = require('./targets/' + target);
var targetObj = {
log: target.bind(target, options || {}),
formatter: DEFAULT_FORMATTER.bind(this, [{}]),
blacklist: {},
whitelist: {},
leastVerbose: 0,
mostVerbose: Infinity
};
this._targets.push(targetObj);
return this._getTargetConfigChain(targetObj);
};
/**
* Adds a transform function to the Bristol instance. The transform functions
* are called for every individual element to be logged, so Bristol can be made
* aware of any application-specific data types and log out only appropriate
* pieces of information when they're passed as an element. This mechanism can
* also be used to customize/silence the automatically provided metadata, such
* as the origin file/line. Transform functions take an element to be logged
* as their only argument, and return the transformed version of that element.
*
* If a given element should not be transformed, simply return null. Returning
* anything other than null will halt any more transforms being run on top
* of that element. Transforms are executed in the order in which they are
* added.
* @param {function} transform A transform function, accepting an element
* that was passed to the logger and returning what should be logged.
*/
Bristol.prototype.addTransform = function(transform) {
this._transforms.push(transform);
};
/**
* Removes a previously-set global key/value pair. Log messages pushed after
* this is called will no longer include the removed pair.
* @param {string} key The key of the global value to be deleted
*/
Bristol.prototype.deleteGlobal = function(key) {
if (this._globals.hasOwnProperty(key))
delete this._globals[key];
};
/**
* Pushes the provided elements to each added target, under the given severity.
* Only targets that have not been restricted against this severity or type
* of element will be triggered. The given elements can be of any type, as
* long as there is a transform to handle it or the target's formatter can
* sufficiently serialize it.
*
* This function emits two events:
* - log : fired for every call to the logger, immediately after the log
* elements are pushed to the targets. The supplied argument will have
* the following properties:
* - {string} severity: The severity under which the elements were
* logged
* - {Date} date: A javascript Date object with the date under which
* the messages were logged
* - {Array} elements: An array of elements that were logged. These
* elements could be of any type
* - log:SEVERITY : fired for every call to the logger, with 'SEVERITY'
* replaced by the actual severity used for the log message. Argument
* is the same as for the 'log' event.
*
* @param {string} severity A string defining the severity of the log message.
* This string should be one of the set passed to {@link #setSeverities},
* or one from the default set of ['error', 'warn', 'info', 'debug',
* 'trace'] if that function was not called.
* @param {...*} elements One or more elements of any type to be logged
*/
Bristol.prototype.log = function(severity, elements) {
if (!this._severities.hasOwnProperty(severity))
throw new Error("Severity '" + severity + "' does not exist.");
var args = Array.prototype.slice.call(arguments),
logTime = new Date(),
objArgs = {},
logElems = [],
self = this;
// Remove the severity arg and put metadata first, all in one fell swoop
args[0] = logUtil.safeMerge(this._getOrigin(), this._getGlobals());
for (var i = 0; i < args.length; i++) {
var arg = this._transform(args[i]);
if (typeof arg == 'object' && !(arg instanceof Error))
logUtil.safeMerge(objArgs, arg);
else
logElems.push(arg);
}
logElems.push(objArgs);
this._targets.forEach(function(target) {
self._logToTarget(target, severity, logTime, logElems);
});
var eventObj = {
severity: severity,
date: logTime,
elements: logElems
};
this.emit('log', eventObj);
this.emit('log:' + severity, eventObj);
};
/**
* Sets a global key/value pair that will be logged with every message sent
* by this Bristol instance. If val is provided as a function, the function
* will be executed for every log message, and the logged value for that key
* will be its result.
* @param {string} key The key number under which to log the value
* @param {*} val The value to be logged
*/
Bristol.prototype.setGlobal = function(key, val) {
this._globals[key] = val;
};
/**
* Replaces the currently set severity levels with a new set. This function
* will make a new set of severity-named functions available on the Bristol
* instances, and remove the old ones. Function calls to a previously-set
* severity level WILL fail, if that level does not also appear in the new set.
*
* Severity levels should be supplied in an array of strings, in the order of
* most-severe to least-severe.
* @param {Array.<string>} levels The severity levels to use in this Bristol
* instance
*/
Bristol.prototype.setSeverities = function(levels) {
var self = this,
oldLevels = this._severities;
// Delete the existing error level functions
logUtil.forEachObj(this._severities, function(key) {
delete self[key];
});
// Create the new ones
levels.forEach(function(level, idx) {
self._severities[level] = idx;
if (!self[level]) {
self[level] = function() {
var args = Array.prototype.slice.call(arguments);
args.unshift(level);
self.log.apply(self, args);
};
}
else {
self.setSeverities(oldLevels);
throw new Error("Error level '" + level +
"' is already a Bristol function and cannot be used.");
}
});
};
/**
* Retrieves the set global key/value pairs, executing any values that were
* supplied as functions.
* @returns {{}} An object containing global key/value pairs, with any
* function values replaced with their result.
* @private
*/
Bristol.prototype._getGlobals = function() {
var globals = {};
logUtil.forEachObj(this._globals, function(key, val) {
if (typeof val == 'function')
globals[key] = val();
else
globals[key] = val;
});
return globals;
};
/**
* Finds the origin of the Bristol log call, and supplies the file path and
* line number.
* @returns {null|{file, line}} An object containing the file path and line
* number of the originating Bristol call, or null if this information
* cannot be found.
* @private
*/
Bristol.prototype._getOrigin = function() {
var stack = (new Error()).stack.split(/\s*\n\s*(?:at\s)?/),
origin = null,
caller;
for (var i = 1; i < stack.length; i++) {
if (!stack[i].match(/^Bristol\./)) {
caller = stack[i].match(/([^:\s\(]+):(\d+):(\d+)\)?$/);
break;
}
}
if (caller && caller.length == 4) {
origin = {
file: caller[1],
line: caller[2]
};
}
return origin;
};
/**
* Gets an object containing chainable configuration functions that allow
* options to be specified on a given target.
* @param {{
* log,
* formatter,
* blacklist,
* whitelist,
* leastVerbose,
* mostVerbose
* }} target The target to be modified
* @returns {{
* withFormatter,
* excluding,
* onlyIncluding,
* withLowestSeverity,
* withHighestSeverity
* }} A config chain object
* @private
*/
Bristol.prototype._getTargetConfigChain = function(target) {
var chain = {},
self = this;
chain.withFormatter = function(formatter, options) {
if (typeof formatter == 'string')
formatter = require('./formatters/' + formatter);
target.formatter = formatter.bind(formatter, options || {});
return chain;
};
chain.excluding = function(blacklist) {
target.blacklist = blacklist;
return chain;
};
chain.onlyIncluding = function(whitelist) {
target.whitelist = whitelist;
return chain;
};
chain.withLowestSeverity = function(severity) {
if (!self._severities.hasOwnProperty(severity))
throw new Error("Severity '" + severity + "' does not exist.");
target.mostVerbose = self._severities[severity];
return chain;
};
chain.withHighestSeverity = function(severity) {
if (!self._severities.hasOwnProperty(severity))
throw new Error("Severity '" + severity + "' does not exist.");
target.leastVerbose = self._severities[severity];
return chain;
};
return chain;
};
/**
* Pushes a set of elements to a given logging target, given that the
* restrictions set on the given target do not block it.
*
* Note that, for efficiency, this function assumes that the elements have
* been rearranged so that all standard JS objects have been merged into a
* single object, and that object is the last element in the array of elements.
* The side-effect of this efficiency-boost is that the blacklist/whitelist
* tests will be run on that resulting object; so if there are any duplicate
* keys that were renamed during the merge, the filters will not be applied
* to those keys. Likelihood of this being a problem is low, but this may be
* revisited in a future version of Bristol.
* @param {{
* log,
* formatter,
* blacklist,
* whitelist,
* leastVerbose,
* mostVerbose
* }} target A target object to which the log elements should be pushed
* @param {string} severity The severity level under which to log the elements
* @param {Date} date A Date object defining the time to be used for the log
* message
* @param {Array} elems An array of elements to be logged, of any type.
* @private
*/
Bristol.prototype._logToTarget = function(target, severity, date, elems) {
var verbosity = this._severities[severity],
testObj = elems[elems.length - 1];
if (verbosity >= target.leastVerbose &&
verbosity <= target.mostVerbose &&
!logUtil.matchesOneKey(testObj, target.blacklist) &&
logUtil.matchesAllKeys(testObj, target.whitelist)) {
var str = target.formatter(severity, date, elems);
target.log(severity, date, str);
}
};
/**
* Applies all transforms to an element, stopping when a transform returns a
* non-null value.
* @param {*} elem Any element to be transformed
* @returns {*} The transformed element, or the original element if no
* transform modified it.
* @private
*/
Bristol.prototype._transform = function(elem) {
var result;
for (var i = 0; i < this._transforms.length; i++) {
result = this._transforms[i](elem);
if (result !== null)
break;
}
return result || elem;
};
module.exports = new Bristol();
module.exports.Bristol = Bristol;
|
module.exports = {
name: 'logout',
command: function logout (args) {
console.log('not yet implemented')
},
options: [
{
name: '',
abbr: '',
boolean: false,
default: null,
help: ''
}
]
}
|
'use strict';
//Projects service used to communicate Projects REST endpoints
angular.module('projects').factory('Projects', ['$resource',
function($resource) {
return $resource('projects/:projectId', {
projectId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
|
var Express = require('express');
var app = Express();
app.use(Express.static(__dirname));
app.listen(3000);
|
search_result['1966']=["topic_00000000000004C4_attached_props--.html","PhoneNumberHelper Attached Properties",""]; |
import DateService from './date.service';
const deepEqual = require('deep-equal');
export default class UserService {
/**
* Gets a list of all the users in the database
* @return {Array} User objects
*/
static getAllUsers() {
const usersRef = firebase.database().ref('users');
usersRef.once('value', (snapshot) => {
console.log('All Users', snapshot.val());
});
}
/**
* Get a single user
* @param {String} userID User's ID
* @return {Object} User Object
*/
static getUser(userID) {
const usersRef = firebase.database().ref(`users/${userID}`);
usersRef.once('value', (snapshot) => {
console.log('single user: ', snapshot.val());
});
}
/**
* Gets a list of all the weeks the user has exercises in
* @param {String} userID User's ID
* @return {Array} Array of Weeks which contain Date Objects
*/
static getAllWeeks(userID) {
const userWeekRef = firebase.database().ref(`users/${userID}/weeks`);
userWeekRef.once('value', (snapshot) => {
console.log('All weeks', snapshot.val());
});
}
/**
* Gets a single Week for a given user
* @param {string} userID User's ID
* @param {string} week Date formatted as a 6 digit number MMDDYY.
* It is always a Sundays date as it is the
* beginning of the week
* @return {Object} Week object containing Date objects for each
* weekday.
*/
static getSingleWeek(userID, week, callback) {
const userWeekRef = firebase.database().ref(`users/${userID}/weeks/${week}`);
userWeekRef.once('value', (snapshot) => {
callback(snapshot.val());
});
}
/**
* Updates the title of a day
* @param {string} userID User's ID
* @param {string} weekOf Date formatted as a 6 digit number MMDDYY.
* Beginning date of the week
* @param {string} date Date formatted as a 6 digit number MMDDYY.
* @param {string} name Name of the days workout
*/
static updateDay(userID, weekOf, date, name) {
const updates = {};
updates[`users/${userID}/weeks/${weekOf}/${date}/`] = name;
firebase.database().ref().update(updates);
}
/**
*
* Currently not being used. Use updateDay for adds
*
* Adds a new day with a title
* @param {string} userID User's ID
* @param {string} weekOf Date formatted as a 6 digit number MMDDYY.
* Beginning date of the week
* @param {string} date Date formatted as a 6 digit number MMDDYY.
* @param {string} name Name of the days workout
*/
// static addDay(userID, weekOf, date, name) {
// const ref = `users/${userID}/weeks/${weekOf}/${date}/`;
// //firebase.database().ref(ref) = name;
// }
/**
* Removes a day
* @param {string} userID User's ID
* @param {string} weekOf Date formatted as a 6 digit number MMDDYY.
* Beginning date of the week
* @param {string} date Date formatted as a 6 digit number MMDDYY.
* @param {string} name Name of the days workout
*/
static deleteDay(userID, weekOf, date) {
const ref = `users/${userID}/weeks/${weekOf}/${date}`;
firebase.database().ref(ref).remove();
}
static addWeekForUser(userID, week) {
const userWeekRef = firebase.database().ref(`users/${userID}/weeks/${week}`);
const weekObj = {};
let weekDay = week;
for (let i = 0; i < 7; i++) {
weekObj[weekDay] = '';
let nextDay = DateService.getNextDay(weekDay);
// Reformat the formattedDate with the next day
weekDay = `${weekDay.substr(0, 2)}${nextDay}${weekDay.substr(4, 2)}`;
}
userWeekRef.update(weekObj);
}
static getExercises(userID, date, callback) {
const path = `days/${date}/${userID}`;
const ref = firebase.database().ref(path);
ref.on('value', (snapshot) => {
console.log('snapshot', snapshot.val());
callback(snapshot.val());
});
}
/**
* Adds an exercise to a specific date for a user
* @param {string]} userID User's ID
* @param {string} date Date formatted as a 6 digit number MMDDYY
* @param {string} exercise Exercise object. Contains fields name, reps,
* sets, weight
*/
static addExercise(userID, date, exercise) {
const path = `days/${date}/${userID}`;
console.log(path, exercise);
firebase.database().ref(path).push(exercise);
}
/**
* Updates an exercise information for a given day
* @param {string} userID [description]
* @param {string} date Date formatted as a 6 digit number MMDDYY
* @param {object} oldExercise Exercise Object to be changed
* @param {object} newExercise Exercise Object to change to
*/
static updateExercise(userID, date, oldExercise, newExercise) {
const path = `days/${date}/${userID}`;
const ref = firebase.database().ref(path);
ref.once('value', (snapshot) => {
Object.keys(snapshot.val()).forEach((ex) => {
if (deepEqual(snapshot.val()[ex], oldExercise)) {
firebase.database().ref(`${path}/${ex}`).update(newExercise);
}
});
});
}
/**
* Updates an exercise information for a given day
* @param {string} userID [description]
* @param {string} date Date formatted as a 6 digit number MMDDYY
* @param {object} oldExercise Exercise Object to be changed
* @param {object} newExercise Exercise Object to change to
*/
static updateExerciseByKey(userID, date, key, newExercise) {
const path = `days/${date}/${userID}/${key}`;
const ref = firebase.database().ref(path);
ref.update(newExercise);
}
/**
* Deletes an exercise for a user on a given day
* @param {string} userID [description]
* @param {string} date Date formatted as a 6 digit number MMDDYY
* @param {string} key Key for the Exercise to delete
*/
static deleteExercise(userID, date, key) {
const path = `days/${date}/${userID}/${key}`;
const ref = firebase.database().ref(path);
ref.remove();
}
}
|
/*!
* Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file.
*/
/* istanbul ignore else */
if (!global._babelPolyfill) {
/* eslint global-require: [0] */
require(`babel-polyfill`);
}
module.exports = require(`./ciscospark`);
/**
* The date and time, specified in ISO 8601 extended offset date/time
* format (e.g. `2015-10-18T14:26:16+00:00`).
*
* @typedef {string} isoDate
*/
/**
* An email address, as a string.
* @typedef {string} email
*/
|
/* eslint-disable no-var, no-unused-vars, no-underscore-dangle */
// Make a proxy of the global Jest expect function so we can test the global
// expect-webdriverio version
global._expect = global.expect;
|
Auslastung.editMenu = new Class({
Extends: Auslastung.actionMenu,
Implements: Events,
entryid: null,
name: null,
hideAble: false,
showEl: null,
hideEl: null,
hideState: false,
deleteAble: true,
customEventListener: null,
initialize: function( parent, table, id, name, options ) {
this.parent( parent, table );
this.entryid = id;
this.name = name;
if ( typeof options !== 'undefined' ) {
for( var i in options ) this[i] = options[i];
}
this.el = new Element( 'ul', { 'class': 'editmenu' } );
this.offEl = new Element( 'li', { 'class': 'off' } ).inject( this.el );
if ( this.hideAble ) {
this.hideEl = new Element( 'li', { 'class': 'hide', 'title': 'Verbergen' } ).inject( this.el );
this.showEl = new Element( 'li', { 'class': 'show', 'title': 'Einblenden' } ).inject( this.el );
if ( this.hideState ) {
this.hideEl.setStyle( 'display', 'none' );
} else {
this.showEl.setStyle( 'display', 'none' );
}
}
var edit = new Element( 'li', { 'class': 'edit', 'title': 'Bearbeiten' } ).inject( this.el );
if (this.deleteAble) {
var del = new Element( 'li', { 'class': 'delete', 'title': 'Löschen' } ).inject( this.el );
}
this.el.inject( parent );
this.el.getChildren().each(function(li) {
if (!li.hasClass('off')) li.setStyle('display', 'none');
});
if (this.customEventListener === null) {
this.el.addEvent('click', this.eventListener.bind(this));
} else {
this.el.addEvent('click', this.customEventListener.bind(this));
}
parent.store( 'editmenu', this );
parent.setStyle('position', 'relative');
parent.addEvent( 'mouseenter', function( ev ) {
this.addClass('active');
this.retrieve('editmenu').el.getChildren().each(function(li) {
li.setStyle('display', li.hasClass('off') ? 'none' : 'block');
});
} );
parent.addEvent( 'mouseleave', function( ev ) {
this.removeClass('active');
this.retrieve('editmenu').el.getChildren().each(function(li) {
li.setStyle('display', li.hasClass('off') ? 'block' : 'none');
});
} );
},
eventListener: function( ev )
{
ev.stopPropagation();
if ( ev.target.hasClass( 'delete' ) ) {
if ( confirm( this.name + ' wirklich löschen?' ) ) {
new Request.JSON({
url: '/api/' + this.table + '/' + this.entryid + '?method=delete',
onSuccess: function( response ) {
if ( Auslastung.View.ResponseChecker.check( response ) ) {
this.parentEl.destroy();
}
}.bind( this )
}).post();
}
} else if ( ev.target.hasClass( 'edit' ) ) {
new Request.JSON({
url: '/api/' + this.table + '/form',
onSuccess: function( response ) {
if ( Auslastung.View.ResponseChecker.check( response ) ) {
var form = new Auslastung.FormRenderer( this.table, this.entryid, response.result, this.name + ' bearbeiten' );
form.addEvent( 'saved', function( updatedEntry ) {
this.fireEvent( 'updated', updatedEntry );
}.bind( this ) );
}
}.bind( this )
}).get( { 'id': this.entryid } );
} else if ( ev.target.hasClass( 'hide' ) ) {
this.hideState = true;
this.showEl.setStyle( 'display', 'block' );
this.hideEl.setStyle( 'display', 'none' );
this.fireEvent( 'hide' );
} else if ( ev.target.hasClass( 'show' ) ) {
this.hideState = false;
this.showEl.setStyle( 'display', 'none' );
this.hideEl.setStyle( 'display', 'block' );
this.fireEvent( 'show' );
}
}
}); |
//~ name c422
alert(c422);
//~ component c423.js
|
module.exports = {
parseSubreddit: function(subredditData, visited){
}
} |
import { takeLatest, takeEvery } from 'redux-saga';
import { fork, put } from 'redux-saga/effects';
import { browserHistory } from 'react-router';
import * as API from '../api';
import { serverName } from '../components/ServerList';
import createFetchSaga from './helpers/createFetchSaga';
import { showNotification, showErrorNotification } from '../actions/notificationActions';
import {
FETCH_SERVER_LIST_REQUEST,
FETCH_SERVER_LIST_RESPONSE,
FETCH_SERVER_REQUEST,
FETCH_SERVER_RESPONSE,
PATCH_SERVER_REQUEST,
PATCH_SERVER_RESPONSE,
CREATE_SERVER_REQUEST,
CREATE_SERVER_RESPONSE,
DELETE_SERVER_REQUEST,
DELETE_SERVER_RESPONSE,
} from '../constants';
const fetchServerList = createFetchSaga({
apiCall: API.fetchServerList,
responseKey: FETCH_SERVER_LIST_RESPONSE,
});
const fetchServer = createFetchSaga({
apiCall: API.fetchServer,
responseKey: FETCH_SERVER_RESPONSE,
});
const patchServer = createFetchSaga({
apiCall: API.patchServer,
responseKey: PATCH_SERVER_RESPONSE,
});
const createServer = createFetchSaga({
apiCall: API.createServer,
responseKey: CREATE_SERVER_RESPONSE,
});
const deleteServer = createFetchSaga({
apiCall: API.deleteServer,
responseKey: DELETE_SERVER_RESPONSE,
});
function* patchServerResponse(action) {
const name = serverName(action.request);
if (!action.error) {
yield fork(fetchServer, action);
yield put(showNotification(`Updated server ${name}`));
} else {
yield put(showErrorNotification(`Failed to update server ${name}`, action.payload));
}
}
function* createServerResponse(action) {
const name = serverName(action.request);
if (!action.error) {
const { hostname, environment } = action.request;
yield put(showNotification(`Created server ${name}`));
browserHistory.push(`/server/${environment}/${hostname}`);
} else {
yield put(showErrorNotification(`Failed to create server ${name}`, action.payload));
}
}
function* deleteServerResponse(action) {
const name = serverName(action.request);
if (!action.error) {
yield put(showNotification(`Deleted server ${name}`));
browserHistory.push('/server');
} else {
yield put(showErrorNotification(`Failed to delete server ${name}`, action.payload));
}
}
export default function* serverSagas() {
yield fork(takeLatest, FETCH_SERVER_REQUEST, fetchServer);
yield fork(takeLatest, FETCH_SERVER_LIST_REQUEST, fetchServerList);
yield fork(takeEvery, PATCH_SERVER_REQUEST, patchServer);
yield fork(takeEvery, PATCH_SERVER_RESPONSE, patchServerResponse);
yield fork(takeEvery, CREATE_SERVER_REQUEST, createServer);
yield fork(takeEvery, CREATE_SERVER_RESPONSE, createServerResponse);
yield fork(takeEvery, DELETE_SERVER_REQUEST, deleteServer);
yield fork(takeEvery, DELETE_SERVER_RESPONSE, deleteServerResponse);
}
|
'use strict';
describe('Service: vnApiProducts', function () {
// load the service's module
beforeEach(module('Volusion.toolboxCommon'));
// instantiate service
var vnApiProducts;
beforeEach(inject(function (_vnApiProducts_) {
vnApiProducts = _vnApiProducts_;
}));
it('should default to an empty object', function () {
expect(vnApiProducts).toEqual({});
});
// When mocking or ajax testing is enabled test the integrity
// of the responses structure.
});
|
import { diff } from 'adiff';
function compareArrays(collector, base, target) {
const changes = diff(base, target);
if (changes.length > 0) {
collector.$splice = changes;
}
return collector;
}
export default compareArrays;
|
console.log(JSXTransformer.exec(_TPL_["/jsx/hw.jsx"]));
|
const webpack = require('webpack');
const path = require('path');
var CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = (env) => {
const plugins = [
new CopyWebpackPlugin([
{ from: 'src/static', to: 'static' },
{ from: 'src/styles/preload.css', to: 'preload.css' }
])
];
if (env && env.prod) {
plugins.push(
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
screw_ie8: true,
conditionals: true,
unused: true,
comparisons: true,
sequences: true,
dead_code: true,
evaluate: true,
if_return: true,
join_vars: true
},
output: {
comments: false
}
})
);
}
return {
entry: {
app: './src/index.js',
vendor: ['react', 'react-dom']
},
output: {
path: path.join(__dirname, './dist'),
filename: '[name].bundle.js',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: [
path.resolve(__dirname, "src"),
path.resolve(__dirname, "node_modules/piwik-tracker")
],
use: [
'babel-loader'
]
},
{
test: /\.(html)$/,
exclude: /node_modules/,
use: {
loader: 'file-loader',
query: {
name: '[name].[ext]'
},
},
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
'postcss-loader'
],
include: [
path.resolve(__dirname, "src"),
path.resolve(__dirname, "node_modules/normalize.css")
]
},
{
test: /\.scss$/,
exclude: /node_modules/,
use: [
'style-loader',
'css-loader',
'postcss-loader',
'sass-loader'
]
}
],
},
resolve: {
extensions: ['.js', '.jsx'],
modules: [
path.resolve(__dirname, 'node_modules'),
path.join(__dirname, './src')
]
},
plugins
};
}; |
const path = require('path');
module.exports = {
entry: {
main: "./lib/index.js",
// test: "mocha!./test/index.js"
test: 'sinon/pkg/sinon.js'
},
output: {
path: __dirname,
filename: "[name].bundle.js",
},
module: {
noParse: [
/\/sinon\.js/,
],
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}, {
test: /\.css$/,
loader: "style!css"
}, {
test: /\.scss$/,
loader: "style!css!sass"
}, {
test: /sinon\/pkg\/sinon\.js/,
loader: "imports?define=>false,require=>false"
}]
},
resolve: {
alias: {
sinon: 'sinon/pkg/sinon.js',
},
extensions: ['', '.js', '.json', '.scss', '.css']
}
};
|
// use this hack to prevent async errors from DOM.importStyles
jasmine.clock().install();
DOM.importStyles("@keyframes fade", "from {opacity: 1} to {opacity: 0}");
DOM.importStyles("@-webkit-keyframes fade", "from {opacity: 1} to {opacity: 0}");
jasmine.clock().uninstall();
DOM.importStyles(".hidden", "display:none");
DOM.importStyles(".invisible", "visibility:hidden");
DOM.importStyles(".fade", "opacity:1;transform:scale(1,1);-webkit-transform:scale(1,1)");
DOM.importStyles(".fade[aria-hidden=true]", "opacity:0;transform:scale(0,0);-webkit-transform:scale(0,0)");
describe("visibility", function() {
"use strict";
var link;
beforeEach(function() {
link = DOM.create("<a>123</a>");
jasmine.sandbox.set(link);
});
describe("hide", function() {
it("should support exec callback when no transition is defined", function(done) {
expect(link.hide(done));
});
it("should support exec callback when animation is defined", function(done) {
link.set("style", "animation:none 10ms;-webkit-animation:none 10ms;display:block");
link.hide("fade", done);
});
it("should support exec callback when transition is defined", function(done) {
link.addClass("fade").set("style", "transition:opacity 10ms;-webkit-transition:opacity 10ms");
link.hide(done);
});
it("should work properly in legacy browsers", function(done) {
link.css("transition-duration", "1");
link.hide(function() {
link.css("animation-duration", "1");
link.show(function() {
link.css("transition-duration", null);
link.hide(done);
});
});
});
// it("by default updates display property", function(done) {
// expect(link.css("display")).not.toBe("none");
// link.hide(function() {
// expect(link.css("display")).toBe("none");
// done();
// });
// });
// it("should work for several transitions", function(done) {
// var start = Date.now();
// var link = DOM.create("<a class=\"fade\" style='transition:opacity 50ms, transform 100ms;-webkit-transition:opacity 50ms, -webkit-transform 100ms'>abc</a>");
// jasmine.sandbox.set(link);
// link.hide(function() {
// var delta = Date.now() - start;
// expect(delta < 50 || delta > 75).toBe(true);
// done();
// });
// });
it("should throw error if arguments are invalid", function() {
// expect(function() { link.hide("123") }).toThrow();
expect(function() { link.hide(-10) }).toThrow();
expect(function() { link.hide(true) }).toThrow();
});
});
describe("show", function() {
it("should trigger callback for initially hidden elements", function(done) {
link.addClass("hidden");
link.show("fade", done);
});
it("should throw error if arguments are invalid", function() {
// expect(function() { link.show("123") }).toThrow();
expect(function() { link.show(-10) }).toThrow();
expect(function() { link.show(true) }).toThrow();
});
// it("should handle initially hidden element", function(done) {
// link.addClass("hidden");
// link.show(function() {
// expect(link.css("display")).not.toBe("none");
// expect(link).toHaveAttr("aria-hidden", "false");
// done();
// });
// });
it("should handle initially invisible element", function(done) {
link.addClass("invisible");
link.show(function() {
expect(link.css("visibility")).not.toBe("hidden");
expect(link).toHaveAttr("aria-hidden", "false");
done();
});
});
});
describe("toggle", function() {
beforeEach(function() {
link = DOM.create("<a>123</a>");
jasmine.sandbox.set(link);
});
it("should allow to toggle visibility", function(done) {
expect(link.matches(":hidden")).toBe(false);
link.toggle(function() {
expect(link.matches(":hidden")).toBe(true);
link.toggle(function() {
expect(link.matches(":hidden")).toBe(false);
done();
});
});
});
it("should work properly with show/hide combination", function(done) {
expect(link).not.toHaveStyle("visibility", "hidden");
link.toggle(function() {
expect(link).toHaveStyle("visibility", "hidden");
link.toggle(function() {
expect(link).not.toHaveStyle("visibility", "hidden");
done();
});
});
});
it("should toggle aria-hidden for detached elements", function(done) {
link.remove();
expect(link).not.toHaveAttr("aria-hidden");
link.hide(function() {
expect(link).toHaveAttr("aria-hidden", "true");
link.show(function() {
expect(link).toHaveAttr("aria-hidden", "false");
done();
});
});
});
it("should update aria-hidden", function(done) {
expect(link).not.toHaveAttr("aria-hidden");
link.hide(function() {
expect(link).toHaveAttr("aria-hidden", "true");
link.show(function() {
expect(link).toHaveAttr("aria-hidden", "false");
done();
});
});
});
it("cancel previous call if it was scheduled", function(done) {
var firstSpy = jasmine.createSpy("first"),
secondSpy = jasmine.createSpy("second");
secondSpy.and.callFake(function() {
expect(firstSpy).not.toHaveBeenCalled();
done();
});
link.toggle(firstSpy);
link.toggle(secondSpy);
});
// it("should trigger callback only once", function(done) {
// var showSpy = jasmine.createSpy("show"),
// hideSpy = jasmine.createSpy("hide");
// link.set("style", "animation:none 10ms;-webkit-animation:none 10ms;display:block");
// link.toggle("fade", hideSpy);
// hideSpy.and.callFake(function() {
// link.toggle(showSpy);
// showSpy.and.callFake(function() {
// expect(hideSpy.calls.count()).toBe(1);
// expect(showSpy.calls.count()).toBe(1);
// done();
// });
// });
// });
});
it("should return this for empty nodes", function() {
var emptyEl = DOM.find("some-node");
expect(emptyEl.show()).toBe(emptyEl);
expect(emptyEl.hide()).toBe(emptyEl);
expect(emptyEl.toggle()).toBe(emptyEl);
});
it("should handle unknown aria-hidden values as false", function(done) {
expect(link.matches(":hidden")).toBe(false);
link.set("aria-hidden", "123");
expect(link.matches(":hidden")).toBe(false);
link.toggle(function() {
expect(link.matches(":hidden")).toBe(true);
done();
});
});
}); |
import React from 'react'
import { render } from 'react-dom'
import { Router, Route, hashHistory } from 'react-router'
import childRoutes from './utils/urls'
import Library from './components/Library'
const routes = {
path: '/',
component: Library,
childRoutes
}
render((
<Router history={hashHistory} routes={routes} />
), document.getElementById('app'))
|
var mw = require('./middleware');
module.exports = [ {
title: 'Membership',
template: 'admin/pages/landing',
pages: [
{
title: 'Roles',
middleware: [ mw.roles.formatQuery, mw.roles.paginate, mw.roles.find ],
template: 'admin/pages/membership/roles',
reload: true,
pages: [ {
title: 'Role',
path: ':id',
template: 'admin/pages/membership/role',
middleware: mw.roles.findById,
name: 'role',
reload: true,
nav: false
}]
}, {
title: 'Permissions',
middleware: [ mw.permissions.formatQuery, mw.permissions.paginate, mw.permissions.find ],
template: 'admin/pages/membership/permissions',
reload: true,
pages: [ {
title: 'Permission',
path: ':id',
template: 'admin/pages/membership/permission',
name: 'permission',
reload: true,
middleware: [ mw.roles.getAll, function(req, res, next) {
res.locals.allRoles = res.locals.roles;
delete res.locals.roles;
next();
}, mw.permissions.findById ],
nav: false
}]
}, {
title: 'Invites',
middleware: [ mw.invites.formatQuery, mw.invites.paginate, mw.invites.find ],
template: 'admin/pages/membership/invites',
reload: true,
pages: [ {
title: 'Invite',
name: 'invite',
path: ':id',
template: 'admin/pages/membership/invite',
reload: true,
middleware: [ mw.roles.getAll, function(req, res, next) {
res.locals.allRoles = res.locals.roles;
delete res.locals.roles;
next();
}, mw.invites.findById ],
nav: false
}]
}, {
title: 'Users'
}
]
} ];
|
// https://github.com/nodejs/node/blob/b4cf8c403623a9f0bdbbb8aa43df79c68cbe8f66/test/parallel/test-assert.js
'use strict';
var assert = require('../../src');
var a = require('../../src');
describe('core assert tests', function () {
it('should pass', function () {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function makeBlock(f) {
var args = Array.prototype.slice.call(arguments, 1);
return function() {
return f.apply(this, args);
};
}
var node_0_12 = process.version.match('v0.12')
assert.ok(a.AssertionError.prototype instanceof Error,
'a.AssertionError instanceof Error');
assert.throws(makeBlock(a, false), a.AssertionError, 'ok(false)');
assert.doesNotThrow(makeBlock(a, true), a.AssertionError, 'ok(true)');
assert.doesNotThrow(makeBlock(a, 'test', 'ok(\'test\')'));
assert.throws(makeBlock(a.ok, false),
a.AssertionError, 'ok(false)');
assert.doesNotThrow(makeBlock(a.ok, true),
a.AssertionError, 'ok(true)');
assert.doesNotThrow(makeBlock(a.ok, 'test'), 'ok(\'test\')');
assert.throws(makeBlock(a.equal, true, false),
a.AssertionError, 'equal(true, false)');
assert.doesNotThrow(makeBlock(a.equal, null, null),
'equal(null, null)');
assert.doesNotThrow(makeBlock(a.equal, undefined, undefined),
'equal(undefined, undefined)');
assert.doesNotThrow(makeBlock(a.equal, null, undefined),
'equal(null, undefined)');
assert.doesNotThrow(makeBlock(a.equal, true, true), 'equal(true, true)');
assert.doesNotThrow(makeBlock(a.equal, 2, '2'), 'equal(2, \'2\')');
assert.doesNotThrow(makeBlock(a.notEqual, true, false),
'notEqual(true, false)');
assert.throws(makeBlock(a.notEqual, true, true),
a.AssertionError, 'notEqual(true, true)');
assert.throws(makeBlock(a.strictEqual, 2, '2'),
a.AssertionError, 'strictEqual(2, \'2\')');
assert.throws(makeBlock(a.strictEqual, null, undefined),
a.AssertionError, 'strictEqual(null, undefined)');
assert.throws(makeBlock(a.notStrictEqual, 2, 2),
a.AssertionError, 'notStrictEqual(2, 2)');
assert.doesNotThrow(makeBlock(a.notStrictEqual, 2, '2'),
'notStrictEqual(2, \'2\')');
// deepEqual joy!
// 7.2
assert.doesNotThrow(makeBlock(a.deepEqual, new Date(2000, 3, 14),
new Date(2000, 3, 14)),
'deepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))');
assert.throws(makeBlock(a.deepEqual, new Date(), new Date(2000, 3, 14)),
a.AssertionError,
'deepEqual(new Date(), new Date(2000, 3, 14))');
assert.throws(
makeBlock(a.notDeepEqual, new Date(2000, 3, 14), new Date(2000, 3, 14)),
a.AssertionError,
'notDeepEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))'
);
assert.doesNotThrow(makeBlock(
a.notDeepEqual,
new Date(),
new Date(2000, 3, 14)),
'notDeepEqual(new Date(), new Date(2000, 3, 14))'
);
// 7.3
assert.doesNotThrow(makeBlock(a.deepEqual, /a/, /a/));
assert.doesNotThrow(makeBlock(a.deepEqual, /a/g, /a/g));
assert.doesNotThrow(makeBlock(a.deepEqual, /a/i, /a/i));
assert.doesNotThrow(makeBlock(a.deepEqual, /a/m, /a/m));
assert.doesNotThrow(makeBlock(a.deepEqual, /a/igm, /a/igm));
assert.throws(makeBlock(a.deepEqual, /ab/, /a/),
/^AssertionError: \/ab\/ deepEqual \/a\/$/);
assert.throws(makeBlock(a.deepEqual, /a/g, /a/),
/^AssertionError: \/a\/g deepEqual \/a\/$/);
assert.throws(makeBlock(a.deepEqual, /a/i, /a/),
/^AssertionError: \/a\/i deepEqual \/a\/$/);
assert.throws(makeBlock(a.deepEqual, /a/m, /a/),
/^AssertionError: \/a\/m deepEqual \/a\/$/);
assert.throws(makeBlock(a.deepEqual, /a/igm, /a/im),
/^AssertionError: \/a\/gim deepEqual \/a\/im$/);
{
const re1 = /a/g;
re1.lastIndex = 3;
assert.throws(makeBlock(a.deepEqual, re1, /a/g),
/^AssertionError: \/a\/g deepEqual \/a\/g$/);
}
// 7.4
assert.doesNotThrow(makeBlock(a.deepEqual, 4, '4'), 'deepEqual(4, \'4\')');
assert.doesNotThrow(makeBlock(a.deepEqual, true, 1), 'deepEqual(true, 1)');
assert.throws(makeBlock(a.deepEqual, 4, '5'),
a.AssertionError,
'deepEqual( 4, \'5\')');
// 7.5
// having the same number of owned properties && the same set of keys
(makeBlock(a.deepEqual, {a: 4}, {a: 4}))()
assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4, b: '2'}, {a: 4, b: '2'}));
assert.doesNotThrow(makeBlock(a.deepEqual, [4], ['4']));
assert.throws(makeBlock(a.deepEqual, {a: 4}, {a: 4, b: true}),
a.AssertionError);
assert.doesNotThrow(makeBlock(a.deepEqual, ['a'], {0: 'a'}));
//(although not necessarily the same order),
assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4, b: '1'}, {b: '1', a: 4}));
var a1 = [1, 2, 3];
var a2 = [1, 2, 3];
a1.a = 'test';
a1.b = true;
a2.b = true;
a2.a = 'test';
assert.throws(makeBlock(a.deepEqual, Object.keys(a1), Object.keys(a2)),
a.AssertionError);
assert.doesNotThrow(makeBlock(a.deepEqual, a1, a2));
// having an identical prototype property
var nbRoot = {
toString: function() { return this.first + ' ' + this.last; }
};
function nameBuilder(first, last) {
this.first = first;
this.last = last;
return this;
}
nameBuilder.prototype = nbRoot;
function nameBuilder2(first, last) {
this.first = first;
this.last = last;
return this;
}
nameBuilder2.prototype = nbRoot;
var nb1 = new nameBuilder('Ryan', 'Dahl');
var nb2 = new nameBuilder2('Ryan', 'Dahl');
assert.doesNotThrow(makeBlock(a.deepEqual, nb1, nb2));
nameBuilder2.prototype = Object;
nb2 = new nameBuilder2('Ryan', 'Dahl');
assert.doesNotThrow(makeBlock(a.deepEqual, nb1, nb2));
// primitives and object
assert.throws(makeBlock(a.deepEqual, null, {}), a.AssertionError);
assert.throws(makeBlock(a.deepEqual, undefined, {}), a.AssertionError);
assert.throws(makeBlock(a.deepEqual, 'a', ['a']), a.AssertionError);
assert.throws(makeBlock(a.deepEqual, 'a', {0: 'a'}), a.AssertionError);
assert.throws(makeBlock(a.deepEqual, 1, {}), a.AssertionError);
assert.throws(makeBlock(a.deepEqual, true, {}), a.AssertionError);
if (!node_0_12) {
assert.throws(makeBlock(a.deepEqual, Symbol(), {}), a.AssertionError);
}
// primitive wrappers and object
assert.doesNotThrow(makeBlock(a.deepEqual, new String('a'), ['a']),
a.AssertionError);
assert.doesNotThrow(makeBlock(a.deepEqual, new String('a'), {0: 'a'}),
a.AssertionError);
assert.doesNotThrow(makeBlock(a.deepEqual, new Number(1), {}),
a.AssertionError);
assert.doesNotThrow(makeBlock(a.deepEqual, new Boolean(true), {}),
a.AssertionError);
// same number of keys but different key names
assert.throws(makeBlock(a.deepEqual, {a: 1}, {b: 1}), a.AssertionError);
//deepStrictEqual
assert.doesNotThrow(
makeBlock(a.deepStrictEqual, new Date(2000, 3, 14), new Date(2000, 3, 14)),
'deepStrictEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))'
);
assert.throws(
makeBlock(a.deepStrictEqual, new Date(), new Date(2000, 3, 14)),
a.AssertionError,
'deepStrictEqual(new Date(), new Date(2000, 3, 14))'
);
assert.throws(
makeBlock(a.notDeepStrictEqual, new Date(2000, 3, 14), new Date(2000, 3, 14)),
a.AssertionError,
'notDeepStrictEqual(new Date(2000, 3, 14), new Date(2000, 3, 14))'
);
assert.doesNotThrow(
makeBlock(a.notDeepStrictEqual, new Date(), new Date(2000, 3, 14)),
'notDeepStrictEqual(new Date(), new Date(2000, 3, 14))'
);
// 7.3 - strict
assert.doesNotThrow(makeBlock(a.deepStrictEqual, /a/, /a/));
assert.doesNotThrow(makeBlock(a.deepStrictEqual, /a/g, /a/g));
assert.doesNotThrow(makeBlock(a.deepStrictEqual, /a/i, /a/i));
assert.doesNotThrow(makeBlock(a.deepStrictEqual, /a/m, /a/m));
assert.doesNotThrow(makeBlock(a.deepStrictEqual, /a/igm, /a/igm));
assert.throws(
makeBlock(a.deepStrictEqual, /ab/, /a/),
/^AssertionError: \/ab\/ deepStrictEqual \/a\/$/
);
assert.throws(
makeBlock(a.deepStrictEqual, /a/g, /a/),
/^AssertionError: \/a\/g deepStrictEqual \/a\/$/
);
assert.throws(
makeBlock(a.deepStrictEqual, /a/i, /a/),
/^AssertionError: \/a\/i deepStrictEqual \/a\/$/
);
assert.throws(
makeBlock(a.deepStrictEqual, /a/m, /a/),
/^AssertionError: \/a\/m deepStrictEqual \/a\/$/
);
assert.throws(
makeBlock(a.deepStrictEqual, /a/igm, /a/im),
/^AssertionError: \/a\/gim deepStrictEqual \/a\/im$/
);
{
const re1 = /a/;
re1.lastIndex = 3;
assert.throws(makeBlock(a.deepStrictEqual, re1, /a/));
}
// 7.4 - strict
assert.throws(makeBlock(a.deepStrictEqual, 4, '4'),
a.AssertionError,
'deepStrictEqual(4, \'4\')');
assert.throws(makeBlock(a.deepStrictEqual, true, 1),
a.AssertionError,
'deepStrictEqual(true, 1)');
assert.throws(makeBlock(a.deepStrictEqual, 4, '5'),
a.AssertionError,
'deepStrictEqual(4, \'5\')');
// 7.5 - strict
// having the same number of owned properties && the same set of keys
assert.doesNotThrow(makeBlock(a.deepStrictEqual, {a: 4}, {a: 4}));
assert.doesNotThrow(makeBlock(a.deepStrictEqual,
{a: 4, b: '2'},
{a: 4, b: '2'}));
assert.throws(makeBlock(a.deepStrictEqual, [4], ['4']));
assert.throws(makeBlock(a.deepStrictEqual, {a: 4}, {a: 4, b: true}),
a.AssertionError);
assert.throws(makeBlock(a.deepStrictEqual, ['a'], {0: 'a'}));
//(although not necessarily the same order),
assert.doesNotThrow(makeBlock(a.deepStrictEqual,
{a: 4, b: '1'},
{b: '1', a: 4}));
assert.throws(makeBlock(a.deepStrictEqual,
[0, 1, 2, 'a', 'b'],
[0, 1, 2, 'b', 'a']),
a.AssertionError);
assert.doesNotThrow(makeBlock(a.deepStrictEqual, a1, a2));
// Prototype check
function Constructor1(first, last) {
this.first = first;
this.last = last;
}
function Constructor2(first, last) {
this.first = first;
this.last = last;
}
var obj1 = new Constructor1('Ryan', 'Dahl');
var obj2 = new Constructor2('Ryan', 'Dahl');
assert.throws(makeBlock(a.deepStrictEqual, obj1, obj2), a.AssertionError);
Constructor2.prototype = Constructor1.prototype;
obj2 = new Constructor2('Ryan', 'Dahl');
assert.doesNotThrow(makeBlock(a.deepStrictEqual, obj1, obj2));
// primitives
assert.throws(makeBlock(assert.deepStrictEqual, 4, '4'),
a.AssertionError);
assert.throws(makeBlock(assert.deepStrictEqual, true, 1),
a.AssertionError);
if (!node_0_12) {
assert.throws(makeBlock(assert.deepStrictEqual, Symbol(), Symbol()),
a.AssertionError);
var s = Symbol();
assert.doesNotThrow(makeBlock(assert.deepStrictEqual, s, s));
}
// primitives and object
assert.throws(makeBlock(a.deepStrictEqual, null, {}), a.AssertionError);
assert.throws(makeBlock(a.deepStrictEqual, undefined, {}), a.AssertionError);
assert.throws(makeBlock(a.deepStrictEqual, 'a', ['a']), a.AssertionError);
assert.throws(makeBlock(a.deepStrictEqual, 'a', {0: 'a'}), a.AssertionError);
assert.throws(makeBlock(a.deepStrictEqual, 1, {}), a.AssertionError);
assert.throws(makeBlock(a.deepStrictEqual, true, {}), a.AssertionError);
if (!node_0_12) {
assert.throws(makeBlock(assert.deepStrictEqual, Symbol(), {}),
a.AssertionError);
}
// primitive wrappers and object
assert.throws(makeBlock(a.deepStrictEqual, new String('a'), ['a']),
a.AssertionError);
assert.throws(makeBlock(a.deepStrictEqual, new String('a'), {0: 'a'}),
a.AssertionError);
assert.throws(makeBlock(a.deepStrictEqual, new Number(1), {}),
a.AssertionError);
assert.throws(makeBlock(a.deepStrictEqual, new Boolean(true), {}),
a.AssertionError);
// Testing the throwing
function thrower(errorConstructor) {
throw new errorConstructor('test');
}
// the basic calls work
assert.throws(makeBlock(thrower, a.AssertionError),
a.AssertionError, 'message');
assert.throws(makeBlock(thrower, a.AssertionError), a.AssertionError);
assert.throws(makeBlock(thrower, a.AssertionError));
// if not passing an error, catch all.
assert.throws(makeBlock(thrower, TypeError));
// when passing a type, only catch errors of the appropriate type
var threw = false;
try {
a.throws(makeBlock(thrower, TypeError), a.AssertionError);
} catch (e) {
threw = true;
assert.ok(e instanceof TypeError, 'type');
}
assert.equal(true, threw,
'a.throws with an explicit error is eating extra errors',
a.AssertionError);
threw = false;
// doesNotThrow should pass through all errors
try {
a.doesNotThrow(makeBlock(thrower, TypeError), a.AssertionError);
} catch (e) {
threw = true;
assert.ok(e instanceof TypeError);
}
assert.equal(true, threw,
'a.doesNotThrow with an explicit error is eating extra errors');
// key difference is that throwing our correct error makes an assertion error
try {
a.doesNotThrow(makeBlock(thrower, TypeError), TypeError);
} catch (e) {
threw = true;
assert.ok(e instanceof a.AssertionError);
}
assert.equal(true, threw,
'a.doesNotThrow is not catching type matching errors');
assert.throws(function() { assert.ifError(new Error('test error')); },
/^Error: test error$/);
assert.doesNotThrow(function() { assert.ifError(null); });
assert.doesNotThrow(function() { assert.ifError(); });
assert.throws(() => {
assert.doesNotThrow(makeBlock(thrower, Error), 'user message');
}, /Got unwanted exception. user message/,
'a.doesNotThrow ignores user message');
// make sure that validating using constructor really works
threw = false;
try {
assert.throws(
function() {
throw ({});
},
Array
);
} catch (e) {
threw = true;
}
assert.ok(threw, 'wrong constructor validation');
// use a RegExp to validate error message
a.throws(makeBlock(thrower, TypeError), /test/);
// use a fn to validate error object
a.throws(makeBlock(thrower, TypeError), function(err) {
if ((err instanceof TypeError) && /test/.test(err)) {
return true;
}
});
// // https://github.com/nodejs/node/issues/3188
// threw = false;
// try {
// var ES6Error = class extends Error {};
// var AnotherErrorType = class extends Error {};
// const functionThatThrows = function() {
// throw new AnotherErrorType('foo');
// };
// assert.throws(functionThatThrows, ES6Error);
// } catch (e) {
// threw = true;
// assert(e instanceof AnotherErrorType,
// `expected AnotherErrorType, received ${e}`);
// }
// assert.ok(threw);
// https://github.com/nodejs/node/issues/6416
// Make sure circular refs don't throw.
{
const b = {};
b.b = b;
const c = {};
c.b = c;
a.doesNotThrow(makeBlock(a.deepEqual, b, c));
a.doesNotThrow(makeBlock(a.deepStrictEqual, b, c));
const d = {};
d.a = 1;
d.b = d;
const e = {};
e.a = 1;
e.b = e.a;
a.throws(makeBlock(a.deepEqual, d, e), /AssertionError/);
a.throws(makeBlock(a.deepStrictEqual, d, e), /AssertionError/);
}
// GH-7178. Ensure reflexivity of deepEqual with `arguments` objects.
var args = (function() { return arguments; })();
a.throws(makeBlock(a.deepEqual, [], args));
a.throws(makeBlock(a.deepEqual, args, []));
// more checking that arguments objects are handled correctly
{
const returnArguments = function() { return arguments; };
const someArgs = returnArguments('a');
const sameArgs = returnArguments('a');
const diffArgs = returnArguments('b');
a.throws(makeBlock(a.deepEqual, someArgs, ['a']));
a.throws(makeBlock(a.deepEqual, ['a'], someArgs));
a.throws(makeBlock(a.deepEqual, someArgs, {'0': 'a'}));
a.throws(makeBlock(a.deepEqual, someArgs, diffArgs));
a.doesNotThrow(makeBlock(a.deepEqual, someArgs, sameArgs));
}
var circular = {y: 1};
circular.x = circular;
function testAssertionMessage(actual, expected) {
try {
assert.equal(actual, '');
} catch (e) {
assert.equal(e.toString(),
['AssertionError:', expected, '==', '\'\''].join(' '));
assert.ok(e.generatedMessage, 'Message not marked as generated');
}
}
testAssertionMessage(undefined, 'undefined');
testAssertionMessage(null, 'null');
testAssertionMessage(true, 'true');
testAssertionMessage(false, 'false');
testAssertionMessage(0, '0');
testAssertionMessage(100, '100');
testAssertionMessage(NaN, 'NaN');
testAssertionMessage(Infinity, 'Infinity');
testAssertionMessage(-Infinity, '-Infinity');
testAssertionMessage('', '""');
testAssertionMessage('foo', '\'foo\'');
testAssertionMessage([], '[]');
testAssertionMessage([1, 2, 3], '[ 1, 2, 3 ]');
testAssertionMessage(/a/, '/a/');
testAssertionMessage(/abc/gim, '/abc/gim');
testAssertionMessage(function f() {}, '[Function: f]');
testAssertionMessage(function() {}, '[Function]');
testAssertionMessage({}, '{}');
testAssertionMessage(circular, '{ y: 1, x: [Circular] }');
testAssertionMessage({a: undefined, b: null}, '{ a: undefined, b: null }');
testAssertionMessage({a: NaN, b: Infinity, c: -Infinity},
'{ a: NaN, b: Infinity, c: -Infinity }');
// #2893
try {
assert.throws(function() {
assert.ifError(null);
});
} catch (e) {
threw = true;
assert.equal(e.message, 'Missing expected exception..');
}
assert.ok(threw);
// #5292
try {
assert.equal(1, 2);
} catch (e) {
assert.equal(e.toString().split('\n')[0], 'AssertionError: 1 == 2');
assert.ok(e.generatedMessage, 'Message not marked as generated');
}
try {
assert.equal(1, 2, 'oh no');
} catch (e) {
assert.equal(e.toString().split('\n')[0], 'AssertionError: oh no');
assert.equal(e.generatedMessage, false,
'Message incorrectly marked as generated');
}
// Verify that throws() and doesNotThrow() throw on non-function block
function testBlockTypeError(method, block) {
var threw = true;
try {
method(block);
threw = false;
} catch (e) {
assert.equal(e.toString(),
'TypeError: "block" argument must be a function');
}
assert.ok(threw);
}
testBlockTypeError(assert.throws, 'string');
testBlockTypeError(assert.doesNotThrow, 'string');
testBlockTypeError(assert.throws, 1);
testBlockTypeError(assert.doesNotThrow, 1);
testBlockTypeError(assert.throws, true);
testBlockTypeError(assert.doesNotThrow, true);
testBlockTypeError(assert.throws, false);
testBlockTypeError(assert.doesNotThrow, false);
testBlockTypeError(assert.throws, []);
testBlockTypeError(assert.doesNotThrow, []);
testBlockTypeError(assert.throws, {});
testBlockTypeError(assert.doesNotThrow, {});
testBlockTypeError(assert.throws, /foo/);
testBlockTypeError(assert.doesNotThrow, /foo/);
testBlockTypeError(assert.throws, null);
testBlockTypeError(assert.doesNotThrow, null);
testBlockTypeError(assert.throws, undefined);
testBlockTypeError(assert.doesNotThrow, undefined);
// https://github.com/nodejs/node/issues/3275
assert.throws(() => { throw 'error'; }, (err) => err === 'error');
assert.throws(() => { throw new Error(); }, (err) => err instanceof Error);
var repeat = (char, n) => Array(n+1).join().split('').map(() => char).join('')
// Long values should be truncated for display.
assert.throws(() => {
// assert.strictEqual('A'.repeat(1000), '');
assert.equal(repeat('A', 3), 'AAA')
assert.equal(repeat('A', 4), 'AAAA')
assert.strictEqual(repeat('A', 1000), '');
// }, new RegExp(`^AssertionError: '${'A'.repeat(127)} === ''$`));
}, new RegExp(`^AssertionError: '${repeat('A', 127)} === ''$`));
})
})
|
/*
Highcharts JS v9.0.1 (2021-02-15)
(c) 2009-2021 Torstein Honsi
License: www.highcharts.com/license
*/
(function(c){"object"===typeof module&&module.exports?(c["default"]=c,module.exports=c):"function"===typeof define&&define.amd?define("highcharts/modules/broken-axis",["highcharts"],function(h){c(h);c.Highcharts=h;return c}):c("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(c){function h(c,h,w,k){c.hasOwnProperty(h)||(c[h]=k.apply(null,w))}c=c?c._modules:{};h(c,"Core/Axis/BrokenAxis.js",[c["Core/Axis/Axis.js"],c["Core/Series/Series.js"],c["Extensions/Stacking.js"],c["Core/Utilities.js"]],
function(c,h,w,k){var r=k.addEvent,A=k.find,y=k.fireEvent,B=k.isArray,z=k.isNumber,t=k.pick,C=function(){function l(b){this.hasBreaks=!1;this.axis=b}l.isInBreak=function(b,e){var d=b.repeat||Infinity,a=b.from,f=b.to-b.from;e=e>=a?(e-a)%d:d-(a-e)%d;return b.inclusive?e<=f:e<f&&0!==e};l.lin2Val=function(b){var e=this.brokenAxis;e=e&&e.breakArray;if(!e)return b;var d;for(d=0;d<e.length;d++){var a=e[d];if(a.from>=b)break;else a.to<b?b+=a.len:l.isInBreak(a,b)&&(b+=a.len)}return b};l.val2Lin=function(b){var e=
this.brokenAxis;e=e&&e.breakArray;if(!e)return b;var d=b,a;for(a=0;a<e.length;a++){var f=e[a];if(f.to<=b)d-=f.len;else if(f.from>=b)break;else if(l.isInBreak(f,b)){d-=b-f.from;break}}return d};l.prototype.findBreakAt=function(b,e){return A(e,function(d){return d.from<b&&b<d.to})};l.prototype.isInAnyBreak=function(b,e){var d=this.axis,a=d.options.breaks,f=a&&a.length,u;if(f){for(;f--;)if(l.isInBreak(a[f],b)){var p=!0;u||(u=t(a[f].showPoints,!d.isXAxis))}var c=p&&e?p&&!u:p}return c};l.prototype.setBreaks=
function(b,e){var d=this,a=d.axis,f=B(b)&&!!b.length;a.isDirty=d.hasBreaks!==f;d.hasBreaks=f;a.options.breaks=a.userOptions.breaks=b;a.forceRedraw=!0;a.series.forEach(function(a){a.isDirty=!0});f||a.val2lin!==l.val2Lin||(delete a.val2lin,delete a.lin2val);f&&(a.userOptions.ordinal=!1,a.lin2val=l.lin2Val,a.val2lin=l.val2Lin,a.setExtremes=function(a,b,f,g,e){if(d.hasBreaks){for(var p,u=this.options.breaks;p=d.findBreakAt(a,u);)a=p.to;for(;p=d.findBreakAt(b,u);)b=p.from;b<a&&(b=a)}c.prototype.setExtremes.call(this,
a,b,f,g,e)},a.setAxisTranslation=function(){c.prototype.setAxisTranslation.call(this);d.unitLength=null;if(d.hasBreaks){var b=a.options.breaks||[],f=[],e=[],g=0,m,q=a.userMin||a.min,h=a.userMax||a.max,k=t(a.pointRangePadding,0),v;b.forEach(function(a){m=a.repeat||Infinity;l.isInBreak(a,q)&&(q+=a.to%m-q%m);l.isInBreak(a,h)&&(h-=h%m-a.from%m)});b.forEach(function(a){n=a.from;for(m=a.repeat||Infinity;n-m>q;)n-=m;for(;n<q;)n+=m;for(v=n;v<h;v+=m)f.push({value:v,move:"in"}),f.push({value:v+(a.to-a.from),
move:"out",size:a.breakSize})});f.sort(function(a,b){return a.value===b.value?("in"===a.move?0:1)-("in"===b.move?0:1):a.value-b.value});var x=0;var n=q;f.forEach(function(a){x+="in"===a.move?1:-1;1===x&&"in"===a.move&&(n=a.value);0===x&&(e.push({from:n,to:a.value,len:a.value-n-(a.size||0)}),g+=a.value-n-(a.size||0))});a.breakArray=d.breakArray=e;d.unitLength=h-q-g+k;y(a,"afterBreaks");a.staticScale?a.transA=a.staticScale:d.unitLength&&(a.transA*=(h-a.min+k)/d.unitLength);k&&(a.minPixelPadding=a.transA*
a.minPointOffset);a.min=q;a.max=h}});t(e,!0)&&a.chart.redraw()};return l}();k=function(){function c(){}c.compose=function(b,e){b.keepProps.push("brokenAxis");var d=h.prototype;d.drawBreaks=function(a,b){var f=this,e=f.points,d,g,c,h;if(a&&a.brokenAxis&&a.brokenAxis.hasBreaks){var k=a.brokenAxis;b.forEach(function(b){d=k&&k.breakArray||[];g=a.isXAxis?a.min:t(f.options.threshold,a.min);e.forEach(function(f){h=t(f["stack"+b.toUpperCase()],f[b]);d.forEach(function(b){if(z(g)&&z(h)){c=!1;if(g<b.from&&
h>b.to||g>b.from&&h<b.from)c="pointBreak";else if(g<b.from&&h>b.from&&h<b.to||g>b.from&&h>b.to&&h<b.from)c="pointInBreak";c&&y(a,c,{point:f,brk:b})}})})})}};d.gappedPath=function(){var a=this.currentDataGrouping,b=a&&a.gapSize;a=this.options.gapSize;var e=this.points.slice(),d=e.length-1,c=this.yAxis,g;if(a&&0<d)for("value"!==this.options.gapUnit&&(a*=this.basePointRange),b&&b>a&&b>=this.basePointRange&&(a=b),g=void 0;d--;)g&&!1!==g.visible||(g=e[d+1]),b=e[d],!1!==g.visible&&!1!==b.visible&&(g.x-
b.x>a&&(g=(b.x+g.x)/2,e.splice(d+1,0,{isNull:!0,x:g}),c.stacking&&this.options.stacking&&(g=c.stacking.stacks[this.stackKey][g]=new w(c,c.options.stackLabels,!1,g,this.stack),g.total=0)),g=b);return this.getGraphPath(e)};r(b,"init",function(){this.brokenAxis||(this.brokenAxis=new C(this))});r(b,"afterInit",function(){"undefined"!==typeof this.brokenAxis&&this.brokenAxis.setBreaks(this.options.breaks,!1)});r(b,"afterSetTickPositions",function(){var a=this.brokenAxis;if(a&&a.hasBreaks){var b=this.tickPositions,
e=this.tickPositions.info,d=[],c;for(c=0;c<b.length;c++)a.isInAnyBreak(b[c])||d.push(b[c]);this.tickPositions=d;this.tickPositions.info=e}});r(b,"afterSetOptions",function(){this.brokenAxis&&this.brokenAxis.hasBreaks&&(this.options.ordinal=!1)});r(e,"afterGeneratePoints",function(){var a=this.options.connectNulls,b=this.points,c=this.xAxis,d=this.yAxis;if(this.isDirty)for(var e=b.length;e--;){var g=b[e],h=!(null===g.y&&!1===a)&&(c&&c.brokenAxis&&c.brokenAxis.isInAnyBreak(g.x,!0)||d&&d.brokenAxis&&
d.brokenAxis.isInAnyBreak(g.y,!0));g.visible=h?!1:!1!==g.options.visible}});r(e,"afterRender",function(){this.drawBreaks(this.xAxis,["x"]);this.drawBreaks(this.yAxis,t(this.pointArrayMap,["y"]))})};return c}();k.compose(c,h);return k});h(c,"masters/modules/broken-axis.src.js",[],function(){})});
//# sourceMappingURL=broken-axis.js.map |
(function() {
return {
name: 'fr',
weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),
weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),
weekdaysMin: 'di_lu_ma_me_je_ve_sa'.split('_'),
months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),
monthsShort: 'janv_févr_mars_avril_mai_juin_juil_août_sept_oct_nov_déc'.split('_'),
weekStart: 1,
formats: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'DD/MM/YYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY HH:mm',
LLLL: 'dddd D MMMM YYYY HH:mm'
},
relativeTime: {
future: 'dans %s',
past: 'il y a %s',
s: 'quelques secondes',
m: 'une minute',
mm: '%d minutes',
h: 'une heure',
hh: '%d heures',
d: 'un jour',
dd: '%d jours',
M: 'un mois',
MM: '%d mois',
y: 'un an',
yy: '%d ans'
},
ordinal: function(n) {
var o = n === 1 ? 'er' : '';
return '' + n + o;
}
};
})();
|
/*!
Autosize v1.18.6 - 2014-03-13
Automatically adjust textarea height based on user input.
(c) 2014 Jack Moore - http://www.jacklmoore.com/autosize
license: http://www.opensource.org/licenses/mit-license.php
*/
(function ($) {
var
defaults = {
className: 'autosizejs',
id: 'autosizejs',
append: '',
callback: false,
resizeDelay: 10,
placeholder: true
},
// border:0 is unnecessary, but avoids a bug in Firefox on OSX
copy = '<textarea tabindex="-1" style="position:absolute; top:-999px; left:0; right:auto; bottom:auto; border:0; padding: 0; -moz-box-sizing:content-box; -webkit-box-sizing:content-box; box-sizing:content-box; word-wrap:break-word; height:0 !important; min-height:0 !important; overflow:hidden; transition:none; -webkit-transition:none; -moz-transition:none;"/>',
// line-height is conditionally included because IE7/IE8/old Opera do not return the correct value.
typographyStyles = [
'fontFamily',
'fontSize',
'fontWeight',
'fontStyle',
'letterSpacing',
'textTransform',
'wordSpacing',
'textIndent'
],
// to keep track which textarea is being mirrored when adjust() is called.
mirrored,
// the mirror element, which is used to calculate what size the mirrored element should be.
mirror = $(copy).data('autosize', true)[0];
// test that line-height can be accurately copied.
mirror.style.lineHeight = '99px';
if ($(mirror).css('lineHeight') === '99px') {
typographyStyles.push('lineHeight');
}
mirror.style.lineHeight = '';
$.fn.autosize = function (options) {
if (!this.length) {
return this;
}
options = $.extend({}, defaults, options || {});
if (mirror.parentNode !== document.body) {
$(document.body).append(mirror);
}
return this.each(function () {
var
ta = this,
$ta = $(ta),
maxHeight,
minHeight,
boxOffset = 0,
callback = $.isFunction(options.callback),
originalStyles = {
height: ta.style.height,
overflow: ta.style.overflow,
overflowY: ta.style.overflowY,
wordWrap: ta.style.wordWrap,
resize: ta.style.resize
},
timeout,
width = $ta.width();
if ($ta.data('autosize')) {
// exit if autosize has already been applied, or if the textarea is the mirror element.
return;
}
$ta.data('autosize', true);
if ($ta.css('box-sizing') === 'border-box' || $ta.css('-moz-box-sizing') === 'border-box' || $ta.css('-webkit-box-sizing') === 'border-box'){
boxOffset = $ta.outerHeight() - $ta.height();
}
// IE8 and lower return 'auto', which parses to NaN, if no min-height is set.
minHeight = Math.max(parseInt($ta.css('minHeight'), 10) - boxOffset || 0, $ta.height());
$ta.css({
overflow: 'hidden',
overflowY: 'hidden',
wordWrap: 'break-word', // horizontal overflow is hidden, so break-word is necessary for handling words longer than the textarea width
resize: ($ta.css('resize') === 'none' || $ta.css('resize') === 'vertical') ? 'none' : 'horizontal'
});
// The mirror width must exactly match the textarea width, so using getBoundingClientRect because it doesn't round the sub-pixel value.
// window.getComputedStyle, getBoundingClientRect returning a width are unsupported, but also unneeded in IE8 and lower.
function setWidth() {
var width;
var style = window.getComputedStyle ? window.getComputedStyle(ta, null) : false;
if (style) {
width = ta.getBoundingClientRect().width;
if (width === 0) {
width = parseInt(style.width,10);
}
$.each(['paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'], function(i,val){
width -= parseInt(style[val],10);
});
} else {
width = Math.max($ta.width(), 0);
}
mirror.style.width = width + 'px';
}
function initMirror() {
var styles = {};
mirrored = ta;
mirror.className = options.className;
mirror.id = options.id;
maxHeight = parseInt($ta.css('maxHeight'), 10);
// mirror is a duplicate textarea located off-screen that
// is automatically updated to contain the same text as the
// original textarea. mirror always has a height of 0.
// This gives a cross-browser supported way getting the actual
// height of the text, through the scrollTop property.
$.each(typographyStyles, function(i,val){
styles[val] = $ta.css(val);
});
$(mirror).css(styles).attr('wrap', $ta.attr('wrap'));
setWidth();
// Chrome-specific fix:
// When the textarea y-overflow is hidden, Chrome doesn't reflow the text to account for the space
// made available by removing the scrollbar. This workaround triggers the reflow for Chrome.
if (window.chrome) {
var width = ta.style.width;
ta.style.width = '0px';
var ignore = ta.offsetWidth;
ta.style.width = width;
}
}
// Using mainly bare JS in this function because it is going
// to fire very often while typing, and needs to very efficient.
function adjust() {
var height, original;
if (mirrored !== ta) {
initMirror();
} else {
setWidth();
}
if (!ta.value && options.placeholder) {
// If the textarea is empty, copy the placeholder text into
// the mirror control and use that for sizing so that we
// don't end up with placeholder getting trimmed.
mirror.value = ($ta.attr("placeholder") || '') + options.append;
} else {
mirror.value = ta.value + options.append;
}
mirror.style.overflowY = ta.style.overflowY;
original = parseInt(ta.style.height,10);
// Setting scrollTop to zero is needed in IE8 and lower for the next step to be accurately applied
mirror.scrollTop = 0;
mirror.scrollTop = 9e4;
// Using scrollTop rather than scrollHeight because scrollHeight is non-standard and includes padding.
height = mirror.scrollTop;
if (maxHeight && height > maxHeight) {
ta.style.overflowY = 'scroll';
height = maxHeight;
} else {
ta.style.overflowY = 'hidden';
if (height < minHeight) {
height = minHeight;
}
}
height += boxOffset;
if (original !== height) {
ta.style.height = height + 'px';
if (callback) {
options.callback.call(ta,ta);
}
}
}
function resize () {
clearTimeout(timeout);
timeout = setTimeout(function(){
var newWidth = $ta.width();
if (newWidth !== width) {
width = newWidth;
adjust();
}
}, parseInt(options.resizeDelay,10));
}
if ('onpropertychange' in ta) {
if ('oninput' in ta) {
// Detects IE9. IE9 does not fire onpropertychange or oninput for deletions,
// so binding to onkeyup to catch most of those occasions. There is no way that I
// know of to detect something like 'cut' in IE9.
$ta.on('input.autosize keyup.autosize', adjust);
} else {
// IE7 / IE8
$ta.on('propertychange.autosize', function(){
if(event.propertyName === 'value'){
adjust();
}
});
}
} else {
// Modern Browsers
$ta.on('input.autosize', adjust);
}
// Set options.resizeDelay to false if using fixed-width textarea elements.
// Uses a timeout and width check to reduce the amount of times adjust needs to be called after window resize.
if (options.resizeDelay !== false) {
$(window).on('resize.autosize', resize);
}
// Event for manual triggering if needed.
// Should only be needed when the value of the textarea is changed through JavaScript rather than user input.
$ta.on('autosize.resize', adjust);
// Event for manual triggering that also forces the styles to update as well.
// Should only be needed if one of typography styles of the textarea change, and the textarea is already the target of the adjust method.
$ta.on('autosize.resizeIncludeStyle', function() {
mirrored = null;
adjust();
});
$ta.on('autosize.destroy', function(){
mirrored = null;
clearTimeout(timeout);
$(window).off('resize', resize);
$ta
.off('autosize')
.off('.autosize')
.css(originalStyles)
.removeData('autosize');
});
// Call adjust in case the textarea already contains text.
adjust();
});
};
}(window.jQuery || window.$)); // jQuery or jQuery-like library, such as Zepto
|
/**
* @license
* Lo-Dash 1.2.0 <http://lodash.com/>
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.4.4 <http://underscorejs.org/>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
* Available under MIT license <http://lodash.com/license>
*/
;(function(window) {
/** Used as a safe reference for `undefined` in pre ES5 environments */
var undefined;
/** Detect free variable `exports` */
var freeExports = typeof exports == 'object' && exports;
/** Detect free variable `module` */
var freeModule = typeof module == 'object' && module && module.exports == freeExports && module;
/** Detect free variable `global`, from Node.js or Browserified code, and use it as `window` */
var freeGlobal = typeof global == 'object' && global;
if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
window = freeGlobal;
}
/** Used to generate unique IDs */
var idCounter = 0;
/** Used internally to indicate various things */
var indicatorObject = {};
/** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */
var keyPrefix = +new Date + '';
/** Used as the size when optimizations are enabled for large arrays */
var largeArraySize = 200;
/** Used to match empty string literals in compiled template source */
var reEmptyStringLeading = /\b__p \+= '';/g,
reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
/** Used to match HTML entities */
var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g;
/**
* Used to match ES6 template delimiters
* http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.8.6
*/
var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
/** Used to match regexp flags from their coerced string values */
var reFlags = /\w*$/;
/** Used to match "interpolate" template delimiters */
var reInterpolate = /<%=([\s\S]+?)%>/g;
/** Used to match leading zeros to be removed */
var reLeadingZeros = /^0+(?=.$)/;
/** Used to ensure capturing order of template delimiters */
var reNoMatch = /($^)/;
/** Used to match HTML characters */
var reUnescapedHtml = /[&<>"']/g;
/** Used to match unescaped characters in compiled string literals */
var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g;
/** Used to assign default `context` object properties */
var contextProps = [
'Array', 'Boolean', 'Date', 'Function', 'Math', 'Number', 'Object', 'RegExp',
'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN', 'parseInt',
'setImmediate', 'setTimeout'
];
/** Used to fix the JScript [[DontEnum]] bug */
var shadowedProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
'toLocaleString', 'toString', 'valueOf'
];
/** Used to make template sourceURLs easier to identify */
var templateCounter = 0;
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
/** Used to identify object classifications that `_.clone` supports */
var cloneableClasses = {};
cloneableClasses[funcClass] = false;
cloneableClasses[argsClass] = cloneableClasses[arrayClass] =
cloneableClasses[boolClass] = cloneableClasses[dateClass] =
cloneableClasses[numberClass] = cloneableClasses[objectClass] =
cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true;
/** Used to determine if values are of the language type Object */
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
/** Used to escape characters for inclusion in compiled string literals */
var stringEscapes = {
'\\': '\\',
"'": "'",
'\n': 'n',
'\r': 'r',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
/*--------------------------------------------------------------------------*/
/**
* Create a new `lodash` function using the given `context` object.
*
* @static
* @memberOf _
* @category Utilities
* @param {Object} [context=window] The context object.
* @returns {Function} Returns the `lodash` function.
*/
function runInContext(context) {
// Avoid issues with some ES3 environments that attempt to use values, named
// after built-in constructors like `Object`, for the creation of literals.
// ES5 clears this up by stating that literals must use built-in constructors.
// See http://es5.github.com/#x11.1.5.
context = context ? _.defaults(window.Object(), context, _.pick(window, contextProps)) : window;
/** Native constructor references */
var Array = context.Array,
Boolean = context.Boolean,
Date = context.Date,
Function = context.Function,
Math = context.Math,
Number = context.Number,
Object = context.Object,
RegExp = context.RegExp,
String = context.String,
TypeError = context.TypeError;
/** Used for `Array` and `Object` method references */
var arrayRef = Array(),
objectRef = Object();
/** Used to restore the original `_` reference in `noConflict` */
var oldDash = context._;
/** Used to detect if a method is native */
var reNative = RegExp('^' +
String(objectRef.valueOf)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/valueOf|for [^\]]+/g, '.+?') + '$'
);
/** Native method shortcuts */
var ceil = Math.ceil,
clearTimeout = context.clearTimeout,
concat = arrayRef.concat,
floor = Math.floor,
getPrototypeOf = reNative.test(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf,
hasOwnProperty = objectRef.hasOwnProperty,
push = arrayRef.push,
setImmediate = context.setImmediate,
setTimeout = context.setTimeout,
toString = objectRef.toString;
/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeBind = reNative.test(nativeBind = toString.bind) && nativeBind,
nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray,
nativeIsFinite = context.isFinite,
nativeIsNaN = context.isNaN,
nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys,
nativeMax = Math.max,
nativeMin = Math.min,
nativeParseInt = context.parseInt,
nativeRandom = Math.random,
nativeSlice = arrayRef.slice;
/** Detect various environments */
var isIeOpera = reNative.test(context.attachEvent),
isV8 = nativeBind && !/\n|true/.test(nativeBind + isIeOpera);
/** Used to lookup a built-in constructor by [[Class]] */
var ctorByClass = {};
ctorByClass[arrayClass] = Array;
ctorByClass[boolClass] = Boolean;
ctorByClass[dateClass] = Date;
ctorByClass[objectClass] = Object;
ctorByClass[numberClass] = Number;
ctorByClass[regexpClass] = RegExp;
ctorByClass[stringClass] = String;
/*--------------------------------------------------------------------------*/
/**
* Creates a `lodash` object, which wraps the given `value`, to enable method
* chaining.
*
* In addition to Lo-Dash methods, wrappers also have the following `Array` methods:
* `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`,
* and `unshift`
*
* Chaining is supported in custom builds as long as the `value` method is
* implicitly or explicitly included in the build.
*
* The chainable wrapper functions are:
* `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`,
* `compose`, `concat`, `countBy`, `createCallback`, `debounce`, `defaults`,
* `defer`, `delay`, `difference`, `filter`, `flatten`, `forEach`, `forIn`,
* `forOwn`, `functions`, `groupBy`, `initial`, `intersection`, `invert`,
* `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`,
* `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `push`, `range`,
* `reject`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, `sortBy`, `splice`,
* `tap`, `throttle`, `times`, `toArray`, `union`, `uniq`, `unshift`, `unzip`,
* `values`, `where`, `without`, `wrap`, and `zip`
*
* The non-chainable wrapper functions are:
* `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `has`,
* `identity`, `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`,
* `isElement`, `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`,
* `isNull`, `isNumber`, `isObject`, `isPlainObject`, `isRegExp`, `isString`,
* `isUndefined`, `join`, `lastIndexOf`, `mixin`, `noConflict`, `parseInt`,
* `pop`, `random`, `reduce`, `reduceRight`, `result`, `shift`, `size`, `some`,
* `sortedIndex`, `runInContext`, `template`, `unescape`, `uniqueId`, and `value`
*
* The wrapper functions `first` and `last` return wrapped values when `n` is
* passed, otherwise they return unwrapped values.
*
* @name _
* @constructor
* @category Chaining
* @param {Mixed} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns a `lodash` instance.
* @example
*
* var wrapped = _([1, 2, 3]);
*
* // returns an unwrapped value
* wrapped.reduce(function(sum, num) {
* return sum + num;
* });
* // => 6
*
* // returns a wrapped value
* var squares = wrapped.map(function(num) {
* return num * num;
* });
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
// don't wrap if already wrapped, even if wrapped by a different `lodash` constructor
return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__'))
? value
: new lodashWrapper(value);
}
/**
* An object used to flag environments features.
*
* @static
* @memberOf _
* @type Object
*/
var support = lodash.support = {};
(function() {
var ctor = function() { this.x = 1; },
object = { '0': 1, 'length': 1 },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var prop in new ctor) { props.push(prop); }
for (prop in arguments) { }
/**
* Detect if `arguments` objects are `Object` objects (all but Narwhal and Opera < 10.5).
*
* @memberOf _.support
* @type Boolean
*/
support.argsObject = arguments.constructor == Object && !(arguments instanceof Array);
/**
* Detect if an `arguments` object's [[Class]] is resolvable (all but Firefox < 4, IE < 9).
*
* @memberOf _.support
* @type Boolean
*/
support.argsClass = isArguments(arguments);
/**
* Detect if `prototype` properties are enumerable by default.
*
* Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
* (if the prototype or a property on the prototype has been set)
* incorrectly sets a function's `prototype` property [[Enumerable]]
* value to `true`.
*
* @memberOf _.support
* @type Boolean
*/
support.enumPrototypes = ctor.propertyIsEnumerable('prototype');
/**
* Detect if `Function#bind` exists and is inferred to be fast (all but V8).
*
* @memberOf _.support
* @type Boolean
*/
support.fastBind = nativeBind && !isV8;
/**
* Detect if own properties are iterated after inherited properties (all but IE < 9).
*
* @memberOf _.support
* @type Boolean
*/
support.ownLast = props[0] != 'x';
/**
* Detect if `arguments` object indexes are non-enumerable
* (Firefox < 4, IE < 9, PhantomJS, Safari < 5.1).
*
* @memberOf _.support
* @type Boolean
*/
support.nonEnumArgs = prop != 0;
/**
* Detect if properties shadowing those on `Object.prototype` are non-enumerable.
*
* In IE < 9 an objects own properties, shadowing non-enumerable ones, are
* made non-enumerable as well (a.k.a the JScript [[DontEnum]] bug).
*
* @memberOf _.support
* @type Boolean
*/
support.nonEnumShadows = !/valueOf/.test(props);
/**
* Detect if `Array#shift` and `Array#splice` augment array-like objects correctly.
*
* Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array `shift()`
* and `splice()` functions that fail to remove the last element, `value[0]`,
* of array-like objects even though the `length` property is set to `0`.
* The `shift()` method is buggy in IE 8 compatibility mode, while `splice()`
* is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9.
*
* @memberOf _.support
* @type Boolean
*/
support.spliceObjects = (arrayRef.splice.call(object, 0, 1), !object[0]);
/**
* Detect lack of support for accessing string characters by index.
*
* IE < 8 can't access characters by index and IE 8 can only access
* characters by index on string literals.
*
* @memberOf _.support
* @type Boolean
*/
support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx';
/**
* Detect if a DOM node's [[Class]] is resolvable (all but IE < 9)
* and that the JS engine errors when attempting to coerce an object to
* a string without a `toString` function.
*
* @memberOf _.support
* @type Boolean
*/
try {
support.nodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
support.nodeClass = true;
}
}(1));
/**
* By default, the template delimiters used by Lo-Dash are similar to those in
* embedded Ruby (ERB). Change the following template settings to use alternative
* delimiters.
*
* @static
* @memberOf _
* @type Object
*/
lodash.templateSettings = {
/**
* Used to detect `data` property values to be HTML-escaped.
*
* @memberOf _.templateSettings
* @type RegExp
*/
'escape': /<%-([\s\S]+?)%>/g,
/**
* Used to detect code to be evaluated.
*
* @memberOf _.templateSettings
* @type RegExp
*/
'evaluate': /<%([\s\S]+?)%>/g,
/**
* Used to detect `data` property values to inject.
*
* @memberOf _.templateSettings
* @type RegExp
*/
'interpolate': reInterpolate,
/**
* Used to reference the data object in the template text.
*
* @memberOf _.templateSettings
* @type String
*/
'variable': '',
/**
* Used to import variables into the compiled template.
*
* @memberOf _.templateSettings
* @type Object
*/
'imports': {
/**
* A reference to the `lodash` function.
*
* @memberOf _.templateSettings.imports
* @type Function
*/
'_': lodash
}
};
/*--------------------------------------------------------------------------*/
/**
* The template used to create iterator functions.
*
* @private
* @param {Object} data The data object used to populate the text.
* @returns {String} Returns the interpolated text.
*/
var iteratorTemplate = template(
// the `iterable` may be reassigned by the `top` snippet
'var index, iterable = <%= firstArg %>, ' +
// assign the `result` variable an initial value
'result = <%= init %>;\n' +
// exit early if the first argument is falsey
'if (!iterable) return result;\n' +
// add code before the iteration branches
'<%= top %>;\n' +
// array-like iteration:
'<% if (arrays) { %>' +
'var length = iterable.length; index = -1;\n' +
'if (<%= arrays %>) {' +
// add support for accessing string characters by index if needed
' <% if (support.unindexedChars) { %>\n' +
' if (isString(iterable)) {\n' +
" iterable = iterable.split('')\n" +
' }' +
' <% } %>\n' +
// iterate over the array-like value
' while (++index < length) {\n' +
' <%= loop %>\n' +
' }\n' +
'}\n' +
'else {' +
// object iteration:
// add support for iterating over `arguments` objects if needed
' <% } else if (support.nonEnumArgs) { %>\n' +
' var length = iterable.length; index = -1;\n' +
' if (length && isArguments(iterable)) {\n' +
' while (++index < length) {\n' +
" index += '';\n" +
' <%= loop %>\n' +
' }\n' +
' } else {' +
' <% } %>' +
// avoid iterating over `prototype` properties in older Firefox, Opera, and Safari
' <% if (support.enumPrototypes) { %>\n' +
" var skipProto = typeof iterable == 'function';\n" +
' <% } %>' +
// iterate own properties using `Object.keys` if it's fast
' <% if (useHas && useKeys) { %>\n' +
' var ownIndex = -1,\n' +
' ownProps = objectTypes[typeof iterable] ? keys(iterable) : [],\n' +
' length = ownProps.length;\n\n' +
' while (++ownIndex < length) {\n' +
' index = ownProps[ownIndex];\n' +
" <% if (support.enumPrototypes) { %>if (!(skipProto && index == 'prototype')) {\n <% } %>" +
' <%= loop %>\n' +
' <% if (support.enumPrototypes) { %>}\n<% } %>' +
' }' +
// else using a for-in loop
' <% } else { %>\n' +
' for (index in iterable) {<%' +
' if (support.enumPrototypes || useHas) { %>\n if (<%' +
" if (support.enumPrototypes) { %>!(skipProto && index == 'prototype')<% }" +
' if (support.enumPrototypes && useHas) { %> && <% }' +
' if (useHas) { %>hasOwnProperty.call(iterable, index)<% }' +
' %>) {' +
' <% } %>\n' +
' <%= loop %>;' +
' <% if (support.enumPrototypes || useHas) { %>\n }<% } %>\n' +
' }' +
// Because IE < 9 can't set the `[[Enumerable]]` attribute of an
// existing property and the `constructor` property of a prototype
// defaults to non-enumerable, Lo-Dash skips the `constructor`
// property when it infers it's iterating over a `prototype` object.
' <% if (support.nonEnumShadows) { %>\n\n' +
' var ctor = iterable.constructor;\n' +
' <% for (var k = 0; k < 7; k++) { %>\n' +
" index = '<%= shadowedProps[k] %>';\n" +
' if (<%' +
" if (shadowedProps[k] == 'constructor') {" +
' %>!(ctor && ctor.prototype === iterable) && <%' +
' } %>hasOwnProperty.call(iterable, index)) {\n' +
' <%= loop %>\n' +
' }' +
' <% } %>' +
' <% } %>' +
' <% } %>' +
' <% if (arrays || support.nonEnumArgs) { %>\n}<% } %>\n' +
// add code to the bottom of the iteration function
'<%= bottom %>;\n' +
// finally, return the `result`
'return result'
);
/** Reusable iterator options for `assign` and `defaults` */
var defaultsIteratorOptions = {
'args': 'object, source, guard',
'top':
'var args = arguments,\n' +
' argsIndex = 0,\n' +
" argsLength = typeof guard == 'number' ? 2 : args.length;\n" +
'while (++argsIndex < argsLength) {\n' +
' iterable = args[argsIndex];\n' +
' if (iterable && objectTypes[typeof iterable]) {',
'loop': "if (typeof result[index] == 'undefined') result[index] = iterable[index]",
'bottom': ' }\n}'
};
/** Reusable iterator options shared by `each`, `forIn`, and `forOwn` */
var eachIteratorOptions = {
'args': 'collection, callback, thisArg',
'top': "callback = callback && typeof thisArg == 'undefined' ? callback : lodash.createCallback(callback, thisArg)",
'arrays': "typeof length == 'number'",
'loop': 'if (callback(iterable[index], index, collection) === false) return result'
};
/** Reusable iterator options for `forIn` and `forOwn` */
var forOwnIteratorOptions = {
'top': 'if (!objectTypes[typeof iterable]) return result;\n' + eachIteratorOptions.top,
'arrays': false
};
/*--------------------------------------------------------------------------*/
/**
* Creates a function optimized to search large arrays for a given `value`,
* starting at `fromIndex`, using strict equality for comparisons, i.e. `===`.
*
* @private
* @param {Array} array The array to search.
* @param {Mixed} value The value to search for.
* @returns {Boolean} Returns `true`, if `value` is found, else `false`.
*/
function cachedContains(array) {
var length = array.length,
isLarge = length >= largeArraySize;
if (isLarge) {
var cache = {},
index = -1;
while (++index < length) {
var key = keyPrefix + array[index];
(cache[key] || (cache[key] = [])).push(array[index]);
}
}
return function(value) {
if (isLarge) {
var key = keyPrefix + value;
return cache[key] && indexOf(cache[key], value) > -1;
}
return indexOf(array, value) > -1;
}
}
/**
* Used by `_.max` and `_.min` as the default `callback` when a given
* `collection` is a string value.
*
* @private
* @param {String} value The character to inspect.
* @returns {Number} Returns the code unit of given character.
*/
function charAtCallback(value) {
return value.charCodeAt(0);
}
/**
* Used by `sortBy` to compare transformed `collection` values, stable sorting
* them in ascending order.
*
* @private
* @param {Object} a The object to compare to `b`.
* @param {Object} b The object to compare to `a`.
* @returns {Number} Returns the sort order indicator of `1` or `-1`.
*/
function compareAscending(a, b) {
var ai = a.index,
bi = b.index;
a = a.criteria;
b = b.criteria;
// ensure a stable sort in V8 and other engines
// http://code.google.com/p/v8/issues/detail?id=90
if (a !== b) {
if (a > b || typeof a == 'undefined') {
return 1;
}
if (a < b || typeof b == 'undefined') {
return -1;
}
}
return ai < bi ? -1 : 1;
}
/**
* Creates a function that, when called, invokes `func` with the `this` binding
* of `thisArg` and prepends any `partialArgs` to the arguments passed to the
* bound function.
*
* @private
* @param {Function|String} func The function to bind or the method name.
* @param {Mixed} [thisArg] The `this` binding of `func`.
* @param {Array} partialArgs An array of arguments to be partially applied.
* @param {Object} [idicator] Used to indicate binding by key or partially
* applying arguments from the right.
* @returns {Function} Returns the new bound function.
*/
function createBound(func, thisArg, partialArgs, indicator) {
var isFunc = isFunction(func),
isPartial = !partialArgs,
key = thisArg;
// juggle arguments
if (isPartial) {
var rightIndicator = indicator;
partialArgs = thisArg;
}
else if (!isFunc) {
if (!indicator) {
throw new TypeError;
}
thisArg = func;
}
function bound() {
// `Function#bind` spec
// http://es5.github.com/#x15.3.4.5
var args = arguments,
thisBinding = isPartial ? this : thisArg;
if (!isFunc) {
func = thisArg[key];
}
if (partialArgs.length) {
args = args.length
? (args = nativeSlice.call(args), rightIndicator ? args.concat(partialArgs) : partialArgs.concat(args))
: partialArgs;
}
if (this instanceof bound) {
// ensure `new bound` is an instance of `func`
noop.prototype = func.prototype;
thisBinding = new noop;
noop.prototype = null;
// mimic the constructor's `return` behavior
// http://es5.github.com/#x13.2.2
var result = func.apply(thisBinding, args);
return isObject(result) ? result : thisBinding;
}
return func.apply(thisBinding, args);
}
return bound;
}
/**
* Creates compiled iteration functions.
*
* @private
* @param {Object} [options1, options2, ...] The compile options object(s).
* arrays - A string of code to determine if the iterable is an array or array-like.
* useHas - A boolean to specify using `hasOwnProperty` checks in the object loop.
* useKeys - A boolean to specify using `_.keys` for own property iteration.
* args - A string of comma separated arguments the iteration function will accept.
* top - A string of code to execute before the iteration branches.
* loop - A string of code to execute in the object loop.
* bottom - A string of code to execute after the iteration branches.
* @returns {Function} Returns the compiled function.
*/
function createIterator() {
var data = {
// data properties
'shadowedProps': shadowedProps,
'support': support,
// iterator options
'arrays': 'isArray(iterable)',
'bottom': '',
'init': 'iterable',
'loop': '',
'top': '',
'useHas': true,
'useKeys': !!keys
};
// merge options into a template data object
for (var object, index = 0; object = arguments[index]; index++) {
for (var key in object) {
data[key] = object[key];
}
}
var args = data.args;
data.firstArg = /^[^,]+/.exec(args)[0];
// create the function factory
var factory = Function(
'hasOwnProperty, isArguments, isArray, isString, keys, ' +
'lodash, objectTypes',
'return function(' + args + ') {\n' + iteratorTemplate(data) + '\n}'
);
// return the compiled function
return factory(
hasOwnProperty, isArguments, isArray, isString, keys,
lodash, objectTypes
);
}
/**
* Used by `template` to escape characters for inclusion in compiled
* string literals.
*
* @private
* @param {String} match The matched character to escape.
* @returns {String} Returns the escaped character.
*/
function escapeStringChar(match) {
return '\\' + stringEscapes[match];
}
/**
* Used by `escape` to convert characters to HTML entities.
*
* @private
* @param {String} match The matched character to escape.
* @returns {String} Returns the escaped character.
*/
function escapeHtmlChar(match) {
return htmlEscapes[match];
}
/**
* Checks if `value` is a DOM node in IE < 9.
*
* @private
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the `value` is a DOM node, else `false`.
*/
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
/**
* A fast path for creating `lodash` wrapper objects.
*
* @private
* @param {Mixed} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns a `lodash` instance.
*/
function lodashWrapper(value) {
this.__wrapped__ = value;
}
// ensure `new lodashWrapper` is an instance of `lodash`
lodashWrapper.prototype = lodash.prototype;
/**
* A no-operation function.
*
* @private
*/
function noop() {
// no operation performed
}
/**
* A fallback implementation of `isPlainObject` which checks if a given `value`
* is an object created by the `Object` constructor, assuming objects created
* by the `Object` constructor have no inherited enumerable properties and that
* there are no `Object.prototype` extensions.
*
* @private
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true`, if `value` is a plain object, else `false`.
*/
function shimIsPlainObject(value) {
// avoid non-objects and false positives for `arguments` objects
var result = false;
if (!(value && toString.call(value) == objectClass) || (!support.argsClass && isArguments(value))) {
return result;
}
// check that the constructor is `Object` (i.e. `Object instanceof Object`)
var ctor = value.constructor;
if (isFunction(ctor) ? ctor instanceof ctor : (support.nodeClass || !isNode(value))) {
// IE < 9 iterates inherited properties before own properties. If the first
// iterated property is an object's own property then there are no inherited
// enumerable properties.
if (support.ownLast) {
forIn(value, function(value, key, object) {
result = hasOwnProperty.call(object, key);
return false;
});
return result === true;
}
// In most environments an object's own properties are iterated before
// its inherited properties. If the last iterated property is an object's
// own property then there are no inherited enumerable properties.
forIn(value, function(value, key) {
result = key;
});
return result === false || hasOwnProperty.call(value, result);
}
return result;
}
/**
* Slices the `collection` from the `start` index up to, but not including,
* the `end` index.
*
* Note: This function is used, instead of `Array#slice`, to support node lists
* in IE < 9 and to ensure dense arrays are returned.
*
* @private
* @param {Array|Object|String} collection The collection to slice.
* @param {Number} start The start index.
* @param {Number} end The end index.
* @returns {Array} Returns the new array.
*/
function slice(array, start, end) {
start || (start = 0);
if (typeof end == 'undefined') {
end = array ? array.length : 0;
}
var index = -1,
length = end - start || 0,
result = Array(length < 0 ? 0 : length);
while (++index < length) {
result[index] = array[start + index];
}
return result;
}
/**
* Used by `unescape` to convert HTML entities to characters.
*
* @private
* @param {String} match The matched character to unescape.
* @returns {String} Returns the unescaped character.
*/
function unescapeHtmlChar(match) {
return htmlUnescapes[match];
}
/*--------------------------------------------------------------------------*/
/**
* Checks if `value` is an `arguments` object.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true`, if the `value` is an `arguments` object, else `false`.
* @example
*
* (function() { return _.isArguments(arguments); })(1, 2, 3);
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
return toString.call(value) == argsClass;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!support.argsClass) {
isArguments = function(value) {
return value ? hasOwnProperty.call(value, 'callee') : false;
};
}
/**
* A fallback implementation of `Object.keys` which produces an array of the
* given object's own enumerable property names.
*
* @private
* @type Function
* @param {Object} object The object to inspect.
* @returns {Array} Returns a new array of property names.
*/
var shimKeys = createIterator({
'args': 'object',
'init': '[]',
'top': 'if (!(objectTypes[typeof object])) return result',
'loop': 'result.push(index)',
'arrays': false
});
/**
* Creates an array composed of the own enumerable property names of `object`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns a new array of property names.
* @example
*
* _.keys({ 'one': 1, 'two': 2, 'three': 3 });
* // => ['one', 'two', 'three'] (order is not guaranteed)
*/
var keys = !nativeKeys ? shimKeys : function(object) {
if (!isObject(object)) {
return [];
}
if ((support.enumPrototypes && typeof object == 'function') ||
(support.nonEnumArgs && object.length && isArguments(object))) {
return shimKeys(object);
}
return nativeKeys(object);
};
/**
* A function compiled to iterate `arguments` objects, arrays, objects, and
* strings consistenly across environments, executing the `callback` for each
* element in the `collection`. The `callback` is bound to `thisArg` and invoked
* with three arguments; (value, index|key, collection). Callbacks may exit
* iteration early by explicitly returning `false`.
*
* @private
* @type Function
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Array|Object|String} Returns `collection`.
*/
var each = createIterator(eachIteratorOptions);
/**
* Used to convert characters to HTML entities:
*
* Though the `>` character is escaped for symmetry, characters like `>` and `/`
* don't require escaping in HTML and have no special meaning unless they're part
* of a tag or an unquoted attribute value.
* http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact")
*/
var htmlEscapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
/** Used to convert HTML entities to characters */
var htmlUnescapes = invert(htmlEscapes);
/*--------------------------------------------------------------------------*/
/**
* Assigns own enumerable properties of source object(s) to the destination
* object. Subsequent sources will overwrite property assignments of previous
* sources. If a `callback` function is passed, it will be executed to produce
* the assigned values. The `callback` is bound to `thisArg` and invoked with
* two arguments; (objectValue, sourceValue).
*
* @static
* @memberOf _
* @type Function
* @alias extend
* @category Objects
* @param {Object} object The destination object.
* @param {Object} [source1, source2, ...] The source objects.
* @param {Function} [callback] The function to customize assigning values.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the destination object.
* @example
*
* _.assign({ 'name': 'moe' }, { 'age': 40 });
* // => { 'name': 'moe', 'age': 40 }
*
* var defaults = _.partialRight(_.assign, function(a, b) {
* return typeof a == 'undefined' ? b : a;
* });
*
* var food = { 'name': 'apple' };
* defaults(food, { 'name': 'banana', 'type': 'fruit' });
* // => { 'name': 'apple', 'type': 'fruit' }
*/
var assign = createIterator(defaultsIteratorOptions, {
'top':
defaultsIteratorOptions.top.replace(';',
';\n' +
"if (argsLength > 3 && typeof args[argsLength - 2] == 'function') {\n" +
' var callback = lodash.createCallback(args[--argsLength - 1], args[argsLength--], 2);\n' +
"} else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {\n" +
' callback = args[--argsLength];\n' +
'}'
),
'loop': 'result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]'
});
/**
* Creates a clone of `value`. If `deep` is `true`, nested objects will also
* be cloned, otherwise they will be assigned by reference. If a `callback`
* function is passed, it will be executed to produce the cloned values. If
* `callback` returns `undefined`, cloning will be handled by the method instead.
* The `callback` is bound to `thisArg` and invoked with one argument; (value).
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to clone.
* @param {Boolean} [deep=false] A flag to indicate a deep clone.
* @param {Function} [callback] The function to customize cloning values.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @param- {Array} [stackA=[]] Tracks traversed source objects.
* @param- {Array} [stackB=[]] Associates clones with source counterparts.
* @returns {Mixed} Returns the cloned `value`.
* @example
*
* var stooges = [
* { 'name': 'moe', 'age': 40 },
* { 'name': 'larry', 'age': 50 }
* ];
*
* var shallow = _.clone(stooges);
* shallow[0] === stooges[0];
* // => true
*
* var deep = _.clone(stooges, true);
* deep[0] === stooges[0];
* // => false
*
* _.mixin({
* 'clone': _.partialRight(_.clone, function(value) {
* return _.isElement(value) ? value.cloneNode(false) : undefined;
* })
* });
*
* var clone = _.clone(document.body);
* clone.childNodes.length;
* // => 0
*/
function clone(value, deep, callback, thisArg, stackA, stackB) {
var result = value;
// allows working with "Collections" methods without using their `callback`
// argument, `index|key`, for this method's `callback`
if (typeof deep == 'function') {
thisArg = callback;
callback = deep;
deep = false;
}
if (typeof callback == 'function') {
callback = (typeof thisArg == 'undefined')
? callback
: lodash.createCallback(callback, thisArg, 1);
result = callback(result);
if (typeof result != 'undefined') {
return result;
}
result = value;
}
// inspect [[Class]]
var isObj = isObject(result);
if (isObj) {
var className = toString.call(result);
if (!cloneableClasses[className] || (!support.nodeClass && isNode(result))) {
return result;
}
var isArr = isArray(result);
}
// shallow clone
if (!isObj || !deep) {
return isObj
? (isArr ? slice(result) : assign({}, result))
: result;
}
var ctor = ctorByClass[className];
switch (className) {
case boolClass:
case dateClass:
return new ctor(+result);
case numberClass:
case stringClass:
return new ctor(result);
case regexpClass:
return ctor(result.source, reFlags.exec(result));
}
// check for circular references and return corresponding clone
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == value) {
return stackB[length];
}
}
// init cloned object
result = isArr ? ctor(result.length) : {};
// add array properties assigned by `RegExp#exec`
if (isArr) {
if (hasOwnProperty.call(value, 'index')) {
result.index = value.index;
}
if (hasOwnProperty.call(value, 'input')) {
result.input = value.input;
}
}
// add the source value to the stack of traversed objects
// and associate it with its clone
stackA.push(value);
stackB.push(result);
// recursively populate clone (susceptible to call stack limits)
(isArr ? forEach : forOwn)(value, function(objValue, key) {
result[key] = clone(objValue, deep, callback, undefined, stackA, stackB);
});
return result;
}
/**
* Creates a deep clone of `value`. If a `callback` function is passed,
* it will be executed to produce the cloned values. If `callback` returns
* `undefined`, cloning will be handled by the method instead. The `callback`
* is bound to `thisArg` and invoked with one argument; (value).
*
* Note: This function is loosely based on the structured clone algorithm. Functions
* and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and
* objects created by constructors other than `Object` are cloned to plain `Object` objects.
* See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to deep clone.
* @param {Function} [callback] The function to customize cloning values.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Mixed} Returns the deep cloned `value`.
* @example
*
* var stooges = [
* { 'name': 'moe', 'age': 40 },
* { 'name': 'larry', 'age': 50 }
* ];
*
* var deep = _.cloneDeep(stooges);
* deep[0] === stooges[0];
* // => false
*
* var view = {
* 'label': 'docs',
* 'node': element
* };
*
* var clone = _.cloneDeep(view, function(value) {
* return _.isElement(value) ? value.cloneNode(true) : undefined;
* });
*
* clone.node == view.node;
* // => false
*/
function cloneDeep(value, callback, thisArg) {
return clone(value, true, callback, thisArg);
}
/**
* Assigns own enumerable properties of source object(s) to the destination
* object for all destination properties that resolve to `undefined`. Once a
* property is set, additional defaults of the same property will be ignored.
*
* @static
* @memberOf _
* @type Function
* @category Objects
* @param {Object} object The destination object.
* @param {Object} [source1, source2, ...] The source objects.
* @param- {Object} [guard] Allows working with `_.reduce` without using its
* callback's `key` and `object` arguments as sources.
* @returns {Object} Returns the destination object.
* @example
*
* var food = { 'name': 'apple' };
* _.defaults(food, { 'name': 'banana', 'type': 'fruit' });
* // => { 'name': 'apple', 'type': 'fruit' }
*/
var defaults = createIterator(defaultsIteratorOptions);
/**
* This method is similar to `_.find`, except that it returns the key of the
* element that passes the callback check, instead of the element itself.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to search.
* @param {Function|Object|String} [callback=identity] The function called per
* iteration. If a property name or object is passed, it will be used to create
* a "_.pluck" or "_.where" style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Mixed} Returns the key of the found element, else `undefined`.
* @example
*
* _.findKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) {
* return num % 2 == 0;
* });
* // => 'b'
*/
function findKey(object, callback, thisArg) {
var result;
callback = lodash.createCallback(callback, thisArg);
forOwn(object, function(value, key, object) {
if (callback(value, key, object)) {
result = key;
return false;
}
});
return result;
}
/**
* Iterates over `object`'s own and inherited enumerable properties, executing
* the `callback` for each property. The `callback` is bound to `thisArg` and
* invoked with three arguments; (value, key, object). Callbacks may exit iteration
* early by explicitly returning `false`.
*
* @static
* @memberOf _
* @type Function
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns `object`.
* @example
*
* function Dog(name) {
* this.name = name;
* }
*
* Dog.prototype.bark = function() {
* alert('Woof, woof!');
* };
*
* _.forIn(new Dog('Dagny'), function(value, key) {
* alert(key);
* });
* // => alerts 'name' and 'bark' (order is not guaranteed)
*/
var forIn = createIterator(eachIteratorOptions, forOwnIteratorOptions, {
'useHas': false
});
/**
* Iterates over an object's own enumerable properties, executing the `callback`
* for each property. The `callback` is bound to `thisArg` and invoked with three
* arguments; (value, key, object). Callbacks may exit iteration early by explicitly
* returning `false`.
*
* @static
* @memberOf _
* @type Function
* @category Objects
* @param {Object} object The object to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns `object`.
* @example
*
* _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) {
* alert(key);
* });
* // => alerts '0', '1', and 'length' (order is not guaranteed)
*/
var forOwn = createIterator(eachIteratorOptions, forOwnIteratorOptions);
/**
* Creates a sorted array of all enumerable properties, own and inherited,
* of `object` that have function values.
*
* @static
* @memberOf _
* @alias methods
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns a new array of property names that have function values.
* @example
*
* _.functions(_);
* // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...]
*/
function functions(object) {
var result = [];
forIn(object, function(value, key) {
if (isFunction(value)) {
result.push(key);
}
});
return result.sort();
}
/**
* Checks if the specified object `property` exists and is a direct property,
* instead of an inherited property.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to check.
* @param {String} property The property to check for.
* @returns {Boolean} Returns `true` if key is a direct property, else `false`.
* @example
*
* _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b');
* // => true
*/
function has(object, property) {
return object ? hasOwnProperty.call(object, property) : false;
}
/**
* Creates an object composed of the inverted keys and values of the given `object`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to invert.
* @returns {Object} Returns the created inverted object.
* @example
*
* _.invert({ 'first': 'moe', 'second': 'larry' });
* // => { 'moe': 'first', 'larry': 'second' }
*/
function invert(object) {
var index = -1,
props = keys(object),
length = props.length,
result = {};
while (++index < length) {
var key = props[index];
result[object[key]] = key;
}
return result;
}
/**
* Checks if `value` is an array.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true`, if the `value` is an array, else `false`.
* @example
*
* (function() { return _.isArray(arguments); })();
* // => false
*
* _.isArray([1, 2, 3]);
* // => true
*/
function isArray(value) {
// `instanceof` may cause a memory leak in IE 7 if `value` is a host object
// http://ajaxian.com/archives/working-aroung-the-instanceof-memory-leak
return (support.argsObject && value instanceof Array) ||
(nativeIsArray ? nativeIsArray(value) : toString.call(value) == arrayClass);
}
/**
* Checks if `value` is a boolean value.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true`, if the `value` is a boolean value, else `false`.
* @example
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return value === true || value === false || toString.call(value) == boolClass;
}
/**
* Checks if `value` is a date.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true`, if the `value` is a date, else `false`.
* @example
*
* _.isDate(new Date);
* // => true
*/
function isDate(value) {
return value instanceof Date || toString.call(value) == dateClass;
}
/**
* Checks if `value` is a DOM element.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true`, if the `value` is a DOM element, else `false`.
* @example
*
* _.isElement(document.body);
* // => true
*/
function isElement(value) {
return value ? value.nodeType === 1 : false;
}
/**
* Checks if `value` is empty. Arrays, strings, or `arguments` objects with a
* length of `0` and objects with no own enumerable properties are considered
* "empty".
*
* @static
* @memberOf _
* @category Objects
* @param {Array|Object|String} value The value to inspect.
* @returns {Boolean} Returns `true`, if the `value` is empty, else `false`.
* @example
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({});
* // => true
*
* _.isEmpty('');
* // => true
*/
function isEmpty(value) {
var result = true;
if (!value) {
return result;
}
var className = toString.call(value),
length = value.length;
if ((className == arrayClass || className == stringClass ||
(support.argsClass ? className == argsClass : isArguments(value))) ||
(className == objectClass && typeof length == 'number' && isFunction(value.splice))) {
return !length;
}
forOwn(value, function() {
return (result = false);
});
return result;
}
/**
* Performs a deep comparison between two values to determine if they are
* equivalent to each other. If `callback` is passed, it will be executed to
* compare values. If `callback` returns `undefined`, comparisons will be handled
* by the method instead. The `callback` is bound to `thisArg` and invoked with
* two arguments; (a, b).
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} a The value to compare.
* @param {Mixed} b The other value to compare.
* @param {Function} [callback] The function to customize comparing values.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @param- {Array} [stackA=[]] Tracks traversed `a` objects.
* @param- {Array} [stackB=[]] Tracks traversed `b` objects.
* @returns {Boolean} Returns `true`, if the values are equivalent, else `false`.
* @example
*
* var moe = { 'name': 'moe', 'age': 40 };
* var copy = { 'name': 'moe', 'age': 40 };
*
* moe == copy;
* // => false
*
* _.isEqual(moe, copy);
* // => true
*
* var words = ['hello', 'goodbye'];
* var otherWords = ['hi', 'goodbye'];
*
* _.isEqual(words, otherWords, function(a, b) {
* var reGreet = /^(?:hello|hi)$/i,
* aGreet = _.isString(a) && reGreet.test(a),
* bGreet = _.isString(b) && reGreet.test(b);
*
* return (aGreet || bGreet) ? (aGreet == bGreet) : undefined;
* });
* // => true
*/
function isEqual(a, b, callback, thisArg, stackA, stackB) {
// used to indicate that when comparing objects, `a` has at least the properties of `b`
var whereIndicator = callback === indicatorObject;
if (typeof callback == 'function' && !whereIndicator) {
callback = lodash.createCallback(callback, thisArg, 2);
var result = callback(a, b);
if (typeof result != 'undefined') {
return !!result;
}
}
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a &&
(!a || (type != 'function' && type != 'object')) &&
(!b || (otherType != 'function' && otherType != 'object'))) {
return false;
}
// exit early for `null` and `undefined`, avoiding ES3's Function#call behavior
// http://es5.github.com/#x15.3.4.4
if (a == null || b == null) {
return a === b;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0`, treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a)
? b != +b
// but treat `+0` vs. `-0` as not equal
: (a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.com/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// unwrap any `lodash` wrapped values
if (hasOwnProperty.call(a, '__wrapped__ ') || hasOwnProperty.call(b, '__wrapped__')) {
return isEqual(a.__wrapped__ || a, b.__wrapped__ || b, callback, thisArg, stackA, stackB);
}
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB && !(
isFunction(ctorA) && ctorA instanceof ctorA &&
isFunction(ctorB) && ctorB instanceof ctorB
)) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.com/#x15.12.3)
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
length = a.length;
size = b.length;
// compare lengths to determine if a deep comparison is necessary
result = size == a.length;
if (!result && !whereIndicator) {
return result;
}
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (whereIndicator) {
while (index--) {
if ((result = isEqual(a[index], value, callback, thisArg, stackA, stackB))) {
break;
}
}
} else if (!(result = isEqual(a[size], value, callback, thisArg, stackA, stackB))) {
break;
}
}
return result;
}
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
forIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && isEqual(a[key], value, callback, thisArg, stackA, stackB));
}
});
if (result && !whereIndicator) {
// ensure both objects have the same number of properties
forIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
return result;
}
/**
* Checks if `value` is, or can be coerced to, a finite number.
*
* Note: This is not the same as native `isFinite`, which will return true for
* booleans and empty strings. See http://es5.github.com/#x15.1.2.5.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true`, if the `value` is finite, else `false`.
* @example
*
* _.isFinite(-101);
* // => true
*
* _.isFinite('10');
* // => true
*
* _.isFinite(true);
* // => false
*
* _.isFinite('');
* // => false
*
* _.isFinite(Infinity);
* // => false
*/
function isFinite(value) {
return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value));
}
/**
* Checks if `value` is a function.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true`, if the `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*/
function isFunction(value) {
return typeof value == 'function';
}
// fallback for older versions of Chrome and Safari
if (isFunction(/x/)) {
isFunction = function(value) {
return value instanceof Function || toString.call(value) == funcClass;
};
}
/**
* Checks if `value` is the language type of Object.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true`, if the `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.com/#x8
// and avoid a V8 bug
// http://code.google.com/p/v8/issues/detail?id=2291
return value ? objectTypes[typeof value] : false;
}
/**
* Checks if `value` is `NaN`.
*
* Note: This is not the same as native `isNaN`, which will return `true` for
* `undefined` and other values. See http://es5.github.com/#x15.1.2.4.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true`, if the `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// `NaN` as a primitive is the only value that is not equal to itself
// (perform the [[Class]] check first to avoid errors with some host objects in IE)
return isNumber(value) && value != +value
}
/**
* Checks if `value` is `null`.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true`, if the `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(undefined);
* // => false
*/
function isNull(value) {
return value === null;
}
/**
* Checks if `value` is a number.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true`, if the `value` is a number, else `false`.
* @example
*
* _.isNumber(8.4 * 5);
* // => true
*/
function isNumber(value) {
return typeof value == 'number' || toString.call(value) == numberClass;
}
/**
* Checks if a given `value` is an object created by the `Object` constructor.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true`, if `value` is a plain object, else `false`.
* @example
*
* function Stooge(name, age) {
* this.name = name;
* this.age = age;
* }
*
* _.isPlainObject(new Stooge('moe', 40));
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'name': 'moe', 'age': 40 });
* // => true
*/
var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) {
if (!(value && toString.call(value) == objectClass) || (!support.argsClass && isArguments(value))) {
return false;
}
var valueOf = value.valueOf,
objProto = typeof valueOf == 'function' && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto);
return objProto
? (value == objProto || getPrototypeOf(value) == objProto)
: shimIsPlainObject(value);
};
/**
* Checks if `value` is a regular expression.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true`, if the `value` is a regular expression, else `false`.
* @example
*
* _.isRegExp(/moe/);
* // => true
*/
function isRegExp(value) {
return value instanceof RegExp || toString.call(value) == regexpClass;
}
/**
* Checks if `value` is a string.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true`, if the `value` is a string, else `false`.
* @example
*
* _.isString('moe');
* // => true
*/
function isString(value) {
return typeof value == 'string' || toString.call(value) == stringClass;
}
/**
* Checks if `value` is `undefined`.
*
* @static
* @memberOf _
* @category Objects
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true`, if the `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*/
function isUndefined(value) {
return typeof value == 'undefined';
}
/**
* Recursively merges own enumerable properties of the source object(s), that
* don't resolve to `undefined`, into the destination object. Subsequent sources
* will overwrite property assignments of previous sources. If a `callback` function
* is passed, it will be executed to produce the merged values of the destination
* and source properties. If `callback` returns `undefined`, merging will be
* handled by the method instead. The `callback` is bound to `thisArg` and
* invoked with two arguments; (objectValue, sourceValue).
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The destination object.
* @param {Object} [source1, source2, ...] The source objects.
* @param {Function} [callback] The function to customize merging properties.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @param- {Object} [deepIndicator] Indicates that `stackA` and `stackB` are
* arrays of traversed objects, instead of source objects.
* @param- {Array} [stackA=[]] Tracks traversed source objects.
* @param- {Array} [stackB=[]] Associates values with source counterparts.
* @returns {Object} Returns the destination object.
* @example
*
* var names = {
* 'stooges': [
* { 'name': 'moe' },
* { 'name': 'larry' }
* ]
* };
*
* var ages = {
* 'stooges': [
* { 'age': 40 },
* { 'age': 50 }
* ]
* };
*
* _.merge(names, ages);
* // => { 'stooges': [{ 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 }] }
*
* var food = {
* 'fruits': ['apple'],
* 'vegetables': ['beet']
* };
*
* var otherFood = {
* 'fruits': ['banana'],
* 'vegetables': ['carrot']
* };
*
* _.merge(food, otherFood, function(a, b) {
* return _.isArray(a) ? a.concat(b) : undefined;
* });
* // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] }
*/
function merge(object, source, deepIndicator) {
var args = arguments,
index = 0,
length = 2;
if (!isObject(object)) {
return object;
}
if (deepIndicator === indicatorObject) {
var callback = args[3],
stackA = args[4],
stackB = args[5];
} else {
stackA = [];
stackB = [];
// allows working with `_.reduce` and `_.reduceRight` without
// using their `callback` arguments, `index|key` and `collection`
if (typeof deepIndicator != 'number') {
length = args.length;
}
if (length > 3 && typeof args[length - 2] == 'function') {
callback = lodash.createCallback(args[--length - 1], args[length--], 2);
} else if (length > 2 && typeof args[length - 1] == 'function') {
callback = args[--length];
}
}
while (++index < length) {
(isArray(args[index]) ? forEach : forOwn)(args[index], function(source, key) {
var found,
isArr,
result = source,
value = object[key];
if (source && ((isArr = isArray(source)) || isPlainObject(source))) {
// avoid merging previously merged cyclic sources
var stackLength = stackA.length;
while (stackLength--) {
if ((found = stackA[stackLength] == source)) {
value = stackB[stackLength];
break;
}
}
if (!found) {
var isShallow;
if (callback) {
result = callback(value, source);
if ((isShallow = typeof result != 'undefined')) {
value = result;
}
}
if (!isShallow) {
value = isArr
? (isArray(value) ? value : [])
: (isPlainObject(value) ? value : {});
}
// add `source` and associated `value` to the stack of traversed objects
stackA.push(source);
stackB.push(value);
// recursively merge objects and arrays (susceptible to call stack limits)
if (!isShallow) {
value = merge(value, source, indicatorObject, callback, stackA, stackB);
}
}
}
else {
if (callback) {
result = callback(value, source);
if (typeof result == 'undefined') {
result = source;
}
}
if (typeof result != 'undefined') {
value = result;
}
}
object[key] = value;
});
}
return object;
}
/**
* Creates a shallow clone of `object` excluding the specified properties.
* Property names may be specified as individual arguments or as arrays of
* property names. If a `callback` function is passed, it will be executed
* for each property in the `object`, omitting the properties `callback`
* returns truthy for. The `callback` is bound to `thisArg` and invoked
* with three arguments; (value, key, object).
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The source object.
* @param {Function|String} callback|[prop1, prop2, ...] The properties to omit
* or the function called per iteration.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns an object without the omitted properties.
* @example
*
* _.omit({ 'name': 'moe', 'age': 40 }, 'age');
* // => { 'name': 'moe' }
*
* _.omit({ 'name': 'moe', 'age': 40 }, function(value) {
* return typeof value == 'number';
* });
* // => { 'name': 'moe' }
*/
function omit(object, callback, thisArg) {
var isFunc = typeof callback == 'function',
result = {};
if (isFunc) {
callback = lodash.createCallback(callback, thisArg);
} else {
var props = concat.apply(arrayRef, nativeSlice.call(arguments, 1));
}
forIn(object, function(value, key, object) {
if (isFunc
? !callback(value, key, object)
: indexOf(props, key) < 0
) {
result[key] = value;
}
});
return result;
}
/**
* Creates a two dimensional array of the given object's key-value pairs,
* i.e. `[[key1, value1], [key2, value2]]`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns new array of key-value pairs.
* @example
*
* _.pairs({ 'moe': 30, 'larry': 40 });
* // => [['moe', 30], ['larry', 40]] (order is not guaranteed)
*/
function pairs(object) {
var index = -1,
props = keys(object),
length = props.length,
result = Array(length);
while (++index < length) {
var key = props[index];
result[index] = [key, object[key]];
}
return result;
}
/**
* Creates a shallow clone of `object` composed of the specified properties.
* Property names may be specified as individual arguments or as arrays of property
* names. If `callback` is passed, it will be executed for each property in the
* `object`, picking the properties `callback` returns truthy for. The `callback`
* is bound to `thisArg` and invoked with three arguments; (value, key, object).
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The source object.
* @param {Array|Function|String} callback|[prop1, prop2, ...] The function called
* per iteration or properties to pick, either as individual arguments or arrays.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns an object composed of the picked properties.
* @example
*
* _.pick({ 'name': 'moe', '_userid': 'moe1' }, 'name');
* // => { 'name': 'moe' }
*
* _.pick({ 'name': 'moe', '_userid': 'moe1' }, function(value, key) {
* return key.charAt(0) != '_';
* });
* // => { 'name': 'moe' }
*/
function pick(object, callback, thisArg) {
var result = {};
if (typeof callback != 'function') {
var index = -1,
props = concat.apply(arrayRef, nativeSlice.call(arguments, 1)),
length = isObject(object) ? props.length : 0;
while (++index < length) {
var key = props[index];
if (key in object) {
result[key] = object[key];
}
}
} else {
callback = lodash.createCallback(callback, thisArg);
forIn(object, function(value, key, object) {
if (callback(value, key, object)) {
result[key] = value;
}
});
}
return result;
}
/**
* Creates an array composed of the own enumerable property values of `object`.
*
* @static
* @memberOf _
* @category Objects
* @param {Object} object The object to inspect.
* @returns {Array} Returns a new array of property values.
* @example
*
* _.values({ 'one': 1, 'two': 2, 'three': 3 });
* // => [1, 2, 3] (order is not guaranteed)
*/
function values(object) {
var index = -1,
props = keys(object),
length = props.length,
result = Array(length);
while (++index < length) {
result[index] = object[props[index]];
}
return result;
}
/*--------------------------------------------------------------------------*/
/**
* Creates an array of elements from the specified indexes, or keys, of the
* `collection`. Indexes may be specified as individual arguments or as arrays
* of indexes.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Array|Number|String} [index1, index2, ...] The indexes of
* `collection` to retrieve, either as individual arguments or arrays.
* @returns {Array} Returns a new array of elements corresponding to the
* provided indexes.
* @example
*
* _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]);
* // => ['a', 'c', 'e']
*
* _.at(['moe', 'larry', 'curly'], 0, 2);
* // => ['moe', 'curly']
*/
function at(collection) {
var index = -1,
props = concat.apply(arrayRef, nativeSlice.call(arguments, 1)),
length = props.length,
result = Array(length);
if (support.unindexedChars && isString(collection)) {
collection = collection.split('');
}
while(++index < length) {
result[index] = collection[props[index]];
}
return result;
}
/**
* Checks if a given `target` element is present in a `collection` using strict
* equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used
* as the offset from the end of the collection.
*
* @static
* @memberOf _
* @alias include
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Mixed} target The value to check for.
* @param {Number} [fromIndex=0] The index to search from.
* @returns {Boolean} Returns `true` if the `target` element is found, else `false`.
* @example
*
* _.contains([1, 2, 3], 1);
* // => true
*
* _.contains([1, 2, 3], 1, 2);
* // => false
*
* _.contains({ 'name': 'moe', 'age': 40 }, 'moe');
* // => true
*
* _.contains('curly', 'ur');
* // => true
*/
function contains(collection, target, fromIndex) {
var index = -1,
length = collection ? collection.length : 0,
result = false;
fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0;
if (typeof length == 'number') {
result = (isString(collection)
? collection.indexOf(target, fromIndex)
: indexOf(collection, target, fromIndex)
) > -1;
} else {
each(collection, function(value) {
if (++index >= fromIndex) {
return !(result = value === target);
}
});
}
return result;
}
/**
* Creates an object composed of keys returned from running each element of the
* `collection` through the given `callback`. The corresponding value of each key
* is the number of times the key was returned by the `callback`. The `callback`
* is bound to `thisArg` and invoked with three arguments; (value, index|key, collection).
*
* If a property name is passed for `callback`, the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is passed for `callback`, the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function|Object|String} [callback=identity] The function called per
* iteration. If a property name or object is passed, it will be used to create
* a "_.pluck" or "_.where" style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
* // => { '4': 1, '6': 2 }
*
* _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
* // => { '4': 1, '6': 2 }
*
* _.countBy(['one', 'two', 'three'], 'length');
* // => { '3': 2, '5': 1 }
*/
function countBy(collection, callback, thisArg) {
var result = {};
callback = lodash.createCallback(callback, thisArg);
forEach(collection, function(value, key, collection) {
key = String(callback(value, key, collection));
(hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1);
});
return result;
}
/**
* Checks if the `callback` returns a truthy value for **all** elements of a
* `collection`. The `callback` is bound to `thisArg` and invoked with three
* arguments; (value, index|key, collection).
*
* If a property name is passed for `callback`, the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is passed for `callback`, the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias all
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function|Object|String} [callback=identity] The function called per
* iteration. If a property name or object is passed, it will be used to create
* a "_.pluck" or "_.where" style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Boolean} Returns `true` if all elements pass the callback check,
* else `false`.
* @example
*
* _.every([true, 1, null, 'yes'], Boolean);
* // => false
*
* var stooges = [
* { 'name': 'moe', 'age': 40 },
* { 'name': 'larry', 'age': 50 }
* ];
*
* // using "_.pluck" callback shorthand
* _.every(stooges, 'age');
* // => true
*
* // using "_.where" callback shorthand
* _.every(stooges, { 'age': 50 });
* // => false
*/
function every(collection, callback, thisArg) {
var result = true;
callback = lodash.createCallback(callback, thisArg);
if (isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
if (!(result = !!callback(collection[index], index, collection))) {
break;
}
}
} else {
each(collection, function(value, index, collection) {
return (result = !!callback(value, index, collection));
});
}
return result;
}
/**
* Examines each element in a `collection`, returning an array of all elements
* the `callback` returns truthy for. The `callback` is bound to `thisArg` and
* invoked with three arguments; (value, index|key, collection).
*
* If a property name is passed for `callback`, the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is passed for `callback`, the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias select
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function|Object|String} [callback=identity] The function called per
* iteration. If a property name or object is passed, it will be used to create
* a "_.pluck" or "_.where" style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of elements that passed the callback check.
* @example
*
* var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
* // => [2, 4, 6]
*
* var food = [
* { 'name': 'apple', 'organic': false, 'type': 'fruit' },
* { 'name': 'carrot', 'organic': true, 'type': 'vegetable' }
* ];
*
* // using "_.pluck" callback shorthand
* _.filter(food, 'organic');
* // => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }]
*
* // using "_.where" callback shorthand
* _.filter(food, { 'type': 'fruit' });
* // => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }]
*/
function filter(collection, callback, thisArg) {
var result = [];
callback = lodash.createCallback(callback, thisArg);
if (isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
if (callback(value, index, collection)) {
result.push(value);
}
}
} else {
each(collection, function(value, index, collection) {
if (callback(value, index, collection)) {
result.push(value);
}
});
}
return result;
}
/**
* Examines each element in a `collection`, returning the first that the `callback`
* returns truthy for. The `callback` is bound to `thisArg` and invoked with three
* arguments; (value, index|key, collection).
*
* If a property name is passed for `callback`, the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is passed for `callback`, the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias detect
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function|Object|String} [callback=identity] The function called per
* iteration. If a property name or object is passed, it will be used to create
* a "_.pluck" or "_.where" style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Mixed} Returns the found element, else `undefined`.
* @example
*
* _.find([1, 2, 3, 4], function(num) {
* return num % 2 == 0;
* });
* // => 2
*
* var food = [
* { 'name': 'apple', 'organic': false, 'type': 'fruit' },
* { 'name': 'banana', 'organic': true, 'type': 'fruit' },
* { 'name': 'beet', 'organic': false, 'type': 'vegetable' }
* ];
*
* // using "_.where" callback shorthand
* _.find(food, { 'type': 'vegetable' });
* // => { 'name': 'beet', 'organic': false, 'type': 'vegetable' }
*
* // using "_.pluck" callback shorthand
* _.find(food, 'organic');
* // => { 'name': 'banana', 'organic': true, 'type': 'fruit' }
*/
function find(collection, callback, thisArg) {
callback = lodash.createCallback(callback, thisArg);
if (isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
if (callback(value, index, collection)) {
return value;
}
}
} else {
var result;
each(collection, function(value, index, collection) {
if (callback(value, index, collection)) {
result = value;
return false;
}
});
return result;
}
}
/**
* Iterates over a `collection`, executing the `callback` for each element in
* the `collection`. The `callback` is bound to `thisArg` and invoked with three
* arguments; (value, index|key, collection). Callbacks may exit iteration early
* by explicitly returning `false`.
*
* @static
* @memberOf _
* @alias each
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Array|Object|String} Returns `collection`.
* @example
*
* _([1, 2, 3]).forEach(alert).join(',');
* // => alerts each number and returns '1,2,3'
*
* _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert);
* // => alerts each number value (order is not guaranteed)
*/
function forEach(collection, callback, thisArg) {
if (callback && typeof thisArg == 'undefined' && isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
if (callback(collection[index], index, collection) === false) {
break;
}
}
} else {
each(collection, callback, thisArg);
}
return collection;
}
/**
* Creates an object composed of keys returned from running each element of the
* `collection` through the `callback`. The corresponding value of each key is
* an array of elements passed to `callback` that returned the key. The `callback`
* is bound to `thisArg` and invoked with three arguments; (value, index|key, collection).
*
* If a property name is passed for `callback`, the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is passed for `callback`, the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function|Object|String} [callback=identity] The function called per
* iteration. If a property name or object is passed, it will be used to create
* a "_.pluck" or "_.where" style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); });
* // => { '4': [4.2], '6': [6.1, 6.4] }
*
* _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
* // => { '4': [4.2], '6': [6.1, 6.4] }
*
* // using "_.pluck" callback shorthand
* _.groupBy(['one', 'two', 'three'], 'length');
* // => { '3': ['one', 'two'], '5': ['three'] }
*/
function groupBy(collection, callback, thisArg) {
var result = {};
callback = lodash.createCallback(callback, thisArg);
forEach(collection, function(value, key, collection) {
key = String(callback(value, key, collection));
(hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value);
});
return result;
}
/**
* Invokes the method named by `methodName` on each element in the `collection`,
* returning an array of the results of each invoked method. Additional arguments
* will be passed to each invoked method. If `methodName` is a function, it will
* be invoked for, and `this` bound to, each element in the `collection`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function|String} methodName The name of the method to invoke or
* the function invoked per iteration.
* @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with.
* @returns {Array} Returns a new array of the results of each invoked method.
* @example
*
* _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
* // => [[1, 5, 7], [1, 2, 3]]
*
* _.invoke([123, 456], String.prototype.split, '');
* // => [['1', '2', '3'], ['4', '5', '6']]
*/
function invoke(collection, methodName) {
var args = nativeSlice.call(arguments, 2),
index = -1,
isFunc = typeof methodName == 'function',
length = collection ? collection.length : 0,
result = Array(typeof length == 'number' ? length : 0);
forEach(collection, function(value) {
result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args);
});
return result;
}
/**
* Creates an array of values by running each element in the `collection`
* through the `callback`. The `callback` is bound to `thisArg` and invoked with
* three arguments; (value, index|key, collection).
*
* If a property name is passed for `callback`, the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is passed for `callback`, the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias collect
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function|Object|String} [callback=identity] The function called per
* iteration. If a property name or object is passed, it will be used to create
* a "_.pluck" or "_.where" style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of the results of each `callback` execution.
* @example
*
* _.map([1, 2, 3], function(num) { return num * 3; });
* // => [3, 6, 9]
*
* _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; });
* // => [3, 6, 9] (order is not guaranteed)
*
* var stooges = [
* { 'name': 'moe', 'age': 40 },
* { 'name': 'larry', 'age': 50 }
* ];
*
* // using "_.pluck" callback shorthand
* _.map(stooges, 'name');
* // => ['moe', 'larry']
*/
function map(collection, callback, thisArg) {
var index = -1,
length = collection ? collection.length : 0,
result = Array(typeof length == 'number' ? length : 0);
callback = lodash.createCallback(callback, thisArg);
if (isArray(collection)) {
while (++index < length) {
result[index] = callback(collection[index], index, collection);
}
} else {
each(collection, function(value, key, collection) {
result[++index] = callback(value, key, collection);
});
}
return result;
}
/**
* Retrieves the maximum value of an `array`. If `callback` is passed,
* it will be executed for each value in the `array` to generate the
* criterion by which the value is ranked. The `callback` is bound to
* `thisArg` and invoked with three arguments; (value, index, collection).
*
* If a property name is passed for `callback`, the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is passed for `callback`, the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function|Object|String} [callback=identity] The function called per
* iteration. If a property name or object is passed, it will be used to create
* a "_.pluck" or "_.where" style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Mixed} Returns the maximum value.
* @example
*
* _.max([4, 2, 8, 6]);
* // => 8
*
* var stooges = [
* { 'name': 'moe', 'age': 40 },
* { 'name': 'larry', 'age': 50 }
* ];
*
* _.max(stooges, function(stooge) { return stooge.age; });
* // => { 'name': 'larry', 'age': 50 };
*
* // using "_.pluck" callback shorthand
* _.max(stooges, 'age');
* // => { 'name': 'larry', 'age': 50 };
*/
function max(collection, callback, thisArg) {
var computed = -Infinity,
result = computed;
if (!callback && isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
if (value > result) {
result = value;
}
}
} else {
callback = (!callback && isString(collection))
? charAtCallback
: lodash.createCallback(callback, thisArg);
each(collection, function(value, index, collection) {
var current = callback(value, index, collection);
if (current > computed) {
computed = current;
result = value;
}
});
}
return result;
}
/**
* Retrieves the minimum value of an `array`. If `callback` is passed,
* it will be executed for each value in the `array` to generate the
* criterion by which the value is ranked. The `callback` is bound to `thisArg`
* and invoked with three arguments; (value, index, collection).
*
* If a property name is passed for `callback`, the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is passed for `callback`, the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function|Object|String} [callback=identity] The function called per
* iteration. If a property name or object is passed, it will be used to create
* a "_.pluck" or "_.where" style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Mixed} Returns the minimum value.
* @example
*
* _.min([4, 2, 8, 6]);
* // => 2
*
* var stooges = [
* { 'name': 'moe', 'age': 40 },
* { 'name': 'larry', 'age': 50 }
* ];
*
* _.min(stooges, function(stooge) { return stooge.age; });
* // => { 'name': 'moe', 'age': 40 };
*
* // using "_.pluck" callback shorthand
* _.min(stooges, 'age');
* // => { 'name': 'moe', 'age': 40 };
*/
function min(collection, callback, thisArg) {
var computed = Infinity,
result = computed;
if (!callback && isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
var value = collection[index];
if (value < result) {
result = value;
}
}
} else {
callback = (!callback && isString(collection))
? charAtCallback
: lodash.createCallback(callback, thisArg);
each(collection, function(value, index, collection) {
var current = callback(value, index, collection);
if (current < computed) {
computed = current;
result = value;
}
});
}
return result;
}
/**
* Retrieves the value of a specified property from all elements in the `collection`.
*
* @static
* @memberOf _
* @type Function
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {String} property The property to pluck.
* @returns {Array} Returns a new array of property values.
* @example
*
* var stooges = [
* { 'name': 'moe', 'age': 40 },
* { 'name': 'larry', 'age': 50 }
* ];
*
* _.pluck(stooges, 'name');
* // => ['moe', 'larry']
*/
var pluck = map;
/**
* Reduces a `collection` to a value which is the accumulated result of running
* each element in the `collection` through the `callback`, where each successive
* `callback` execution consumes the return value of the previous execution.
* If `accumulator` is not passed, the first element of the `collection` will be
* used as the initial `accumulator` value. The `callback` is bound to `thisArg`
* and invoked with four arguments; (accumulator, value, index|key, collection).
*
* @static
* @memberOf _
* @alias foldl, inject
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [accumulator] Initial value of the accumulator.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Mixed} Returns the accumulated value.
* @example
*
* var sum = _.reduce([1, 2, 3], function(sum, num) {
* return sum + num;
* });
* // => 6
*
* var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) {
* result[key] = num * 3;
* return result;
* }, {});
* // => { 'a': 3, 'b': 6, 'c': 9 }
*/
function reduce(collection, callback, accumulator, thisArg) {
var noaccum = arguments.length < 3;
callback = lodash.createCallback(callback, thisArg, 4);
if (isArray(collection)) {
var index = -1,
length = collection.length;
if (noaccum) {
accumulator = collection[++index];
}
while (++index < length) {
accumulator = callback(accumulator, collection[index], index, collection);
}
} else {
each(collection, function(value, index, collection) {
accumulator = noaccum
? (noaccum = false, value)
: callback(accumulator, value, index, collection)
});
}
return accumulator;
}
/**
* This method is similar to `_.reduce`, except that it iterates over a
* `collection` from right to left.
*
* @static
* @memberOf _
* @alias foldr
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function} [callback=identity] The function called per iteration.
* @param {Mixed} [accumulator] Initial value of the accumulator.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Mixed} Returns the accumulated value.
* @example
*
* var list = [[0, 1], [2, 3], [4, 5]];
* var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
* // => [4, 5, 2, 3, 0, 1]
*/
function reduceRight(collection, callback, accumulator, thisArg) {
var iterable = collection,
length = collection ? collection.length : 0,
noaccum = arguments.length < 3;
if (typeof length != 'number') {
var props = keys(collection);
length = props.length;
} else if (support.unindexedChars && isString(collection)) {
iterable = collection.split('');
}
callback = lodash.createCallback(callback, thisArg, 4);
forEach(collection, function(value, index, collection) {
index = props ? props[--length] : --length;
accumulator = noaccum
? (noaccum = false, iterable[index])
: callback(accumulator, iterable[index], index, collection);
});
return accumulator;
}
/**
* The opposite of `_.filter`, this method returns the elements of a
* `collection` that `callback` does **not** return truthy for.
*
* If a property name is passed for `callback`, the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is passed for `callback`, the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function|Object|String} [callback=identity] The function called per
* iteration. If a property name or object is passed, it will be used to create
* a "_.pluck" or "_.where" style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of elements that did **not** pass the
* callback check.
* @example
*
* var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; });
* // => [1, 3, 5]
*
* var food = [
* { 'name': 'apple', 'organic': false, 'type': 'fruit' },
* { 'name': 'carrot', 'organic': true, 'type': 'vegetable' }
* ];
*
* // using "_.pluck" callback shorthand
* _.reject(food, 'organic');
* // => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }]
*
* // using "_.where" callback shorthand
* _.reject(food, { 'type': 'fruit' });
* // => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }]
*/
function reject(collection, callback, thisArg) {
callback = lodash.createCallback(callback, thisArg);
return filter(collection, function(value, index, collection) {
return !callback(value, index, collection);
});
}
/**
* Creates an array of shuffled `array` values, using a version of the
* Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to shuffle.
* @returns {Array} Returns a new shuffled collection.
* @example
*
* _.shuffle([1, 2, 3, 4, 5, 6]);
* // => [4, 1, 6, 3, 5, 2]
*/
function shuffle(collection) {
var index = -1,
length = collection ? collection.length : 0,
result = Array(typeof length == 'number' ? length : 0);
forEach(collection, function(value) {
var rand = floor(nativeRandom() * (++index + 1));
result[index] = result[rand];
result[rand] = value;
});
return result;
}
/**
* Gets the size of the `collection` by returning `collection.length` for arrays
* and array-like objects or the number of own enumerable properties for objects.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to inspect.
* @returns {Number} Returns `collection.length` or number of own enumerable properties.
* @example
*
* _.size([1, 2]);
* // => 2
*
* _.size({ 'one': 1, 'two': 2, 'three': 3 });
* // => 3
*
* _.size('curly');
* // => 5
*/
function size(collection) {
var length = collection ? collection.length : 0;
return typeof length == 'number' ? length : keys(collection).length;
}
/**
* Checks if the `callback` returns a truthy value for **any** element of a
* `collection`. The function returns as soon as it finds passing value, and
* does not iterate over the entire `collection`. The `callback` is bound to
* `thisArg` and invoked with three arguments; (value, index|key, collection).
*
* If a property name is passed for `callback`, the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is passed for `callback`, the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias any
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function|Object|String} [callback=identity] The function called per
* iteration. If a property name or object is passed, it will be used to create
* a "_.pluck" or "_.where" style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Boolean} Returns `true` if any element passes the callback check,
* else `false`.
* @example
*
* _.some([null, 0, 'yes', false], Boolean);
* // => true
*
* var food = [
* { 'name': 'apple', 'organic': false, 'type': 'fruit' },
* { 'name': 'carrot', 'organic': true, 'type': 'vegetable' }
* ];
*
* // using "_.pluck" callback shorthand
* _.some(food, 'organic');
* // => true
*
* // using "_.where" callback shorthand
* _.some(food, { 'type': 'meat' });
* // => false
*/
function some(collection, callback, thisArg) {
var result;
callback = lodash.createCallback(callback, thisArg);
if (isArray(collection)) {
var index = -1,
length = collection.length;
while (++index < length) {
if ((result = callback(collection[index], index, collection))) {
break;
}
}
} else {
each(collection, function(value, index, collection) {
return !(result = callback(value, index, collection));
});
}
return !!result;
}
/**
* Creates an array of elements, sorted in ascending order by the results of
* running each element in the `collection` through the `callback`. This method
* performs a stable sort, that is, it will preserve the original sort order of
* equal elements. The `callback` is bound to `thisArg` and invoked with three
* arguments; (value, index|key, collection).
*
* If a property name is passed for `callback`, the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is passed for `callback`, the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Function|Object|String} [callback=identity] The function called per
* iteration. If a property name or object is passed, it will be used to create
* a "_.pluck" or "_.where" style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of sorted elements.
* @example
*
* _.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
* // => [3, 1, 2]
*
* _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
* // => [3, 1, 2]
*
* // using "_.pluck" callback shorthand
* _.sortBy(['banana', 'strawberry', 'apple'], 'length');
* // => ['apple', 'banana', 'strawberry']
*/
function sortBy(collection, callback, thisArg) {
var index = -1,
length = collection ? collection.length : 0,
result = Array(typeof length == 'number' ? length : 0);
callback = lodash.createCallback(callback, thisArg);
forEach(collection, function(value, key, collection) {
result[++index] = {
'criteria': callback(value, key, collection),
'index': index,
'value': value
};
});
length = result.length;
result.sort(compareAscending);
while (length--) {
result[length] = result[length].value;
}
return result;
}
/**
* Converts the `collection` to an array.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|String} collection The collection to convert.
* @returns {Array} Returns the new converted array.
* @example
*
* (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
* // => [2, 3, 4]
*/
function toArray(collection) {
if (collection && typeof collection.length == 'number') {
return (support.unindexedChars && isString(collection))
? collection.split('')
: slice(collection);
}
return values(collection);
}
/**
* Examines each element in a `collection`, returning an array of all elements
* that have the given `properties`. When checking `properties`, this method
* performs a deep comparison between values to determine if they are equivalent
* to each other.
*
* @static
* @memberOf _
* @type Function
* @category Collections
* @param {Array|Object|String} collection The collection to iterate over.
* @param {Object} properties The object of property values to filter by.
* @returns {Array} Returns a new array of elements that have the given `properties`.
* @example
*
* var stooges = [
* { 'name': 'moe', 'age': 40 },
* { 'name': 'larry', 'age': 50 }
* ];
*
* _.where(stooges, { 'age': 40 });
* // => [{ 'name': 'moe', 'age': 40 }]
*/
var where = filter;
/*--------------------------------------------------------------------------*/
/**
* Creates an array with all falsey values of `array` removed. The values
* `false`, `null`, `0`, `""`, `undefined` and `NaN` are all falsey.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to compact.
* @returns {Array} Returns a new filtered array.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var index = -1,
length = array ? array.length : 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result.push(value);
}
}
return result;
}
/**
* Creates an array of `array` elements not present in the other arrays
* using strict equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to process.
* @param {Array} [array1, array2, ...] Arrays to check.
* @returns {Array} Returns a new array of `array` elements not present in the
* other arrays.
* @example
*
* _.difference([1, 2, 3, 4, 5], [5, 2, 10]);
* // => [1, 3, 4]
*/
function difference(array) {
var index = -1,
length = array ? array.length : 0,
flattened = concat.apply(arrayRef, nativeSlice.call(arguments, 1)),
contains = cachedContains(flattened),
result = [];
while (++index < length) {
var value = array[index];
if (!contains(value)) {
result.push(value);
}
}
return result;
}
/**
* This method is similar to `_.find`, except that it returns the index of
* the element that passes the callback check, instead of the element itself.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {Function|Object|String} [callback=identity] The function called per
* iteration. If a property name or object is passed, it will be used to create
* a "_.pluck" or "_.where" style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Mixed} Returns the index of the found element, else `-1`.
* @example
*
* _.findIndex(['apple', 'banana', 'beet'], function(food) {
* return /^b/.test(food);
* });
* // => 1
*/
function findIndex(array, callback, thisArg) {
var index = -1,
length = array ? array.length : 0;
callback = lodash.createCallback(callback, thisArg);
while (++index < length) {
if (callback(array[index], index, array)) {
return index;
}
}
return -1;
}
/**
* Gets the first element of the `array`. If a number `n` is passed, the first
* `n` elements of the `array` are returned. If a `callback` function is passed,
* elements at the beginning of the array are returned as long as the `callback`
* returns truthy. The `callback` is bound to `thisArg` and invoked with three
* arguments; (value, index, array).
*
* If a property name is passed for `callback`, the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is passed for `callback`, the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias head, take
* @category Arrays
* @param {Array} array The array to query.
* @param {Function|Object|Number|String} [callback|n] The function called
* per element or the number of elements to return. If a property name or
* object is passed, it will be used to create a "_.pluck" or "_.where"
* style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Mixed} Returns the first element(s) of `array`.
* @example
*
* _.first([1, 2, 3]);
* // => 1
*
* _.first([1, 2, 3], 2);
* // => [1, 2]
*
* _.first([1, 2, 3], function(num) {
* return num < 3;
* });
* // => [1, 2]
*
* var food = [
* { 'name': 'banana', 'organic': true },
* { 'name': 'beet', 'organic': false },
* ];
*
* // using "_.pluck" callback shorthand
* _.first(food, 'organic');
* // => [{ 'name': 'banana', 'organic': true }]
*
* var food = [
* { 'name': 'apple', 'type': 'fruit' },
* { 'name': 'banana', 'type': 'fruit' },
* { 'name': 'beet', 'type': 'vegetable' }
* ];
*
* // using "_.where" callback shorthand
* _.first(food, { 'type': 'fruit' });
* // => [{ 'name': 'apple', 'type': 'fruit' }, { 'name': 'banana', 'type': 'fruit' }]
*/
function first(array, callback, thisArg) {
if (array) {
var n = 0,
length = array.length;
if (typeof callback != 'number' && callback != null) {
var index = -1;
callback = lodash.createCallback(callback, thisArg);
while (++index < length && callback(array[index], index, array)) {
n++;
}
} else {
n = callback;
if (n == null || thisArg) {
return array[0];
}
}
return slice(array, 0, nativeMin(nativeMax(0, n), length));
}
}
/**
* Flattens a nested array (the nesting can be to any depth). If `isShallow`
* is truthy, `array` will only be flattened a single level. If `callback`
* is passed, each element of `array` is passed through a callback` before
* flattening. The `callback` is bound to `thisArg` and invoked with three
* arguments; (value, index, array).
*
* If a property name is passed for `callback`, the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is passed for `callback`, the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to flatten.
* @param {Boolean} [isShallow=false] A flag to indicate only flattening a single level.
* @param {Function|Object|String} [callback=identity] The function called per
* iteration. If a property name or object is passed, it will be used to create
* a "_.pluck" or "_.where" style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new flattened array.
* @example
*
* _.flatten([1, [2], [3, [[4]]]]);
* // => [1, 2, 3, 4];
*
* _.flatten([1, [2], [3, [[4]]]], true);
* // => [1, 2, 3, [[4]]];
*
* var stooges = [
* { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] },
* { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] }
* ];
*
* // using "_.pluck" callback shorthand
* _.flatten(stooges, 'quotes');
* // => ['Oh, a wise guy, eh?', 'Poifect!', 'Spread out!', 'You knucklehead!']
*/
function flatten(array, isShallow, callback, thisArg) {
var index = -1,
length = array ? array.length : 0,
result = [];
// juggle arguments
if (typeof isShallow != 'boolean' && isShallow != null) {
thisArg = callback;
callback = isShallow;
isShallow = false;
}
if (callback != null) {
callback = lodash.createCallback(callback, thisArg);
}
while (++index < length) {
var value = array[index];
if (callback) {
value = callback(value, index, array);
}
// recursively flatten arrays (susceptible to call stack limits)
if (isArray(value)) {
push.apply(result, isShallow ? value : flatten(value));
} else {
result.push(value);
}
}
return result;
}
/**
* Gets the index at which the first occurrence of `value` is found using
* strict equality for comparisons, i.e. `===`. If the `array` is already
* sorted, passing `true` for `fromIndex` will run a faster binary search.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {Mixed} value The value to search for.
* @param {Boolean|Number} [fromIndex=0] The index to search from or `true` to
* perform a binary search on a sorted `array`.
* @returns {Number} Returns the index of the matched value or `-1`.
* @example
*
* _.indexOf([1, 2, 3, 1, 2, 3], 2);
* // => 1
*
* _.indexOf([1, 2, 3, 1, 2, 3], 2, 3);
* // => 4
*
* _.indexOf([1, 1, 2, 2, 3, 3], 2, true);
* // => 2
*/
function indexOf(array, value, fromIndex) {
var index = -1,
length = array ? array.length : 0;
if (typeof fromIndex == 'number') {
index = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0) - 1;
} else if (fromIndex) {
index = sortedIndex(array, value);
return array[index] === value ? index : -1;
}
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* Gets all but the last element of `array`. If a number `n` is passed, the
* last `n` elements are excluded from the result. If a `callback` function
* is passed, elements at the end of the array are excluded from the result
* as long as the `callback` returns truthy. The `callback` is bound to
* `thisArg` and invoked with three arguments; (value, index, array).
*
* If a property name is passed for `callback`, the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is passed for `callback`, the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to query.
* @param {Function|Object|Number|String} [callback|n=1] The function called
* per element or the number of elements to exclude. If a property name or
* object is passed, it will be used to create a "_.pluck" or "_.where"
* style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a slice of `array`.
* @example
*
* _.initial([1, 2, 3]);
* // => [1, 2]
*
* _.initial([1, 2, 3], 2);
* // => [1]
*
* _.initial([1, 2, 3], function(num) {
* return num > 1;
* });
* // => [1]
*
* var food = [
* { 'name': 'beet', 'organic': false },
* { 'name': 'carrot', 'organic': true }
* ];
*
* // using "_.pluck" callback shorthand
* _.initial(food, 'organic');
* // => [{ 'name': 'beet', 'organic': false }]
*
* var food = [
* { 'name': 'banana', 'type': 'fruit' },
* { 'name': 'beet', 'type': 'vegetable' },
* { 'name': 'carrot', 'type': 'vegetable' }
* ];
*
* // using "_.where" callback shorthand
* _.initial(food, { 'type': 'vegetable' });
* // => [{ 'name': 'banana', 'type': 'fruit' }]
*/
function initial(array, callback, thisArg) {
if (!array) {
return [];
}
var n = 0,
length = array.length;
if (typeof callback != 'number' && callback != null) {
var index = length;
callback = lodash.createCallback(callback, thisArg);
while (index-- && callback(array[index], index, array)) {
n++;
}
} else {
n = (callback == null || thisArg) ? 1 : callback || n;
}
return slice(array, 0, nativeMin(nativeMax(0, length - n), length));
}
/**
* Computes the intersection of all the passed-in arrays using strict equality
* for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} [array1, array2, ...] Arrays to process.
* @returns {Array} Returns a new array of unique elements that are present
* in **all** of the arrays.
* @example
*
* _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
* // => [1, 2]
*/
function intersection(array) {
var args = arguments,
argsLength = args.length,
cache = { '0': {} },
index = -1,
length = array ? array.length : 0,
isLarge = length >= largeArraySize,
result = [],
seen = result;
outer:
while (++index < length) {
var value = array[index];
if (isLarge) {
var key = keyPrefix + value;
var inited = cache[0][key]
? !(seen = cache[0][key])
: (seen = cache[0][key] = []);
}
if (inited || indexOf(seen, value) < 0) {
if (isLarge) {
seen.push(value);
}
var argsIndex = argsLength;
while (--argsIndex) {
if (!(cache[argsIndex] || (cache[argsIndex] = cachedContains(args[argsIndex])))(value)) {
continue outer;
}
}
result.push(value);
}
}
return result;
}
/**
* Gets the last element of the `array`. If a number `n` is passed, the
* last `n` elements of the `array` are returned. If a `callback` function
* is passed, elements at the end of the array are returned as long as the
* `callback` returns truthy. The `callback` is bound to `thisArg` and
* invoked with three arguments;(value, index, array).
*
*
* If a property name is passed for `callback`, the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is passed for `callback`, the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to query.
* @param {Function|Object|Number|String} [callback|n] The function called
* per element or the number of elements to return. If a property name or
* object is passed, it will be used to create a "_.pluck" or "_.where"
* style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Mixed} Returns the last element(s) of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*
* _.last([1, 2, 3], 2);
* // => [2, 3]
*
* _.last([1, 2, 3], function(num) {
* return num > 1;
* });
* // => [2, 3]
*
* var food = [
* { 'name': 'beet', 'organic': false },
* { 'name': 'carrot', 'organic': true }
* ];
*
* // using "_.pluck" callback shorthand
* _.last(food, 'organic');
* // => [{ 'name': 'carrot', 'organic': true }]
*
* var food = [
* { 'name': 'banana', 'type': 'fruit' },
* { 'name': 'beet', 'type': 'vegetable' },
* { 'name': 'carrot', 'type': 'vegetable' }
* ];
*
* // using "_.where" callback shorthand
* _.last(food, { 'type': 'vegetable' });
* // => [{ 'name': 'beet', 'type': 'vegetable' }, { 'name': 'carrot', 'type': 'vegetable' }]
*/
function last(array, callback, thisArg) {
if (array) {
var n = 0,
length = array.length;
if (typeof callback != 'number' && callback != null) {
var index = length;
callback = lodash.createCallback(callback, thisArg);
while (index-- && callback(array[index], index, array)) {
n++;
}
} else {
n = callback;
if (n == null || thisArg) {
return array[length - 1];
}
}
return slice(array, nativeMax(0, length - n));
}
}
/**
* Gets the index at which the last occurrence of `value` is found using strict
* equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used
* as the offset from the end of the collection.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {Mixed} value The value to search for.
* @param {Number} [fromIndex=array.length-1] The index to search from.
* @returns {Number} Returns the index of the matched value or `-1`.
* @example
*
* _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
* // => 4
*
* _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
* // => 1
*/
function lastIndexOf(array, value, fromIndex) {
var index = array ? array.length : 0;
if (typeof fromIndex == 'number') {
index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1;
}
while (index--) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to but not including `end`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Number} [start=0] The start of the range.
* @param {Number} end The end of the range.
* @param {Number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns a new range array.
* @example
*
* _.range(10);
* // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
*
* _.range(1, 11);
* // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
*
* _.range(0, 30, 5);
* // => [0, 5, 10, 15, 20, 25]
*
* _.range(0, -10, -1);
* // => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
*
* _.range(0);
* // => []
*/
function range(start, end, step) {
start = +start || 0;
step = +step || 1;
if (end == null) {
end = start;
start = 0;
}
// use `Array(length)` so V8 will avoid the slower "dictionary" mode
// http://youtu.be/XAqIpGU8ZZk#t=17m25s
var index = -1,
length = nativeMax(0, ceil((end - start) / step)),
result = Array(length);
while (++index < length) {
result[index] = start;
start += step;
}
return result;
}
/**
* The opposite of `_.initial`, this method gets all but the first value of
* `array`. If a number `n` is passed, the first `n` values are excluded from
* the result. If a `callback` function is passed, elements at the beginning
* of the array are excluded from the result as long as the `callback` returns
* truthy. The `callback` is bound to `thisArg` and invoked with three
* arguments; (value, index, array).
*
* If a property name is passed for `callback`, the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is passed for `callback`, the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias drop, tail
* @category Arrays
* @param {Array} array The array to query.
* @param {Function|Object|Number|String} [callback|n=1] The function called
* per element or the number of elements to exclude. If a property name or
* object is passed, it will be used to create a "_.pluck" or "_.where"
* style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a slice of `array`.
* @example
*
* _.rest([1, 2, 3]);
* // => [2, 3]
*
* _.rest([1, 2, 3], 2);
* // => [3]
*
* _.rest([1, 2, 3], function(num) {
* return num < 3;
* });
* // => [3]
*
* var food = [
* { 'name': 'banana', 'organic': true },
* { 'name': 'beet', 'organic': false },
* ];
*
* // using "_.pluck" callback shorthand
* _.rest(food, 'organic');
* // => [{ 'name': 'beet', 'organic': false }]
*
* var food = [
* { 'name': 'apple', 'type': 'fruit' },
* { 'name': 'banana', 'type': 'fruit' },
* { 'name': 'beet', 'type': 'vegetable' }
* ];
*
* // using "_.where" callback shorthand
* _.rest(food, { 'type': 'fruit' });
* // => [{ 'name': 'beet', 'type': 'vegetable' }]
*/
function rest(array, callback, thisArg) {
if (typeof callback != 'number' && callback != null) {
var n = 0,
index = -1,
length = array ? array.length : 0;
callback = lodash.createCallback(callback, thisArg);
while (++index < length && callback(array[index], index, array)) {
n++;
}
} else {
n = (callback == null || thisArg) ? 1 : nativeMax(0, callback);
}
return slice(array, n);
}
/**
* Uses a binary search to determine the smallest index at which the `value`
* should be inserted into `array` in order to maintain the sort order of the
* sorted `array`. If `callback` is passed, it will be executed for `value` and
* each element in `array` to compute their sort ranking. The `callback` is
* bound to `thisArg` and invoked with one argument; (value).
*
* If a property name is passed for `callback`, the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is passed for `callback`, the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to inspect.
* @param {Mixed} value The value to evaluate.
* @param {Function|Object|String} [callback=identity] The function called per
* iteration. If a property name or object is passed, it will be used to create
* a "_.pluck" or "_.where" style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Number} Returns the index at which the value should be inserted
* into `array`.
* @example
*
* _.sortedIndex([20, 30, 50], 40);
* // => 2
*
* // using "_.pluck" callback shorthand
* _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
* // => 2
*
* var dict = {
* 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 }
* };
*
* _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
* return dict.wordToNumber[word];
* });
* // => 2
*
* _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) {
* return this.wordToNumber[word];
* }, dict);
* // => 2
*/
function sortedIndex(array, value, callback, thisArg) {
var low = 0,
high = array ? array.length : low;
// explicitly reference `identity` for better inlining in Firefox
callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity;
value = callback(value);
while (low < high) {
var mid = (low + high) >>> 1;
(callback(array[mid]) < value)
? low = mid + 1
: high = mid;
}
return low;
}
/**
* Computes the union of the passed-in arrays using strict equality for
* comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} [array1, array2, ...] Arrays to process.
* @returns {Array} Returns a new array of unique values, in order, that are
* present in one or more of the arrays.
* @example
*
* _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
* // => [1, 2, 3, 101, 10]
*/
function union(array) {
if (!isArray(array)) {
arguments[0] = array ? nativeSlice.call(array) : arrayRef;
}
return uniq(concat.apply(arrayRef, arguments));
}
/**
* Creates a duplicate-value-free version of the `array` using strict equality
* for comparisons, i.e. `===`. If the `array` is already sorted, passing `true`
* for `isSorted` will run a faster algorithm. If `callback` is passed, each
* element of `array` is passed through a callback` before uniqueness is computed.
* The `callback` is bound to `thisArg` and invoked with three arguments; (value, index, array).
*
* If a property name is passed for `callback`, the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is passed for `callback`, the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @alias unique
* @category Arrays
* @param {Array} array The array to process.
* @param {Boolean} [isSorted=false] A flag to indicate that the `array` is already sorted.
* @param {Function|Object|String} [callback=identity] The function called per
* iteration. If a property name or object is passed, it will be used to create
* a "_.pluck" or "_.where" style callback, respectively.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a duplicate-value-free array.
* @example
*
* _.uniq([1, 2, 1, 3, 1]);
* // => [1, 2, 3]
*
* _.uniq([1, 1, 2, 2, 3], true);
* // => [1, 2, 3]
*
* _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return Math.floor(num); });
* // => [1, 2, 3]
*
* _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return this.floor(num); }, Math);
* // => [1, 2, 3]
*
* // using "_.pluck" callback shorthand
* _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
function uniq(array, isSorted, callback, thisArg) {
var index = -1,
length = array ? array.length : 0,
result = [],
seen = result;
// juggle arguments
if (typeof isSorted != 'boolean' && isSorted != null) {
thisArg = callback;
callback = isSorted;
isSorted = false;
}
// init value cache for large arrays
var isLarge = !isSorted && length >= largeArraySize;
if (isLarge) {
var cache = {};
}
if (callback != null) {
seen = [];
callback = lodash.createCallback(callback, thisArg);
}
while (++index < length) {
var value = array[index],
computed = callback ? callback(value, index, array) : value;
if (isLarge) {
var key = keyPrefix + computed;
var inited = cache[key]
? !(seen = cache[key])
: (seen = cache[key] = []);
}
if (isSorted
? !index || seen[seen.length - 1] !== computed
: inited || indexOf(seen, computed) < 0
) {
if (callback || isLarge) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
/**
* The inverse of `_.zip`, this method splits groups of elements into arrays
* composed of elements from each group at their corresponding indexes.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to process.
* @returns {Array} Returns a new array of the composed arrays.
* @example
*
* _.unzip([['moe', 30, true], ['larry', 40, false]]);
* // => [['moe', 'larry'], [30, 40], [true, false]];
*/
function unzip(array) {
var index = -1,
length = array ? array.length : 0,
tupleLength = length ? max(pluck(array, 'length')) : 0,
result = Array(tupleLength);
while (++index < length) {
var tupleIndex = -1,
tuple = array[index];
while (++tupleIndex < tupleLength) {
(result[tupleIndex] || (result[tupleIndex] = Array(length)))[index] = tuple[tupleIndex];
}
}
return result;
}
/**
* Creates an array with all occurrences of the passed values removed using
* strict equality for comparisons, i.e. `===`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to filter.
* @param {Mixed} [value1, value2, ...] Values to remove.
* @returns {Array} Returns a new filtered array.
* @example
*
* _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
* // => [2, 3, 4]
*/
function without(array) {
return difference(array, nativeSlice.call(arguments, 1));
}
/**
* Groups the elements of each array at their corresponding indexes. Useful for
* separate data sources that are coordinated through matching array indexes.
* For a matrix of nested arrays, `_.zip.apply(...)` can transpose the matrix
* in a similar fashion.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} [array1, array2, ...] Arrays to process.
* @returns {Array} Returns a new array of grouped elements.
* @example
*
* _.zip(['moe', 'larry'], [30, 40], [true, false]);
* // => [['moe', 30, true], ['larry', 40, false]]
*/
function zip(array) {
var index = -1,
length = array ? max(pluck(arguments, 'length')) : 0,
result = Array(length);
while (++index < length) {
result[index] = pluck(arguments, index);
}
return result;
}
/**
* Creates an object composed from arrays of `keys` and `values`. Pass either
* a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`, or
* two arrays, one of `keys` and one of corresponding `values`.
*
* @static
* @memberOf _
* @alias object
* @category Arrays
* @param {Array} keys The array of keys.
* @param {Array} [values=[]] The array of values.
* @returns {Object} Returns an object composed of the given keys and
* corresponding values.
* @example
*
* _.zipObject(['moe', 'larry'], [30, 40]);
* // => { 'moe': 30, 'larry': 40 }
*/
function zipObject(keys, values) {
var index = -1,
length = keys ? keys.length : 0,
result = {};
while (++index < length) {
var key = keys[index];
if (values) {
result[key] = values[index];
} else {
result[key[0]] = key[1];
}
}
return result;
}
/*--------------------------------------------------------------------------*/
/**
* If `n` is greater than `0`, a function is created that is restricted to
* executing `func`, with the `this` binding and arguments of the created
* function, only after it is called `n` times. If `n` is less than `1`,
* `func` is executed immediately, without a `this` binding or additional
* arguments, and its result is returned.
*
* @static
* @memberOf _
* @category Functions
* @param {Number} n The number of times the function must be called before
* it is executed.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var renderNotes = _.after(notes.length, render);
* _.forEach(notes, function(note) {
* note.asyncSave({ 'success': renderNotes });
* });
* // `renderNotes` is run once, after all notes have saved
*/
function after(n, func) {
if (n < 1) {
return func();
}
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
};
}
/**
* Creates a function that, when called, invokes `func` with the `this`
* binding of `thisArg` and prepends any additional `bind` arguments to those
* passed to the bound function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to bind.
* @param {Mixed} [thisArg] The `this` binding of `func`.
* @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var func = function(greeting) {
* return greeting + ' ' + this.name;
* };
*
* func = _.bind(func, { 'name': 'moe' }, 'hi');
* func();
* // => 'hi moe'
*/
function bind(func, thisArg) {
// use `Function#bind` if it exists and is fast
// (in V8 `Function#bind` is slower except when partially applied)
return support.fastBind || (nativeBind && arguments.length > 2)
? nativeBind.call.apply(nativeBind, arguments)
: createBound(func, thisArg, nativeSlice.call(arguments, 2));
}
/**
* Binds methods on `object` to `object`, overwriting the existing method.
* Method names may be specified as individual arguments or as arrays of method
* names. If no method names are provided, all the function properties of `object`
* will be bound.
*
* @static
* @memberOf _
* @category Functions
* @param {Object} object The object to bind and assign the bound methods to.
* @param {String} [methodName1, methodName2, ...] Method names on the object to bind.
* @returns {Object} Returns `object`.
* @example
*
* var view = {
* 'label': 'docs',
* 'onClick': function() { alert('clicked ' + this.label); }
* };
*
* _.bindAll(view);
* jQuery('#docs').on('click', view.onClick);
* // => alerts 'clicked docs', when the button is clicked
*/
function bindAll(object) {
var funcs = arguments.length > 1 ? concat.apply(arrayRef, nativeSlice.call(arguments, 1)) : functions(object),
index = -1,
length = funcs.length;
while (++index < length) {
var key = funcs[index];
object[key] = bind(object[key], object);
}
return object;
}
/**
* Creates a function that, when called, invokes the method at `object[key]`
* and prepends any additional `bindKey` arguments to those passed to the bound
* function. This method differs from `_.bind` by allowing bound functions to
* reference methods that will be redefined or don't yet exist.
* See http://michaux.ca/articles/lazy-function-definition-pattern.
*
* @static
* @memberOf _
* @category Functions
* @param {Object} object The object the method belongs to.
* @param {String} key The key of the method.
* @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var object = {
* 'name': 'moe',
* 'greet': function(greeting) {
* return greeting + ' ' + this.name;
* }
* };
*
* var func = _.bindKey(object, 'greet', 'hi');
* func();
* // => 'hi moe'
*
* object.greet = function(greeting) {
* return greeting + ', ' + this.name + '!';
* };
*
* func();
* // => 'hi, moe!'
*/
function bindKey(object, key) {
return createBound(object, key, nativeSlice.call(arguments, 2), indicatorObject);
}
/**
* Creates a function that is the composition of the passed functions,
* where each function consumes the return value of the function that follows.
* For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`.
* Each function is executed with the `this` binding of the composed function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} [func1, func2, ...] Functions to compose.
* @returns {Function} Returns the new composed function.
* @example
*
* var greet = function(name) { return 'hi ' + name; };
* var exclaim = function(statement) { return statement + '!'; };
* var welcome = _.compose(exclaim, greet);
* welcome('moe');
* // => 'hi moe!'
*/
function compose() {
var funcs = arguments;
return function() {
var args = arguments,
length = funcs.length;
while (length--) {
args = [funcs[length].apply(this, args)];
}
return args[0];
};
}
/**
* Produces a callback bound to an optional `thisArg`. If `func` is a property
* name, the created callback will return the property value for a given element.
* If `func` is an object, the created callback will return `true` for elements
* that contain the equivalent object properties, otherwise it will return `false`.
*
* Note: All Lo-Dash methods, that accept a `callback` argument, use `_.createCallback`.
*
* @static
* @memberOf _
* @category Functions
* @param {Mixed} [func=identity] The value to convert to a callback.
* @param {Mixed} [thisArg] The `this` binding of the created callback.
* @param {Number} [argCount=3] The number of arguments the callback accepts.
* @returns {Function} Returns a callback function.
* @example
*
* var stooges = [
* { 'name': 'moe', 'age': 40 },
* { 'name': 'larry', 'age': 50 }
* ];
*
* // wrap to create custom callback shorthands
* _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) {
* var match = /^(.+?)__([gl]t)(.+)$/.exec(callback);
* return !match ? func(callback, thisArg) : function(object) {
* return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3];
* };
* });
*
* _.filter(stooges, 'age__gt45');
* // => [{ 'name': 'larry', 'age': 50 }]
*
* // create mixins with support for "_.pluck" and "_.where" callback shorthands
* _.mixin({
* 'toLookup': function(collection, callback, thisArg) {
* callback = _.createCallback(callback, thisArg);
* return _.reduce(collection, function(result, value, index, collection) {
* return (result[callback(value, index, collection)] = value, result);
* }, {});
* }
* });
*
* _.toLookup(stooges, 'name');
* // => { 'moe': { 'name': 'moe', 'age': 40 }, 'larry': { 'name': 'larry', 'age': 50 } }
*/
function createCallback(func, thisArg, argCount) {
if (func == null) {
return identity;
}
var type = typeof func;
if (type != 'function') {
if (type != 'object') {
return function(object) {
return object[func];
};
}
var props = keys(func);
return function(object) {
var length = props.length,
result = false;
while (length--) {
if (!(result = isEqual(object[props[length]], func[props[length]], indicatorObject))) {
break;
}
}
return result;
};
}
if (typeof thisArg != 'undefined') {
if (argCount === 1) {
return function(value) {
return func.call(thisArg, value);
};
}
if (argCount === 2) {
return function(a, b) {
return func.call(thisArg, a, b);
};
}
if (argCount === 4) {
return function(accumulator, value, index, collection) {
return func.call(thisArg, accumulator, value, index, collection);
};
}
return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
}
return func;
}
/**
* Creates a function that will delay the execution of `func` until after
* `wait` milliseconds have elapsed since the last time it was invoked. Pass
* an `options` object to indicate that `func` should be invoked on the leading
* and/or trailing edge of the `wait` timeout. Subsequent calls to the debounced
* function will return the result of the last `func` call.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to debounce.
* @param {Number} wait The number of milliseconds to delay.
* @param {Object} options The options object.
* [leading=false] A boolean to specify execution on the leading edge of the timeout.
* [trailing=true] A boolean to specify execution on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* var lazyLayout = _.debounce(calculateLayout, 300);
* jQuery(window).on('resize', lazyLayout);
*/
function debounce(func, wait, options) {
var args,
result,
thisArg,
timeoutId,
trailing = true;
function delayed() {
timeoutId = null;
if (trailing) {
result = func.apply(thisArg, args);
}
}
if (options === true) {
var leading = true;
trailing = false;
} else if (options && objectTypes[typeof options]) {
leading = options.leading;
trailing = 'trailing' in options ? options.trailing : trailing;
}
return function() {
var isLeading = leading && !timeoutId;
args = arguments;
thisArg = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(delayed, wait);
if (isLeading) {
result = func.apply(thisArg, args);
}
return result;
};
}
/**
* Defers executing the `func` function until the current call stack has cleared.
* Additional arguments will be passed to `func` when it is invoked.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to defer.
* @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with.
* @returns {Number} Returns the timer id.
* @example
*
* _.defer(function() { alert('deferred'); });
* // returns from the function before `alert` is called
*/
function defer(func) {
var args = nativeSlice.call(arguments, 1);
return setTimeout(function() { func.apply(undefined, args); }, 1);
}
// use `setImmediate` if it's available in Node.js
if (isV8 && freeModule && typeof setImmediate == 'function') {
defer = bind(setImmediate, context);
}
/**
* Executes the `func` function after `wait` milliseconds. Additional arguments
* will be passed to `func` when it is invoked.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to delay.
* @param {Number} wait The number of milliseconds to delay execution.
* @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with.
* @returns {Number} Returns the timer id.
* @example
*
* var log = _.bind(console.log, console);
* _.delay(log, 1000, 'logged later');
* // => 'logged later' (Appears after one second.)
*/
function delay(func, wait) {
var args = nativeSlice.call(arguments, 2);
return setTimeout(function() { func.apply(undefined, args); }, wait);
}
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* passed, it will be used to determine the cache key for storing the result
* based on the arguments passed to the memoized function. By default, the first
* argument passed to the memoized function is used as the cache key. The `func`
* is executed with the `this` binding of the memoized function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] A function used to resolve the cache key.
* @returns {Function} Returns the new memoizing function.
* @example
*
* var fibonacci = _.memoize(function(n) {
* return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
* });
*/
function memoize(func, resolver) {
var cache = {};
return function() {
var key = keyPrefix + (resolver ? resolver.apply(this, arguments) : arguments[0]);
return hasOwnProperty.call(cache, key)
? cache[key]
: (cache[key] = func.apply(this, arguments));
};
}
/**
* Creates a function that is restricted to execute `func` once. Repeat calls to
* the function will return the value of the first call. The `func` is executed
* with the `this` binding of the created function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // `initialize` executes `createApplication` once
*/
function once(func) {
var ran,
result;
return function() {
if (ran) {
return result;
}
ran = true;
result = func.apply(this, arguments);
// clear the `func` variable so the function may be garbage collected
func = null;
return result;
};
}
/**
* Creates a function that, when called, invokes `func` with any additional
* `partial` arguments prepended to those passed to the new function. This
* method is similar to `_.bind`, except it does **not** alter the `this` binding.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to partially apply arguments to.
* @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* var greet = function(greeting, name) { return greeting + ' ' + name; };
* var hi = _.partial(greet, 'hi');
* hi('moe');
* // => 'hi moe'
*/
function partial(func) {
return createBound(func, nativeSlice.call(arguments, 1));
}
/**
* This method is similar to `_.partial`, except that `partial` arguments are
* appended to those passed to the new function.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to partially apply arguments to.
* @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* var defaultsDeep = _.partialRight(_.merge, _.defaults);
*
* var options = {
* 'variable': 'data',
* 'imports': { 'jq': $ }
* };
*
* defaultsDeep(options, _.templateSettings);
*
* options.variable
* // => 'data'
*
* options.imports
* // => { '_': _, 'jq': $ }
*/
function partialRight(func) {
return createBound(func, nativeSlice.call(arguments, 1), null, indicatorObject);
}
/**
* Creates a function that, when executed, will only call the `func` function
* at most once per every `wait` milliseconds. If the throttled function is
* invoked more than once during the `wait` timeout, `func` will also be called
* on the trailing edge of the timeout. Pass an `options` object to indicate
* that `func` should be invoked on the leading and/or trailing edge of the
* `wait` timeout. Subsequent calls to the throttled function will return
* the result of the last `func` call.
*
* @static
* @memberOf _
* @category Functions
* @param {Function} func The function to throttle.
* @param {Number} wait The number of milliseconds to throttle executions to.
* @param {Object} options The options object.
* [leading=true] A boolean to specify execution on the leading edge of the timeout.
* [trailing=true] A boolean to specify execution on the trailing edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* var throttled = _.throttle(updatePosition, 100);
* jQuery(window).on('scroll', throttled);
*/
function throttle(func, wait, options) {
var args,
result,
thisArg,
timeoutId,
lastCalled = 0,
leading = true,
trailing = true;
function trailingCall() {
lastCalled = new Date;
timeoutId = null;
if (trailing) {
result = func.apply(thisArg, args);
}
}
if (options === false) {
leading = false;
} else if (options && objectTypes[typeof options]) {
leading = 'leading' in options ? options.leading : leading;
trailing = 'trailing' in options ? options.trailing : trailing;
}
return function() {
var now = new Date;
if (!timeoutId && !leading) {
lastCalled = now;
}
var remaining = wait - (now - lastCalled);
args = arguments;
thisArg = this;
if (remaining <= 0) {
clearTimeout(timeoutId);
timeoutId = null;
lastCalled = now;
result = func.apply(thisArg, args);
}
else if (!timeoutId) {
timeoutId = setTimeout(trailingCall, remaining);
}
return result;
};
}
/**
* Creates a function that passes `value` to the `wrapper` function as its
* first argument. Additional arguments passed to the function are appended
* to those passed to the `wrapper` function. The `wrapper` is executed with
* the `this` binding of the created function.
*
* @static
* @memberOf _
* @category Functions
* @param {Mixed} value The value to wrap.
* @param {Function} wrapper The wrapper function.
* @returns {Function} Returns the new function.
* @example
*
* var hello = function(name) { return 'hello ' + name; };
* hello = _.wrap(hello, function(func) {
* return 'before, ' + func('moe') + ', after';
* });
* hello();
* // => 'before, hello moe, after'
*/
function wrap(value, wrapper) {
return function() {
var args = [value];
push.apply(args, arguments);
return wrapper.apply(this, args);
};
}
/*--------------------------------------------------------------------------*/
/**
* Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their
* corresponding HTML entities.
*
* @static
* @memberOf _
* @category Utilities
* @param {String} string The string to escape.
* @returns {String} Returns the escaped string.
* @example
*
* _.escape('Moe, Larry & Curly');
* // => 'Moe, Larry & Curly'
*/
function escape(string) {
return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar);
}
/**
* This function returns the first argument passed to it.
*
* @static
* @memberOf _
* @category Utilities
* @param {Mixed} value Any value.
* @returns {Mixed} Returns `value`.
* @example
*
* var moe = { 'name': 'moe' };
* moe === _.identity(moe);
* // => true
*/
function identity(value) {
return value;
}
/**
* Adds functions properties of `object` to the `lodash` function and chainable
* wrapper.
*
* @static
* @memberOf _
* @category Utilities
* @param {Object} object The object of function properties to add to `lodash`.
* @example
*
* _.mixin({
* 'capitalize': function(string) {
* return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
* }
* });
*
* _.capitalize('moe');
* // => 'Moe'
*
* _('moe').capitalize();
* // => 'Moe'
*/
function mixin(object) {
forEach(functions(object), function(methodName) {
var func = lodash[methodName] = object[methodName];
lodash.prototype[methodName] = function() {
var value = this.__wrapped__,
args = [value];
push.apply(args, arguments);
var result = func.apply(lodash, args);
return (value && typeof value == 'object' && value == result)
? this
: new lodashWrapper(result);
};
});
}
/**
* Reverts the '_' variable to its previous value and returns a reference to
* the `lodash` function.
*
* @static
* @memberOf _
* @category Utilities
* @returns {Function} Returns the `lodash` function.
* @example
*
* var lodash = _.noConflict();
*/
function noConflict() {
context._ = oldDash;
return this;
}
/**
* Converts the given `value` into an integer of the specified `radix`.
*
* Note: This method avoids differences in native ES3 and ES5 `parseInt`
* implementations. See http://es5.github.com/#E.
*
* @static
* @memberOf _
* @category Utilities
* @param {Mixed} value The value to parse.
* @returns {Number} Returns the new integer value.
* @example
*
* _.parseInt('08');
* // => 8
*/
var parseInt = nativeParseInt('08') == 8 ? nativeParseInt : function(value, radix) {
// Firefox and Opera still follow the ES3 specified implementation of `parseInt`
return nativeParseInt(isString(value) ? value.replace(reLeadingZeros, '') : value, radix || 0);
};
/**
* Produces a random number between `min` and `max` (inclusive). If only one
* argument is passed, a number between `0` and the given number will be returned.
*
* @static
* @memberOf _
* @category Utilities
* @param {Number} [min=0] The minimum possible value.
* @param {Number} [max=1] The maximum possible value.
* @returns {Number} Returns a random number.
* @example
*
* _.random(0, 5);
* // => a number between 0 and 5
*
* _.random(5);
* // => also a number between 0 and 5
*/
function random(min, max) {
if (min == null && max == null) {
max = 1;
}
min = +min || 0;
if (max == null) {
max = min;
min = 0;
}
return min + floor(nativeRandom() * ((+max || 0) - min + 1));
}
/**
* Resolves the value of `property` on `object`. If `property` is a function,
* it will be invoked with the `this` binding of `object` and its result returned,
* else the property value is returned. If `object` is falsey, then `undefined`
* is returned.
*
* @static
* @memberOf _
* @category Utilities
* @param {Object} object The object to inspect.
* @param {String} property The property to get the value of.
* @returns {Mixed} Returns the resolved value.
* @example
*
* var object = {
* 'cheese': 'crumpets',
* 'stuff': function() {
* return 'nonsense';
* }
* };
*
* _.result(object, 'cheese');
* // => 'crumpets'
*
* _.result(object, 'stuff');
* // => 'nonsense'
*/
function result(object, property) {
var value = object ? object[property] : undefined;
return isFunction(value) ? object[property]() : value;
}
/**
* A micro-templating method that handles arbitrary delimiters, preserves
* whitespace, and correctly escapes quotes within interpolated code.
*
* Note: In the development build, `_.template` utilizes sourceURLs for easier
* debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
*
* For more information on precompiling templates see:
* http://lodash.com/#custom-builds
*
* For more information on Chrome extension sandboxes see:
* http://developer.chrome.com/stable/extensions/sandboxingEval.html
*
* @static
* @memberOf _
* @category Utilities
* @param {String} text The template text.
* @param {Object} data The data object used to populate the text.
* @param {Object} options The options object.
* escape - The "escape" delimiter regexp.
* evaluate - The "evaluate" delimiter regexp.
* interpolate - The "interpolate" delimiter regexp.
* sourceURL - The sourceURL of the template's compiled source.
* variable - The data object variable name.
* @returns {Function|String} Returns a compiled function when no `data` object
* is given, else it returns the interpolated text.
* @example
*
* // using a compiled template
* var compiled = _.template('hello <%= name %>');
* compiled({ 'name': 'moe' });
* // => 'hello moe'
*
* var list = '<% _.forEach(people, function(name) { %><li><%= name %></li><% }); %>';
* _.template(list, { 'people': ['moe', 'larry'] });
* // => '<li>moe</li><li>larry</li>'
*
* // using the "escape" delimiter to escape HTML in data property values
* _.template('<b><%- value %></b>', { 'value': '<script>' });
* // => '<b><script></b>'
*
* // using the ES6 delimiter as an alternative to the default "interpolate" delimiter
* _.template('hello ${ name }', { 'name': 'curly' });
* // => 'hello curly'
*
* // using the internal `print` function in "evaluate" delimiters
* _.template('<% print("hello " + epithet); %>!', { 'epithet': 'stooge' });
* // => 'hello stooge!'
*
* // using custom template delimiters
* _.templateSettings = {
* 'interpolate': /{{([\s\S]+?)}}/g
* };
*
* _.template('hello {{ name }}!', { 'name': 'mustache' });
* // => 'hello mustache!'
*
* // using the `sourceURL` option to specify a custom sourceURL for the template
* var compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' });
* compiled(data);
* // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
*
* // using the `variable` option to ensure a with-statement isn't used in the compiled template
* var compiled = _.template('hi <%= data.name %>!', null, { 'variable': 'data' });
* compiled.source;
* // => function(data) {
* var __t, __p = '', __e = _.escape;
* __p += 'hi ' + ((__t = ( data.name )) == null ? '' : __t) + '!';
* return __p;
* }
*
* // using the `source` property to inline compiled templates for meaningful
* // line numbers in error messages and a stack trace
* fs.writeFileSync(path.join(cwd, 'jst.js'), '\
* var JST = {\
* "main": ' + _.template(mainText).source + '\
* };\
* ');
*/
function template(text, data, options) {
// based on John Resig's `tmpl` implementation
// http://ejohn.org/blog/javascript-micro-templating/
// and Laura Doktorova's doT.js
// https://github.com/olado/doT
var settings = lodash.templateSettings;
text || (text = '');
// avoid missing dependencies when `iteratorTemplate` is not defined
options = iteratorTemplate ? defaults({}, options, settings) : settings;
var imports = iteratorTemplate && defaults({}, options.imports, settings.imports),
importsKeys = iteratorTemplate ? keys(imports) : ['_'],
importsValues = iteratorTemplate ? values(imports) : [lodash];
var isEvaluating,
index = 0,
interpolate = options.interpolate || reNoMatch,
source = "__p += '";
// compile the regexp to match each delimiter
var reDelimiters = RegExp(
(options.escape || reNoMatch).source + '|' +
interpolate.source + '|' +
(interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
(options.evaluate || reNoMatch).source + '|$'
, 'g');
text.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
interpolateValue || (interpolateValue = esTemplateValue);
// escape characters that cannot be included in string literals
source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar);
// replace delimiters with snippets
if (escapeValue) {
source += "' +\n__e(" + escapeValue + ") +\n'";
}
if (evaluateValue) {
isEvaluating = true;
source += "';\n" + evaluateValue + ";\n__p += '";
}
if (interpolateValue) {
source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
}
index = offset + match.length;
// the JS engine embedded in Adobe products requires returning the `match`
// string in order to produce the correct `offset` value
return match;
});
source += "';\n";
// if `variable` is not specified, wrap a with-statement around the generated
// code to add the data object to the top of the scope chain
var variable = options.variable,
hasVariable = variable;
if (!hasVariable) {
variable = 'obj';
source = 'with (' + variable + ') {\n' + source + '\n}\n';
}
// cleanup code by stripping empty strings
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
.replace(reEmptyStringMiddle, '$1')
.replace(reEmptyStringTrailing, '$1;');
// frame code as the function body
source = 'function(' + variable + ') {\n' +
(hasVariable ? '' : variable + ' || (' + variable + ' = {});\n') +
"var __t, __p = '', __e = _.escape" +
(isEvaluating
? ', __j = Array.prototype.join;\n' +
"function print() { __p += __j.call(arguments, '') }\n"
: ';\n'
) +
source +
'return __p\n}';
// Use a sourceURL for easier debugging and wrap in a multi-line comment to
// avoid issues with Narwhal, IE conditional compilation, and the JS engine
// embedded in Adobe products.
// http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl
var sourceURL = '\n/*\n//@ sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']') + '\n*/';
try {
var result = Function(importsKeys, 'return ' + source + sourceURL).apply(undefined, importsValues);
} catch(e) {
e.source = source;
throw e;
}
if (data) {
return result(data);
}
// provide the compiled function's source via its `toString` method, in
// supported environments, or the `source` property as a convenience for
// inlining compiled templates during the build process
result.source = source;
return result;
}
/**
* Executes the `callback` function `n` times, returning an array of the results
* of each `callback` execution. The `callback` is bound to `thisArg` and invoked
* with one argument; (index).
*
* @static
* @memberOf _
* @category Utilities
* @param {Number} n The number of times to execute the callback.
* @param {Function} callback The function called per iteration.
* @param {Mixed} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of the results of each `callback` execution.
* @example
*
* var diceRolls = _.times(3, _.partial(_.random, 1, 6));
* // => [3, 6, 4]
*
* _.times(3, function(n) { mage.castSpell(n); });
* // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively
*
* _.times(3, function(n) { this.cast(n); }, mage);
* // => also calls `mage.castSpell(n)` three times
*/
function times(n, callback, thisArg) {
n = (n = +n) > -1 ? n : 0;
var index = -1,
result = Array(n);
callback = lodash.createCallback(callback, thisArg, 1);
while (++index < n) {
result[index] = callback(index);
}
return result;
}
/**
* The inverse of `_.escape`, this method converts the HTML entities
* `&`, `<`, `>`, `"`, and `'` in `string` to their
* corresponding characters.
*
* @static
* @memberOf _
* @category Utilities
* @param {String} string The string to unescape.
* @returns {String} Returns the unescaped string.
* @example
*
* _.unescape('Moe, Larry & Curly');
* // => 'Moe, Larry & Curly'
*/
function unescape(string) {
return string == null ? '' : String(string).replace(reEscapedHtml, unescapeHtmlChar);
}
/**
* Generates a unique ID. If `prefix` is passed, the ID will be appended to it.
*
* @static
* @memberOf _
* @category Utilities
* @param {String} [prefix] The value to prefix the ID with.
* @returns {String} Returns the unique ID.
* @example
*
* _.uniqueId('contact_');
* // => 'contact_104'
*
* _.uniqueId();
* // => '105'
*/
function uniqueId(prefix) {
var id = ++idCounter;
return String(prefix == null ? '' : prefix) + id;
}
/*--------------------------------------------------------------------------*/
/**
* Invokes `interceptor` with the `value` as the first argument, and then
* returns `value`. The purpose of this method is to "tap into" a method chain,
* in order to perform operations on intermediate results within the chain.
*
* @static
* @memberOf _
* @category Chaining
* @param {Mixed} value The value to pass to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @returns {Mixed} Returns `value`.
* @example
*
* _([1, 2, 3, 4])
* .filter(function(num) { return num % 2 == 0; })
* .tap(alert)
* .map(function(num) { return num * num; })
* .value();
* // => // [2, 4] (alerted)
* // => [4, 16]
*/
function tap(value, interceptor) {
interceptor(value);
return value;
}
/**
* Produces the `toString` result of the wrapped value.
*
* @name toString
* @memberOf _
* @category Chaining
* @returns {String} Returns the string result.
* @example
*
* _([1, 2, 3]).toString();
* // => '1,2,3'
*/
function wrapperToString() {
return String(this.__wrapped__);
}
/**
* Extracts the wrapped value.
*
* @name valueOf
* @memberOf _
* @alias value
* @category Chaining
* @returns {Mixed} Returns the wrapped value.
* @example
*
* _([1, 2, 3]).valueOf();
* // => [1, 2, 3]
*/
function wrapperValueOf() {
return this.__wrapped__;
}
/*--------------------------------------------------------------------------*/
// add functions that return wrapped values when chaining
lodash.after = after;
lodash.assign = assign;
lodash.at = at;
lodash.bind = bind;
lodash.bindAll = bindAll;
lodash.bindKey = bindKey;
lodash.compact = compact;
lodash.compose = compose;
lodash.countBy = countBy;
lodash.createCallback = createCallback;
lodash.debounce = debounce;
lodash.defaults = defaults;
lodash.defer = defer;
lodash.delay = delay;
lodash.difference = difference;
lodash.filter = filter;
lodash.flatten = flatten;
lodash.forEach = forEach;
lodash.forIn = forIn;
lodash.forOwn = forOwn;
lodash.functions = functions;
lodash.groupBy = groupBy;
lodash.initial = initial;
lodash.intersection = intersection;
lodash.invert = invert;
lodash.invoke = invoke;
lodash.keys = keys;
lodash.map = map;
lodash.max = max;
lodash.memoize = memoize;
lodash.merge = merge;
lodash.min = min;
lodash.omit = omit;
lodash.once = once;
lodash.pairs = pairs;
lodash.partial = partial;
lodash.partialRight = partialRight;
lodash.pick = pick;
lodash.pluck = pluck;
lodash.range = range;
lodash.reject = reject;
lodash.rest = rest;
lodash.shuffle = shuffle;
lodash.sortBy = sortBy;
lodash.tap = tap;
lodash.throttle = throttle;
lodash.times = times;
lodash.toArray = toArray;
lodash.union = union;
lodash.uniq = uniq;
lodash.unzip = unzip;
lodash.values = values;
lodash.where = where;
lodash.without = without;
lodash.wrap = wrap;
lodash.zip = zip;
lodash.zipObject = zipObject;
// add aliases
lodash.collect = map;
lodash.drop = rest;
lodash.each = forEach;
lodash.extend = assign;
lodash.methods = functions;
lodash.object = zipObject;
lodash.select = filter;
lodash.tail = rest;
lodash.unique = uniq;
// add functions to `lodash.prototype`
mixin(lodash);
/*--------------------------------------------------------------------------*/
// add functions that return unwrapped values when chaining
lodash.clone = clone;
lodash.cloneDeep = cloneDeep;
lodash.contains = contains;
lodash.escape = escape;
lodash.every = every;
lodash.find = find;
lodash.findIndex = findIndex;
lodash.findKey = findKey;
lodash.has = has;
lodash.identity = identity;
lodash.indexOf = indexOf;
lodash.isArguments = isArguments;
lodash.isArray = isArray;
lodash.isBoolean = isBoolean;
lodash.isDate = isDate;
lodash.isElement = isElement;
lodash.isEmpty = isEmpty;
lodash.isEqual = isEqual;
lodash.isFinite = isFinite;
lodash.isFunction = isFunction;
lodash.isNaN = isNaN;
lodash.isNull = isNull;
lodash.isNumber = isNumber;
lodash.isObject = isObject;
lodash.isPlainObject = isPlainObject;
lodash.isRegExp = isRegExp;
lodash.isString = isString;
lodash.isUndefined = isUndefined;
lodash.lastIndexOf = lastIndexOf;
lodash.mixin = mixin;
lodash.noConflict = noConflict;
lodash.parseInt = parseInt;
lodash.random = random;
lodash.reduce = reduce;
lodash.reduceRight = reduceRight;
lodash.result = result;
lodash.runInContext = runInContext;
lodash.size = size;
lodash.some = some;
lodash.sortedIndex = sortedIndex;
lodash.template = template;
lodash.unescape = unescape;
lodash.uniqueId = uniqueId;
// add aliases
lodash.all = every;
lodash.any = some;
lodash.detect = find;
lodash.foldl = reduce;
lodash.foldr = reduceRight;
lodash.include = contains;
lodash.inject = reduce;
forOwn(lodash, function(func, methodName) {
if (!lodash.prototype[methodName]) {
lodash.prototype[methodName] = function() {
var args = [this.__wrapped__];
push.apply(args, arguments);
return func.apply(lodash, args);
};
}
});
/*--------------------------------------------------------------------------*/
// add functions capable of returning wrapped and unwrapped values when chaining
lodash.first = first;
lodash.last = last;
// add aliases
lodash.take = first;
lodash.head = first;
forOwn(lodash, function(func, methodName) {
if (!lodash.prototype[methodName]) {
lodash.prototype[methodName]= function(callback, thisArg) {
var result = func(this.__wrapped__, callback, thisArg);
return callback == null || (thisArg && typeof callback != 'function')
? result
: new lodashWrapper(result);
};
}
});
/*--------------------------------------------------------------------------*/
/**
* The semantic version number.
*
* @static
* @memberOf _
* @type String
*/
lodash.VERSION = '1.2.0';
// add "Chaining" functions to the wrapper
lodash.prototype.toString = wrapperToString;
lodash.prototype.value = wrapperValueOf;
lodash.prototype.valueOf = wrapperValueOf;
// add `Array` functions that return unwrapped values
each(['join', 'pop', 'shift'], function(methodName) {
var func = arrayRef[methodName];
lodash.prototype[methodName] = function() {
return func.apply(this.__wrapped__, arguments);
};
});
// add `Array` functions that return the wrapped value
each(['push', 'reverse', 'sort', 'unshift'], function(methodName) {
var func = arrayRef[methodName];
lodash.prototype[methodName] = function() {
func.apply(this.__wrapped__, arguments);
return this;
};
});
// add `Array` functions that return new wrapped values
each(['concat', 'slice', 'splice'], function(methodName) {
var func = arrayRef[methodName];
lodash.prototype[methodName] = function() {
return new lodashWrapper(func.apply(this.__wrapped__, arguments));
};
});
// avoid array-like object bugs with `Array#shift` and `Array#splice`
// in Firefox < 10 and IE < 9
if (!support.spliceObjects) {
each(['pop', 'shift', 'splice'], function(methodName) {
var func = arrayRef[methodName],
isSplice = methodName == 'splice';
lodash.prototype[methodName] = function() {
var value = this.__wrapped__,
result = func.apply(value, arguments);
if (value.length === 0) {
delete value[0];
}
return isSplice ? new lodashWrapper(result) : result;
};
});
}
// add pseudo private property to be used and removed during the build process
lodash._each = each;
lodash._iteratorTemplate = iteratorTemplate;
lodash._shimKeys = shimKeys;
return lodash;
}
/*--------------------------------------------------------------------------*/
// expose Lo-Dash
var _ = runInContext();
// some AMD build optimizers, like r.js, check for specific condition patterns like the following:
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// Expose Lo-Dash to the global object even when an AMD loader is present in
// case Lo-Dash was injected by a third-party script and not intended to be
// loaded as a module. The global assignment can be reverted in the Lo-Dash
// module via its `noConflict()` method.
window._ = _;
// define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module
define(function() {
return _;
});
}
// check for `exports` after `define` in case a build optimizer adds an `exports` object
else if (freeExports && !freeExports.nodeType) {
// in Node.js or RingoJS v0.8.0+
if (freeModule) {
(freeModule.exports = _)._ = _;
}
// in Narwhal or RingoJS v0.7.0-
else {
freeExports._ = _;
}
}
else {
// in a browser or Rhino
window._ = _;
}
}(this));
|
/**
* Created by zekar on 9/15/2016.
*/
import React from 'react';
import Skblock from './details.skblock';
class Overview extends React.Component {
render() {
return (<Skblock header={'Overview'}>
<br/>
{/*<icon-Skblock icon="'/images/group-114.png'" text="car.mileage"></icon-Skblock>*/}
{/*<icon-Skblock icon="'/images/group-115.png'" text="car.transmission"></icon-Skblock>*/}
{/*<icon-Skblock icon="'/images/group-116.png'" text="car.engine"></icon-Skblock>*/}
{/*<icon-Skblock icon="'/images/group-117.png'" text="car.drive"></icon-Skblock>*/}
{/*<icon-Skblock icon="'/images/group-119.png'" text="car.doors + ' doors ' + car.seats + ' seats'"></icon-Skblock>*/}
{/*<icon-Skblock icon="'/images/group-120.png'" text="car.color"></icon-Skblock>*/}
{/*<!--<icon-Skblock icon="'/images/group-121.png'" text="'Black'"></icon-Skblock>-->*/}
</Skblock>);
}
}
export default Overview;
|
(function() {
var moment = require('moment');
function hours(duration){
return format(duration.hours());
}
function minutes(duration){
return format(duration.minutes());
}
function seconds(duration){
return format(duration.seconds());
}
function milliseconds(duration){
return format(duration.milliseconds());
}
function format(duration){
if(!duration){
return '00';
} else if(('' + duration).length == 1){
return '0' + duration;
} else if(('' + duration).length == 3){
return ('' + duration).slice(0, 2);
} else {
return duration;
}
}
function convert(length) {
if(!length) {
return '00:00.00'
}
var duration = moment.duration(length);
var formattedDuration = '';
formattedDuration += hours(duration) + ':';
formattedDuration += minutes(duration) + ':';
formattedDuration += seconds(duration)
return formattedDuration;
}
module.exports = convert;
})()
|
'use strict';
angular.module('cloudoptingApp')
.controller('RegisterController', function ($scope, $translate, $timeout, Auth) {
$scope.scrollTo = function(element) {
$( 'html, body').animate({
scrollTop: $(element).offset().top
}, 500);
};
$scope.scrollTo( "#page-top");
$scope.success = null;
$scope.error = null;
$scope.doNotMatch = null;
$scope.errorUserExists = null;
$scope.registerAccount = {};
$timeout(function (){angular.element('[ng-model="registerAccount.login"]').focus();});
$scope.register = function () {
if ($scope.registerAccount.password !== $scope.confirmPassword) {
$scope.doNotMatch = 'ERROR';
} else {
$scope.registerAccount.langKey = $translate.use();
$scope.doNotMatch = null;
$scope.error = null;
$scope.errorUserExists = null;
$scope.errorEmailExists = null;
Auth.createAccount($scope.registerAccount).then(function () {
$scope.success = 'OK';
}).catch(function (response) {
$scope.success = null;
if (response.status === 400 && response.data === 'login already in use') {
$scope.errorUserExists = 'ERROR';
} else if (response.status === 400 && response.data === 'e-mail address already in use') {
$scope.errorEmailExists = 'ERROR';
} else {
$scope.error = 'ERROR';
}
});
}
};
});
|
import generateNode from '../generate-node';
export default generateNode({
spec: {
inlets: [
{ id: 'd1', type: 'float', value: '0.0' },
{ id: 'd2', type: 'float', value: '0.0' }
],
outlet: { id: 'd', type: 'float' }
},
generate: ({ d1, d2 }) => {
return `max(
-${d1},
${d2}
)`;
}
});
|
// ## Server Loader
// Passes options through the boot process to get a server instance back
var server = require('./server');
// Set the default environment to be `development`
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
function makeGhost(options) {
options = options || {};
return server(options);
}
module.exports = makeGhost;
|
search_result['333']=["topic_00000000000000AA_attached_props--.html","Constants Attached Properties",""]; |
exports.foo = 'module0.foo';
exports.bar = function () {
return 'module0.bar';
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.