code
stringlengths 2
1.05M
|
---|
module.exports={title:"Craft CMS",slug:"craftcms",svg:'<svg role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>Craft CMS icon</title><path d="M21.474 0H2.526A2.516 2.516 0 0 0 0 2.526v18.948A2.516 2.516 0 0 0 2.526 24h18.948A2.534 2.534 0 0 0 24 21.474V2.526A2.516 2.516 0 0 0 21.474 0m-9.516 14.625c.786 0 1.628-.31 2.442-1.039l1.123 1.291c-1.18.955-2.527 1.488-3.874 1.488-2.667 0-4.35-1.769-3.958-4.267.393-2.498 2.667-4.266 5.334-4.266 1.29 0 2.498.505 3.34 1.431l-1.572 1.291c-.45-.59-1.207-.982-2.05-.982-1.6 0-2.834 1.039-3.087 2.526-.224 1.488.674 2.527 2.302 2.527"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://craftcms.com/brand-resources",hex:"E5422B",license:void 0}; |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { isBlank, isPresent, isPrimitive, isStrictStringMap } from './facade/lang';
import * as o from './output/output_ast';
export var MODULE_SUFFIX = '';
var CAMEL_CASE_REGEXP = /([A-Z])/g;
export function camelCaseToDashCase(input) {
return input.replace(CAMEL_CASE_REGEXP, function () {
var m = [];
for (var _i = 0; _i < arguments.length; _i++) {
m[_i - 0] = arguments[_i];
}
return '-' + m[1].toLowerCase();
});
}
export function splitAtColon(input, defaultValues) {
return _splitAt(input, ':', defaultValues);
}
export function splitAtPeriod(input, defaultValues) {
return _splitAt(input, '.', defaultValues);
}
function _splitAt(input, character, defaultValues) {
var characterIndex = input.indexOf(character);
if (characterIndex == -1)
return defaultValues;
return [input.slice(0, characterIndex).trim(), input.slice(characterIndex + 1).trim()];
}
export function sanitizeIdentifier(name) {
return name.replace(/\W/g, '_');
}
export function visitValue(value, visitor, context) {
if (Array.isArray(value)) {
return visitor.visitArray(value, context);
}
if (isStrictStringMap(value)) {
return visitor.visitStringMap(value, context);
}
if (isBlank(value) || isPrimitive(value)) {
return visitor.visitPrimitive(value, context);
}
return visitor.visitOther(value, context);
}
export var ValueTransformer = (function () {
function ValueTransformer() {
}
ValueTransformer.prototype.visitArray = function (arr, context) {
var _this = this;
return arr.map(function (value) { return visitValue(value, _this, context); });
};
ValueTransformer.prototype.visitStringMap = function (map, context) {
var _this = this;
var result = {};
Object.keys(map).forEach(function (key) { result[key] = visitValue(map[key], _this, context); });
return result;
};
ValueTransformer.prototype.visitPrimitive = function (value, context) { return value; };
ValueTransformer.prototype.visitOther = function (value, context) { return value; };
return ValueTransformer;
}());
export function assetUrl(pkg, path, type) {
if (path === void 0) { path = null; }
if (type === void 0) { type = 'src'; }
if (path == null) {
return "asset:@angular/lib/" + pkg + "/index";
}
else {
return "asset:@angular/lib/" + pkg + "/src/" + path;
}
}
export function createDiTokenExpression(token) {
if (isPresent(token.value)) {
return o.literal(token.value);
}
else if (token.identifierIsInstance) {
return o.importExpr(token.identifier)
.instantiate([], o.importType(token.identifier, [], [o.TypeModifier.Const]));
}
else {
return o.importExpr(token.identifier);
}
}
export var SyncAsyncResult = (function () {
function SyncAsyncResult(syncResult, asyncResult) {
if (asyncResult === void 0) { asyncResult = null; }
this.syncResult = syncResult;
this.asyncResult = asyncResult;
if (!asyncResult) {
this.asyncResult = Promise.resolve(syncResult);
}
}
return SyncAsyncResult;
}());
//# sourceMappingURL=util.js.map |
import { AudioEncoder } from './audioEncoder';
const getUserMedia = ((navigator) => {
if (navigator.mediaDevices) {
return navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
}
const legacyGetUserMedia = navigator.getUserMedia
|| navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
if (legacyGetUserMedia) {
return (options) => new Promise((resolve, reject) => {
legacyGetUserMedia.call(navigator, options, resolve, reject);
});
}
})(window.navigator);
const AudioContext = window.AudioContext || window.webkitAudioContext;
class AudioRecorder {
isSupported() {
return Boolean(getUserMedia) && Boolean(AudioContext);
}
createAudioContext() {
if (this.audioContext) {
return;
}
this.audioContext = new AudioContext();
}
destroyAudioContext() {
if (!this.audioContext) {
return;
}
this.audioContext.close();
delete this.audioContext;
}
async createStream() {
if (this.stream) {
return;
}
this.stream = await getUserMedia({ audio: true });
}
destroyStream() {
if (!this.stream) {
return;
}
this.stream.getAudioTracks().forEach((track) => track.stop());
delete this.stream;
}
async createEncoder() {
if (this.encoder) {
return;
}
const input = this.audioContext.createMediaStreamSource(this.stream);
this.encoder = new AudioEncoder(input);
}
destroyEncoder() {
if (!this.encoder) {
return;
}
this.encoder.close();
delete this.encoder;
}
async start(cb) {
try {
await this.createAudioContext();
await this.createStream();
await this.createEncoder();
cb && cb.call(this, true);
} catch (error) {
console.error(error);
this.destroyEncoder();
this.destroyStream();
this.destroyAudioContext();
cb && cb.call(this, false);
}
}
stop(cb) {
this.encoder.on('encoded', cb);
this.encoder.close();
this.destroyEncoder();
this.destroyStream();
this.destroyAudioContext();
}
}
const instance = new AudioRecorder();
export { instance as AudioRecorder };
|
version https://git-lfs.github.com/spec/v1
oid sha256:1668f227ab9bbb326809d8430e0c9d1105688b38b177ab927f0528eb9593a652
size 7357
|
import mdDialog from './mdDialog.vue';
import mdDialogTitle from './mdDialogTitle.vue';
import mdDialogContent from './mdDialogContent.vue';
import mdDialogActions from './mdDialogActions.vue';
import mdDialogAlert from './presets/mdDialogAlert.vue';
import mdDialogConfirm from './presets/mdDialogConfirm.vue';
import mdDialogPrompt from './presets/mdDialogPrompt.vue';
import mdDialogTheme from './mdDialog.theme';
export default function install(Vue) {
Vue.component('md-dialog', mdDialog);
Vue.component('md-dialog-title', mdDialogTitle);
Vue.component('md-dialog-content', mdDialogContent);
Vue.component('md-dialog-actions', mdDialogActions);
/* Presets */
Vue.component('md-dialog-alert', mdDialogAlert);
Vue.component('md-dialog-confirm', mdDialogConfirm);
Vue.component('md-dialog-prompt', mdDialogPrompt);
Vue.material.styles.push(mdDialogTheme);
}
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S10.2.2_A1.1_T3;
* @section: 10.2.2;
* @assertion: The scope chain is initialised to contain the same objects,
* in the same order, as the calling context's scope chain;
* @description: eval within global execution context;
*/
var i;
var j;
str1 = '';
str2 = '';
this.x = 1;
this.y = 2;
for(i in this){
str1+=i;
}
eval('for(j in this){\nstr2+=j;\n}');
if(!(str1 === str2)){
$ERROR("#1: scope chain must contain same objects in the same order as the calling context");
}
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S12.14_A2;
* @section: 12.14;
* @assertion: Throwing exception with "throw" and catching it with "try" statement;
* @description: Checking if execution of "catch" catches an exception thrown with "throw";
*/
// CHECK#1
try {
throw "catchme";
$ERROR('#1: throw "catchme" lead to throwing exception');
}
catch(e){}
// CHECK#2
var c2=0;
try{
try{
throw "exc";
$ERROR('#2.1: throw "exc" lead to throwing exception');
}finally{
c2=1;
}
}
catch(e){
if (c2!==1){
$ERROR('#2.2: "finally" block must be evaluated');
}
}
// CHECK#3
var c3=0;
try{
throw "exc";
$ERROR('#3.1: throw "exc" lead to throwing exception');
}
catch(err){
var x3=1;
}
finally{
c3=1;
}
if (x3!==1){
$ERROR('#3.2: "catch" block must be evaluated');
}
if (c3!==1){
$ERROR('#3.3: "finally" block must be evaluated');
}
|
/* Karma configuration for standalone build */
'use strict';
module.exports = function (config) {
console.log();
console.log('Browser (Standalone) Tests');
console.log();
config.set({
basePath: '.',
frameworks: ['mocha'],
files: [
{pattern: 'swagger-tools-standalone.js', watch: false, included: true},
{pattern: 'test-browser.js', watch: false, included: true}
],
client: {
mocha: {
reporter: 'html',
timeout: 5000,
ui: 'bdd'
}
},
plugins: [
'karma-mocha',
'karma-mocha-reporter',
'karma-phantomjs-launcher'
],
browsers: ['PhantomJS'],
reporters: ['mocha'],
colors: true,
autoWatch: false,
singleRun: true
});
};
|
"use strict";
var inherits = require('util').inherits
, f = require('util').format
, formattedOrderClause = require('./utils').formattedOrderClause
, handleCallback = require('./utils').handleCallback
, ReadPreference = require('./read_preference')
, MongoError = require('mongodb-core').MongoError
, Readable = require('stream').Readable || require('readable-stream').Readable
, Define = require('./metadata')
, CoreCursor = require('mongodb-core').Cursor
, Map = require('mongodb-core').BSON.Map
, Query = require('mongodb-core').Query
, CoreReadPreference = require('mongodb-core').ReadPreference;
/**
* @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB
* allowing for iteration over the results returned from the underlying query. It supports
* one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X
* or higher stream
*
* **CURSORS Cannot directly be instantiated**
* @example
* var MongoClient = require('mongodb').MongoClient,
* test = require('assert');
* // Connection url
* var url = 'mongodb://localhost:27017/test';
* // Connect using MongoClient
* MongoClient.connect(url, function(err, db) {
* // Create a collection we want to drop later
* var col = db.collection('createIndexExample1');
* // Insert a bunch of documents
* col.insert([{a:1, b:1}
* , {a:2, b:2}, {a:3, b:3}
* , {a:4, b:4}], {w:1}, function(err, result) {
* test.equal(null, err);
*
* // Show that duplicate records got dropped
* col.find({}).toArray(function(err, items) {
* test.equal(null, err);
* test.equal(4, items.length);
* db.close();
* });
* });
* });
*/
/**
* Namespace provided by the mongodb-core and node.js
* @external CoreCursor
* @external Readable
*/
// Flags allowed for cursor
var flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial'];
var fields = ['numberOfRetries', 'tailableRetryInterval'];
var push = Array.prototype.push;
/**
* Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly)
* @class Cursor
* @extends external:CoreCursor
* @extends external:Readable
* @property {string} sortValue Cursor query sort setting.
* @property {boolean} timeout Is Cursor able to time out.
* @property {ReadPreference} readPreference Get cursor ReadPreference.
* @fires Cursor#data
* @fires Cursor#end
* @fires Cursor#close
* @fires Cursor#readable
* @return {Cursor} a Cursor instance.
* @example
* Cursor cursor options.
*
* collection.find({}).project({a:1}) // Create a projection of field a
* collection.find({}).skip(1).limit(10) // Skip 1 and limit 10
* collection.find({}).batchSize(5) // Set batchSize on cursor to 5
* collection.find({}).filter({a:1}) // Set query on the cursor
* collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries
* collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable
* collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay
* collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout
* collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData
* collection.find({}).addCursorFlag('partial', true) // Set cursor as partial
* collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1}
* collection.find({}).max(10) // Set the cursor maxScan
* collection.find({}).maxScan(10) // Set the cursor maxScan
* collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS
* collection.find({}).min(100) // Set the cursor min
* collection.find({}).returnKey(10) // Set the cursor returnKey
* collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference
* collection.find({}).showRecordId(true) // Set the cursor showRecordId
* collection.find({}).snapshot(true) // Set the cursor snapshot
* collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query
* collection.find({}).hint('a_1') // Set the cursor hint
*
* All options are chainable, so one can do the following.
*
* collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..)
*/
var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) {
CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0));
var self = this;
var state = Cursor.INIT;
var streamOptions = {};
// Tailable cursor options
var numberOfRetries = options.numberOfRetries || 5;
var tailableRetryInterval = options.tailableRetryInterval || 500;
var currentNumberOfRetries = numberOfRetries;
// Get the promiseLibrary
var promiseLibrary = options.promiseLibrary;
// No promise library selected fall back
if(!promiseLibrary) {
promiseLibrary = typeof global.Promise == 'function' ?
global.Promise : require('es6-promise').Promise;
}
// Set up
Readable.call(this, {objectMode: true});
// Internal cursor state
this.s = {
// Tailable cursor options
numberOfRetries: numberOfRetries
, tailableRetryInterval: tailableRetryInterval
, currentNumberOfRetries: currentNumberOfRetries
// State
, state: state
// Stream options
, streamOptions: streamOptions
// BSON
, bson: bson
// Namespace
, ns: ns
// Command
, cmd: cmd
// Options
, options: options
// Topology
, topology: topology
// Topology options
, topologyOptions: topologyOptions
// Promise library
, promiseLibrary: promiseLibrary
// Current doc
, currentDoc: null
}
// Translate correctly
if(self.s.options.noCursorTimeout == true) {
self.addCursorFlag('noCursorTimeout', true);
}
// Set the sort value
this.sortValue = self.s.cmd.sort;
}
/**
* Cursor stream data event, fired for each document in the cursor.
*
* @event Cursor#data
* @type {object}
*/
/**
* Cursor stream end event
*
* @event Cursor#end
* @type {null}
*/
/**
* Cursor stream close event
*
* @event Cursor#close
* @type {null}
*/
/**
* Cursor stream readable event
*
* @event Cursor#readable
* @type {null}
*/
// Inherit from Readable
inherits(Cursor, Readable);
// Map core cursor _next method so we can apply mapping
CoreCursor.prototype._next = CoreCursor.prototype.next;
for(var name in CoreCursor.prototype) {
Cursor.prototype[name] = CoreCursor.prototype[name];
}
var define = Cursor.define = new Define('Cursor', Cursor, true);
/**
* Check if there is any document still available in the cursor
* @method
* @param {Cursor~resultCallback} [callback] The result callback.
* @throws {MongoError}
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.hasNext = function(callback) {
var self = this;
// Execute using callback
if(typeof callback == 'function') {
if(self.s.currentDoc){
return callback(null, true);
} else {
return nextObject(self, function(err, doc) {
if(!doc) return callback(null, false);
self.s.currentDoc = doc;
callback(null, true);
});
}
}
// Return a Promise
return new this.s.promiseLibrary(function(resolve, reject) {
if(self.s.currentDoc){
resolve(true);
} else {
nextObject(self, function(err, doc) {
if(self.s.state == Cursor.CLOSED || self.isDead()) return resolve(false);
if(err) return reject(err);
if(!doc) return resolve(false);
self.s.currentDoc = doc;
resolve(true);
});
}
});
}
define.classMethod('hasNext', {callback: true, promise:true});
/**
* Get the next available document from the cursor, returns null if no more documents are available.
* @method
* @param {Cursor~resultCallback} [callback] The result callback.
* @throws {MongoError}
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.next = function(callback) {
var self = this;
// Execute using callback
if(typeof callback == 'function') {
// Return the currentDoc if someone called hasNext first
if(self.s.currentDoc) {
var doc = self.s.currentDoc;
self.s.currentDoc = null;
return callback(null, doc);
}
// Return the next object
return nextObject(self, callback)
};
// Return a Promise
return new this.s.promiseLibrary(function(resolve, reject) {
// Return the currentDoc if someone called hasNext first
if(self.s.currentDoc) {
var doc = self.s.currentDoc;
self.s.currentDoc = null;
return resolve(doc);
}
nextObject(self, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
}
define.classMethod('next', {callback: true, promise:true});
/**
* Set the cursor query
* @method
* @param {object} filter The filter object used for the cursor.
* @return {Cursor}
*/
Cursor.prototype.filter = function(filter) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.query = filter;
return this;
}
define.classMethod('filter', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor maxScan
* @method
* @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query
* @return {Cursor}
*/
Cursor.prototype.maxScan = function(maxScan) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.maxScan = maxScan;
return this;
}
define.classMethod('maxScan', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor hint
* @method
* @param {object} hint If specified, then the query system will only consider plans using the hinted index.
* @return {Cursor}
*/
Cursor.prototype.hint = function(hint) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.hint = hint;
return this;
}
define.classMethod('hint', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor min
* @method
* @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order.
* @return {Cursor}
*/
Cursor.prototype.min = function(min) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.min = min;
return this;
}
define.classMethod('min', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor max
* @method
* @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order.
* @return {Cursor}
*/
Cursor.prototype.max = function(max) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.max = max;
return this;
}
define.classMethod('max', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor returnKey
* @method
* @param {object} returnKey Only return the index field or fields for the results of the query. If $returnKey is set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. Use one of the following forms:
* @return {Cursor}
*/
Cursor.prototype.returnKey = function(value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.returnKey = value;
return this;
}
define.classMethod('returnKey', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor showRecordId
* @method
* @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find.
* @return {Cursor}
*/
Cursor.prototype.showRecordId = function(value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.showDiskLoc = value;
return this;
}
define.classMethod('showRecordId', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor snapshot
* @method
* @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document.
* @return {Cursor}
*/
Cursor.prototype.snapshot = function(value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.snapshot = value;
return this;
}
define.classMethod('snapshot', {callback: false, promise:false, returns: [Cursor]});
/**
* Set a node.js specific cursor option
* @method
* @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval'].
* @param {object} value The field value.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.setCursorOption = function(field, value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
if(fields.indexOf(field) == -1) throw MongoError.create({message: f("option %s not a supported option %s", field, fields), driver:true });
this.s[field] = value;
if(field == 'numberOfRetries')
this.s.currentNumberOfRetries = value;
return this;
}
define.classMethod('setCursorOption', {callback: false, promise:false, returns: [Cursor]});
/**
* Add a cursor flag to the cursor
* @method
* @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial'].
* @param {boolean} value The flag boolean value.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.addCursorFlag = function(flag, value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
if(flags.indexOf(flag) == -1) throw MongoError.create({message: f("flag %s not a supported flag %s", flag, flags), driver:true });
if(typeof value != 'boolean') throw MongoError.create({message: f("flag %s must be a boolean value", flag), driver:true});
this.s.cmd[flag] = value;
return this;
}
define.classMethod('addCursorFlag', {callback: false, promise:false, returns: [Cursor]});
/**
* Add a query modifier to the cursor query
* @method
* @param {string} name The query modifier (must start with $, such as $orderby etc)
* @param {boolean} value The flag boolean value.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.addQueryModifier = function(name, value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
if(name[0] != '$') throw MongoError.create({message: f("%s is not a valid query modifier"), driver:true});
// Strip of the $
var field = name.substr(1);
// Set on the command
this.s.cmd[field] = value;
// Deal with the special case for sort
if(field == 'orderby') this.s.cmd.sort = this.s.cmd[field];
return this;
}
define.classMethod('addQueryModifier', {callback: false, promise:false, returns: [Cursor]});
/**
* Add a comment to the cursor query allowing for tracking the comment in the log.
* @method
* @param {string} value The comment attached to this query.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.comment = function(value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.comment = value;
return this;
}
define.classMethod('comment', {callback: false, promise:false, returns: [Cursor]});
/**
* Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise)
* @method
* @param {number} value Number of milliseconds to wait before aborting the tailed query.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.maxAwaitTimeMS = function(value) {
if(typeof value != 'number') throw MongoError.create({message: "maxAwaitTimeMS must be a number", driver:true});
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.maxAwaitTimeMS = value;
return this;
}
define.classMethod('maxAwaitTimeMS', {callback: false, promise:false, returns: [Cursor]});
/**
* Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
* @method
* @param {number} value Number of milliseconds to wait before aborting the query.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.maxTimeMS = function(value) {
if(typeof value != 'number') throw MongoError.create({message: "maxTimeMS must be a number", driver:true});
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.maxTimeMS = value;
return this;
}
define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [Cursor]});
Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS;
define.classMethod('maxTimeMs', {callback: false, promise:false, returns: [Cursor]});
/**
* Sets a field projection for the query.
* @method
* @param {object} value The field projection object.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.project = function(value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.fields = value;
return this;
}
define.classMethod('project', {callback: false, promise:false, returns: [Cursor]});
/**
* Sets the sort order of the cursor query.
* @method
* @param {(string|array|object)} keyOrList The key or keys set for the sort.
* @param {number} [direction] The direction of the sorting (1 or -1).
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.sort = function(keyOrList, direction) {
if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support sorting", driver:true});
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
var order = keyOrList;
// We have an array of arrays, we need to preserve the order of the sort
// so we will us a Map
if(Array.isArray(order) && Array.isArray(order[0])) {
order = new Map(order.map(function(x) {
var value = [x[0], null];
if(x[1] == 'asc') {
value[1] = 1;
} else if(x[1] == 'desc') {
value[1] = -1;
} else if(x[1] == 1 || x[1] == -1) {
value[1] = x[1];
} else {
throw new MongoError("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]");
}
return value;
}));
}
if(direction != null) {
order = [[keyOrList, direction]];
}
this.s.cmd.sort = order;
this.sortValue = order;
return this;
}
define.classMethod('sort', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the batch size for the cursor.
* @method
* @param {number} value The batchSize for the cursor.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.batchSize = function(value) {
if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support batchSize", driver:true});
if(this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true});
this.s.cmd.batchSize = value;
this.setCursorBatchSize(value);
return this;
}
define.classMethod('batchSize', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the limit for the cursor.
* @method
* @param {number} value The limit for the cursor query.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.limit = function(value) {
if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support limit", driver:true});
if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
if(typeof value != 'number') throw MongoError.create({message: "limit requires an integer", driver:true});
this.s.cmd.limit = value;
// this.cursorLimit = value;
this.setCursorLimit(value);
return this;
}
define.classMethod('limit', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the skip for the cursor.
* @method
* @param {number} value The skip for the cursor query.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.skip = function(value) {
if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support skip", driver:true});
if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
if(typeof value != 'number') throw MongoError.create({message: "skip requires an integer", driver:true});
this.s.cmd.skip = value;
this.setCursorSkip(value);
return this;
}
define.classMethod('skip', {callback: false, promise:false, returns: [Cursor]});
/**
* The callback format for results
* @callback Cursor~resultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {(object|null|boolean)} result The result object if the command was executed successfully.
*/
/**
* Clone the cursor
* @function external:CoreCursor#clone
* @return {Cursor}
*/
/**
* Resets the cursor
* @function external:CoreCursor#rewind
* @return {null}
*/
/**
* Get the next available document from the cursor, returns null if no more documents are available.
* @method
* @param {Cursor~resultCallback} [callback] The result callback.
* @throws {MongoError}
* @deprecated
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.nextObject = Cursor.prototype.next;
var nextObject = function(self, callback) {
// console.log("cursor:: nextObject")
if(self.s.state == Cursor.CLOSED || self.isDead && self.isDead()) return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true}));
if(self.s.state == Cursor.INIT && self.s.cmd.sort) {
try {
self.s.cmd.sort = formattedOrderClause(self.s.cmd.sort);
} catch(err) {
return handleCallback(callback, err);
}
}
// Get the next object
self._next(function(err, doc) {
self.s.state = Cursor.OPEN;
if(err) return handleCallback(callback, err);
handleCallback(callback, null, doc);
});
}
define.classMethod('nextObject', {callback: true, promise:true});
// Trampoline emptying the number of retrieved items
// without incurring a nextTick operation
var loop = function(self, callback) {
// No more items we are done
if(self.bufferedCount() == 0) return;
// Get the next document
self._next(callback);
// Loop
return loop;
}
Cursor.prototype.next = Cursor.prototype.nextObject;
define.classMethod('next', {callback: true, promise:true});
/**
* Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
* not all of the elements will be iterated if this cursor had been previouly accessed.
* In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
* **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
* at any given time if batch size is specified. Otherwise, the caller is responsible
* for making sure that the entire result can fit the memory.
* @method
* @deprecated
* @param {Cursor~resultCallback} callback The result callback.
* @throws {MongoError}
* @return {null}
*/
Cursor.prototype.each = function(callback) {
// Rewind cursor state
this.rewind();
// Set current cursor to INIT
this.s.state = Cursor.INIT;
// Run the query
_each(this, callback);
};
define.classMethod('each', {callback: true, promise:false});
// Run the each loop
var _each = function(self, callback) {
if(!callback) throw MongoError.create({message: 'callback is mandatory', driver:true});
if(self.isNotified()) return;
if(self.s.state == Cursor.CLOSED || self.isDead()) {
return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true}));
}
if(self.s.state == Cursor.INIT) self.s.state = Cursor.OPEN;
// Define function to avoid global scope escape
var fn = null;
// Trampoline all the entries
if(self.bufferedCount() > 0) {
while(fn = loop(self, callback)) fn(self, callback);
_each(self, callback);
} else {
self.next(function(err, item) {
if(err) return handleCallback(callback, err);
if(item == null) {
self.s.state = Cursor.CLOSED;
return handleCallback(callback, null, null);
}
if(handleCallback(callback, null, item) == false) return;
_each(self, callback);
})
}
}
/**
* The callback format for the forEach iterator method
* @callback Cursor~iteratorCallback
* @param {Object} doc An emitted document for the iterator
*/
/**
* The callback error format for the forEach iterator method
* @callback Cursor~endCallback
* @param {MongoError} error An error instance representing the error during the execution.
*/
/**
* Iterates over all the documents for this cursor using the iterator, callback pattern.
* @method
* @param {Cursor~iteratorCallback} iterator The iteration callback.
* @param {Cursor~endCallback} callback The end callback.
* @throws {MongoError}
* @return {null}
*/
Cursor.prototype.forEach = function(iterator, callback) {
this.each(function(err, doc){
if(err) { callback(err); return false; }
if(doc != null) { iterator(doc); return true; }
if(doc == null && callback) {
var internalCallback = callback;
callback = null;
internalCallback(null);
return false;
}
});
}
define.classMethod('forEach', {callback: true, promise:false});
/**
* Set the ReadPreference for the cursor.
* @method
* @param {(string|ReadPreference)} readPreference The new read preference for the cursor.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.setReadPreference = function(r) {
if(this.s.state != Cursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true});
if(r instanceof ReadPreference) {
this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags);
} else if(typeof r == 'string'){
this.s.options.readPreference = new CoreReadPreference(r);
} else if(r instanceof CoreReadPreference) {
this.s.options.readPreference = r;
}
return this;
}
define.classMethod('setReadPreference', {callback: false, promise:false, returns: [Cursor]});
/**
* The callback format for results
* @callback Cursor~toArrayResultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {object[]} documents All the documents the satisfy the cursor.
*/
/**
* Returns an array of documents. The caller is responsible for making sure that there
* is enough memory to store the results. Note that the array only contain partial
* results when this cursor had been previouly accessed. In that case,
* cursor.rewind() can be used to reset the cursor.
* @method
* @param {Cursor~toArrayResultCallback} [callback] The result callback.
* @throws {MongoError}
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.toArray = function(callback) {
var self = this;
if(self.s.options.tailable) throw MongoError.create({message: 'Tailable cursor cannot be converted to array', driver:true});
// Execute using callback
if(typeof callback == 'function') return toArray(self, callback);
// Return a Promise
return new this.s.promiseLibrary(function(resolve, reject) {
toArray(self, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
}
var toArray = function(self, callback) {
var items = [];
// console.log("!!!!!!!!!!!!! toArray :: 0")
// Reset cursor
self.rewind();
self.s.state = Cursor.INIT;
// console.log("!!!!!!!!!!!!! toArray :: 1")
// Fetch all the documents
var fetchDocs = function() {
// console.log("!!!!!!!!!!!!! toArray :: 2")
self._next(function(err, doc) {
// console.log("!!!!!!!!!!!!! toArray :: 3")
if(err) return handleCallback(callback, err);
if(doc == null) {
self.s.state = Cursor.CLOSED;
return handleCallback(callback, null, items);
}
// Add doc to items
items.push(doc)
// Get all buffered objects
if(self.bufferedCount() > 0) {
var docs = self.readBufferedDocuments(self.bufferedCount())
// Transform the doc if transform method added
if(self.s.transforms && typeof self.s.transforms.doc == 'function') {
docs = docs.map(self.s.transforms.doc);
}
push.apply(items, docs);
}
// Attempt a fetch
fetchDocs();
})
}
fetchDocs();
}
define.classMethod('toArray', {callback: true, promise:true});
/**
* The callback format for results
* @callback Cursor~countResultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {number} count The count of documents.
*/
/**
* Get the count of documents for this cursor
* @method
* @param {boolean} applySkipLimit Should the count command apply limit and skip settings on the cursor or in the passed in options.
* @param {object} [options=null] Optional settings.
* @param {number} [options.skip=null] The number of documents to skip.
* @param {number} [options.limit=null] The maximum amounts to count before aborting.
* @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query.
* @param {string} [options.hint=null] An index name hint for the query.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {Cursor~countResultCallback} [callback] The result callback.
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.count = function(applySkipLimit, opts, callback) {
var self = this;
if(self.s.cmd.query == null) throw MongoError.create({message: "count can only be used with find command", driver:true});
if(typeof opts == 'function') callback = opts, opts = {};
opts = opts || {};
// Execute using callback
if(typeof callback == 'function') return count(self, applySkipLimit, opts, callback);
// Return a Promise
return new this.s.promiseLibrary(function(resolve, reject) {
count(self, applySkipLimit, opts, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
};
var count = function(self, applySkipLimit, opts, callback) {
if(typeof applySkipLimit == 'function') {
callback = applySkipLimit;
applySkipLimit = true;
}
if(applySkipLimit) {
if(typeof self.cursorSkip() == 'number') opts.skip = self.cursorSkip();
if(typeof self.cursorLimit() == 'number') opts.limit = self.cursorLimit();
}
// Command
var delimiter = self.s.ns.indexOf('.');
var command = {
'count': self.s.ns.substr(delimiter+1), 'query': self.s.cmd.query
}
if(typeof opts.maxTimeMS == 'number') {
command.maxTimeMS = opts.maxTimeMS;
} else if(self.s.cmd && typeof self.s.cmd.maxTimeMS == 'number') {
command.maxTimeMS = self.s.cmd.maxTimeMS;
}
// Merge in any options
if(opts.skip) command.skip = opts.skip;
if(opts.limit) command.limit = opts.limit;
if(self.s.options.hint) command.hint = self.s.options.hint;
// Execute the command
self.topology.command(f("%s.$cmd", self.s.ns.substr(0, delimiter))
, command, function(err, result) {
callback(err, result ? result.result.n : null)
});
}
define.classMethod('count', {callback: true, promise:true});
/**
* Close the cursor, sending a KillCursor command and emitting close.
* @method
* @param {Cursor~resultCallback} [callback] The result callback.
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.close = function(callback) {
this.s.state = Cursor.CLOSED;
// Kill the cursor
this.kill();
// Emit the close event for the cursor
this.emit('close');
// Callback if provided
if(typeof callback == 'function') return handleCallback(callback, null, this);
// Return a Promise
return new this.s.promiseLibrary(function(resolve, reject) {
resolve();
});
}
define.classMethod('close', {callback: true, promise:true});
/**
* Map all documents using the provided function
* @method
* @param {function} [transform] The mapping transformation method.
* @return {null}
*/
Cursor.prototype.map = function(transform) {
this.cursorState.transforms = { doc: transform };
return this;
}
define.classMethod('map', {callback: false, promise:false, returns: [Cursor]});
/**
* Is the cursor closed
* @method
* @return {boolean}
*/
Cursor.prototype.isClosed = function() {
return this.isDead();
}
define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]});
Cursor.prototype.destroy = function(err) {
if(err) this.emit('error', err);
this.pause();
this.close();
}
define.classMethod('destroy', {callback: false, promise:false});
/**
* Return a modified Readable stream including a possible transform method.
* @method
* @param {object} [options=null] Optional settings.
* @param {function} [options.transform=null] A transformation method applied to each document emitted by the stream.
* @return {Cursor}
*/
Cursor.prototype.stream = function(options) {
this.s.streamOptions = options || {};
return this;
}
define.classMethod('stream', {callback: false, promise:false, returns: [Cursor]});
/**
* Execute the explain for the cursor
* @method
* @param {Cursor~resultCallback} [callback] The result callback.
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.explain = function(callback) {
var self = this;
this.s.cmd.explain = true;
// Do we have a readConcern
if(this.s.cmd.readConcern) {
delete this.s.cmd['readConcern'];
}
// Execute using callback
if(typeof callback == 'function') return this._next(callback);
// Return a Promise
return new this.s.promiseLibrary(function(resolve, reject) {
self._next(function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
}
define.classMethod('explain', {callback: true, promise:true});
Cursor.prototype._read = function(n) {
// console.log("=== _read")
var self = this;
if(self.s.state == Cursor.CLOSED || self.isDead()) {
return self.push(null);
}
// Get the next item
self.nextObject(function(err, result) {
// console.log("=== _read 1")
// console.dir(err)
if(err) {
if(self.listeners('error') && self.listeners('error').length > 0) {
self.emit('error', err);
}
if(!self.isDead()) self.close();
// Emit end event
self.emit('end');
return self.emit('finish');
}
// If we provided a transformation method
if(typeof self.s.streamOptions.transform == 'function' && result != null) {
return self.push(self.s.streamOptions.transform(result));
}
// If we provided a map function
if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function' && result != null) {
return self.push(self.cursorState.transforms.doc(result));
}
// Return the result
self.push(result);
});
}
Object.defineProperty(Cursor.prototype, 'readPreference', {
enumerable:true,
get: function() {
if (!this || !this.s) {
return null;
}
return this.s.options.readPreference;
}
});
Object.defineProperty(Cursor.prototype, 'namespace', {
enumerable: true,
get: function() {
if (!this || !this.s) {
return null;
}
// TODO: refactor this logic into core
var ns = this.s.ns || '';
var firstDot = ns.indexOf('.');
if (firstDot < 0) {
return {
database: this.s.ns,
collection: ''
};
}
return {
database: ns.substr(0, firstDot),
collection: ns.substr(firstDot + 1)
};
}
});
/**
* The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null.
* @function external:Readable#read
* @param {number} size Optional argument to specify how much data to read.
* @return {(String | Buffer | null)}
*/
/**
* Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects.
* @function external:Readable#setEncoding
* @param {string} encoding The encoding to use.
* @return {null}
*/
/**
* This method will cause the readable stream to resume emitting data events.
* @function external:Readable#resume
* @return {null}
*/
/**
* This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer.
* @function external:Readable#pause
* @return {null}
*/
/**
* This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.
* @function external:Readable#pipe
* @param {Writable} destination The destination for writing data
* @param {object} [options] Pipe options
* @return {null}
*/
/**
* This method will remove the hooks set up for a previous pipe() call.
* @function external:Readable#unpipe
* @param {Writable} [destination] The destination for writing data
* @return {null}
*/
/**
* This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party.
* @function external:Readable#unshift
* @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue.
* @return {null}
*/
/**
* Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.)
* @function external:Readable#wrap
* @param {Stream} stream An "old style" readable stream.
* @return {null}
*/
Cursor.INIT = 0;
Cursor.OPEN = 1;
Cursor.CLOSED = 2;
Cursor.GET_MORE = 3;
module.exports = Cursor;
|
/*! =========================================================
* bootstrap-slider.js
*
* Maintainers:
* Kyle Kemp
* - Twitter: @seiyria
* - Github: seiyria
* Rohit Kalkur
* - Twitter: @Rovolutionary
* - Github: rovolution
*
* =========================================================
*
* 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.
* ========================================================= */
/**
* Bridget makes jQuery widgets
* v1.0.1
* MIT license
*/
(function(root, factory) {
if(typeof define === "function" && define.amd) {
define(["jquery"], factory);
} else if(typeof module === "object" && module.exports) {
var jQuery;
try {
jQuery = require("jquery");
} catch (err) {
jQuery = null;
}
module.exports = factory(jQuery);
} else {
root.Slider = factory(root.jQuery);
}
}(this, function($) {
// Reference to Slider constructor
var Slider;
(function( $ ) {
'use strict';
// -------------------------- utils -------------------------- //
var slice = Array.prototype.slice;
function noop() {}
// -------------------------- definition -------------------------- //
function defineBridget( $ ) {
// bail if no jQuery
if ( !$ ) {
return;
}
// -------------------------- addOptionMethod -------------------------- //
/**
* adds option method -> $().plugin('option', {...})
* @param {Function} PluginClass - constructor class
*/
function addOptionMethod( PluginClass ) {
// don't overwrite original option method
if ( PluginClass.prototype.option ) {
return;
}
// option setter
PluginClass.prototype.option = function( opts ) {
// bail out if not an object
if ( !$.isPlainObject( opts ) ){
return;
}
this.options = $.extend( true, this.options, opts );
};
}
// -------------------------- plugin bridge -------------------------- //
// helper function for logging errors
// $.error breaks jQuery chaining
var logError = typeof console === 'undefined' ? noop :
function( message ) {
console.error( message );
};
/**
* jQuery plugin bridge, access methods like $elem.plugin('method')
* @param {String} namespace - plugin name
* @param {Function} PluginClass - constructor class
*/
function bridge( namespace, PluginClass ) {
// add to jQuery fn namespace
$.fn[ namespace ] = function( options ) {
if ( typeof options === 'string' ) {
// call plugin method when first argument is a string
// get arguments for method
var args = slice.call( arguments, 1 );
for ( var i=0, len = this.length; i < len; i++ ) {
var elem = this[i];
var instance = $.data( elem, namespace );
if ( !instance ) {
logError( "cannot call methods on " + namespace + " prior to initialization; " +
"attempted to call '" + options + "'" );
continue;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === '_' ) {
logError( "no such method '" + options + "' for " + namespace + " instance" );
continue;
}
// trigger method with arguments
var returnValue = instance[ options ].apply( instance, args);
// break look and return first value if provided
if ( returnValue !== undefined && returnValue !== instance) {
return returnValue;
}
}
// return this if no return value
return this;
} else {
var objects = this.map( function() {
var instance = $.data( this, namespace );
if ( instance ) {
// apply options & init
instance.option( options );
instance._init();
} else {
// initialize new instance
instance = new PluginClass( this, options );
$.data( this, namespace, instance );
}
return $(this);
});
if(!objects || objects.length > 1) {
return objects;
} else {
return objects[0];
}
}
};
}
// -------------------------- bridget -------------------------- //
/**
* converts a Prototypical class into a proper jQuery plugin
* the class must have a ._init method
* @param {String} namespace - plugin name, used in $().pluginName
* @param {Function} PluginClass - constructor class
*/
$.bridget = function( namespace, PluginClass ) {
addOptionMethod( PluginClass );
bridge( namespace, PluginClass );
};
return $.bridget;
}
// get jquery from browser global
defineBridget( $ );
})( $ );
/*************************************************
BOOTSTRAP-SLIDER SOURCE CODE
**************************************************/
(function($) {
var ErrorMsgs = {
formatInvalidInputErrorMsg : function(input) {
return "Invalid input value '" + input + "' passed in";
},
callingContextNotSliderInstance : "Calling context element does not have instance of Slider bound to it. Check your code to make sure the JQuery object returned from the call to the slider() initializer is calling the method"
};
/*************************************************
CONSTRUCTOR
**************************************************/
Slider = function(element, options) {
createNewSlider.call(this, element, options);
return this;
};
function createNewSlider(element, options) {
/*************************************************
Create Markup
**************************************************/
if(typeof element === "string") {
this.element = document.querySelector(element);
} else if(element instanceof HTMLElement) {
this.element = element;
}
var origWidth = this.element.style.width;
var updateSlider = false;
var parent = this.element.parentNode;
var sliderTrackSelection;
var sliderMinHandle;
var sliderMaxHandle;
if (this.sliderElem) {
updateSlider = true;
} else {
/* Create elements needed for slider */
this.sliderElem = document.createElement("div");
this.sliderElem.className = "slider";
/* Create slider track elements */
var sliderTrack = document.createElement("div");
sliderTrack.className = "slider-track";
sliderTrackSelection = document.createElement("div");
sliderTrackSelection.className = "slider-selection";
sliderMinHandle = document.createElement("div");
sliderMinHandle.className = "slider-handle min-slider-handle";
sliderMaxHandle = document.createElement("div");
sliderMaxHandle.className = "slider-handle max-slider-handle";
sliderTrack.appendChild(sliderTrackSelection);
sliderTrack.appendChild(sliderMinHandle);
sliderTrack.appendChild(sliderMaxHandle);
var createAndAppendTooltipSubElements = function(tooltipElem) {
var arrow = document.createElement("div");
arrow.className = "tooltip-arrow";
var inner = document.createElement("div");
inner.className = "tooltip-inner";
tooltipElem.appendChild(arrow);
tooltipElem.appendChild(inner);
};
/* Create tooltip elements */
var sliderTooltip = document.createElement("div");
sliderTooltip.className = "tooltip tooltip-main";
createAndAppendTooltipSubElements(sliderTooltip);
var sliderTooltipMin = document.createElement("div");
sliderTooltipMin.className = "tooltip tooltip-min";
createAndAppendTooltipSubElements(sliderTooltipMin);
var sliderTooltipMax = document.createElement("div");
sliderTooltipMax.className = "tooltip tooltip-max";
createAndAppendTooltipSubElements(sliderTooltipMax);
/* Append components to sliderElem */
this.sliderElem.appendChild(sliderTrack);
this.sliderElem.appendChild(sliderTooltip);
this.sliderElem.appendChild(sliderTooltipMin);
this.sliderElem.appendChild(sliderTooltipMax);
/* Append slider element to parent container, right before the original <input> element */
parent.insertBefore(this.sliderElem, this.element);
/* Hide original <input> element */
this.element.style.display = "none";
}
/* If JQuery exists, cache JQ references */
if($) {
this.$element = $(this.element);
this.$sliderElem = $(this.sliderElem);
}
/*************************************************
Process Options
**************************************************/
options = options ? options : {};
var optionTypes = Object.keys(this.defaultOptions);
for(var i = 0; i < optionTypes.length; i++) {
var optName = optionTypes[i];
// First check if an option was passed in via the constructor
var val = options[optName];
// If no data attrib, then check data atrributes
val = (typeof val !== 'undefined') ? val : getDataAttrib(this.element, optName);
// Finally, if nothing was specified, use the defaults
val = (val !== null) ? val : this.defaultOptions[optName];
// Set all options on the instance of the Slider
if(!this.options) {
this.options = {};
}
this.options[optName] = val;
}
function getDataAttrib(element, optName) {
var dataName = "data-slider-" + optName;
var dataValString = element.getAttribute(dataName);
try {
return JSON.parse(dataValString);
}
catch(err) {
return dataValString;
}
}
/*************************************************
Setup
**************************************************/
this.eventToCallbackMap = {};
this.sliderElem.id = this.options.id;
this.touchCapable = 'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch);
this.tooltip = this.sliderElem.querySelector('.tooltip-main');
this.tooltipInner = this.tooltip.querySelector('.tooltip-inner');
this.tooltip_min = this.sliderElem.querySelector('.tooltip-min');
this.tooltipInner_min = this.tooltip_min.querySelector('.tooltip-inner');
this.tooltip_max = this.sliderElem.querySelector('.tooltip-max');
this.tooltipInner_max= this.tooltip_max.querySelector('.tooltip-inner');
if (updateSlider === true) {
// Reset classes
this._removeClass(this.sliderElem, 'slider-horizontal');
this._removeClass(this.sliderElem, 'slider-vertical');
this._removeClass(this.tooltip, 'hide');
this._removeClass(this.tooltip_min, 'hide');
this._removeClass(this.tooltip_max, 'hide');
// Undo existing inline styles for track
["left", "top", "width", "height"].forEach(function(prop) {
this._removeProperty(this.trackSelection, prop);
}, this);
// Undo inline styles on handles
[this.handle1, this.handle2].forEach(function(handle) {
this._removeProperty(handle, 'left');
this._removeProperty(handle, 'top');
}, this);
// Undo inline styles and classes on tooltips
[this.tooltip, this.tooltip_min, this.tooltip_max].forEach(function(tooltip) {
this._removeProperty(tooltip, 'left');
this._removeProperty(tooltip, 'top');
this._removeProperty(tooltip, 'margin-left');
this._removeProperty(tooltip, 'margin-top');
this._removeClass(tooltip, 'right');
this._removeClass(tooltip, 'top');
}, this);
}
if(this.options.orientation === 'vertical') {
this._addClass(this.sliderElem,'slider-vertical');
this.stylePos = 'top';
this.mousePos = 'pageY';
this.sizePos = 'offsetHeight';
this._addClass(this.tooltip, 'right');
this.tooltip.style.left = '100%';
this._addClass(this.tooltip_min, 'right');
this.tooltip_min.style.left = '100%';
this._addClass(this.tooltip_max, 'right');
this.tooltip_max.style.left = '100%';
} else {
this._addClass(this.sliderElem, 'slider-horizontal');
this.sliderElem.style.width = origWidth;
this.options.orientation = 'horizontal';
this.stylePos = 'left';
this.mousePos = 'pageX';
this.sizePos = 'offsetWidth';
this._addClass(this.tooltip, 'top');
this.tooltip.style.top = -this.tooltip.outerHeight - 14 + 'px';
this._addClass(this.tooltip_min, 'top');
this.tooltip_min.style.top = -this.tooltip_min.outerHeight - 14 + 'px';
this._addClass(this.tooltip_max, 'top');
this.tooltip_max.style.top = -this.tooltip_max.outerHeight - 14 + 'px';
}
if (this.options.value instanceof Array) {
this.options.range = true;
} else if (this.options.range) {
// User wants a range, but value is not an array
this.options.value = [this.options.value, this.options.max];
}
this.trackSelection = sliderTrackSelection || this.trackSelection;
if (this.options.selection === 'none') {
this._addClass(this.trackSelection, 'hide');
}
this.handle1 = sliderMinHandle || this.handle1;
this.handle2 = sliderMaxHandle || this.handle2;
if (updateSlider === true) {
// Reset classes
this._removeClass(this.handle1, 'round triangle');
this._removeClass(this.handle2, 'round triangle hide');
}
var availableHandleModifiers = ['round', 'triangle', 'custom'];
var isValidHandleType = availableHandleModifiers.indexOf(this.options.handle) !== -1;
if (isValidHandleType) {
this._addClass(this.handle1, this.options.handle);
this._addClass(this.handle2, this.options.handle);
}
this.offset = this._offset(this.sliderElem);
this.size = this.sliderElem[this.sizePos];
this.setValue(this.options.value);
/******************************************
Bind Event Listeners
******************************************/
// Bind keyboard handlers
this.handle1Keydown = this._keydown.bind(this, 0);
this.handle1.addEventListener("keydown", this.handle1Keydown, false);
this.handle2Keydown = this._keydown.bind(this, 1);
this.handle2.addEventListener("keydown", this.handle2Keydown, false);
if (this.touchCapable) {
// Bind touch handlers
this.mousedown = this._mousedown.bind(this);
this.sliderElem.addEventListener("touchstart", this.mousedown, false);
} else {
// Bind mouse handlers
this.mousedown = this._mousedown.bind(this);
this.sliderElem.addEventListener("mousedown", this.mousedown, false);
}
// Bind tooltip-related handlers
if(this.options.tooltip === 'hide') {
this._addClass(this.tooltip, 'hide');
this._addClass(this.tooltip_min, 'hide');
this._addClass(this.tooltip_max, 'hide');
} else if(this.options.tooltip === 'always') {
this._showTooltip();
this._alwaysShowTooltip = true;
} else {
this.showTooltip = this._showTooltip.bind(this);
this.hideTooltip = this._hideTooltip.bind(this);
this.sliderElem.addEventListener("mouseenter", this.showTooltip, false);
this.sliderElem.addEventListener("mouseleave", this.hideTooltip, false);
this.handle1.addEventListener("focus", this.showTooltip, false);
this.handle1.addEventListener("blur", this.hideTooltip, false);
this.handle2.addEventListener("focus", this.showTooltip, false);
this.handle2.addEventListener("blur", this.hideTooltip, false);
}
if(this.options.enabled) {
this.enable();
} else {
this.disable();
}
}
/*************************************************
INSTANCE PROPERTIES/METHODS
- Any methods bound to the prototype are considered
part of the plugin's `public` interface
**************************************************/
Slider.prototype = {
_init: function() {}, // NOTE: Must exist to support bridget
constructor: Slider,
defaultOptions: {
id: "",
min: 0,
max: 10,
step: 1,
precision: 0,
orientation: 'horizontal',
value: 5,
range: false,
selection: 'before',
tooltip: 'show',
tooltip_split: false,
handle: 'round',
reversed: false,
enabled: true,
formatter: function(val) {
if(val instanceof Array) {
return val[0] + " : " + val[1];
} else {
return val;
}
},
natural_arrow_keys: false
},
over: false,
inDrag: false,
getValue: function() {
if (this.options.range) {
return this.options.value;
}
return this.options.value[0];
},
setValue: function(val, triggerSlideEvent) {
if (!val) {
val = 0;
}
this.options.value = this._validateInputValue(val);
var applyPrecision = this._applyPrecision.bind(this);
if (this.options.range) {
this.options.value[0] = applyPrecision(this.options.value[0]);
this.options.value[1] = applyPrecision(this.options.value[1]);
this.options.value[0] = Math.max(this.options.min, Math.min(this.options.max, this.options.value[0]));
this.options.value[1] = Math.max(this.options.min, Math.min(this.options.max, this.options.value[1]));
} else {
this.options.value = applyPrecision(this.options.value);
this.options.value = [ Math.max(this.options.min, Math.min(this.options.max, this.options.value))];
this._addClass(this.handle2, 'hide');
if (this.options.selection === 'after') {
this.options.value[1] = this.options.max;
} else {
this.options.value[1] = this.options.min;
}
}
this.diff = this.options.max - this.options.min;
if (this.diff > 0) {
this.percentage = [
(this.options.value[0] - this.options.min) * 100 / this.diff,
(this.options.value[1] - this.options.min) * 100 / this.diff,
this.options.step * 100 / this.diff
];
} else {
this.percentage = [0, 0, 100];
}
this._layout();
var sliderValue = this.options.range ? this.options.value : this.options.value[0];
this._setDataVal(sliderValue);
if(triggerSlideEvent === true) {
this._trigger('slide', sliderValue);
}
return this;
},
destroy: function(){
// Remove event handlers on slider elements
this._removeSliderEventHandlers();
// Remove the slider from the DOM
this.sliderElem.parentNode.removeChild(this.sliderElem);
/* Show original <input> element */
this.element.style.display = "";
// Clear out custom event bindings
this._cleanUpEventCallbacksMap();
// Remove data values
this.element.removeAttribute("data");
// Remove JQuery handlers/data
if($) {
this._unbindJQueryEventHandlers();
this.$element.removeData('slider');
}
},
disable: function() {
this.options.enabled = false;
this.handle1.removeAttribute("tabindex");
this.handle2.removeAttribute("tabindex");
this._addClass(this.sliderElem, 'slider-disabled');
this._trigger('slideDisabled');
return this;
},
enable: function() {
this.options.enabled = true;
this.handle1.setAttribute("tabindex", 0);
this.handle2.setAttribute("tabindex", 0);
this._removeClass(this.sliderElem, 'slider-disabled');
this._trigger('slideEnabled');
return this;
},
toggle: function() {
if(this.options.enabled) {
this.disable();
} else {
this.enable();
}
return this;
},
isEnabled: function() {
return this.options.enabled;
},
on: function(evt, callback) {
if($) {
this.$element.on(evt, callback);
this.$sliderElem.on(evt, callback);
} else {
this._bindNonQueryEventHandler(evt, callback);
}
return this;
},
getAttribute: function(attribute) {
if(attribute) {
return this.options[attribute];
} else {
return this.options;
}
},
setAttribute: function(attribute, value) {
this.options[attribute] = value;
return this;
},
refresh: function() {
this._removeSliderEventHandlers();
createNewSlider.call(this, this.element, this.options);
if($) {
// Bind new instance of slider to the element
$.data(this.element, 'slider', this);
}
return this;
},
/******************************+
HELPERS
- Any method that is not part of the public interface.
- Place it underneath this comment block and write its signature like so:
_fnName : function() {...}
********************************/
_removeSliderEventHandlers: function() {
// Remove event listeners from handle1
this.handle1.removeEventListener("keydown", this.handle1Keydown, false);
this.handle1.removeEventListener("focus", this.showTooltip, false);
this.handle1.removeEventListener("blur", this.hideTooltip, false);
// Remove event listeners from handle2
this.handle2.removeEventListener("keydown", this.handle2Keydown, false);
this.handle2.removeEventListener("focus", this.handle2Keydown, false);
this.handle2.removeEventListener("blur", this.handle2Keydown, false);
// Remove event listeners from sliderElem
this.sliderElem.removeEventListener("mouseenter", this.showTooltip, false);
this.sliderElem.removeEventListener("mouseleave", this.hideTooltip, false);
this.sliderElem.removeEventListener("touchstart", this.mousedown, false);
this.sliderElem.removeEventListener("mousedown", this.mousedown, false);
},
_bindNonQueryEventHandler: function(evt, callback) {
if(this.eventToCallbackMap[evt]===undefined) {
this.eventToCallbackMap[evt] = [];
}
this.eventToCallbackMap[evt].push(callback);
},
_cleanUpEventCallbacksMap: function() {
var eventNames = Object.keys(this.eventToCallbackMap);
for(var i = 0; i < eventNames.length; i++) {
var eventName = eventNames[i];
this.eventToCallbackMap[eventName] = null;
}
},
_showTooltip: function() {
if (this.options.tooltip_split === false ){
this._addClass(this.tooltip, 'in');
} else {
this._addClass(this.tooltip_min, 'in');
this._addClass(this.tooltip_max, 'in');
}
this.over = true;
},
_hideTooltip: function() {
if (this.inDrag === false && this.alwaysShowTooltip !== true) {
this._removeClass(this.tooltip, 'in');
this._removeClass(this.tooltip_min, 'in');
this._removeClass(this.tooltip_max, 'in');
}
this.over = false;
},
_layout: function() {
var positionPercentages;
if(this.options.reversed) {
positionPercentages = [ 100 - this.percentage[0], this.percentage[1] ];
} else {
positionPercentages = [ this.percentage[0], this.percentage[1] ];
}
this.handle1.style[this.stylePos] = positionPercentages[0]+'%';
this.handle2.style[this.stylePos] = positionPercentages[1]+'%';
if (this.options.orientation === 'vertical') {
this.trackSelection.style.top = Math.min(positionPercentages[0], positionPercentages[1]) +'%';
this.trackSelection.style.height = Math.abs(positionPercentages[0] - positionPercentages[1]) +'%';
} else {
this.trackSelection.style.left = Math.min(positionPercentages[0], positionPercentages[1]) +'%';
this.trackSelection.style.width = Math.abs(positionPercentages[0] - positionPercentages[1]) +'%';
var offset_min = this.tooltip_min.getBoundingClientRect();
var offset_max = this.tooltip_max.getBoundingClientRect();
if (offset_min.right > offset_max.left) {
this._removeClass(this.tooltip_max, 'top');
this._addClass(this.tooltip_max, 'bottom');
this.tooltip_max.style.top = 18 + 'px';
} else {
this._removeClass(this.tooltip_max, 'bottom');
this._addClass(this.tooltip_max, 'top');
this.tooltip_max.style.top = -30 + 'px';
}
}
var formattedTooltipVal;
if (this.options.range) {
formattedTooltipVal = this.options.formatter(this.options.value);
this._setText(this.tooltipInner, formattedTooltipVal);
this.tooltip.style[this.stylePos] = (positionPercentages[1] + positionPercentages[0])/2 + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
}
if (this.options.orientation === 'vertical') {
this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
}
var innerTooltipMinText = this.options.formatter(this.options.value[0]);
this._setText(this.tooltipInner_min, innerTooltipMinText);
var innerTooltipMaxText = this.options.formatter(this.options.value[1]);
this._setText(this.tooltipInner_max, innerTooltipMaxText);
this.tooltip_min.style[this.stylePos] = positionPercentages[0] + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip_min, 'margin-top', -this.tooltip_min.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip_min, 'margin-left', -this.tooltip_min.offsetWidth / 2 + 'px');
}
this.tooltip_max.style[this.stylePos] = positionPercentages[1] + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip_max, 'margin-top', -this.tooltip_max.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip_max, 'margin-left', -this.tooltip_max.offsetWidth / 2 + 'px');
}
} else {
formattedTooltipVal = this.options.formatter(this.options.value[0]);
this._setText(this.tooltipInner, formattedTooltipVal);
this.tooltip.style[this.stylePos] = positionPercentages[0] + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
}
}
},
_removeProperty: function(element, prop) {
if (element.style.removeProperty) {
element.style.removeProperty(prop);
} else {
element.style.removeAttribute(prop);
}
},
_mousedown: function(ev) {
if(!this.options.enabled) {
return false;
}
this._triggerFocusOnHandle();
this.offset = this._offset(this.sliderElem);
this.size = this.sliderElem[this.sizePos];
var percentage = this._getPercentage(ev);
if (this.options.range) {
var diff1 = Math.abs(this.percentage[0] - percentage);
var diff2 = Math.abs(this.percentage[1] - percentage);
this.dragged = (diff1 < diff2) ? 0 : 1;
} else {
this.dragged = 0;
}
this.percentage[this.dragged] = this.options.reversed ? 100 - percentage : percentage;
this._layout();
if (this.touchCapable) {
document.removeEventListener("touchmove", this.mousemove, false);
document.removeEventListener("touchend", this.mouseup, false);
}
if(this.mousemove){
document.removeEventListener("mousemove", this.mousemove, false);
}
if(this.mouseup){
document.removeEventListener("mouseup", this.mouseup, false);
}
this.mousemove = this._mousemove.bind(this);
this.mouseup = this._mouseup.bind(this);
if (this.touchCapable) {
// Touch: Bind touch events:
document.addEventListener("touchmove", this.mousemove, false);
document.addEventListener("touchend", this.mouseup, false);
}
// Bind mouse events:
document.addEventListener("mousemove", this.mousemove, false);
document.addEventListener("mouseup", this.mouseup, false);
this.inDrag = true;
var val = this._calculateValue();
this._trigger('slideStart', val);
this._setDataVal(val);
this.setValue(val);
this._pauseEvent(ev);
return true;
},
_triggerFocusOnHandle: function(handleIdx) {
if(handleIdx === 0) {
this.handle1.focus();
}
if(handleIdx === 1) {
this.handle2.focus();
}
},
_keydown: function(handleIdx, ev) {
if(!this.options.enabled) {
return false;
}
var dir;
switch (ev.keyCode) {
case 37: // left
case 40: // down
dir = -1;
break;
case 39: // right
case 38: // up
dir = 1;
break;
}
if (!dir) {
return;
}
// use natural arrow keys instead of from min to max
if (this.options.natural_arrow_keys) {
var ifVerticalAndNotReversed = (this.options.orientation === 'vertical' && !this.options.reversed);
var ifHorizontalAndReversed = (this.options.orientation === 'horizontal' && this.options.reversed);
if (ifVerticalAndNotReversed || ifHorizontalAndReversed) {
dir = dir * -1;
}
}
var oneStepValuePercentageChange = dir * this.percentage[2];
var percentage = this.percentage[handleIdx] + oneStepValuePercentageChange;
if (percentage > 100) {
percentage = 100;
} else if (percentage < 0) {
percentage = 0;
}
this.dragged = handleIdx;
this._adjustPercentageForRangeSliders(percentage);
this.percentage[this.dragged] = percentage;
this._layout();
var val = this._calculateValue();
this._trigger('slideStart', val);
this._setDataVal(val);
this.setValue(val, true);
this._trigger('slideStop', val);
this._setDataVal(val);
this._pauseEvent(ev);
return false;
},
_pauseEvent: function(ev) {
if(ev.stopPropagation) {
ev.stopPropagation();
}
if(ev.preventDefault) {
ev.preventDefault();
}
ev.cancelBubble=true;
ev.returnValue=false;
},
_mousemove: function(ev) {
if(!this.options.enabled) {
return false;
}
var percentage = this._getPercentage(ev);
this._adjustPercentageForRangeSliders(percentage);
this.percentage[this.dragged] = this.options.reversed ? 100 - percentage : percentage;
this._layout();
var val = this._calculateValue();
this.setValue(val, true);
return false;
},
_adjustPercentageForRangeSliders: function(percentage) {
if (this.options.range) {
if (this.dragged === 0 && this.percentage[1] < percentage) {
this.percentage[0] = this.percentage[1];
this.dragged = 1;
} else if (this.dragged === 1 && this.percentage[0] > percentage) {
this.percentage[1] = this.percentage[0];
this.dragged = 0;
}
}
},
_mouseup: function() {
if(!this.options.enabled) {
return false;
}
if (this.touchCapable) {
// Touch: Unbind touch event handlers:
document.removeEventListener("touchmove", this.mousemove, false);
document.removeEventListener("touchend", this.mouseup, false);
}
// Unbind mouse event handlers:
document.removeEventListener("mousemove", this.mousemove, false);
document.removeEventListener("mouseup", this.mouseup, false);
this.inDrag = false;
if (this.over === false) {
this._hideTooltip();
}
var val = this._calculateValue();
this._layout();
this._setDataVal(val);
this._trigger('slideStop', val);
return false;
},
_calculateValue: function() {
var val;
if (this.options.range) {
val = [this.options.min,this.options.max];
if (this.percentage[0] !== 0){
val[0] = (Math.max(this.options.min, this.options.min + Math.round((this.diff * this.percentage[0]/100)/this.options.step)*this.options.step));
val[0] = this._applyPrecision(val[0]);
}
if (this.percentage[1] !== 100){
val[1] = (Math.min(this.options.max, this.options.min + Math.round((this.diff * this.percentage[1]/100)/this.options.step)*this.options.step));
val[1] = this._applyPrecision(val[1]);
}
this.options.value = val;
} else {
val = (this.options.min + Math.round((this.diff * this.percentage[0]/100)/this.options.step)*this.options.step);
if (val < this.options.min) {
val = this.options.min;
}
else if (val > this.options.max) {
val = this.options.max;
}
val = parseFloat(val);
val = this._applyPrecision(val);
this.options.value = [val, this.options.value[1]];
}
return val;
},
_applyPrecision: function(val) {
var precision = this.options.precision || this._getNumDigitsAfterDecimalPlace(this.options.step);
return this._applyToFixedAndParseFloat(val, precision);
},
_getNumDigitsAfterDecimalPlace: function(num) {
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0));
},
_applyToFixedAndParseFloat: function(num, toFixedInput) {
var truncatedNum = num.toFixed(toFixedInput);
return parseFloat(truncatedNum);
},
/*
Credits to Mike Samuel for the following method!
Source: http://stackoverflow.com/questions/10454518/javascript-how-to-retrieve-the-number-of-decimals-of-a-string-number
*/
_getPercentage: function(ev) {
if (this.touchCapable && (ev.type === 'touchstart' || ev.type === 'touchmove')) {
ev = ev.touches[0];
}
var percentage = (ev[this.mousePos] - this.offset[this.stylePos])*100/this.size;
percentage = Math.round(percentage/this.percentage[2])*this.percentage[2];
return Math.max(0, Math.min(100, percentage));
},
_validateInputValue: function(val) {
if(typeof val === 'number') {
return val;
} else if(val instanceof Array) {
this._validateArray(val);
return val;
} else {
throw new Error( ErrorMsgs.formatInvalidInputErrorMsg(val) );
}
},
_validateArray: function(val) {
for(var i = 0; i < val.length; i++) {
var input = val[i];
if (typeof input !== 'number') { throw new Error( ErrorMsgs.formatInvalidInputErrorMsg(input) ); }
}
},
_setDataVal: function(val) {
var value = "value: '" + val + "'";
this.element.setAttribute('data', value);
this.element.setAttribute('value', val);
},
_trigger: function(evt, val) {
val = (val || val === 0) ? val : undefined;
var callbackFnArray = this.eventToCallbackMap[evt];
if(callbackFnArray && callbackFnArray.length) {
for(var i = 0; i < callbackFnArray.length; i++) {
var callbackFn = callbackFnArray[i];
callbackFn(val);
}
}
/* If JQuery exists, trigger JQuery events */
if($) {
this._triggerJQueryEvent(evt, val);
}
},
_triggerJQueryEvent: function(evt, val) {
var eventData = {
type: evt,
value: val
};
this.$element.trigger(eventData);
this.$sliderElem.trigger(eventData);
},
_unbindJQueryEventHandlers: function() {
this.$element.off();
this.$sliderElem.off();
},
_setText: function(element, text) {
if(typeof element.innerText !== "undefined") {
element.innerText = text;
} else if(typeof element.textContent !== "undefined") {
element.textContent = text;
}
},
_removeClass: function(element, classString) {
var classes = classString.split(" ");
var newClasses = element.className;
for(var i = 0; i < classes.length; i++) {
var classTag = classes[i];
var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)");
newClasses = newClasses.replace(regex, " ");
}
element.className = newClasses.trim();
},
_addClass: function(element, classString) {
var classes = classString.split(" ");
var newClasses = element.className;
for(var i = 0; i < classes.length; i++) {
var classTag = classes[i];
var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)");
var ifClassExists = regex.test(newClasses);
if(!ifClassExists) {
newClasses += " " + classTag;
}
}
element.className = newClasses.trim();
},
_offset: function (obj) {
var ol = 0;
var ot = 0;
if (obj.offsetParent) {
do {
ol += obj.offsetLeft;
ot += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return {
left: ol,
top: ot
};
},
_css: function(elementRef, styleName, value) {
if ($) {
$.style(elementRef, styleName, value);
} else {
var style = styleName.replace(/^-ms-/, "ms-").replace(/-([\da-z])/gi, function (all, letter) {
return letter.toUpperCase();
});
elementRef.style[style] = value;
}
}
};
/*********************************
Attach to global namespace
*********************************/
if($) {
var namespace = $.fn.slider ? 'bootstrapSlider' : 'slider';
$.bridget(namespace, Slider);
}
})( $ );
return Slider;
})); |
/*
YUI 3.5.0 (build 5089)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add("lang/datatype-date-format_fr",function(a){a.Intl.add("datatype-date-format","fr",{"a":["dim.","lun.","mar.","mer.","jeu.","ven.","sam."],"A":["dimanche","lundi","mardi","mercredi","jeudi","vendredi","samedi"],"b":["janv.","févr.","mars","avr.","mai","juin","juil.","août","sept.","oct.","nov.","déc."],"B":["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre"],"c":"%a %d %b %Y %H:%M:%S %Z","p":["AM","PM"],"P":["am","pm"],"x":"%d/%m/%y","X":"%H:%M:%S"});},"3.5.0"); |
version https://git-lfs.github.com/spec/v1
oid sha256:ecdcfeb6d9c10e04bf103e6105698af7bda97180bfc3c7545cce74ce2a73f5eb
size 4291
|
/**
* @ngdoc service
* @name merchello.models.extendedDataDisplayBuilder
*
* @description
* A utility service that builds ExtendedDataBuilder models
*/
angular.module('merchello.models')
.factory('extendedDataDisplayBuilder',
['genericModelBuilder', 'ExtendedDataDisplay', 'ExtendedDataItemDisplay',
function(genericModelBuilder, ExtendedDataDisplay, ExtendedDataItemDisplay) {
var Constructor = ExtendedDataDisplay;
return {
createDefault: function() {
return new Constructor();
},
transform: function(jsonResult) {
var extendedData = new Constructor();
if (jsonResult !== undefined) {
var items = genericModelBuilder.transform(jsonResult, ExtendedDataItemDisplay);
if(items.length > 0) {
extendedData.items = items;
}
}
return extendedData;
}
};
}]);
|
import Ember from 'ember-metal/core'; // reexports
import Test from 'ember-testing/test';
import Adapter from 'ember-testing/adapters/adapter';
import setupForTesting from 'ember-testing/setup_for_testing';
import require from 'require';
import 'ember-testing/support'; // to handle various edge cases
import 'ember-testing/ext/application';
import 'ember-testing/ext/rsvp';
import 'ember-testing/helpers'; // adds helpers to helpers object in Test
import 'ember-testing/initializers'; // to setup initializer
/**
@module ember
@submodule ember-testing
*/
Ember.Test = Test;
Ember.Test.Adapter = Adapter;
Ember.setupForTesting = setupForTesting;
Object.defineProperty(Test, 'QUnitAdapter', {
get: () => require('ember-testing/adapters/qunit').default
});
|
CKEDITOR.plugins.setLang( 'html5audio', 'de', {
button: 'HTML5 Audio einfügen',
title: 'HTML5 Audio',
infoLabel: 'Audio Infos',
urlMissing: 'Sie haben keine URL zur Audio-Datei angegeben.',
audioProperties: 'Audio-Einstellungen',
upload: 'Hochladen',
btnUpload: 'Zum Server senden',
advanced: 'Erweitert',
autoplay: 'Autoplay?',
allowdownload: 'Download zulassen?',
yes: 'Ja',
no: 'Nein'
} );
|
function foo() {
console.log('foo');
}
|
/**
@license
* @pnp/logging v1.0.3 - pnp - light-weight, subscribable logging framework
* MIT (https://github.com/pnp/pnp/blob/master/LICENSE)
* Copyright (c) 2018 Microsoft
* docs: http://officedev.github.io/PnP-JS-Core
* source: https://github.com/pnp/pnp
* bugs: https://github.com/pnp/pnp/issues
*/
/**
* Class used to subscribe ILogListener and log messages throughout an application
*
*/
class Logger {
/**
* Gets or sets the active log level to apply for log filtering
*/
static get activeLogLevel() {
return Logger.instance.activeLogLevel;
}
static set activeLogLevel(value) {
Logger.instance.activeLogLevel = value;
}
static get instance() {
if (typeof Logger._instance === "undefined" || Logger._instance === null) {
Logger._instance = new LoggerImpl();
}
return Logger._instance;
}
/**
* Adds ILogListener instances to the set of subscribed listeners
*
* @param listeners One or more listeners to subscribe to this log
*/
static subscribe(...listeners) {
listeners.map(listener => Logger.instance.subscribe(listener));
}
/**
* Clears the subscribers collection, returning the collection before modifiction
*/
static clearSubscribers() {
return Logger.instance.clearSubscribers();
}
/**
* Gets the current subscriber count
*/
static get count() {
return Logger.instance.count;
}
/**
* Writes the supplied string to the subscribed listeners
*
* @param message The message to write
* @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Verbose)
*/
static write(message, level = 0 /* Verbose */) {
Logger.instance.log({ level: level, message: message });
}
/**
* Writes the supplied string to the subscribed listeners
*
* @param json The json object to stringify and write
* @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Verbose)
*/
static writeJSON(json, level = 0 /* Verbose */) {
Logger.instance.log({ level: level, message: JSON.stringify(json) });
}
/**
* Logs the supplied entry to the subscribed listeners
*
* @param entry The message to log
*/
static log(entry) {
Logger.instance.log(entry);
}
/**
* Logs an error object to the subscribed listeners
*
* @param err The error object
*/
static error(err) {
Logger.instance.log({ data: err, level: 3 /* Error */, message: err.message });
}
}
class LoggerImpl {
constructor(activeLogLevel = 2 /* Warning */, subscribers = []) {
this.activeLogLevel = activeLogLevel;
this.subscribers = subscribers;
}
subscribe(listener) {
this.subscribers.push(listener);
}
clearSubscribers() {
const s = this.subscribers.slice(0);
this.subscribers.length = 0;
return s;
}
get count() {
return this.subscribers.length;
}
write(message, level = 0 /* Verbose */) {
this.log({ level: level, message: message });
}
log(entry) {
if (typeof entry !== "undefined" && this.activeLogLevel <= entry.level) {
this.subscribers.map(subscriber => subscriber.log(entry));
}
}
}
/**
* Implementation of LogListener which logs to the console
*
*/
class ConsoleListener {
/**
* Any associated data that a given logging listener may choose to log or ignore
*
* @param entry The information to be logged
*/
log(entry) {
const msg = this.format(entry);
switch (entry.level) {
case 0 /* Verbose */:
case 1 /* Info */:
console.log(msg);
break;
case 2 /* Warning */:
console.warn(msg);
break;
case 3 /* Error */:
console.error(msg);
break;
}
}
/**
* Formats the message
*
* @param entry The information to format into a string
*/
format(entry) {
const msg = [];
msg.push("Message: " + entry.message);
if (typeof entry.data !== "undefined") {
msg.push(" Data: " + JSON.stringify(entry.data));
}
return msg.join("");
}
}
/**
* Implementation of LogListener which logs to the supplied function
*
*/
class FunctionListener {
/**
* Creates a new instance of the FunctionListener class
*
* @constructor
* @param method The method to which any logging data will be passed
*/
constructor(method) {
this.method = method;
}
/**
* Any associated data that a given logging listener may choose to log or ignore
*
* @param entry The information to be logged
*/
log(entry) {
this.method(entry);
}
}
export { Logger, ConsoleListener, FunctionListener };
//# sourceMappingURL=logging.js.map
|
/**
@module ember
@submodule ember-runtime
*/
import { get } from "ember-metal/property_get";
import { set } from "ember-metal/property_set";
import { required } from "ember-metal/mixin";
import { Freezable } from "ember-runtime/mixins/freezable";
import { Mixin } from 'ember-metal/mixin';
import { fmt } from "ember-runtime/system/string";
import EmberError from 'ember-metal/error';
/**
Implements some standard methods for copying an object. Add this mixin to
any object you create that can create a copy of itself. This mixin is
added automatically to the built-in array.
You should generally implement the `copy()` method to return a copy of the
receiver.
Note that `frozenCopy()` will only work if you also implement
`Ember.Freezable`.
@class Copyable
@namespace Ember
@since Ember 0.9
*/
export default Mixin.create({
/**
Override to return a copy of the receiver. Default implementation raises
an exception.
@method copy
@param {Boolean} deep if `true`, a deep copy of the object should be made
@return {Object} copy of receiver
*/
copy: required(Function),
/**
If the object implements `Ember.Freezable`, then this will return a new
copy if the object is not frozen and the receiver if the object is frozen.
Raises an exception if you try to call this method on a object that does
not support freezing.
You should use this method whenever you want a copy of a freezable object
since a freezable object can simply return itself without actually
consuming more memory.
@method frozenCopy
@return {Object} copy of receiver or receiver
*/
frozenCopy: function() {
if (Freezable && Freezable.detect(this)) {
return get(this, 'isFrozen') ? this : this.copy().freeze();
} else {
throw new EmberError(fmt("%@ does not support freezing", [this]));
}
}
});
|
var Example = function Example() {
"use strict";
babelHelpers.classCallCheck(this, Example);
var _Example;
};
var t = new Example();
|
'use strict';
module.exports = function (math, config) {
var util = require('../../util/index'),
Matrix = math.type.Matrix,
Unit = require('../../type/Unit'),
collection = math.collection,
isBoolean = util['boolean'].isBoolean,
isInteger = util.number.isInteger,
isNumber = util.number.isNumber,
isCollection = collection.isCollection;
/**
* Bitwise right logical shift of value x by y number of bits, `x >>> y`.
* For matrices, the function is evaluated element wise.
* For units, the function is evaluated on the best prefix base.
*
* Syntax:
*
* math.rightLogShift(x, y)
*
* Examples:
*
* math.rightLogShift(4, 2); // returns Number 1
*
* math.rightLogShift([16, -32, 64], 4); // returns Array [1, 2, 3]
*
* See also:
*
* bitAnd, bitNot, bitOr, bitXor, leftShift, rightArithShift
*
* @param {Number | Boolean | Array | Matrix | null} x Value to be shifted
* @param {Number | Boolean | null} y Amount of shifts
* @return {Number | Array | Matrix} `x` zero-filled shifted right `y` times
*/
math.rightLogShift = function rightLogShift(x, y) {
if (arguments.length != 2) {
throw new math.error.ArgumentsError('rightLogShift', arguments.length, 2);
}
if (isNumber(x) && isNumber(y)) {
if (!isInteger(x) || !isInteger(y)) {
throw new Error('Parameters in function rightLogShift must be integer numbers');
}
return x >>> y;
}
if (isCollection(x) && isNumber(y)) {
return collection.deepMap2(x, y, rightLogShift);
}
if (isBoolean(x) || x === null) {
return rightLogShift(+x, y);
}
if (isBoolean(y) || y === null) {
return rightLogShift(x, +y);
}
throw new math.error.UnsupportedTypeError('rightLogShift', math['typeof'](x), math['typeof'](y));
};
};
|
import defaults from './defaults.js';
import _ from './underscore.js';
import './templateSettings.js';
// When customizing `_.templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;
function escapeChar(match) {
return '\\' + escapes[match];
}
// In order to prevent third-party code injection through
// `_.templateSettings.variable`, we test it against the following regular
// expression. It is intentionally a bit more liberal than just matching valid
// identifiers, but still prevents possible loopholes through defaults or
// destructuring assignment.
var bareIdentifier = /^\s*(\w|\$)+\s*$/;
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
// NB: `oldSettings` only exists for backwards compatibility.
export default function template(text, settings, oldSettings) {
if (!settings && oldSettings) settings = oldSettings;
settings = defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
index = offset + match.length;
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
} else if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
} else if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
// Adobe VMs need the match returned to produce the correct offset.
return match;
});
source += "';\n";
var argument = settings.variable;
if (argument) {
// Insure against third-party code injection. (CVE-2021-23358)
if (!bareIdentifier.test(argument)) throw new Error(
'variable is not a bare identifier: ' + argument
);
} else {
// If a variable is not specified, place data values in local scope.
source = 'with(obj||{}){\n' + source + '}\n';
argument = 'obj';
}
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + 'return __p;\n';
var render;
try {
render = new Function(argument, '_', source);
} catch (e) {
e.source = source;
throw e;
}
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled source as a convenience for precompilation.
template.source = 'function(' + argument + '){\n' + source + '}';
return template;
}
|
var _ref =
/*#__PURE__*/
<foo />;
function render() {
return _ref;
}
var _ref2 =
/*#__PURE__*/
<div className="foo"><input type="checkbox" checked={true} /></div>;
function render() {
return _ref2;
}
|
exports.forward = require('./forward');
exports.respond = require('./respond');
|
'use strict';
/* globals generateInputCompilerHelper: false */
describe('ngModel', function() {
describe('NgModelController', function() {
/* global NgModelController: false */
var ctrl, scope, element, parentFormCtrl;
beforeEach(inject(function($rootScope, $controller) {
var attrs = {name: 'testAlias', ngModel: 'value'};
parentFormCtrl = {
$$setPending: jasmine.createSpy('$$setPending'),
$setValidity: jasmine.createSpy('$setValidity'),
$setDirty: jasmine.createSpy('$setDirty'),
$$clearControlValidity: noop
};
element = jqLite('<form><input></form>');
scope = $rootScope;
ctrl = $controller(NgModelController, {
$scope: scope,
$element: element.find('input'),
$attrs: attrs
});
//Assign the mocked parentFormCtrl to the model controller
ctrl.$$parentForm = parentFormCtrl;
}));
afterEach(function() {
dealoc(element);
});
it('should init the properties', function() {
expect(ctrl.$untouched).toBe(true);
expect(ctrl.$touched).toBe(false);
expect(ctrl.$dirty).toBe(false);
expect(ctrl.$pristine).toBe(true);
expect(ctrl.$valid).toBe(true);
expect(ctrl.$invalid).toBe(false);
expect(ctrl.$viewValue).toBeDefined();
expect(ctrl.$modelValue).toBeDefined();
expect(ctrl.$formatters).toEqual([]);
expect(ctrl.$parsers).toEqual([]);
expect(ctrl.$name).toBe('testAlias');
});
describe('setValidity', function() {
function expectOneError() {
expect(ctrl.$error).toEqual({someError: true});
expect(ctrl.$$success).toEqual({});
expect(ctrl.$pending).toBeUndefined();
}
function expectOneSuccess() {
expect(ctrl.$error).toEqual({});
expect(ctrl.$$success).toEqual({someError: true});
expect(ctrl.$pending).toBeUndefined();
}
function expectOnePending() {
expect(ctrl.$error).toEqual({});
expect(ctrl.$$success).toEqual({});
expect(ctrl.$pending).toEqual({someError: true});
}
function expectCleared() {
expect(ctrl.$error).toEqual({});
expect(ctrl.$$success).toEqual({});
expect(ctrl.$pending).toBeUndefined();
}
it('should propagate validity to the parent form', function() {
expect(parentFormCtrl.$setValidity).not.toHaveBeenCalled();
ctrl.$setValidity('ERROR', false);
expect(parentFormCtrl.$setValidity).toHaveBeenCalledOnceWith('ERROR', false, ctrl);
});
it('should transition from states correctly', function() {
expectCleared();
ctrl.$setValidity('someError', false);
expectOneError();
ctrl.$setValidity('someError', undefined);
expectOnePending();
ctrl.$setValidity('someError', true);
expectOneSuccess();
ctrl.$setValidity('someError', null);
expectCleared();
});
it('should set valid/invalid with multiple errors', function() {
ctrl.$setValidity('first', false);
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
ctrl.$setValidity('second', false);
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
ctrl.$setValidity('third', undefined);
expect(ctrl.$valid).toBeUndefined();
expect(ctrl.$invalid).toBeUndefined();
ctrl.$setValidity('third', null);
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
ctrl.$setValidity('second', true);
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
ctrl.$setValidity('first', true);
expect(ctrl.$valid).toBe(true);
expect(ctrl.$invalid).toBe(false);
});
});
describe('setPristine', function() {
it('should set control to its pristine state', function() {
ctrl.$setViewValue('edit');
expect(ctrl.$dirty).toBe(true);
expect(ctrl.$pristine).toBe(false);
ctrl.$setPristine();
expect(ctrl.$dirty).toBe(false);
expect(ctrl.$pristine).toBe(true);
});
});
describe('setDirty', function() {
it('should set control to its dirty state', function() {
expect(ctrl.$pristine).toBe(true);
expect(ctrl.$dirty).toBe(false);
ctrl.$setDirty();
expect(ctrl.$pristine).toBe(false);
expect(ctrl.$dirty).toBe(true);
});
it('should set parent form to its dirty state', function() {
ctrl.$setDirty();
expect(parentFormCtrl.$setDirty).toHaveBeenCalled();
});
});
describe('setUntouched', function() {
it('should set control to its untouched state', function() {
ctrl.$setTouched();
ctrl.$setUntouched();
expect(ctrl.$touched).toBe(false);
expect(ctrl.$untouched).toBe(true);
});
});
describe('setTouched', function() {
it('should set control to its touched state', function() {
ctrl.$setUntouched();
ctrl.$setTouched();
expect(ctrl.$touched).toBe(true);
expect(ctrl.$untouched).toBe(false);
});
});
describe('view -> model', function() {
it('should set the value to $viewValue', function() {
ctrl.$setViewValue('some-val');
expect(ctrl.$viewValue).toBe('some-val');
});
it('should pipeline all registered parsers and set result to $modelValue', function() {
var log = [];
ctrl.$parsers.push(function(value) {
log.push(value);
return value + '-a';
});
ctrl.$parsers.push(function(value) {
log.push(value);
return value + '-b';
});
ctrl.$setViewValue('init');
expect(log).toEqual(['init', 'init-a']);
expect(ctrl.$modelValue).toBe('init-a-b');
});
it('should fire viewChangeListeners when the value changes in the view (even if invalid)',
function() {
var spy = jasmine.createSpy('viewChangeListener');
ctrl.$viewChangeListeners.push(spy);
ctrl.$setViewValue('val');
expect(spy).toHaveBeenCalledOnce();
spy.calls.reset();
// invalid
ctrl.$parsers.push(function() {return undefined;});
ctrl.$setViewValue('val2');
expect(spy).toHaveBeenCalledOnce();
});
it('should reset the model when the view is invalid', function() {
ctrl.$setViewValue('aaaa');
expect(ctrl.$modelValue).toBe('aaaa');
// add a validator that will make any input invalid
ctrl.$parsers.push(function() {return undefined;});
expect(ctrl.$modelValue).toBe('aaaa');
ctrl.$setViewValue('bbbb');
expect(ctrl.$modelValue).toBeUndefined();
});
it('should not reset the model when the view is invalid due to an external validator', function() {
ctrl.$setViewValue('aaaa');
expect(ctrl.$modelValue).toBe('aaaa');
ctrl.$setValidity('someExternalError', false);
ctrl.$setViewValue('bbbb');
expect(ctrl.$modelValue).toBe('bbbb');
});
it('should not reset the view when the view is invalid', function() {
// this test fails when the view changes the model and
// then the model listener in ngModel picks up the change and
// tries to update the view again.
// add a validator that will make any input invalid
ctrl.$parsers.push(function() {return undefined;});
spyOn(ctrl, '$render');
// first digest
ctrl.$setViewValue('bbbb');
expect(ctrl.$modelValue).toBeUndefined();
expect(ctrl.$viewValue).toBe('bbbb');
expect(ctrl.$render).not.toHaveBeenCalled();
expect(scope.value).toBeUndefined();
// further digests
scope.$apply('value = "aaa"');
expect(ctrl.$viewValue).toBe('aaa');
ctrl.$render.calls.reset();
ctrl.$setViewValue('cccc');
expect(ctrl.$modelValue).toBeUndefined();
expect(ctrl.$viewValue).toBe('cccc');
expect(ctrl.$render).not.toHaveBeenCalled();
expect(scope.value).toBeUndefined();
});
it('should call parentForm.$setDirty only when pristine', function() {
ctrl.$setViewValue('');
expect(ctrl.$pristine).toBe(false);
expect(ctrl.$dirty).toBe(true);
expect(parentFormCtrl.$setDirty).toHaveBeenCalledOnce();
parentFormCtrl.$setDirty.calls.reset();
ctrl.$setViewValue('');
expect(ctrl.$pristine).toBe(false);
expect(ctrl.$dirty).toBe(true);
expect(parentFormCtrl.$setDirty).not.toHaveBeenCalled();
});
it('should remove all other errors when any parser returns undefined', function() {
var a, b, val = function(val, x) {
return x ? val : x;
};
ctrl.$parsers.push(function(v) { return val(v, a); });
ctrl.$parsers.push(function(v) { return val(v, b); });
ctrl.$validators.high = function(value) {
return !isDefined(value) || value > 5;
};
ctrl.$validators.even = function(value) {
return !isDefined(value) || value % 2 === 0;
};
a = b = true;
ctrl.$setViewValue('3');
expect(ctrl.$error).toEqual({ high: true, even: true });
ctrl.$setViewValue('10');
expect(ctrl.$error).toEqual({});
a = undefined;
ctrl.$setViewValue('12');
expect(ctrl.$error).toEqual({ parse: true });
a = true;
b = undefined;
ctrl.$setViewValue('14');
expect(ctrl.$error).toEqual({ parse: true });
a = undefined;
b = undefined;
ctrl.$setViewValue('16');
expect(ctrl.$error).toEqual({ parse: true });
a = b = false; //not undefined
ctrl.$setViewValue('2');
expect(ctrl.$error).toEqual({ high: true });
});
it('should not remove external validators when a parser failed', function() {
ctrl.$parsers.push(function(v) { return undefined; });
ctrl.$setValidity('externalError', false);
ctrl.$setViewValue('someValue');
expect(ctrl.$error).toEqual({ externalError: true, parse: true });
});
it('should remove all non-parse-related CSS classes from the form when a parser fails',
inject(function($compile, $rootScope) {
var element = $compile('<form name="myForm">' +
'<input name="myControl" ng-model="value" >' +
'</form>')($rootScope);
var inputElm = element.find('input');
var ctrl = $rootScope.myForm.myControl;
var parserIsFailing = false;
ctrl.$parsers.push(function(value) {
return parserIsFailing ? undefined : value;
});
ctrl.$validators.alwaysFail = function() {
return false;
};
ctrl.$setViewValue('123');
scope.$digest();
expect(element).toHaveClass('ng-valid-parse');
expect(element).not.toHaveClass('ng-invalid-parse');
expect(element).toHaveClass('ng-invalid-always-fail');
parserIsFailing = true;
ctrl.$setViewValue('12345');
scope.$digest();
expect(element).not.toHaveClass('ng-valid-parse');
expect(element).toHaveClass('ng-invalid-parse');
expect(element).not.toHaveClass('ng-invalid-always-fail');
dealoc(element);
}));
it('should set the ng-invalid-parse and ng-valid-parse CSS class when parsers fail and pass', function() {
var pass = true;
ctrl.$parsers.push(function(v) {
return pass ? v : undefined;
});
var input = element.find('input');
ctrl.$setViewValue('1');
expect(input).toHaveClass('ng-valid-parse');
expect(input).not.toHaveClass('ng-invalid-parse');
pass = undefined;
ctrl.$setViewValue('2');
expect(input).not.toHaveClass('ng-valid-parse');
expect(input).toHaveClass('ng-invalid-parse');
});
it('should update the model after all async validators resolve', inject(function($q) {
var defer;
ctrl.$asyncValidators.promiseValidator = function(value) {
defer = $q.defer();
return defer.promise;
};
// set view value on first digest
ctrl.$setViewValue('b');
expect(ctrl.$modelValue).toBeUndefined();
expect(scope.value).toBeUndefined();
defer.resolve();
scope.$digest();
expect(ctrl.$modelValue).toBe('b');
expect(scope.value).toBe('b');
// set view value on further digests
ctrl.$setViewValue('c');
expect(ctrl.$modelValue).toBe('b');
expect(scope.value).toBe('b');
defer.resolve();
scope.$digest();
expect(ctrl.$modelValue).toBe('c');
expect(scope.value).toBe('c');
}));
it('should not throw an error if the scope has been destroyed', function() {
scope.$destroy();
ctrl.$setViewValue('some-val');
expect(ctrl.$viewValue).toBe('some-val');
});
});
describe('model -> view', function() {
it('should set the value to $modelValue', function() {
scope.$apply('value = 10');
expect(ctrl.$modelValue).toBe(10);
});
it('should pipeline all registered formatters in reversed order and set result to $viewValue',
function() {
var log = [];
ctrl.$formatters.unshift(function(value) {
log.push(value);
return value + 2;
});
ctrl.$formatters.unshift(function(value) {
log.push(value);
return value + '';
});
scope.$apply('value = 3');
expect(log).toEqual([3, 5]);
expect(ctrl.$viewValue).toBe('5');
});
it('should $render only if value changed', function() {
spyOn(ctrl, '$render');
scope.$apply('value = 3');
expect(ctrl.$render).toHaveBeenCalledOnce();
ctrl.$render.calls.reset();
ctrl.$formatters.push(function() {return 3;});
scope.$apply('value = 5');
expect(ctrl.$render).not.toHaveBeenCalled();
});
it('should clear the view even if invalid', function() {
spyOn(ctrl, '$render');
ctrl.$formatters.push(function() {return undefined;});
scope.$apply('value = 5');
expect(ctrl.$render).toHaveBeenCalledOnce();
});
it('should render immediately even if there are async validators', inject(function($q) {
spyOn(ctrl, '$render');
ctrl.$asyncValidators.someValidator = function() {
return $q.defer().promise;
};
scope.$apply('value = 5');
expect(ctrl.$viewValue).toBe(5);
expect(ctrl.$render).toHaveBeenCalledOnce();
}));
it('should not rerender nor validate in case view value is not changed', function() {
ctrl.$formatters.push(function(value) {
return 'nochange';
});
spyOn(ctrl, '$render');
ctrl.$validators.spyValidator = jasmine.createSpy('spyValidator');
scope.$apply('value = "first"');
scope.$apply('value = "second"');
expect(ctrl.$validators.spyValidator).toHaveBeenCalledOnce();
expect(ctrl.$render).toHaveBeenCalledOnce();
});
it('should always format the viewValue as a string for a blank input type when the value is present',
inject(function($compile, $rootScope, $sniffer) {
var form = $compile('<form name="form"><input name="field" ng-model="val" /></form>')($rootScope);
$rootScope.val = 123;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe('123');
$rootScope.val = null;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe(null);
dealoc(form);
}));
it('should always format the viewValue as a string for a `text` input type when the value is present',
inject(function($compile, $rootScope, $sniffer) {
var form = $compile('<form name="form"><input type="text" name="field" ng-model="val" /></form>')($rootScope);
$rootScope.val = 123;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe('123');
$rootScope.val = null;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe(null);
dealoc(form);
}));
it('should always format the viewValue as a string for an `email` input type when the value is present',
inject(function($compile, $rootScope, $sniffer) {
var form = $compile('<form name="form"><input type="email" name="field" ng-model="val" /></form>')($rootScope);
$rootScope.val = 123;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe('123');
$rootScope.val = null;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe(null);
dealoc(form);
}));
it('should always format the viewValue as a string for a `url` input type when the value is present',
inject(function($compile, $rootScope, $sniffer) {
var form = $compile('<form name="form"><input type="url" name="field" ng-model="val" /></form>')($rootScope);
$rootScope.val = 123;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe('123');
$rootScope.val = null;
$rootScope.$digest();
expect($rootScope.form.field.$viewValue).toBe(null);
dealoc(form);
}));
it('should set NaN as the $modelValue when an asyncValidator is present',
inject(function($q) {
ctrl.$asyncValidators.test = function() {
return $q(function(resolve, reject) {
resolve();
});
};
scope.$apply('value = 10');
expect(ctrl.$modelValue).toBe(10);
expect(function() {
scope.$apply(function() {
scope.value = NaN;
});
}).not.toThrow();
expect(ctrl.$modelValue).toBeNaN();
}));
describe('$processModelValue', function() {
// Emulate setting the model on the scope
function setModelValue(ctrl, value) {
ctrl.$modelValue = ctrl.$$rawModelValue = value;
ctrl.$$parserValid = undefined;
}
it('should run the model -> view pipeline', function() {
var log = [];
var input = ctrl.$$element;
ctrl.$formatters.unshift(function(value) {
log.push(value);
return value + 2;
});
ctrl.$formatters.unshift(function(value) {
log.push(value);
return value + '';
});
spyOn(ctrl, '$render');
setModelValue(ctrl, 3);
expect(ctrl.$modelValue).toBe(3);
ctrl.$processModelValue();
expect(ctrl.$modelValue).toBe(3);
expect(log).toEqual([3, 5]);
expect(ctrl.$viewValue).toBe('5');
expect(ctrl.$render).toHaveBeenCalledOnce();
});
it('should add the validation and empty-state classes',
inject(function($compile, $rootScope, $animate) {
var input = $compile('<input name="myControl" maxlength="1" ng-model="value" >')($rootScope);
$rootScope.$digest();
spyOn($animate, 'addClass');
spyOn($animate, 'removeClass');
var ctrl = input.controller('ngModel');
expect(input).toHaveClass('ng-empty');
expect(input).toHaveClass('ng-valid');
setModelValue(ctrl, 3);
ctrl.$processModelValue();
// $animate adds / removes classes in the $$postDigest, which
// we cannot trigger with $digest, because that would set the model from the scope,
// so we simply check if the functions have been called
expect($animate.removeClass.calls.mostRecent().args[0][0]).toBe(input[0]);
expect($animate.removeClass.calls.mostRecent().args[1]).toBe('ng-empty');
expect($animate.addClass.calls.mostRecent().args[0][0]).toBe(input[0]);
expect($animate.addClass.calls.mostRecent().args[1]).toBe('ng-not-empty');
$animate.removeClass.calls.reset();
$animate.addClass.calls.reset();
setModelValue(ctrl, 35);
ctrl.$processModelValue();
expect($animate.addClass.calls.argsFor(1)[0][0]).toBe(input[0]);
expect($animate.addClass.calls.argsFor(1)[1]).toBe('ng-invalid');
expect($animate.addClass.calls.argsFor(2)[0][0]).toBe(input[0]);
expect($animate.addClass.calls.argsFor(2)[1]).toBe('ng-invalid-maxlength');
})
);
// this is analogue to $setViewValue
it('should run the model -> view pipeline even if the value has not changed', function() {
var log = [];
ctrl.$formatters.unshift(function(value) {
log.push(value);
return value + 2;
});
ctrl.$formatters.unshift(function(value) {
log.push(value);
return value + '';
});
spyOn(ctrl, '$render');
setModelValue(ctrl, 3);
ctrl.$processModelValue();
expect(ctrl.$modelValue).toBe(3);
expect(ctrl.$viewValue).toBe('5');
expect(log).toEqual([3, 5]);
expect(ctrl.$render).toHaveBeenCalledOnce();
ctrl.$processModelValue();
expect(ctrl.$modelValue).toBe(3);
expect(ctrl.$viewValue).toBe('5');
expect(log).toEqual([3, 5, 3, 5]);
// $render() is not called if the viewValue didn't change
expect(ctrl.$render).toHaveBeenCalledOnce();
});
});
});
describe('validation', function() {
describe('$validate', function() {
it('should perform validations when $validate() is called', function() {
scope.$apply('value = ""');
var validatorResult = false;
ctrl.$validators.someValidator = function(value) {
return validatorResult;
};
ctrl.$validate();
expect(ctrl.$valid).toBe(false);
validatorResult = true;
ctrl.$validate();
expect(ctrl.$valid).toBe(true);
});
it('should pass the last parsed modelValue to the validators', function() {
ctrl.$parsers.push(function(modelValue) {
return modelValue + 'def';
});
ctrl.$setViewValue('abc');
ctrl.$validators.test = function(modelValue, viewValue) {
return true;
};
spyOn(ctrl.$validators, 'test');
ctrl.$validate();
expect(ctrl.$validators.test).toHaveBeenCalledWith('abcdef', 'abc');
});
it('should set the model to undefined when it becomes invalid', function() {
var valid = true;
ctrl.$validators.test = function(modelValue, viewValue) {
return valid;
};
scope.$apply('value = "abc"');
expect(scope.value).toBe('abc');
valid = false;
ctrl.$validate();
expect(scope.value).toBeUndefined();
});
it('should update the model when it becomes valid', function() {
var valid = true;
ctrl.$validators.test = function(modelValue, viewValue) {
return valid;
};
scope.$apply('value = "abc"');
expect(scope.value).toBe('abc');
valid = false;
ctrl.$validate();
expect(scope.value).toBeUndefined();
valid = true;
ctrl.$validate();
expect(scope.value).toBe('abc');
});
it('should not update the model when it is valid, but there is a parse error', function() {
ctrl.$parsers.push(function(modelValue) {
return undefined;
});
ctrl.$setViewValue('abc');
expect(ctrl.$error.parse).toBe(true);
expect(scope.value).toBeUndefined();
ctrl.$validators.test = function(modelValue, viewValue) {
return true;
};
ctrl.$validate();
expect(ctrl.$error).toEqual({parse: true});
expect(scope.value).toBeUndefined();
});
it('should not set an invalid model to undefined when validity is the same', function() {
ctrl.$validators.test = function() {
return false;
};
scope.$apply('value = "invalid"');
expect(ctrl.$valid).toBe(false);
expect(scope.value).toBe('invalid');
ctrl.$validate();
expect(ctrl.$valid).toBe(false);
expect(scope.value).toBe('invalid');
});
it('should not change a model that has a formatter', function() {
ctrl.$validators.test = function() {
return true;
};
ctrl.$formatters.push(function(modelValue) {
return 'xyz';
});
scope.$apply('value = "abc"');
expect(ctrl.$viewValue).toBe('xyz');
ctrl.$validate();
expect(scope.value).toBe('abc');
});
it('should not change a model that has a parser', function() {
ctrl.$validators.test = function() {
return true;
};
ctrl.$parsers.push(function(modelValue) {
return 'xyz';
});
scope.$apply('value = "abc"');
ctrl.$validate();
expect(scope.value).toBe('abc');
});
});
describe('view -> model update', function() {
it('should always perform validations using the parsed model value', function() {
var captures;
ctrl.$validators.raw = function() {
captures = Array.prototype.slice.call(arguments);
return captures[0];
};
ctrl.$parsers.push(function(value) {
return value.toUpperCase();
});
ctrl.$setViewValue('my-value');
expect(captures).toEqual(['MY-VALUE', 'my-value']);
});
it('should always perform validations using the formatted view value', function() {
var captures;
ctrl.$validators.raw = function() {
captures = Array.prototype.slice.call(arguments);
return captures[0];
};
ctrl.$formatters.push(function(value) {
return value + '...';
});
scope.$apply('value = "matias"');
expect(captures).toEqual(['matias', 'matias...']);
});
it('should only perform validations if the view value is different', function() {
var count = 0;
ctrl.$validators.countMe = function() {
count++;
};
ctrl.$setViewValue('my-value');
expect(count).toBe(1);
ctrl.$setViewValue('my-value');
expect(count).toBe(1);
ctrl.$setViewValue('your-value');
expect(count).toBe(2);
});
});
it('should perform validations twice each time the model value changes within a digest', function() {
var count = 0;
ctrl.$validators.number = function(value) {
count++;
return (/^\d+$/).test(value);
};
scope.$apply('value = ""');
expect(count).toBe(1);
scope.$apply('value = 1');
expect(count).toBe(2);
scope.$apply('value = 1');
expect(count).toBe(2);
scope.$apply('value = ""');
expect(count).toBe(3);
});
it('should only validate to true if all validations are true', function() {
ctrl.$modelValue = undefined;
ctrl.$validators.a = valueFn(true);
ctrl.$validators.b = valueFn(true);
ctrl.$validators.c = valueFn(false);
ctrl.$validate();
expect(ctrl.$valid).toBe(false);
ctrl.$validators.c = valueFn(true);
ctrl.$validate();
expect(ctrl.$valid).toBe(true);
});
it('should treat all responses as boolean for synchronous validators', function() {
var expectValid = function(value, expected) {
ctrl.$modelValue = undefined;
ctrl.$validators.a = valueFn(value);
ctrl.$validate();
expect(ctrl.$valid).toBe(expected);
};
// False tests
expectValid(false, false);
expectValid(undefined, false);
expectValid(null, false);
expectValid(0, false);
expectValid(NaN, false);
expectValid('', false);
// True tests
expectValid(true, true);
expectValid(1, true);
expectValid('0', true);
expectValid('false', true);
expectValid([], true);
expectValid({}, true);
});
it('should register invalid validations on the $error object', function() {
ctrl.$modelValue = undefined;
ctrl.$validators.unique = valueFn(false);
ctrl.$validators.tooLong = valueFn(false);
ctrl.$validators.notNumeric = valueFn(true);
ctrl.$validate();
expect(ctrl.$error.unique).toBe(true);
expect(ctrl.$error.tooLong).toBe(true);
expect(ctrl.$error.notNumeric).not.toBe(true);
});
it('should render a validator asynchronously when a promise is returned', inject(function($q) {
var defer;
ctrl.$asyncValidators.promiseValidator = function(value) {
defer = $q.defer();
return defer.promise;
};
scope.$apply('value = ""');
expect(ctrl.$valid).toBeUndefined();
expect(ctrl.$invalid).toBeUndefined();
expect(ctrl.$pending.promiseValidator).toBe(true);
defer.resolve();
scope.$digest();
expect(ctrl.$valid).toBe(true);
expect(ctrl.$invalid).toBe(false);
expect(ctrl.$pending).toBeUndefined();
scope.$apply('value = "123"');
defer.reject();
scope.$digest();
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
expect(ctrl.$pending).toBeUndefined();
}));
it('should throw an error when a promise is not returned for an asynchronous validator', inject(function($q) {
ctrl.$asyncValidators.async = function(value) {
return true;
};
expect(function() {
scope.$apply('value = "123"');
}).toThrowMinErr('ngModel', 'nopromise',
'Expected asynchronous validator to return a promise but got \'true\' instead.');
}));
it('should only run the async validators once all the sync validators have passed',
inject(function($q) {
var stages = {};
stages.sync = { status1: false, status2: false, count: 0 };
ctrl.$validators.syncValidator1 = function(modelValue, viewValue) {
stages.sync.count++;
return stages.sync.status1;
};
ctrl.$validators.syncValidator2 = function(modelValue, viewValue) {
stages.sync.count++;
return stages.sync.status2;
};
stages.async = { defer: null, count: 0 };
ctrl.$asyncValidators.asyncValidator = function(modelValue, viewValue) {
stages.async.defer = $q.defer();
stages.async.count++;
return stages.async.defer.promise;
};
scope.$apply('value = "123"');
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
expect(stages.sync.count).toBe(2);
expect(stages.async.count).toBe(0);
stages.sync.status1 = true;
scope.$apply('value = "456"');
expect(stages.sync.count).toBe(4);
expect(stages.async.count).toBe(0);
stages.sync.status2 = true;
scope.$apply('value = "789"');
expect(stages.sync.count).toBe(6);
expect(stages.async.count).toBe(1);
stages.async.defer.resolve();
scope.$apply();
expect(ctrl.$valid).toBe(true);
expect(ctrl.$invalid).toBe(false);
}));
it('should ignore expired async validation promises once delivered', inject(function($q) {
var defer, oldDefer, newDefer;
ctrl.$asyncValidators.async = function(value) {
defer = $q.defer();
return defer.promise;
};
scope.$apply('value = ""');
oldDefer = defer;
scope.$apply('value = "123"');
newDefer = defer;
newDefer.reject();
scope.$digest();
oldDefer.resolve();
scope.$digest();
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
expect(ctrl.$pending).toBeUndefined();
}));
it('should clear and ignore all pending promises when the model value changes', inject(function($q) {
ctrl.$validators.sync = function(value) {
return true;
};
var defers = [];
ctrl.$asyncValidators.async = function(value) {
var defer = $q.defer();
defers.push(defer);
return defer.promise;
};
scope.$apply('value = "123"');
expect(ctrl.$pending).toEqual({async: true});
expect(ctrl.$valid).toBeUndefined();
expect(ctrl.$invalid).toBeUndefined();
expect(defers.length).toBe(1);
expect(isObject(ctrl.$pending)).toBe(true);
scope.$apply('value = "456"');
expect(ctrl.$pending).toEqual({async: true});
expect(ctrl.$valid).toBeUndefined();
expect(ctrl.$invalid).toBeUndefined();
expect(defers.length).toBe(2);
expect(isObject(ctrl.$pending)).toBe(true);
defers[1].resolve();
scope.$digest();
expect(ctrl.$valid).toBe(true);
expect(ctrl.$invalid).toBe(false);
expect(isObject(ctrl.$pending)).toBe(false);
}));
it('should clear and ignore all pending promises when a parser fails', inject(function($q) {
var failParser = false;
ctrl.$parsers.push(function(value) {
return failParser ? undefined : value;
});
var defer;
ctrl.$asyncValidators.async = function(value) {
defer = $q.defer();
return defer.promise;
};
ctrl.$setViewValue('x..y..z');
expect(ctrl.$valid).toBeUndefined();
expect(ctrl.$invalid).toBeUndefined();
failParser = true;
ctrl.$setViewValue('1..2..3');
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
expect(isObject(ctrl.$pending)).toBe(false);
defer.resolve();
scope.$digest();
expect(ctrl.$valid).toBe(false);
expect(ctrl.$invalid).toBe(true);
expect(isObject(ctrl.$pending)).toBe(false);
}));
it('should clear all errors from async validators if a parser fails', inject(function($q) {
var failParser = false;
ctrl.$parsers.push(function(value) {
return failParser ? undefined : value;
});
ctrl.$asyncValidators.async = function(value) {
return $q.reject();
};
ctrl.$setViewValue('x..y..z');
expect(ctrl.$error).toEqual({async: true});
failParser = true;
ctrl.$setViewValue('1..2..3');
expect(ctrl.$error).toEqual({parse: true});
}));
it('should clear all errors from async validators if a sync validator fails', inject(function($q) {
var failValidator = false;
ctrl.$validators.sync = function(value) {
return !failValidator;
};
ctrl.$asyncValidators.async = function(value) {
return $q.reject();
};
ctrl.$setViewValue('x..y..z');
expect(ctrl.$error).toEqual({async: true});
failValidator = true;
ctrl.$setViewValue('1..2..3');
expect(ctrl.$error).toEqual({sync: true});
}));
it('should be possible to extend Object prototype and still be able to do form validation',
inject(function($compile, $rootScope) {
// eslint-disable-next-line no-extend-native
Object.prototype.someThing = function() {};
var element = $compile('<form name="myForm">' +
'<input type="text" name="username" ng-model="username" minlength="10" required />' +
'</form>')($rootScope);
var inputElm = element.find('input');
var formCtrl = $rootScope.myForm;
var usernameCtrl = formCtrl.username;
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(true);
expect(formCtrl.$invalid).toBe(true);
usernameCtrl.$setViewValue('valid-username');
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(false);
expect(formCtrl.$invalid).toBe(false);
delete Object.prototype.someThing;
dealoc(element);
}));
it('should re-evaluate the form validity state once the asynchronous promise has been delivered',
inject(function($compile, $rootScope, $q) {
var element = $compile('<form name="myForm">' +
'<input type="text" name="username" ng-model="username" minlength="10" required />' +
'<input type="number" name="age" ng-model="age" min="10" required />' +
'</form>')($rootScope);
var inputElm = element.find('input');
var formCtrl = $rootScope.myForm;
var usernameCtrl = formCtrl.username;
var ageCtrl = formCtrl.age;
var usernameDefer;
usernameCtrl.$asyncValidators.usernameAvailability = function() {
usernameDefer = $q.defer();
return usernameDefer.promise;
};
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(true);
expect(formCtrl.$invalid).toBe(true);
usernameCtrl.$setViewValue('valid-username');
$rootScope.$digest();
expect(formCtrl.$pending.usernameAvailability).toBeTruthy();
expect(usernameCtrl.$invalid).toBeUndefined();
expect(formCtrl.$invalid).toBeUndefined();
usernameDefer.resolve();
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(false);
expect(formCtrl.$invalid).toBe(true);
ageCtrl.$setViewValue(22);
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(false);
expect(ageCtrl.$invalid).toBe(false);
expect(formCtrl.$invalid).toBe(false);
usernameCtrl.$setViewValue('valid');
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(true);
expect(ageCtrl.$invalid).toBe(false);
expect(formCtrl.$invalid).toBe(true);
usernameCtrl.$setViewValue('another-valid-username');
$rootScope.$digest();
usernameDefer.resolve();
$rootScope.$digest();
expect(usernameCtrl.$invalid).toBe(false);
expect(formCtrl.$invalid).toBe(false);
expect(formCtrl.$pending).toBeFalsy();
expect(ageCtrl.$invalid).toBe(false);
dealoc(element);
}));
it('should always use the most recent $viewValue for validation', function() {
ctrl.$parsers.push(function(value) {
if (value && value.substr(-1) === 'b') {
value = 'a';
ctrl.$setViewValue(value);
ctrl.$render();
}
return value;
});
ctrl.$validators.mock = function(modelValue) {
return true;
};
spyOn(ctrl.$validators, 'mock').and.callThrough();
ctrl.$setViewValue('ab');
expect(ctrl.$validators.mock).toHaveBeenCalledWith('a', 'a');
expect(ctrl.$validators.mock).toHaveBeenCalledTimes(2);
});
it('should validate even if the modelValue did not change', function() {
ctrl.$parsers.push(function(value) {
if (value && value.substr(-1) === 'b') {
value = 'a';
}
return value;
});
ctrl.$validators.mock = function(modelValue) {
return true;
};
spyOn(ctrl.$validators, 'mock').and.callThrough();
ctrl.$setViewValue('a');
expect(ctrl.$validators.mock).toHaveBeenCalledWith('a', 'a');
expect(ctrl.$validators.mock).toHaveBeenCalledTimes(1);
ctrl.$setViewValue('ab');
expect(ctrl.$validators.mock).toHaveBeenCalledWith('a', 'ab');
expect(ctrl.$validators.mock).toHaveBeenCalledTimes(2);
});
it('should validate correctly when $parser name equals $validator key', function() {
ctrl.$validators.parserOrValidator = function(value) {
switch (value) {
case 'allInvalid':
case 'parseValid-validatorsInvalid':
case 'stillParseValid-validatorsInvalid':
return false;
default:
return true;
}
};
ctrl.$validators.validator = function(value) {
switch (value) {
case 'allInvalid':
case 'parseValid-validatorsInvalid':
case 'stillParseValid-validatorsInvalid':
return false;
default:
return true;
}
};
ctrl.$parsers.push(function(value) {
switch (value) {
case 'allInvalid':
case 'stillAllInvalid':
case 'parseInvalid-validatorsValid':
case 'stillParseInvalid-validatorsValid':
ctrl.$$parserName = 'parserOrValidator';
return undefined;
default:
return value;
}
});
//Parser and validators are invalid
scope.$apply('value = "allInvalid"');
expect(scope.value).toBe('allInvalid');
expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true});
ctrl.$validate();
expect(scope.value).toEqual('allInvalid');
expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true});
ctrl.$setViewValue('stillAllInvalid');
expect(scope.value).toBeUndefined();
expect(ctrl.$error).toEqual({parserOrValidator: true});
ctrl.$validate();
expect(scope.value).toBeUndefined();
expect(ctrl.$error).toEqual({parserOrValidator: true});
//Parser is valid, validators are invalid
scope.$apply('value = "parseValid-validatorsInvalid"');
expect(scope.value).toBe('parseValid-validatorsInvalid');
expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true});
ctrl.$validate();
expect(scope.value).toBe('parseValid-validatorsInvalid');
expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true});
ctrl.$setViewValue('stillParseValid-validatorsInvalid');
expect(scope.value).toBeUndefined();
expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true});
ctrl.$validate();
expect(scope.value).toBeUndefined();
expect(ctrl.$error).toEqual({parserOrValidator: true, validator: true});
//Parser is invalid, validators are valid
scope.$apply('value = "parseInvalid-validatorsValid"');
expect(scope.value).toBe('parseInvalid-validatorsValid');
expect(ctrl.$error).toEqual({});
ctrl.$validate();
expect(scope.value).toBe('parseInvalid-validatorsValid');
expect(ctrl.$error).toEqual({});
ctrl.$setViewValue('stillParseInvalid-validatorsValid');
expect(scope.value).toBeUndefined();
expect(ctrl.$error).toEqual({parserOrValidator: true});
ctrl.$validate();
expect(scope.value).toBeUndefined();
expect(ctrl.$error).toEqual({parserOrValidator: true});
});
});
describe('override ModelOptions', function() {
it('should replace the previous model options', function() {
var $options = ctrl.$options;
ctrl.$overrideModelOptions({});
expect(ctrl.$options).not.toBe($options);
});
it('should set the given options', function() {
var $options = ctrl.$options;
ctrl.$overrideModelOptions({ debounce: 1000, updateOn: 'blur' });
expect(ctrl.$options.getOption('debounce')).toEqual(1000);
expect(ctrl.$options.getOption('updateOn')).toEqual('blur');
expect(ctrl.$options.getOption('updateOnDefault')).toBe(false);
});
it('should inherit from a parent model options if specified', inject(function($compile, $rootScope) {
var element = $compile(
'<form name="form" ng-model-options="{debounce: 1000, updateOn: \'blur\'}">' +
' <input ng-model="value" name="input">' +
'</form>')($rootScope);
var ctrl = $rootScope.form.input;
ctrl.$overrideModelOptions({ debounce: 2000, '*': '$inherit' });
expect(ctrl.$options.getOption('debounce')).toEqual(2000);
expect(ctrl.$options.getOption('updateOn')).toEqual('blur');
expect(ctrl.$options.getOption('updateOnDefault')).toBe(false);
dealoc(element);
}));
it('should not inherit from a parent model options if not specified', inject(function($compile, $rootScope) {
var element = $compile(
'<form name="form" ng-model-options="{debounce: 1000, updateOn: \'blur\'}">' +
' <input ng-model="value" name="input">' +
'</form>')($rootScope);
var ctrl = $rootScope.form.input;
ctrl.$overrideModelOptions({ debounce: 2000 });
expect(ctrl.$options.getOption('debounce')).toEqual(2000);
expect(ctrl.$options.getOption('updateOn')).toEqual('');
expect(ctrl.$options.getOption('updateOnDefault')).toBe(true);
dealoc(element);
}));
});
});
describe('CSS classes', function() {
var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
it('should set ng-empty or ng-not-empty when the view value changes',
inject(function($compile, $rootScope, $sniffer) {
var element = $compile('<input ng-model="value" />')($rootScope);
$rootScope.$digest();
expect(element).toBeEmpty();
$rootScope.value = 'XXX';
$rootScope.$digest();
expect(element).toBeNotEmpty();
element.val('');
browserTrigger(element, $sniffer.hasEvent('input') ? 'input' : 'change');
expect(element).toBeEmpty();
element.val('YYY');
browserTrigger(element, $sniffer.hasEvent('input') ? 'input' : 'change');
expect(element).toBeNotEmpty();
}));
it('should set css classes (ng-valid, ng-invalid, ng-pristine, ng-dirty, ng-untouched, ng-touched)',
inject(function($compile, $rootScope, $sniffer) {
var element = $compile('<input type="email" ng-model="value" />')($rootScope);
$rootScope.$digest();
expect(element).toBeValid();
expect(element).toBePristine();
expect(element).toBeUntouched();
expect(element.hasClass('ng-valid-email')).toBe(true);
expect(element.hasClass('ng-invalid-email')).toBe(false);
$rootScope.$apply('value = \'invalid-email\'');
expect(element).toBeInvalid();
expect(element).toBePristine();
expect(element.hasClass('ng-valid-email')).toBe(false);
expect(element.hasClass('ng-invalid-email')).toBe(true);
element.val('invalid-again');
browserTrigger(element, ($sniffer.hasEvent('input')) ? 'input' : 'change');
expect(element).toBeInvalid();
expect(element).toBeDirty();
expect(element.hasClass('ng-valid-email')).toBe(false);
expect(element.hasClass('ng-invalid-email')).toBe(true);
element.val('[email protected]');
browserTrigger(element, $sniffer.hasEvent('input') ? 'input' : 'change');
expect(element).toBeValid();
expect(element).toBeDirty();
expect(element.hasClass('ng-valid-email')).toBe(true);
expect(element.hasClass('ng-invalid-email')).toBe(false);
browserTrigger(element, 'blur');
expect(element).toBeTouched();
dealoc(element);
}));
it('should set invalid classes on init', inject(function($compile, $rootScope) {
var element = $compile('<input type="email" ng-model="value" required />')($rootScope);
$rootScope.$digest();
expect(element).toBeInvalid();
expect(element).toHaveClass('ng-invalid-required');
dealoc(element);
}));
});
describe('custom formatter and parser that are added by a directive in post linking', function() {
var inputElm, scope;
beforeEach(module(function($compileProvider) {
$compileProvider.directive('customFormat', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
ngModelCtrl.$formatters.push(function(value) {
return value.part;
});
ngModelCtrl.$parsers.push(function(value) {
return {part: value};
});
}
};
});
}));
afterEach(function() {
dealoc(inputElm);
});
function createInput(type) {
inject(function($compile, $rootScope) {
scope = $rootScope;
inputElm = $compile('<input type="' + type + '" ng-model="val" custom-format/>')($rootScope);
});
}
it('should use them after the builtin ones for text inputs', function() {
createInput('text');
scope.$apply('val = {part: "a"}');
expect(inputElm.val()).toBe('a');
inputElm.val('b');
browserTrigger(inputElm, 'change');
expect(scope.val).toEqual({part: 'b'});
});
it('should use them after the builtin ones for number inputs', function() {
createInput('number');
scope.$apply('val = {part: 1}');
expect(inputElm.val()).toBe('1');
inputElm.val('2');
browserTrigger(inputElm, 'change');
expect(scope.val).toEqual({part: 2});
});
it('should use them after the builtin ones for date inputs', function() {
createInput('date');
scope.$apply(function() {
scope.val = {part: new Date(2000, 10, 8)};
});
expect(inputElm.val()).toBe('2000-11-08');
inputElm.val('2001-12-09');
browserTrigger(inputElm, 'change');
expect(scope.val).toEqual({part: new Date(2001, 11, 9)});
});
});
describe('$touched', function() {
it('should set the control touched state on "blur" event', inject(function($compile, $rootScope) {
var element = $compile('<form name="myForm">' +
'<input name="myControl" ng-model="value" >' +
'</form>')($rootScope);
var inputElm = element.find('input');
var control = $rootScope.myForm.myControl;
expect(control.$touched).toBe(false);
expect(control.$untouched).toBe(true);
browserTrigger(inputElm, 'blur');
expect(control.$touched).toBe(true);
expect(control.$untouched).toBe(false);
dealoc(element);
}));
it('should not cause a digest on "blur" event if control is already touched',
inject(function($compile, $rootScope) {
var element = $compile('<form name="myForm">' +
'<input name="myControl" ng-model="value" >' +
'</form>')($rootScope);
var inputElm = element.find('input');
var control = $rootScope.myForm.myControl;
control.$setTouched();
spyOn($rootScope, '$apply');
browserTrigger(inputElm, 'blur');
expect($rootScope.$apply).not.toHaveBeenCalled();
dealoc(element);
}));
it('should digest asynchronously on "blur" event if a apply is already in progress',
inject(function($compile, $rootScope) {
var element = $compile('<form name="myForm">' +
'<input name="myControl" ng-model="value" >' +
'</form>')($rootScope);
var inputElm = element.find('input');
var control = $rootScope.myForm.myControl;
$rootScope.$apply(function() {
expect(control.$touched).toBe(false);
expect(control.$untouched).toBe(true);
browserTrigger(inputElm, 'blur');
expect(control.$touched).toBe(false);
expect(control.$untouched).toBe(true);
});
expect(control.$touched).toBe(true);
expect(control.$untouched).toBe(false);
dealoc(element);
}));
});
describe('nested in a form', function() {
it('should register/deregister a nested ngModel with parent form when entering or leaving DOM',
inject(function($compile, $rootScope) {
var element = $compile('<form name="myForm">' +
'<input ng-if="inputPresent" name="myControl" ng-model="value" required >' +
'</form>')($rootScope);
var isFormValid;
$rootScope.inputPresent = false;
$rootScope.$watch('myForm.$valid', function(value) { isFormValid = value; });
$rootScope.$apply();
expect($rootScope.myForm.$valid).toBe(true);
expect(isFormValid).toBe(true);
expect($rootScope.myForm.myControl).toBeUndefined();
$rootScope.inputPresent = true;
$rootScope.$apply();
expect($rootScope.myForm.$valid).toBe(false);
expect(isFormValid).toBe(false);
expect($rootScope.myForm.myControl).toBeDefined();
$rootScope.inputPresent = false;
$rootScope.$apply();
expect($rootScope.myForm.$valid).toBe(true);
expect(isFormValid).toBe(true);
expect($rootScope.myForm.myControl).toBeUndefined();
dealoc(element);
}));
it('should register/deregister a nested ngModel with parent form when entering or leaving DOM with animations',
function() {
// ngAnimate performs the dom manipulation after digest, and since the form validity can be affected by a form
// control going away we must ensure that the deregistration happens during the digest while we are still doing
// dirty checking.
module('ngAnimate');
inject(function($compile, $rootScope) {
var element = $compile('<form name="myForm">' +
'<input ng-if="inputPresent" name="myControl" ng-model="value" required >' +
'</form>')($rootScope);
var isFormValid;
$rootScope.inputPresent = false;
// this watch ensure that the form validity gets updated during digest (so that we can observe it)
$rootScope.$watch('myForm.$valid', function(value) { isFormValid = value; });
$rootScope.$apply();
expect($rootScope.myForm.$valid).toBe(true);
expect(isFormValid).toBe(true);
expect($rootScope.myForm.myControl).toBeUndefined();
$rootScope.inputPresent = true;
$rootScope.$apply();
expect($rootScope.myForm.$valid).toBe(false);
expect(isFormValid).toBe(false);
expect($rootScope.myForm.myControl).toBeDefined();
$rootScope.inputPresent = false;
$rootScope.$apply();
expect($rootScope.myForm.$valid).toBe(true);
expect(isFormValid).toBe(true);
expect($rootScope.myForm.myControl).toBeUndefined();
dealoc(element);
});
});
it('should keep previously defined watches consistent when changes in validity are made',
inject(function($compile, $rootScope) {
var isFormValid;
$rootScope.$watch('myForm.$valid', function(value) { isFormValid = value; });
var element = $compile('<form name="myForm">' +
'<input name="myControl" ng-model="value" required >' +
'</form>')($rootScope);
$rootScope.$apply();
expect(isFormValid).toBe(false);
expect($rootScope.myForm.$valid).toBe(false);
$rootScope.value = 'value';
$rootScope.$apply();
expect(isFormValid).toBe(true);
expect($rootScope.myForm.$valid).toBe(true);
dealoc(element);
}));
});
describe('animations', function() {
function findElementAnimations(element, queue) {
var node = element[0];
var animations = [];
for (var i = 0; i < queue.length; i++) {
var animation = queue[i];
if (animation.element[0] === node) {
animations.push(animation);
}
}
return animations;
}
function assertValidAnimation(animation, event, classNameA, classNameB) {
expect(animation.event).toBe(event);
expect(animation.args[1]).toBe(classNameA);
if (classNameB) expect(animation.args[2]).toBe(classNameB);
}
var doc, input, scope, model;
beforeEach(module('ngAnimateMock'));
beforeEach(inject(function($rootScope, $compile, $rootElement, $animate) {
scope = $rootScope.$new();
doc = jqLite('<form name="myForm">' +
' <input type="text" ng-model="input" name="myInput" />' +
'</form>');
$rootElement.append(doc);
$compile(doc)(scope);
$animate.queue = [];
input = doc.find('input');
model = scope.myForm.myInput;
}));
afterEach(function() {
dealoc(input);
});
it('should trigger an animation when invalid', inject(function($animate) {
model.$setValidity('required', false);
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'removeClass', 'ng-valid');
assertValidAnimation(animations[1], 'addClass', 'ng-invalid');
assertValidAnimation(animations[2], 'addClass', 'ng-invalid-required');
}));
it('should trigger an animation when valid', inject(function($animate) {
model.$setValidity('required', false);
$animate.queue = [];
model.$setValidity('required', true);
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'addClass', 'ng-valid');
assertValidAnimation(animations[1], 'removeClass', 'ng-invalid');
assertValidAnimation(animations[2], 'addClass', 'ng-valid-required');
assertValidAnimation(animations[3], 'removeClass', 'ng-invalid-required');
}));
it('should trigger an animation when dirty', inject(function($animate) {
model.$setViewValue('some dirty value');
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'removeClass', 'ng-empty');
assertValidAnimation(animations[1], 'addClass', 'ng-not-empty');
assertValidAnimation(animations[2], 'removeClass', 'ng-pristine');
assertValidAnimation(animations[3], 'addClass', 'ng-dirty');
}));
it('should trigger an animation when pristine', inject(function($animate) {
model.$setPristine();
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'removeClass', 'ng-dirty');
assertValidAnimation(animations[1], 'addClass', 'ng-pristine');
}));
it('should trigger an animation when untouched', inject(function($animate) {
model.$setUntouched();
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'setClass', 'ng-untouched');
expect(animations[0].args[2]).toBe('ng-touched');
}));
it('should trigger an animation when touched', inject(function($animate) {
model.$setTouched();
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'setClass', 'ng-touched', 'ng-untouched');
expect(animations[0].args[2]).toBe('ng-untouched');
}));
it('should trigger custom errors as addClass/removeClass when invalid/valid', inject(function($animate) {
model.$setValidity('custom-error', false);
var animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'removeClass', 'ng-valid');
assertValidAnimation(animations[1], 'addClass', 'ng-invalid');
assertValidAnimation(animations[2], 'addClass', 'ng-invalid-custom-error');
$animate.queue = [];
model.$setValidity('custom-error', true);
animations = findElementAnimations(input, $animate.queue);
assertValidAnimation(animations[0], 'addClass', 'ng-valid');
assertValidAnimation(animations[1], 'removeClass', 'ng-invalid');
assertValidAnimation(animations[2], 'addClass', 'ng-valid-custom-error');
assertValidAnimation(animations[3], 'removeClass', 'ng-invalid-custom-error');
}));
});
});
|
/* flatpickr v4.4.2, @license MIT */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.ms = {})));
}(this, (function (exports) { 'use strict';
var fp = typeof window !== "undefined" && window.flatpickr !== undefined ? window.flatpickr : {
l10ns: {}
};
var Malaysian = {
weekdays: {
shorthand: ["Min", "Isn", "Sel", "Rab", "Kha", "Jum", "Sab"],
longhand: ["Minggu", "Isnin", "Selasa", "Rabu", "Khamis", "Jumaat", "Sabtu"]
},
months: {
shorthand: ["Jan", "Feb", "Mac", "Apr", "Mei", "Jun", "Jul", "Ogo", "Sep", "Okt", "Nov", "Dis"],
longhand: ["Januari", "Februari", "Mac", "April", "Mei", "Jun", "Julai", "Ogos", "September", "Oktober", "November", "Disember"]
},
firstDayOfWeek: 1,
ordinal: function ordinal() {
return "";
}
};
var ms = fp.l10ns;
exports.Malaysian = Malaysian;
exports.default = ms;
Object.defineProperty(exports, '__esModule', { value: true });
})));
|
var gulp = require('gulp');
var config = require('../config').markup;
var browserSync = require('browser-sync');
var taskDef = function () {
return gulp.src(config.src)
.pipe(gulp.dest(config.dest))
.pipe(browserSync.reload({
stream: true
}));
};
module.exports = taskDef;
gulp.task('markup', taskDef);
|
/*global jasmine*/
var excludes = [
"map_events.html",
"map_lazy_init.html",
"map-lazy-load.html",
"marker_with_dynamic_position.html",
"marker_with_dynamic_address.html",
"marker_with_info_window.html",
"places-auto-complete.html"
];
function using(values, func){
for (var i = 0, count = values.length; i < count; i++) {
if (Object.prototype.toString.call(values[i]) !== '[object Array]') {
values[i] = [values[i]];
}
func.apply(this, values[i]);
jasmine.currentEnv_.currentSpec.description += ' (with using ' + values[i].join(', ') + ')';
}
}
describe('testapp directory', function() {
'use strict';
//var urls = ["aerial-rotate.html", "aerial-simple.html", "hello_map.html", "map_control.html"];
var files = require('fs').readdirSync(__dirname + "/../../testapp");
var urls = files.filter(function(filename) {
return filename.match(/\.html$/) && excludes.indexOf(filename) === -1;
});
console.log('urls', urls);
using(urls, function(url){
it('testapp/'+url, function() {
browser.get(url);
browser.wait( function() {
return browser.executeScript( function() {
var el = document.querySelector("map");
var scope = angular.element(el).scope();
//return scope.map.getCenter().lat();
return scope.map.getCenter();
}).then(function(result) {
return result;
});
}, 5000);
//element(by.css("map")).evaluate('map.getCenter().lat()').then(function(lat) {
// console.log('lat', lat);
// expect(lat).toNotEqual(0);
//});
browser.manage().logs().get('browser').then(function(browserLog) {
(browserLog.length > 0) && console.log('log: ' + require('util').inspect(browserLog));
expect(browserLog).toEqual([]);
});
});
});
});
|
module.exports = {
description: 'does not include called-in-unused-code import'
};
|
//////////////////////////////////////////////////////////////////////////
// //
// This is a generated file. You can view the original //
// source in your browser if your browser supports source maps. //
// Source maps are supported by all recent versions of Chrome, Safari, //
// and Firefox, and by Internet Explorer 11. //
// //
//////////////////////////////////////////////////////////////////////////
(function () {
/* Imports */
var Meteor = Package.meteor.Meteor;
var _ = Package.underscore._;
var ReactiveDict = Package['reactive-dict'].ReactiveDict;
var EJSON = Package.ejson.EJSON;
/* Package-scope variables */
var Session;
(function(){
/////////////////////////////////////////////////////////////////////////////////
// //
// packages/session/session.js //
// //
/////////////////////////////////////////////////////////////////////////////////
//
Session = new ReactiveDict('session'); // 1
// 2
// Documentation here is really awkward because the methods are defined // 3
// elsewhere // 4
// 5
/** // 6
* @memberOf Session // 7
* @method set // 8
* @summary Set a variable in the session. Notify any listeners that the value
* has changed (eg: redraw templates, and rerun any // 10
* [`Tracker.autorun`](#tracker_autorun) computations, that called // 11
* [`Session.get`](#session_get) on this `key`.) // 12
* @locus Client // 13
* @param {String} key The key to set, eg, `selectedItem` // 14
* @param {EJSONable | undefined} value The new value for `key` // 15
*/ // 16
// 17
/** // 18
* @memberOf Session // 19
* @method setDefault // 20
* @summary Set a variable in the session if it hasn't been set before. // 21
* Otherwise works exactly the same as [`Session.set`](#session_set). // 22
* @locus Client // 23
* @param {String} key The key to set, eg, `selectedItem` // 24
* @param {EJSONable | undefined} value The new value for `key` // 25
*/ // 26
// 27
/** // 28
* @memberOf Session // 29
* @method get // 30
* @summary Get the value of a session variable. If inside a [reactive // 31
* computation](#reactivity), invalidate the computation the next time the // 32
* value of the variable is changed by [`Session.set`](#session_set). This // 33
* returns a clone of the session value, so if it's an object or an array, // 34
* mutating the returned value has no effect on the value stored in the // 35
* session. // 36
* @locus Client // 37
* @param {String} key The name of the session variable to return // 38
*/ // 39
// 40
/** // 41
* @memberOf Session // 42
* @method equals // 43
* @summary Test if a session variable is equal to a value. If inside a // 44
* [reactive computation](#reactivity), invalidate the computation the next // 45
* time the variable changes to or from the value. // 46
* @locus Client // 47
* @param {String} key The name of the session variable to test // 48
* @param {String | Number | Boolean | null | undefined} value The value to // 49
* test against // 50
*/ // 51
// 52
/////////////////////////////////////////////////////////////////////////////////
}).call(this);
/* Exports */
if (typeof Package === 'undefined') Package = {};
Package.session = {
Session: Session
};
})();
|
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt
frappe.ui.form.Grid = Class.extend({
init: function(opts) {
$.extend(this, opts);
this.fieldinfo = {};
this.doctype = this.df.options;
this.template = null;
if(this.frm.meta.__form_grid_templates
&& this.frm.meta.__form_grid_templates[this.df.fieldname]) {
this.template = this.frm.meta.__form_grid_templates[this.df.fieldname];
}
this.is_grid = true;
},
make: function() {
var me = this;
this.wrapper = $('<div>\
<div class="form-grid">\
<div class="grid-heading-row" style="font-size: 15px;"></div>\
<div class="panel-body" style="padding-top: 7px;">\
<div class="rows"></div>\
<div class="small grid-footer">\
<a href="#" class="grid-add-row pull-right" style="margin-left: 10px;">+ '
+__("Add new row")+'.</a>\
<a href="#" class="grid-add-multiple-rows pull-right hide" style="margin-left: 10px;">+ '
+__("Add multiple rows")+'.</a>\
<span class="text-muted pull-right" style="margin-right: 5px;">'
+ __("Click on row to view / edit.") + '</span>\
<div class="clearfix"></div>\
</div>\
</div>\
</div>\
</div>')
.appendTo(this.parent)
.attr("data-fieldname", this.df.fieldname);
$(this.wrapper).find(".grid-add-row").click(function() {
me.add_new_row(null, null, true);
return false;
})
},
make_head: function() {
// labels
this.header_row = new frappe.ui.form.GridRow({
parent: $(this.parent).find(".grid-heading-row"),
parent_df: this.df,
docfields: this.docfields,
frm: this.frm,
grid: this
});
},
refresh: function(force) {
!this.wrapper && this.make();
var me = this,
$rows = $(me.parent).find(".rows"),
data = this.get_data();
this.docfields = frappe.meta.get_docfields(this.doctype, this.frm.docname);
this.display_status = frappe.perm.get_field_display_status(this.df, this.frm.doc,
this.perm);
if(this.display_status==="None") return;
if(!force && this.data_rows_are_same(data)) {
// soft refresh
this.header_row && this.header_row.refresh();
for(var i in this.grid_rows) {
this.grid_rows[i].refresh();
}
} else {
// redraw
var _scroll_y = window.scrollY;
this.wrapper.find(".grid-row").remove();
this.make_head();
this.grid_rows = [];
this.grid_rows_by_docname = {};
for(var ri in data) {
var d = data[ri];
var grid_row = new frappe.ui.form.GridRow({
parent: $rows,
parent_df: this.df,
docfields: this.docfields,
doc: d,
frm: this.frm,
grid: this
});
this.grid_rows.push(grid_row)
this.grid_rows_by_docname[d.name] = grid_row;
}
this.wrapper.find(".grid-add-row, .grid-add-multiple-rows").toggle(this.can_add_rows());
if(this.is_editable()) {
this.make_sortable($rows);
}
this.last_display_status = this.display_status;
this.last_docname = this.frm.docname;
scroll(0, _scroll_y);
}
},
refresh_row: function(docname) {
this.grid_rows_by_docname[docname] &&
this.grid_rows_by_docname[docname].refresh();
},
data_rows_are_same: function(data) {
if(this.grid_rows) {
var same = data.length==this.grid_rows.length
&& this.display_status==this.last_display_status
&& this.frm.docname==this.last_docname
&& !$.map(this.grid_rows, function(g, i) {
return (g.doc && g.doc.name==data[i].name) ? null : true;
}).length;
return same;
}
},
make_sortable: function($rows) {
var me =this;
$rows.sortable({
handle: ".data-row, .panel-heading",
helper: 'clone',
update: function(event, ui) {
me.frm.doc[me.df.fieldname] = [];
$rows.find(".grid-row").each(function(i, item) {
var doc = $(item).data("doc");
doc.idx = i + 1;
$(this).find(".row-index").html(i + 1);
me.frm.doc[me.df.fieldname].push(doc);
});
me.frm.dirty();
}
});
},
get_data: function() {
var data = this.frm.doc[this.df.fieldname] || [];
data.sort(function(a, b) { return a.idx - b.idx});
return data;
},
set_column_disp: function(fieldname, show) {
if($.isArray(fieldname)) {
var me = this;
$.each(fieldname, function(i, fname) {
frappe.meta.get_docfield(me.doctype, fname, me.frm.docname).hidden = show ? 0 : 1;
});
} else {
frappe.meta.get_docfield(this.doctype, fieldname, this.frm.docname).hidden = show ? 0 : 1;
}
this.refresh(true);
},
toggle_reqd: function(fieldname, reqd) {
frappe.meta.get_docfield(this.doctype, fieldname, this.frm.docname).reqd = reqd;
this.refresh();
},
get_field: function(fieldname) {
// Note: workaround for get_query
if(!this.fieldinfo[fieldname])
this.fieldinfo[fieldname] = {
}
return this.fieldinfo[fieldname];
},
set_value: function(fieldname, value, doc) {
if(this.display_status!=="None")
this.grid_rows_by_docname[doc.name].refresh_field(fieldname);
},
add_new_row: function(idx, callback, show) {
if(this.is_editable()) {
var d = frappe.model.add_child(this.frm.doc, this.df.options, this.df.fieldname, idx);
this.frm.script_manager.trigger(this.df.fieldname + "_add", d.doctype, d.name);
this.refresh();
if(show) {
if(idx) {
this.wrapper.find("[data-idx='"+idx+"']").data("grid_row")
.toggle_view(true, callback);
} else {
this.wrapper.find(".grid-row:last").data("grid_row").toggle_view(true, callback);
}
}
return d;
}
},
is_editable: function() {
return this.display_status=="Write" && !this.static_rows
},
can_add_rows: function() {
return this.is_editable() && !this.cannot_add_rows
},
set_multiple_add: function(link, qty) {
if(this.multiple_set) return;
var me = this;
var link_field = frappe.meta.get_docfield(this.df.options, link);
$(this.wrapper).find(".grid-add-multiple-rows")
.removeClass("hide")
.on("click", function() {
new frappe.ui.form.LinkSelector({
doctype: link_field.options,
fieldname: link,
qty_fieldname: qty,
target: me,
txt: ""
});
return false;
});
this.multiple_set = true;
}
});
frappe.ui.form.GridRow = Class.extend({
init: function(opts) {
$.extend(this, opts);
this.show = false;
this.make();
},
make: function() {
var me = this;
this.wrapper = $('<div class="grid-row"></div>').appendTo(this.parent).data("grid_row", this);
this.row = $('<div class="data-row" style="min-height: 26px;"></div>').appendTo(this.wrapper)
.on("click", function() {
me.toggle_view();
return false;
});
this.divider = $('<div class="divider row"></div>').appendTo(this.wrapper);
this.set_row_index();
this.make_static_display();
if(this.doc) {
this.set_data();
}
},
set_row_index: function() {
if(this.doc) {
this.wrapper
.attr("data-idx", this.doc.idx)
.find(".row-index").html(this.doc.idx)
}
},
remove: function() {
if(this.grid.is_editable()) {
var me = this;
me.wrapper.toggle(false);
frappe.model.clear_doc(me.doc.doctype, me.doc.name);
me.frm.script_manager.trigger(me.grid.df.fieldname + "_remove", me.doc.doctype, me.doc.name);
me.frm.dirty();
me.grid.refresh();
}
},
insert: function(show) {
var idx = this.doc.idx;
this.toggle_view(false);
this.grid.add_new_row(idx, null, show);
},
refresh: function() {
if(this.doc)
this.doc = locals[this.doc.doctype][this.doc.name];
// re write columns
this.grid.static_display_template = null;
this.make_static_display();
// refersh form fields
if(this.show) {
this.layout.refresh(this.doc);
}
},
make_static_display: function() {
var me = this;
this.row.empty();
$('<div class="col-xs-1 row-index">' + (this.doc ? this.doc.idx : "#")+ '</div>')
.appendTo(this.row);
if(this.grid.template) {
$('<div class="col-xs-10">').appendTo(this.row)
.html(frappe.render(this.grid.template, {
doc: this.doc ? frappe.get_format_helper(this.doc) : null,
frm: this.frm,
row: this
}));
} else {
this.add_visible_columns();
}
this.add_buttons();
$(this.frm.wrapper).trigger("grid-row-render", [this]);
},
add_buttons: function() {
var me = this;
if(this.doc && this.grid.is_editable()) {
if(!this.grid.$row_actions) {
this.grid.$row_actions = $('<div class="col-xs-1 pull-right" \
style="text-align: right; padding-right: 5px;">\
<span class="text-success grid-insert-row" style="padding: 4px;">\
<i class="icon icon-plus-sign"></i></span>\
<span class="grid-delete-row" style="padding: 4px;">\
<i class="icon icon-trash"></i></span>\
</div>');
}
$col = this.grid.$row_actions.clone().appendTo(this.row);
if($col.width() < 50) {
$col.toggle(false);
} else {
$col.toggle(true);
$col.find(".grid-insert-row").click(function() { me.insert(); return false; });
$col.find(".grid-delete-row").click(function() { me.remove(); return false; });
}
} else {
$('<div class="col-xs-1"></div>').appendTo(this.row);
}
},
add_visible_columns: function() {
this.make_static_display_template();
for(var ci in this.static_display_template) {
var df = this.static_display_template[ci][0];
var colsize = this.static_display_template[ci][1];
var txt = this.doc ?
frappe.format(this.doc[df.fieldname], df, null, this.doc) :
__(df.label);
if(this.doc && df.fieldtype === "Select") {
txt = __(txt);
}
var add_class = (["Text", "Small Text"].indexOf(df.fieldtype)===-1) ?
" grid-overflow-ellipsis" : " grid-overflow-no-ellipsis";
add_class += (["Int", "Currency", "Float"].indexOf(df.fieldtype)!==-1) ?
" text-right": "";
$col = $('<div class="col col-xs-'+colsize+add_class+'"></div>')
.html(txt)
.attr("data-fieldname", df.fieldname)
.data("df", df)
.appendTo(this.row)
if(!this.doc) $col.css({"font-weight":"bold"})
}
},
make_static_display_template: function() {
if(this.static_display_template) return;
var total_colsize = 1;
this.static_display_template = [];
for(var ci in this.docfields) {
var df = this.docfields[ci];
if(!df.hidden && df.in_list_view && this.grid.frm.get_perm(df.permlevel, "read")
&& !in_list(frappe.model.layout_fields, df.fieldtype)) {
var colsize = 2;
switch(df.fieldtype) {
case "Text":
case "Small Text":
colsize = 3;
break;
case "Check":
colsize = 1;
break;
}
total_colsize += colsize
if(total_colsize > 11)
return false;
this.static_display_template.push([df, colsize]);
}
}
// redistribute if total-col size is less than 12
var passes = 0;
while(total_colsize < 11 && passes < 10) {
for(var i in this.static_display_template) {
var df = this.static_display_template[i][0];
var colsize = this.static_display_template[i][1];
if(colsize>1 && colsize<12 && ["Int", "Currency", "Float"].indexOf(df.fieldtype)===-1) {
this.static_display_template[i][1] += 1;
total_colsize++;
}
if(total_colsize >= 11)
break;
}
passes++;
}
},
toggle_view: function(show, callback) {
if(!this.doc) return this;
this.doc = locals[this.doc.doctype][this.doc.name];
// hide other
var open_row = $(".grid-row-open").data("grid_row");
this.fields = [];
this.fields_dict = {};
this.show = show===undefined ?
show = !this.show :
show
// call blur
document.activeElement && document.activeElement.blur()
if(show && open_row) {
if(open_row==this) {
// already open, do nothing
callback();
return;
} else {
// close other views
open_row.toggle_view(false);
}
}
this.wrapper.toggleClass("grid-row-open", this.show);
if(this.show) {
if(!this.form_panel) {
this.form_panel = $('<div class="panel panel-warning" style="display: none;"></div>')
.insertBefore(this.divider);
}
this.render_form();
this.row.toggle(false);
this.form_panel.toggle(true);
if(this.frm.doc.docstatus===0) {
var first = this.form_area.find(":input:first");
if(first.length && first.attr("data-fieldtype")!="Date") {
try {
first.get(0).focus();
} catch(e) {
console.log("Dialog: unable to focus on first input: " + e);
}
}
}
} else {
if(this.form_panel)
this.form_panel.toggle(false);
this.row.toggle(true);
this.make_static_display();
}
callback && callback();
return this;
},
open_prev: function() {
if(this.grid.grid_rows[this.doc.idx-2]) {
this.grid.grid_rows[this.doc.idx-2].toggle_view(true);
}
},
open_next: function() {
if(this.grid.grid_rows[this.doc.idx]) {
this.grid.grid_rows[this.doc.idx].toggle_view(true);
} else {
this.grid.add_new_row(null, null, true);
}
},
toggle_add_delete_button_display: function($parent) {
$parent.find(".grid-delete-row, .grid-insert-row, .grid-append-row")
.toggle(this.grid.is_editable());
},
render_form: function() {
var me = this;
this.make_form();
this.form_area.empty();
this.layout = new frappe.ui.form.Layout({
fields: this.docfields,
body: this.form_area,
no_submit_on_enter: true,
frm: this.frm,
});
this.layout.make();
this.fields = this.layout.fields;
this.fields_dict = this.layout.fields_dict;
this.layout.refresh(this.doc);
// copy get_query to fields
$.each(this.grid.fieldinfo || {}, function(fieldname, fi) {
$.extend(me.fields_dict[fieldname], fi);
})
this.toggle_add_delete_button_display(this.wrapper.find(".panel:first"));
this.grid.open_grid_row = this;
this.frm.script_manager.trigger(this.doc.parentfield + "_on_form_rendered", this);
},
make_form: function() {
if(!this.form_area) {
$('<div class="panel-heading">\
<div class="toolbar">\
<span class="panel-title">' + __("Editing Row") + ' #<span class="row-index"></span></span>\
<span class="text-success pull-right grid-toggle-row" \
title="'+__("Close")+'"\
style="margin-left: 7px;">\
<i class="icon-chevron-up"></i></span>\
<span class="pull-right grid-insert-row" \
title="'+__("Insert Row")+'"\
style="margin-left: 7px;">\
<i class="icon-plus grid-insert-row"></i></span>\
<span class="pull-right grid-delete-row"\
title="'+__("Delete Row")+'"\
><i class="icon-trash grid-delete-row"></i></span>\
</div>\
</div>\
<div class="panel-body">\
<div class="form-area"></div>\
<div class="toolbar footer-toolbar" style="margin-top: 15px">\
<span class="text-muted"><a href="#" class="shortcuts"><i class="icon-keyboard"></i>' + __("Shortcuts") + '</a></span>\
<span class="text-success pull-right grid-toggle-row" \
title="'+__("Close")+'"\
style="margin-left: 7px; cursor: pointer;">\
<i class="icon-chevron-up"></i></span>\
<span class="pull-right grid-append-row" \
title="'+__("Insert Below")+'"\
style="margin-left: 7px; cursor: pointer;">\
<i class="icon-plus"></i></span>\
</div>\
</div>').appendTo(this.form_panel);
this.form_area = this.wrapper.find(".form-area");
this.set_row_index();
this.set_form_events();
}
},
set_form_events: function() {
var me = this;
this.form_panel.find(".grid-delete-row")
.click(function() { me.remove(); return false; })
this.form_panel.find(".grid-insert-row")
.click(function() { me.insert(true); return false; })
this.form_panel.find(".grid-append-row")
.click(function() {
me.toggle_view(false);
me.grid.add_new_row(me.doc.idx+1, null, true);
return false;
})
this.form_panel.find(".panel-heading, .grid-toggle-row").on("click", function() {
me.toggle_view();
return false;
});
this.form_panel.find(".shortcuts").on("click", function() {
msgprint(__('Move Up: {0}', ['Ctrl+<i class="icon-arrow-up"></i>']));
msgprint(__('Move Down: {0}', ['Ctrl+<i class="icon-arrow-down"></i>']));
msgprint(__('Close: {0}', ['Esc']));
return false;
})
},
set_data: function() {
this.wrapper.data({
"doc": this.doc
})
},
refresh_field: function(fieldname) {
var $col = this.row.find("[data-fieldname='"+fieldname+"']");
if($col.length) {
$col.html(frappe.format(this.doc[fieldname],
frappe.meta.get_docfield(this.doc.doctype, fieldname, this.frm.docname), null, this.frm.doc));
}
// in form
if(this.fields_dict && this.fields_dict[fieldname]) {
this.fields_dict[fieldname].refresh();
this.layout.refresh_dependency();
}
},
get_visible_columns: function(blacklist) {
var me = this;
var visible_columns = $.map(this.docfields, function(df) {
var visible = !df.hidden && df.in_list_view && me.grid.frm.get_perm(df.permlevel, "read")
&& !in_list(frappe.model.layout_fields, df.fieldtype) && !in_list(blacklist, df.fieldname);
return visible ? df : null;
});
return visible_columns;
}
});
|
// The translations in this file are added by default.
'use strict';
module.exports = {
counterpart: {
names: require('date-names/en'),
pluralize: require('pluralizers/en'),
formats: {
date: {
default: '%a, %e %b %Y',
long: '%A, %B %o, %Y',
short: '%b %e',
},
time: {
default: '%H:%M',
long: '%H:%M:%S %z',
short: '%H:%M',
},
datetime: {
default: '%a, %e %b %Y %H:%M',
long: '%A, %B %o, %Y %H:%M:%S %z',
short: '%e %b %H:%M',
},
},
},
};
|
module.exports={A:{A:{"2":"J C G E B VB","132":"A"},B:{"132":"D Y g H L"},C:{"2":"0 1 3 4 5 6 TB z F I J C G E B A D Y g H L M N O P Q R S T U V W X v Z a b c d e f K h i j k l m n o p q r s x y u t RB QB"},D:{"2":"0 1 3 4 5 6 F I J C G E B A D Y g H L M N O P Q R S T U V W X v Z a b c d e f K h i j k l m n o p q r s x y u t FB AB CB UB DB"},E:{"2":"9 F I J C G E B EB GB HB IB JB KB","513":"A LB"},F:{"2":"7 8 E A D H L M N O P Q R S T U V W X v Z a b c d e f K h i j k l m n o p q r s MB NB OB PB SB w"},G:{"1":"A","2":"2 9 G BB WB XB YB ZB aB bB cB dB"},H:{"2":"eB"},I:{"2":"2 z F fB gB hB iB jB kB","258":"t"},J:{"2":"C B"},K:{"2":"7 8 B A D K w"},L:{"258":"AB"},M:{"2":"u"},N:{"2":"B A"},O:{"2":"lB"},P:{"2":"F","258":"I"},Q:{"2":"mB"},R:{"2":"nB"}},B:6,C:"HEVC/H.265 video format"};
|
/*!
* OOjs UI v0.25.0
* https://www.mediawiki.org/wiki/OOjs_UI
*
* Copyright 2011–2018 OOjs UI Team and other contributors.
* Released under the MIT license
* http://oojs.mit-license.org
*
* Date: 2018-01-10T00:26:02Z
*/
( function ( OO ) {
'use strict';
/**
* @class
* @extends OO.ui.Theme
*
* @constructor
*/
OO.ui.WikimediaUITheme = function OoUiWikimediaUITheme() {
// Parent constructor
OO.ui.WikimediaUITheme.parent.call( this );
};
/* Setup */
OO.inheritClass( OO.ui.WikimediaUITheme, OO.ui.Theme );
/* Methods */
/**
* @inheritdoc
*/
OO.ui.WikimediaUITheme.prototype.getElementClasses = function ( element ) {
// Parent method
var variant, isFramed, isActive,
variants = {
warning: false,
invert: false,
progressive: false,
destructive: false
},
// Parent method
classes = OO.ui.WikimediaUITheme.parent.prototype.getElementClasses.call( this, element );
if ( element.supports( [ 'hasFlag' ] ) ) {
isFramed = element.supports( [ 'isFramed' ] ) && element.isFramed();
isActive = element.supports( [ 'isActive' ] ) && element.isActive();
if (
// Button with a dark background
isFramed && ( isActive || element.isDisabled() || element.hasFlag( 'primary' ) ) ||
// Toolbar with a dark background
OO.ui.ToolGroup && element instanceof OO.ui.ToolGroup && ( isActive || element.hasFlag( 'primary' ) )
) {
// … use white icon / indicator, regardless of other flags
variants.invert = true;
} else if ( !isFramed && element.isDisabled() ) {
// Frameless disabled button, always use black icon / indicator regardless of other flags
variants.invert = false;
} else if ( !element.isDisabled() ) {
// Any other kind of button, use the right colored icon / indicator if available
variants.progressive = element.hasFlag( 'progressive' );
variants.destructive = element.hasFlag( 'destructive' );
variants.warning = element.hasFlag( 'warning' );
}
}
for ( variant in variants ) {
classes[ variants[ variant ] ? 'on' : 'off' ].push( 'oo-ui-image-' + variant );
}
return classes;
};
/**
* @inheritdoc
*/
OO.ui.WikimediaUITheme.prototype.getDialogTransitionDuration = function () {
return 250;
};
/* Instantiation */
OO.ui.theme = new OO.ui.WikimediaUITheme();
}( OO ) );
//# sourceMappingURL=oojs-ui-wikimediaui.js.map |
jQuery(function($){
$.supersized({
// Functionality
slideshow : 1, // Slideshow on/off
autoplay : 1, // Slideshow starts playing automatically
start_slide : 1, // Start slide (0 is random)
stop_loop : 0, // Pauses slideshow on last slide
random : 0, // Randomize slide order (Ignores start slide)
slide_interval : 12000, // Length between transitions
transition : 1, // 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
transition_speed : 1000, // Speed of transition
new_window : 1, // Image links open in new window/tab
pause_hover : 0, // Pause slideshow on hover
keyboard_nav : 1, // Keyboard navigation on/off
performance : 1, // 0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
image_protect : 1, // Disables image dragging and right click with Javascript
// Size & Position
min_width : 0, // Min width allowed (in pixels)
min_height : 0, // Min height allowed (in pixels)
vertical_center : 1, // Vertically center background
horizontal_center : 1, // Horizontally center background
fit_always : 0, // Image will never exceed browser width or height (Ignores min. dimensions)
fit_portrait : 1, // Portrait images will not exceed browser height
fit_landscape : 0, // Landscape images will not exceed browser width
// Components
slide_links : 'blank', // Individual links for each slide (Options: false, 'num', 'name', 'blank')
thumb_links : 0, // Individual thumb links for each slide
thumbnail_navigation : 0, // Thumbnail navigation
slides : [ // Slideshow Images
{image : './images/feat-bg1.jpg', title : '<div class="major">Apollo</div><div class="slidedescription">Quisque non magna ac tortor tincidunt posuere. Vestibulum luctus aliquet gravida. Etiam non dolor sit amet libero porttitor egestas quis sed urna.</div><ul class="footprints"><li><a href="">Our Work</a></li><li><a href="">Our Blog</a></li><li><a href="">Our People</a></li><ul>', thumb : '', url : '#'},
{image : './images/feat-bg6.jpg', title : '<div class="major">LIVE EPIC</div><div class="slidedescription">What a piece of work is a man, how noble in reason, how infinite in faculties, in form and moving how express and admirable, in action how like an angel, in apprehension how like a god.</div>', thumb : '', url : '#'},
{image : './images/feat-bg2.jpg', title : '<div class="major minor">… or lavishly</div><div class="slidedescription">As a space, Work Happy hosts events regularly with the intent to educate and grow our local creative community. From courses on web design and programming, classes on photography, to community meetups to help introduce creatives to other creatives. </div>', thumb : '', url : '#'},
{image : './images/feat-bg3.jpg', title : '<div class="major">Apollo</div><div class="slidedescription">Desks start at $75 a month part time or $125 full time. All Co-workers have access to all Work Happuy events and meetups. Desks are month to month and the facility does have a security system.</div>', thumb : '', url : '#'},
{image : './images/feat-bg4.jpg', title : '<div class="major">Apollo</div><div class="slidedescription">Desks start at $75 a month part time or $125 full time. All Co-workers have access to all Work Happuy events and meetups. Desks are month to month and the facility does have a security system.</div>', thumb : '', url : '#'},
{image : './images/feat-bg5.jpg', title : '<div class="major">Apollo</div><div class="slidedescription">Desks start at $75 a month part time or $125 full time. All Co-workers have access to all Work Happuy events and meetups. Desks are month to month and the facility does have a security system.</div>', thumb : '', url : '#'}
],
// Theme Options
progress_bar : 0, // Timer for each slide
mouse_scrub : 0
});
});
|
var expect = require("chai").expect;
var sinon = require("sinon");
var chalk = require("chalk");
var ReadlineStub = require("../../helpers/readline");
var Base = require("../../../lib/prompts/base");
describe("`base` prompt (e.g. prompt helpers)", function() {
beforeEach(function() {
this.rl = new ReadlineStub();
this.base = new Base({
message: "foo bar",
name: "name"
}, this.rl );
});
it("`suffix` method should only add ':' if last char is a letter", function() {
expect(this.base.suffix("m:")).to.equal("m: ");
expect(this.base.suffix("m?")).to.equal("m? ");
expect(this.base.suffix("my question?")).to.equal("my question? ");
expect(this.base.suffix(chalk.bold("m"))).to.equal("\u001b[1mm:\u001b[22m ");
expect(chalk.stripColor(this.base.suffix(chalk.bold("m?")))).to.equal("m? ");
expect(this.base.suffix("m")).to.equal("m: ");
expect(this.base.suffix("M")).to.equal("M: ");
expect(this.base.suffix("m ")).to.equal("m ");
expect(this.base.suffix("9")).to.equal("9: ");
expect(this.base.suffix("9~")).to.equal("9~ ");
expect(this.base.suffix()).to.equal(": ");
});
it("should not point by reference to the entry `question` object", function() {
var question = {
message: "foo bar",
name: "name"
};
var base = new Base( question, this.rl );
expect(question).to.not.equal(base.opt);
expect(question.name).to.equal(base.opt.name);
expect(question.message).to.equal(base.opt.message);
});
});
|
var formInstance = (
<Form>
<Input placeholder="验证成功" label="验证成功" validation="success" />
<Input placeholder="验证警告" label="验证警告" validation="warning" />
<Input placeholder="验证失败" label="验证失败" validation="error" />
<FormGroup validation="success">
<label>单选按钮:</label>
<Input type="radio" label="男" inline />
<Input type="radio" label="女" inline />
</FormGroup>
</Form>
);
React.render(formInstance, mountNode);
|
// randomColor by David Merfield under the CC0 license
// https://github.com/davidmerfield/randomColor/
;(function(root, factory) {
// Support AMD
if (typeof define === 'function' && define.amd) {
define([], factory);
// Support CommonJS
} else if (typeof exports === 'object') {
var randomColor = factory();
// Support NodeJS & Component, which allow module.exports to be a function
if (typeof module === 'object' && module && module.exports) {
exports = module.exports = randomColor;
}
// Support CommonJS 1.1.1 spec
exports.randomColor = randomColor;
// Support vanilla script loading
} else {
root.randomColor = factory();
}
}(this, function() {
// Seed to get repeatable colors
var seed = null;
// Shared color dictionary
var colorDictionary = {};
// Populate the color dictionary
loadColorBounds();
var randomColor = function (options) {
options = options || {};
// Check if there is a seed and ensure it's an
// integer. Otherwise, reset the seed value.
if (options.seed && options.seed === parseInt(options.seed, 10)) {
seed = options.seed;
// A string was passed as a seed
} else if (typeof options.seed === 'string') {
seed = stringToInteger(options.seed);
// Something was passed as a seed but it wasn't an integer or string
} else if (options.seed !== undefined && options.seed !== null) {
throw new TypeError('The seed value must be an integer or string');
// No seed, reset the value outside.
} else {
seed = null;
}
var H,S,B;
// Check if we need to generate multiple colors
if (options.count !== null && options.count !== undefined) {
var totalColors = options.count,
colors = [];
options.count = null;
while (totalColors > colors.length) {
// Since we're generating multiple colors,
// incremement the seed. Otherwise we'd just
// generate the same color each time...
if (seed && options.seed) options.seed += 1;
colors.push(randomColor(options));
}
options.count = totalColors;
return colors;
}
// First we pick a hue (H)
H = pickHue(options);
// Then use H to determine saturation (S)
S = pickSaturation(H, options);
// Then use S and H to determine brightness (B).
B = pickBrightness(H, S, options);
// Then we return the HSB color in the desired format
return setFormat([H,S,B], options);
};
function pickHue (options) {
var hueRange = getHueRange(options.hue),
hue = randomWithin(hueRange);
// Instead of storing red as two seperate ranges,
// we group them, using negative numbers
if (hue < 0) {hue = 360 + hue;}
return hue;
}
function pickSaturation (hue, options) {
if (options.luminosity === 'random') {
return randomWithin([0,100]);
}
if (options.hue === 'monochrome') {
return 0;
}
var saturationRange = getSaturationRange(hue);
var sMin = saturationRange[0],
sMax = saturationRange[1];
switch (options.luminosity) {
case 'bright':
sMin = 55;
break;
case 'dark':
sMin = sMax - 10;
break;
case 'light':
sMax = 55;
break;
}
return randomWithin([sMin, sMax]);
}
function pickBrightness (H, S, options) {
var bMin = getMinimumBrightness(H, S),
bMax = 100;
switch (options.luminosity) {
case 'dark':
bMax = bMin + 20;
break;
case 'light':
bMin = (bMax + bMin)/2;
break;
case 'random':
bMin = 0;
bMax = 100;
break;
}
return randomWithin([bMin, bMax]);
}
function setFormat (hsv, options) {
switch (options.format) {
case 'hsvArray':
return hsv;
case 'hslArray':
return HSVtoHSL(hsv);
case 'hsl':
var hsl = HSVtoHSL(hsv);
return 'hsl('+hsl[0]+', '+hsl[1]+'%, '+hsl[2]+'%)';
case 'hsla':
var hslColor = HSVtoHSL(hsv);
return 'hsla('+hslColor[0]+', '+hslColor[1]+'%, '+hslColor[2]+'%, ' + Math.random() + ')';
case 'rgbArray':
return HSVtoRGB(hsv);
case 'rgb':
var rgb = HSVtoRGB(hsv);
return 'rgb(' + rgb.join(', ') + ')';
case 'rgba':
var rgbColor = HSVtoRGB(hsv);
return 'rgba(' + rgbColor.join(', ') + ', ' + Math.random() + ')';
default:
return HSVtoHex(hsv);
}
}
function getMinimumBrightness(H, S) {
var lowerBounds = getColorInfo(H).lowerBounds;
for (var i = 0; i < lowerBounds.length - 1; i++) {
var s1 = lowerBounds[i][0],
v1 = lowerBounds[i][1];
var s2 = lowerBounds[i+1][0],
v2 = lowerBounds[i+1][1];
if (S >= s1 && S <= s2) {
var m = (v2 - v1)/(s2 - s1),
b = v1 - m*s1;
return m*S + b;
}
}
return 0;
}
function getHueRange (colorInput) {
if (typeof parseInt(colorInput) === 'number') {
var number = parseInt(colorInput);
if (number < 360 && number > 0) {
return [number, number];
}
}
if (typeof colorInput === 'string') {
if (colorDictionary[colorInput]) {
var color = colorDictionary[colorInput];
if (color.hueRange) {return color.hueRange;}
}
}
return [0,360];
}
function getSaturationRange (hue) {
return getColorInfo(hue).saturationRange;
}
function getColorInfo (hue) {
// Maps red colors to make picking hue easier
if (hue >= 334 && hue <= 360) {
hue-= 360;
}
for (var colorName in colorDictionary) {
var color = colorDictionary[colorName];
if (color.hueRange &&
hue >= color.hueRange[0] &&
hue <= color.hueRange[1]) {
return colorDictionary[colorName];
}
} return 'Color not found';
}
function randomWithin (range) {
if (seed === null) {
return Math.floor(range[0] + Math.random()*(range[1] + 1 - range[0]));
} else {
//Seeded random algorithm from http://indiegamr.com/generate-repeatable-random-numbers-in-js/
var max = range[1] || 1;
var min = range[0] || 0;
seed = (seed * 9301 + 49297) % 233280;
var rnd = seed / 233280.0;
return Math.floor(min + rnd * (max - min));
}
}
function HSVtoHex (hsv){
var rgb = HSVtoRGB(hsv);
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? '0' + hex : hex;
}
var hex = '#' + componentToHex(rgb[0]) + componentToHex(rgb[1]) + componentToHex(rgb[2]);
return hex;
}
function defineColor (name, hueRange, lowerBounds) {
var sMin = lowerBounds[0][0],
sMax = lowerBounds[lowerBounds.length - 1][0],
bMin = lowerBounds[lowerBounds.length - 1][1],
bMax = lowerBounds[0][1];
colorDictionary[name] = {
hueRange: hueRange,
lowerBounds: lowerBounds,
saturationRange: [sMin, sMax],
brightnessRange: [bMin, bMax]
};
}
function loadColorBounds () {
defineColor(
'monochrome',
null,
[[0,0],[100,0]]
);
defineColor(
'red',
[-26,18],
[[20,100],[30,92],[40,89],[50,85],[60,78],[70,70],[80,60],[90,55],[100,50]]
);
defineColor(
'orange',
[19,46],
[[20,100],[30,93],[40,88],[50,86],[60,85],[70,70],[100,70]]
);
defineColor(
'yellow',
[47,62],
[[25,100],[40,94],[50,89],[60,86],[70,84],[80,82],[90,80],[100,75]]
);
defineColor(
'green',
[63,178],
[[30,100],[40,90],[50,85],[60,81],[70,74],[80,64],[90,50],[100,40]]
);
defineColor(
'blue',
[179, 257],
[[20,100],[30,86],[40,80],[50,74],[60,60],[70,52],[80,44],[90,39],[100,35]]
);
defineColor(
'purple',
[258, 282],
[[20,100],[30,87],[40,79],[50,70],[60,65],[70,59],[80,52],[90,45],[100,42]]
);
defineColor(
'pink',
[283, 334],
[[20,100],[30,90],[40,86],[60,84],[80,80],[90,75],[100,73]]
);
}
function HSVtoRGB (hsv) {
// this doesn't work for the values of 0 and 360
// here's the hacky fix
var h = hsv[0];
if (h === 0) {h = 1;}
if (h === 360) {h = 359;}
// Rebase the h,s,v values
h = h/360;
var s = hsv[1]/100,
v = hsv[2]/100;
var h_i = Math.floor(h*6),
f = h * 6 - h_i,
p = v * (1 - s),
q = v * (1 - f*s),
t = v * (1 - (1 - f)*s),
r = 256,
g = 256,
b = 256;
switch(h_i) {
case 0: r = v; g = t; b = p; break;
case 1: r = q; g = v; b = p; break;
case 2: r = p; g = v; b = t; break;
case 3: r = p; g = q; b = v; break;
case 4: r = t; g = p; b = v; break;
case 5: r = v; g = p; b = q; break;
}
var result = [Math.floor(r*255), Math.floor(g*255), Math.floor(b*255)];
return result;
}
function HSVtoHSL (hsv) {
var h = hsv[0],
s = hsv[1]/100,
v = hsv[2]/100,
k = (2-s)*v;
return [
h,
Math.round(s*v / (k<1 ? k : 2-k) * 10000) / 100,
k/2 * 100
];
}
function stringToInteger (string) {
var total = 0
for (var i = 0; i !== string.length; i++) {
if (total >= Number.MAX_SAFE_INTEGER) break;
total += string.charCodeAt(i)
}
return total
}
return randomColor;
}));
|
module.exports={A:{A:{"2":"H E G C B WB","36":"A"},B:{"36":"D u g I J"},C:{"1":"0 1 2 3 4 5 6 n o p q r s t y K","2":"UB x F L H E G C B A D u g I J Y SB RB","36":"O e P Q R S T U V W X v Z a b c d N f M h i j k l m"},D:{"1":"0 1 2 3 4 5 6 h i j k l m n o p q r s t y K GB AB CB VB DB EB","2":"F L H E G C B A D u g I J Y O e P Q R S T U V W X v Z a b c d N f M"},E:{"2":"9 F L H E G C B A FB HB IB JB KB LB MB"},F:{"1":"U V W X v Z a b c d N f M h i j k l m n o p q r s t","2":"7 8 C A D I J Y O e P Q R S T NB OB PB QB TB w"},G:{"2":"9 G A BB z XB YB ZB aB bB cB dB eB"},H:{"2":"fB"},I:{"2":"x F K gB hB iB jB z kB lB"},J:{"2":"E B"},K:{"1":"M","2":"7 8 B A D w"},L:{"1":"AB"},M:{"1":"K"},N:{"2":"B","36":"A"},O:{"1":"mB"},P:{"1":"L","16":"F"},Q:{"2":"nB"},R:{"1":"oB"}},B:5,C:"Screen Orientation"};
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Footer.css';
import Link from '../Link';
function Footer() {
return (
<div className={s.root}>
<div className={s.container}>
<span className={s.text}>© Your Company</span>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/">Home</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/privacy">Privacy</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/not-found">Not Found</Link>
</div>
</div>
);
}
export default withStyles(s)(Footer);
|
var path = require('path');
var package = require('./package');
var webpack = require('webpack');
var ProgressPlugin = require('webpack/lib/ProgressPlugin');
var inspect = require('util').inspect;
var Busboy = require('busboy');
var chalk = require('chalk');
var webpackMiddleware = require('webpack-dev-middleware');
var webpackConfig = require('./webpack.config');
var webpackCompiler = webpack(webpackConfig);
var handler;
webpackCompiler.apply(new ProgressPlugin(function(percentage, msg) {
var stream = process.stderr;
if (stream.isTTY && percentage < 0.71) {
stream.cursorTo(0);
stream.write('📦 ' + chalk.magenta(msg));
stream.clearLine(1);
} else if (percentage === 1) {
console.log(chalk.green('\nwebpack: bundle build is now finished.'));
}
}));
// {{ settings for nico
exports.site = {
name: package.title,
description: package.description,
repo: package.repository.url,
issues: package.bugs.url
};
// PRODUCTION
if (process.env.NODE_ENV === 'PRODUCTION') {
exports.minimized = '.min';
}
exports.package = package;
exports.theme = 'site';
exports.source = process.cwd();
exports.output = path.join(process.cwd(), '_site');
exports.permalink = '{{directory}}/{{filename}}';
exports.ignorefilter = function(filepath, subdir) {
var extname = path.extname(filepath);
if (extname === '.tmp' || extname === '.bak') {
return false;
}
if (/\.DS_Store/.test(filepath)) {
return false;
}
if (/^(_site|_theme|node_modules|site|\.idea)/.test(subdir)) {
return false;
}
return true;
};
exports.middlewares = [
{
name: 'upload',
filter: /upload\.do?$/,
handle: function(req, res, next) {
if (req.method === 'POST') {
var busboy = new Busboy({headers: req.headers});
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
file.on('data', function(data) {
console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
});
file.on('end', function() {
console.log('File [' + fieldname + '] Finished');
});
});
busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) {
console.log('Field [' + fieldname + ']: value: ' + inspect(val));
});
busboy.on('finish', function() {
console.log('Done parsing form!');
//res.writeHead(303, { Connection: 'close', Location: '/' });
res.end(JSON.stringify({
'status': 'success',
'url': '/example.file'
}));
});
req.pipe(busboy);
}
}
},
{
name: 'webpackDevMiddleware',
filter: /\.(js|css)(\.map)?$/,
handle: function(req, res, next) {
handler = handler || webpackMiddleware(webpackCompiler, {
publicPath: '/dist/',
lazy: false,
watchOptions: {
aggregateTimeout: 300,
poll: true
},
noInfo: true
});
try {
return handler(req, res, next);
} catch(e) {}
}
}];
exports.writers = [
'nico-jsx.PageWriter',
'nico-jsx.StaticWriter',
'nico-jsx.FileWriter'
];
// end settings }}
process.on('uncaughtException', function(err) {
console.log(err);
});
|
import demand from 'must';
import { columnsParser, sortParser, filtersParser, filterParser, createFilterObject } from '../index';
import sinon from 'sinon';
describe('<List> query parsers', function () {
beforeEach(function () {
this.fields = {
name: {
path: 'name',
paths: {
first: 'name.first',
last: 'name.last',
full: 'name.full',
},
type: 'name',
label: 'Name',
size: 'full',
required: true,
hasFilterMethod: true,
defaultValue: {
first: '',
last: '',
},
},
email: {
path: 'email',
type: 'email',
label: 'Email',
size: 'full',
required: true,
defaultValue: {
email: '',
},
},
};
this.currentList = {
fields: this.fields,
defaultColumns: { columns: '__DEFAULT_COLUMNS__' },
defaultSort: { sort: '__DEFAULT_SORT__' },
expandColumns: sinon.spy(),
expandSort: sinon.spy(),
};
this.path = 'name';
this.value = { value: 'a', mode: 'contains', inverted: false };
this.filter = Object.assign({}, { path: this.path }, this.value);
});
describe('columnsParser()', function () {
describe('If an empty columns array is added', function () {
it('should call expandColumns with default columns', function () {
const columns = [];
columnsParser(columns, this.currentList);
const result = this.currentList.expandColumns.getCall(0).args[0];
demand(result).eql(this.currentList.defaultColumns);
});
});
describe('If the input columns are undefined', function () {
it('should call expandColumns with default columns', function () {
const columns = void 0;
columnsParser(columns, this.currentList);
const result = this.currentList.expandColumns.getCall(0).args[0];
demand(result).eql(this.currentList.defaultColumns);
});
});
describe('If currentList does not exist', function () {
it('throws an Error', function () {
const columns = ['name', 'email'];
let e = void 0;
try {
columnsParser(columns, null);
} catch (error) {
e = error;
}
demand(e.message).eql('No currentList selected');
});
});
});
describe('sortParser()', function () {
describe('If no path is specified', function () {
it('should return the default sort object', function () {
const path = void 0;
sortParser(path, this.currentList);
const result = this.currentList.expandSort.getCall(0).args[0];
demand(result).eql(this.currentList.defaultSort);
});
});
describe('If currentList does not exist', function () {
it('throws an Error', function () {
const path = 'email';
let e = void 0;
try {
sortParser(path, null);
} catch (error) {
e = error;
}
demand(e.message).eql('No currentList selected');
});
});
});
describe('createFilterObject()', function () {
describe('If prvided with a valid path and a valid currentList', function () {
it('returns an object with a field [object Object], and the passed in value', function () {
const expectedFilter = this.currentList.fields[this.path];
const expectedResult = { field: expectedFilter, value: this.value };
demand(createFilterObject(this.path, this.value, this.currentList.fields)).eql(expectedResult);
});
});
describe('If provided with an invalid path', function () {
it('returns undefined', function () {
const expectedResult = void 0;
demand(createFilterObject(null, null, this.currentList)).eql(expectedResult);
});
});
describe('If provided with an invalid currentListFields', function () {
it('returns undefined', function () {
const expectedResult = void 0;
demand(createFilterObject(this.path, this.value, {})).eql(expectedResult);
});
});
describe('If provided with a null value for currentListFields', function () {
it('returns undefined', function () {
const expectedResult = void 0;
demand(createFilterObject(this.path, this.value, null)).eql(expectedResult);
});
});
describe('If provided with any value that is not a plain object', function () {
it('returns undefined', function () {
const expectedResult = void 0;
demand(createFilterObject(this.path, this.value, 'currentListFields')).eql(expectedResult);
});
});
});
describe('filtersParser()', function () {
describe('Given no matching fields are found', function () {
it('returns an empty array', function () {
const invalidFilter = 'jemena';
const expectedResult = [];
const filters = [invalidFilter];
demand(filtersParser(filters, this.currentList)).eql(expectedResult);
});
});
describe('Given no filters are passed into the function', function () {
it('returns an empty array', function () {
const expectedResult = [];
demand(filtersParser(null, this.currentList)).eql(expectedResult);
});
});
describe('Given an array of filters', function () {
it('returns an array of filters', function () {
const filter = Object.assign(
{},
{ path: 'name' },
this.value
);
const filters = [filter];
const expectedResult = [{
field: this.currentList.fields[filter.path],
value: this.value,
}];
demand(filtersParser(filters, this.currentList)).eql(expectedResult);
});
});
describe('Given a valid stringified filters array', function () {
it('returns an array of filters', function () {
const filter = Object.assign(
{},
{ path: 'name' },
this.value
);
const filters = [filter];
const stringifiedFilters = JSON.stringify(filters);
const expectedResult = [{
field: this.currentList.fields[filter.path],
value: this.value,
}];
demand(filtersParser(stringifiedFilters, this.currentList)).eql(expectedResult);
});
});
describe('If provided with an invalid stringified filters array', function () {
it('returns an empty array', function () {
const stringifiedFilters = 'jemena';
const expectedResult = [];
demand(filtersParser(stringifiedFilters, this.currentList)).eql(expectedResult);
});
});
});
describe('filterParser()', function () {
beforeEach(function () {
const firstEntry = { field: this.currentList.fields[this.path], value: this.value };
const secondEntry = { field: this.currentList.fields.email, value: this.value };
this.activeFilters = [firstEntry, secondEntry];
this.addedFilter = { path: this.filter.path, value: this.value };
});
describe('Given a valid filter object with a path and value', function () {
it('returns an expanded filter object', function () {
const expectedResult = { field: this.currentList.fields[this.path], value: this.value };
demand(filterParser(this.addedFilter, this.activeFilters, this.currentList)).eql(expectedResult);
});
});
describe('Given that activeFilters is not an array', function () {
it('throws an error', function () {
const invalidActiveFilters = 'hello there';
let e = void 0;
try {
filterParser(this.addedFilter, invalidActiveFilters, this.currentList);
} catch (error) {
e = error;
}
demand(e.message).eql('activeFilters must be an array');
});
});
describe('Given that currentList is not a valid object', function () {
it('throws an error', function () {
let e = void 0;
const invalidList = void 0;
try {
filterParser({}, this.activeFilters, invalidList);
} catch (error) {
e = error;
}
demand(e.message).eql('No currentList selected');
});
});
describe('Given that the filter does not exist in activeFilters', function () {
describe('Given that currentList is not an object of the shape that we expect', function () {
it('returns undefined', function () {
const expectedResult = void 0;
const badList = {
someKey: 'some value',
someOtherKey: 'some other value',
};
demand(filterParser(this.addedFilter, [], badList)).eql(expectedResult);
});
});
});
});
});
|
tinyMCE.addI18n('sk.simple',{
bold_desc:"Tu\u010Dn\u00FD text (Ctrl+B)",
italic_desc:"\u0160ikm\u00FD text (kurz\u00EDva) (Ctrl+I)",
underline_desc:"Pod\u010Diarknut\u00FD text (Ctrl+U)",
striketrough_desc:"Pre\u0161krtnut\u00FD text",
bullist_desc:"Zoznam s odr\u00E1\u017Ekami",
numlist_desc:"\u010C\u00EDslovan\u00FD zoznam",
undo_desc:"Sp\u00E4\u0165 (Ctrl+Z)",
redo_desc:"Znovu (Ctrl+Y)",
cleanup_desc:"Vy\u010Disti\u0165 neupraven\u00FD k\u00F3d"
}); |
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
'use strict';
var aStackPool = [];
var bStackPool = [];
/**
* Checks if two values are equal. Values may be primitives, arrays, or objects.
* Returns true if both arguments have the same keys and values.
*
* @see http://underscorejs.org
* @copyright 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
* @license MIT
*/
function areEqual(a, b) {
var aStack = aStackPool.length ? aStackPool.pop() : [];
var bStack = bStackPool.length ? bStackPool.pop() : [];
var result = eq(a, b, aStack, bStack);
aStack.length = 0;
bStack.length = 0;
aStackPool.push(aStack);
bStackPool.push(bStack);
return result;
}
function eq(a, b, aStack, bStack) {
if (a === b) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
return a !== 0 || 1 / a == 1 / b;
}
if (a == null || b == null) {
// a or b can be `null` or `undefined`
return false;
}
if (typeof a != 'object' || typeof b != 'object') {
return false;
}
var objToStr = Object.prototype.toString;
var className = objToStr.call(a);
if (className != objToStr.call(b)) {
return false;
}
switch (className) {
case '[object String]':
return a == String(b);
case '[object Number]':
return isNaN(a) || isNaN(b) ? false : a == Number(b);
case '[object Date]':
case '[object Boolean]':
return +a == +b;
case '[object RegExp]':
return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase;
}
// Assume equality for cyclic structures.
var length = aStack.length;
while (length--) {
if (aStack[length] == a) {
return bStack[length] == b;
}
}
aStack.push(a);
bStack.push(b);
var size = 0;
// Recursively compare objects and arrays.
if (className === '[object Array]') {
size = a.length;
if (size !== b.length) {
return false;
}
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
if (!eq(a[size], b[size], aStack, bStack)) {
return false;
}
}
} else {
if (a.constructor !== b.constructor) {
return false;
}
if (a.hasOwnProperty('valueOf') && b.hasOwnProperty('valueOf')) {
return a.valueOf() == b.valueOf();
}
var keys = Object.keys(a);
if (keys.length != Object.keys(b).length) {
return false;
}
for (var i = 0; i < keys.length; i++) {
if (!eq(a[keys[i]], b[keys[i]], aStack, bStack)) {
return false;
}
}
}
aStack.pop();
bStack.pop();
return true;
}
module.exports = areEqual; |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v14.0.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var context_1 = require("./context/context");
var constants_1 = require("./constants");
var columnController_1 = require("./columnController/columnController");
var utils_1 = require("./utils");
var gridRow_1 = require("./entities/gridRow");
var gridCell_1 = require("./entities/gridCell");
var gridOptionsWrapper_1 = require("./gridOptionsWrapper");
var pinnedRowModel_1 = require("./rowModels/pinnedRowModel");
var CellNavigationService = (function () {
function CellNavigationService() {
}
// returns null if no cell to focus on, ie at the end of the grid
CellNavigationService.prototype.getNextCellToFocus = function (key, lastCellToFocus) {
// starting with the provided cell, we keep moving until we find a cell we can
// focus on.
var pointer = lastCellToFocus;
var finished = false;
// finished will be true when either:
// a) cell found that we can focus on
// b) run out of cells (ie the method returns null)
while (!finished) {
switch (key) {
case constants_1.Constants.KEY_UP:
pointer = this.getCellAbove(pointer);
break;
case constants_1.Constants.KEY_DOWN:
pointer = this.getCellBelow(pointer);
break;
case constants_1.Constants.KEY_RIGHT:
if (this.gridOptionsWrapper.isEnableRtl()) {
pointer = this.getCellToLeft(pointer);
}
else {
pointer = this.getCellToRight(pointer);
}
break;
case constants_1.Constants.KEY_LEFT:
if (this.gridOptionsWrapper.isEnableRtl()) {
pointer = this.getCellToRight(pointer);
}
else {
pointer = this.getCellToLeft(pointer);
}
break;
default:
console.log('ag-Grid: unknown key for navigation ' + key);
pointer = null;
break;
}
if (pointer) {
finished = this.isCellGoodToFocusOn(pointer);
}
else {
finished = true;
}
}
return pointer;
};
CellNavigationService.prototype.isCellGoodToFocusOn = function (gridCell) {
var column = gridCell.column;
var rowNode;
switch (gridCell.floating) {
case constants_1.Constants.PINNED_TOP:
rowNode = this.pinnedRowModel.getPinnedTopRow(gridCell.rowIndex);
break;
case constants_1.Constants.PINNED_BOTTOM:
rowNode = this.pinnedRowModel.getPinnedBottomRow(gridCell.rowIndex);
break;
default:
rowNode = this.rowModel.getRow(gridCell.rowIndex);
break;
}
var suppressNavigable = column.isSuppressNavigable(rowNode);
return !suppressNavigable;
};
CellNavigationService.prototype.getCellToLeft = function (lastCell) {
var colToLeft = this.columnController.getDisplayedColBefore(lastCell.column);
if (!colToLeft) {
return null;
}
else {
var gridCellDef = { rowIndex: lastCell.rowIndex, column: colToLeft, floating: lastCell.floating };
return new gridCell_1.GridCell(gridCellDef);
}
};
CellNavigationService.prototype.getCellToRight = function (lastCell) {
var colToRight = this.columnController.getDisplayedColAfter(lastCell.column);
// if already on right, do nothing
if (!colToRight) {
return null;
}
else {
var gridCellDef = { rowIndex: lastCell.rowIndex, column: colToRight, floating: lastCell.floating };
return new gridCell_1.GridCell(gridCellDef);
}
};
CellNavigationService.prototype.getRowBelow = function (lastRow) {
// if already on top row, do nothing
if (this.isLastRowInContainer(lastRow)) {
if (lastRow.isFloatingBottom()) {
return null;
}
else if (lastRow.isNotFloating()) {
if (this.pinnedRowModel.isRowsToRender(constants_1.Constants.PINNED_BOTTOM)) {
return new gridRow_1.GridRow(0, constants_1.Constants.PINNED_BOTTOM);
}
else {
return null;
}
}
else {
if (this.rowModel.isRowsToRender()) {
return new gridRow_1.GridRow(0, null);
}
else if (this.pinnedRowModel.isRowsToRender(constants_1.Constants.PINNED_BOTTOM)) {
return new gridRow_1.GridRow(0, constants_1.Constants.PINNED_BOTTOM);
}
else {
return null;
}
}
}
else {
return new gridRow_1.GridRow(lastRow.rowIndex + 1, lastRow.floating);
}
};
CellNavigationService.prototype.getCellBelow = function (lastCell) {
var rowBelow = this.getRowBelow(lastCell.getGridRow());
if (rowBelow) {
var gridCellDef = { rowIndex: rowBelow.rowIndex, column: lastCell.column, floating: rowBelow.floating };
return new gridCell_1.GridCell(gridCellDef);
}
else {
return null;
}
};
CellNavigationService.prototype.isLastRowInContainer = function (gridRow) {
if (gridRow.isFloatingTop()) {
var lastTopIndex = this.pinnedRowModel.getPinnedTopRowData().length - 1;
return lastTopIndex <= gridRow.rowIndex;
}
else if (gridRow.isFloatingBottom()) {
var lastBottomIndex = this.pinnedRowModel.getPinnedBottomRowData().length - 1;
return lastBottomIndex <= gridRow.rowIndex;
}
else {
var lastBodyIndex = this.rowModel.getPageLastRow();
return lastBodyIndex <= gridRow.rowIndex;
}
};
CellNavigationService.prototype.getRowAbove = function (lastRow) {
// if already on top row, do nothing
if (lastRow.rowIndex === 0) {
if (lastRow.isFloatingTop()) {
return null;
}
else if (lastRow.isNotFloating()) {
if (this.pinnedRowModel.isRowsToRender(constants_1.Constants.PINNED_TOP)) {
return this.getLastFloatingTopRow();
}
else {
return null;
}
}
else {
// last floating bottom
if (this.rowModel.isRowsToRender()) {
return this.getLastBodyCell();
}
else if (this.pinnedRowModel.isRowsToRender(constants_1.Constants.PINNED_TOP)) {
return this.getLastFloatingTopRow();
}
else {
return null;
}
}
}
else {
return new gridRow_1.GridRow(lastRow.rowIndex - 1, lastRow.floating);
}
};
CellNavigationService.prototype.getCellAbove = function (lastCell) {
var rowAbove = this.getRowAbove(lastCell.getGridRow());
if (rowAbove) {
var gridCellDef = { rowIndex: rowAbove.rowIndex, column: lastCell.column, floating: rowAbove.floating };
return new gridCell_1.GridCell(gridCellDef);
}
else {
return null;
}
};
CellNavigationService.prototype.getLastBodyCell = function () {
var lastBodyRow = this.rowModel.getPageLastRow();
return new gridRow_1.GridRow(lastBodyRow, null);
};
CellNavigationService.prototype.getLastFloatingTopRow = function () {
var lastFloatingRow = this.pinnedRowModel.getPinnedTopRowData().length - 1;
return new gridRow_1.GridRow(lastFloatingRow, constants_1.Constants.PINNED_TOP);
};
CellNavigationService.prototype.getNextTabbedCell = function (gridCell, backwards) {
if (backwards) {
return this.getNextTabbedCellBackwards(gridCell);
}
else {
return this.getNextTabbedCellForwards(gridCell);
}
};
CellNavigationService.prototype.getNextTabbedCellForwards = function (gridCell) {
var displayedColumns = this.columnController.getAllDisplayedColumns();
var newRowIndex = gridCell.rowIndex;
var newFloating = gridCell.floating;
// move along to the next cell
var newColumn = this.columnController.getDisplayedColAfter(gridCell.column);
// check if end of the row, and if so, go forward a row
if (!newColumn) {
newColumn = displayedColumns[0];
var rowBelow = this.getRowBelow(gridCell.getGridRow());
if (utils_1.Utils.missing(rowBelow)) {
return;
}
newRowIndex = rowBelow.rowIndex;
newFloating = rowBelow.floating;
}
var gridCellDef = { rowIndex: newRowIndex, column: newColumn, floating: newFloating };
return new gridCell_1.GridCell(gridCellDef);
};
CellNavigationService.prototype.getNextTabbedCellBackwards = function (gridCell) {
var displayedColumns = this.columnController.getAllDisplayedColumns();
var newRowIndex = gridCell.rowIndex;
var newFloating = gridCell.floating;
// move along to the next cell
var newColumn = this.columnController.getDisplayedColBefore(gridCell.column);
// check if end of the row, and if so, go forward a row
if (!newColumn) {
newColumn = displayedColumns[displayedColumns.length - 1];
var rowAbove = this.getRowAbove(gridCell.getGridRow());
if (utils_1.Utils.missing(rowAbove)) {
return;
}
newRowIndex = rowAbove.rowIndex;
newFloating = rowAbove.floating;
}
var gridCellDef = { rowIndex: newRowIndex, column: newColumn, floating: newFloating };
return new gridCell_1.GridCell(gridCellDef);
};
__decorate([
context_1.Autowired('columnController'),
__metadata("design:type", columnController_1.ColumnController)
], CellNavigationService.prototype, "columnController", void 0);
__decorate([
context_1.Autowired('rowModel'),
__metadata("design:type", Object)
], CellNavigationService.prototype, "rowModel", void 0);
__decorate([
context_1.Autowired('pinnedRowModel'),
__metadata("design:type", pinnedRowModel_1.PinnedRowModel)
], CellNavigationService.prototype, "pinnedRowModel", void 0);
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
], CellNavigationService.prototype, "gridOptionsWrapper", void 0);
CellNavigationService = __decorate([
context_1.Bean('cellNavigationService')
], CellNavigationService);
return CellNavigationService;
}());
exports.CellNavigationService = CellNavigationService;
|
/**
* @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
*/
THREE.ColladaLoader = function () {
var COLLADA = null;
var scene = null;
var daeScene;
var readyCallbackFunc = null;
var sources = {};
var images = {};
var animations = {};
var controllers = {};
var geometries = {};
var materials = {};
var effects = {};
var cameras = {};
var lights = {};
var animData;
var visualScenes;
var baseUrl;
var morphs;
var skins;
var flip_uv = true;
var preferredShading = THREE.SmoothShading;
var options = {
// Force Geometry to always be centered at the local origin of the
// containing Mesh.
centerGeometry: false,
// Axis conversion is done for geometries, animations, and controllers.
// If we ever pull cameras or lights out of the COLLADA file, they'll
// need extra work.
convertUpAxis: false,
subdivideFaces: true,
upAxis: 'Y',
// For reflective or refractive materials we'll use this cubemap
defaultEnvMap: null
};
var colladaUnit = 1.0;
var colladaUp = 'Y';
var upConversion = null;
function load ( url, readyCallback, progressCallback ) {
var length = 0;
if ( document.implementation && document.implementation.createDocument ) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if( request.readyState == 4 ) {
if( request.status == 0 || request.status == 200 ) {
if ( request.responseXML ) {
readyCallbackFunc = readyCallback;
parse( request.responseXML, undefined, url );
} else if ( request.responseText ) {
readyCallbackFunc = readyCallback;
var xmlParser = new DOMParser();
var responseXML = xmlParser.parseFromString( request.responseText, "application/xml" );
parse( responseXML, undefined, url );
} else {
console.error( "ColladaLoader: Empty or non-existing file (" + url + ")" );
}
}
} else if ( request.readyState == 3 ) {
if ( progressCallback ) {
if ( length == 0 ) {
length = request.getResponseHeader( "Content-Length" );
}
progressCallback( { total: length, loaded: request.responseText.length } );
}
}
}
request.open( "GET", url, true );
request.send( null );
} else {
alert( "Don't know how to parse XML!" );
}
};
function parse( doc, callBack, url ) {
COLLADA = doc;
callBack = callBack || readyCallbackFunc;
if ( url !== undefined ) {
var parts = url.split( '/' );
parts.pop();
baseUrl = ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
}
parseAsset();
setUpConversion();
images = parseLib( "//dae:library_images/dae:image", _Image, "image" );
materials = parseLib( "//dae:library_materials/dae:material", Material, "material" );
effects = parseLib( "//dae:library_effects/dae:effect", Effect, "effect" );
geometries = parseLib( "//dae:library_geometries/dae:geometry", Geometry, "geometry" );
cameras = parseLib( ".//dae:library_cameras/dae:camera", Camera, "camera" );
lights = parseLib( ".//dae:library_lights/dae:light", Light, "light" );
controllers = parseLib( "//dae:library_controllers/dae:controller", Controller, "controller" );
animations = parseLib( "//dae:library_animations/dae:animation", Animation, "animation" );
visualScenes = parseLib( ".//dae:library_visual_scenes/dae:visual_scene", VisualScene, "visual_scene" );
morphs = [];
skins = [];
daeScene = parseScene();
scene = new THREE.Object3D();
for ( var i = 0; i < daeScene.nodes.length; i ++ ) {
scene.add( createSceneGraph( daeScene.nodes[ i ] ) );
}
// unit conversion
scene.scale.multiplyScalar( colladaUnit );
createAnimations();
var result = {
scene: scene,
morphs: morphs,
skins: skins,
animations: animData,
dae: {
images: images,
materials: materials,
cameras: cameras,
lights: lights,
effects: effects,
geometries: geometries,
controllers: controllers,
animations: animations,
visualScenes: visualScenes,
scene: daeScene
}
};
if ( callBack ) {
callBack( result );
}
return result;
};
function setPreferredShading ( shading ) {
preferredShading = shading;
};
function parseAsset () {
var elements = COLLADA.evaluate( '//dae:asset', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
var element = elements.iterateNext();
if ( element && element.childNodes ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
switch ( child.nodeName ) {
case 'unit':
var meter = child.getAttribute( 'meter' );
if ( meter ) {
colladaUnit = parseFloat( meter );
}
break;
case 'up_axis':
colladaUp = child.textContent.charAt(0);
break;
}
}
}
};
function parseLib ( q, classSpec, prefix ) {
var elements = COLLADA.evaluate(q, COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ;
var lib = {};
var element = elements.iterateNext();
var i = 0;
while ( element ) {
var daeElement = ( new classSpec() ).parse( element );
if ( !daeElement.id || daeElement.id.length == 0 ) daeElement.id = prefix + ( i ++ );
lib[ daeElement.id ] = daeElement;
element = elements.iterateNext();
}
return lib;
};
function parseScene() {
var sceneElement = COLLADA.evaluate( './/dae:scene/dae:instance_visual_scene', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
if ( sceneElement ) {
var url = sceneElement.getAttribute( 'url' ).replace( /^#/, '' );
return visualScenes[ url.length > 0 ? url : 'visual_scene0' ];
} else {
return null;
}
};
function createAnimations() {
animData = [];
// fill in the keys
recurseHierarchy( scene );
};
function recurseHierarchy( node ) {
var n = daeScene.getChildById( node.name, true ),
newData = null;
if ( n && n.keys ) {
newData = {
fps: 60,
hierarchy: [ {
node: n,
keys: n.keys,
sids: n.sids
} ],
node: node,
name: 'animation_' + node.name,
length: 0
};
animData.push(newData);
for ( var i = 0, il = n.keys.length; i < il; i++ ) {
newData.length = Math.max( newData.length, n.keys[i].time );
}
} else {
newData = {
hierarchy: [ {
keys: [],
sids: []
} ]
}
}
for ( var i = 0, il = node.children.length; i < il; i++ ) {
var d = recurseHierarchy( node.children[i] );
for ( var j = 0, jl = d.hierarchy.length; j < jl; j ++ ) {
newData.hierarchy.push( {
keys: [],
sids: []
} );
}
}
return newData;
};
function calcAnimationBounds () {
var start = 1000000;
var end = -start;
var frames = 0;
for ( var id in animations ) {
var animation = animations[ id ];
for ( var i = 0; i < animation.sampler.length; i ++ ) {
var sampler = animation.sampler[ i ];
sampler.create();
start = Math.min( start, sampler.startTime );
end = Math.max( end, sampler.endTime );
frames = Math.max( frames, sampler.input.length );
}
}
return { start:start, end:end, frames:frames };
};
function createMorph ( geometry, ctrl ) {
var morphCtrl = ctrl instanceof InstanceController ? controllers[ ctrl.url ] : ctrl;
if ( !morphCtrl || !morphCtrl.morph ) {
console.log("could not find morph controller!");
return;
}
var morph = morphCtrl.morph;
for ( var i = 0; i < morph.targets.length; i ++ ) {
var target_id = morph.targets[ i ];
var daeGeometry = geometries[ target_id ];
if ( !daeGeometry.mesh ||
!daeGeometry.mesh.primitives ||
!daeGeometry.mesh.primitives.length ) {
continue;
}
var target = daeGeometry.mesh.primitives[ 0 ].geometry;
if ( target.vertices.length === geometry.vertices.length ) {
geometry.morphTargets.push( { name: "target_1", vertices: target.vertices } );
}
}
geometry.morphTargets.push( { name: "target_Z", vertices: geometry.vertices } );
};
function createSkin ( geometry, ctrl, applyBindShape ) {
var skinCtrl = controllers[ ctrl.url ];
if ( !skinCtrl || !skinCtrl.skin ) {
console.log( "could not find skin controller!" );
return;
}
if ( !ctrl.skeleton || !ctrl.skeleton.length ) {
console.log( "could not find the skeleton for the skin!" );
return;
}
var skin = skinCtrl.skin;
var skeleton = daeScene.getChildById( ctrl.skeleton[ 0 ] );
var hierarchy = [];
applyBindShape = applyBindShape !== undefined ? applyBindShape : true;
var bones = [];
geometry.skinWeights = [];
geometry.skinIndices = [];
//createBones( geometry.bones, skin, hierarchy, skeleton, null, -1 );
//createWeights( skin, geometry.bones, geometry.skinIndices, geometry.skinWeights );
/*
geometry.animation = {
name: 'take_001',
fps: 30,
length: 2,
JIT: true,
hierarchy: hierarchy
};
*/
if ( applyBindShape ) {
for ( var i = 0; i < geometry.vertices.length; i ++ ) {
geometry.vertices[ i ].applyMatrix4( skin.bindShapeMatrix );
}
}
};
function setupSkeleton ( node, bones, frame, parent ) {
node.world = node.world || new THREE.Matrix4();
node.world.copy( node.matrix );
if ( node.channels && node.channels.length ) {
var channel = node.channels[ 0 ];
var m = channel.sampler.output[ frame ];
if ( m instanceof THREE.Matrix4 ) {
node.world.copy( m );
}
}
if ( parent ) {
node.world.multiplyMatrices( parent, node.world );
}
bones.push( node );
for ( var i = 0; i < node.nodes.length; i ++ ) {
setupSkeleton( node.nodes[ i ], bones, frame, node.world );
}
};
function setupSkinningMatrices ( bones, skin ) {
// FIXME: this is dumb...
for ( var i = 0; i < bones.length; i ++ ) {
var bone = bones[ i ];
var found = -1;
if ( bone.type != 'JOINT' ) continue;
for ( var j = 0; j < skin.joints.length; j ++ ) {
if ( bone.sid == skin.joints[ j ] ) {
found = j;
break;
}
}
if ( found >= 0 ) {
var inv = skin.invBindMatrices[ found ];
bone.invBindMatrix = inv;
bone.skinningMatrix = new THREE.Matrix4();
bone.skinningMatrix.multiplyMatrices(bone.world, inv); // (IBMi * JMi)
bone.weights = [];
for ( var j = 0; j < skin.weights.length; j ++ ) {
for (var k = 0; k < skin.weights[ j ].length; k ++) {
var w = skin.weights[ j ][ k ];
if ( w.joint == found ) {
bone.weights.push( w );
}
}
}
} else {
throw 'ColladaLoader: Could not find joint \'' + bone.sid + '\'.';
}
}
};
function applySkin ( geometry, instanceCtrl, frame ) {
var skinController = controllers[ instanceCtrl.url ];
frame = frame !== undefined ? frame : 40;
if ( !skinController || !skinController.skin ) {
console.log( 'ColladaLoader: Could not find skin controller.' );
return;
}
if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) {
console.log( 'ColladaLoader: Could not find the skeleton for the skin. ' );
return;
}
var animationBounds = calcAnimationBounds();
var skeleton = daeScene.getChildById( instanceCtrl.skeleton[0], true ) ||
daeScene.getChildBySid( instanceCtrl.skeleton[0], true );
var i, j, w, vidx, weight;
var v = new THREE.Vector3(), o, s;
// move vertices to bind shape
for ( i = 0; i < geometry.vertices.length; i ++ ) {
geometry.vertices[i].applyMatrix4( skinController.skin.bindShapeMatrix );
}
// process animation, or simply pose the rig if no animation
for ( frame = 0; frame < animationBounds.frames; frame ++ ) {
var bones = [];
var skinned = [];
// zero skinned vertices
for ( i = 0; i < geometry.vertices.length; i++ ) {
skinned.push( new THREE.Vector3() );
}
// process the frame and setup the rig with a fresh
// transform, possibly from the bone's animation channel(s)
setupSkeleton( skeleton, bones, frame );
setupSkinningMatrices( bones, skinController.skin );
// skin 'm
for ( i = 0; i < bones.length; i ++ ) {
if ( bones[ i ].type != 'JOINT' ) continue;
for ( j = 0; j < bones[ i ].weights.length; j ++ ) {
w = bones[ i ].weights[ j ];
vidx = w.index;
weight = w.weight;
o = geometry.vertices[vidx];
s = skinned[vidx];
v.x = o.x;
v.y = o.y;
v.z = o.z;
v.applyMatrix4( bones[i].skinningMatrix );
s.x += (v.x * weight);
s.y += (v.y * weight);
s.z += (v.z * weight);
}
}
geometry.morphTargets.push( { name: "target_" + frame, vertices: skinned } );
}
};
function createSceneGraph ( node, parent ) {
var obj = new THREE.Object3D();
var skinned = false;
var skinController;
var morphController;
var i, j;
// FIXME: controllers
for ( i = 0; i < node.controllers.length; i ++ ) {
var controller = controllers[ node.controllers[ i ].url ];
switch ( controller.type ) {
case 'skin':
if ( geometries[ controller.skin.source ] ) {
var inst_geom = new InstanceGeometry();
inst_geom.url = controller.skin.source;
inst_geom.instance_material = node.controllers[ i ].instance_material;
node.geometries.push( inst_geom );
skinned = true;
skinController = node.controllers[ i ];
} else if ( controllers[ controller.skin.source ] ) {
// urgh: controller can be chained
// handle the most basic case...
var second = controllers[ controller.skin.source ];
morphController = second;
// skinController = node.controllers[i];
if ( second.morph && geometries[ second.morph.source ] ) {
var inst_geom = new InstanceGeometry();
inst_geom.url = second.morph.source;
inst_geom.instance_material = node.controllers[ i ].instance_material;
node.geometries.push( inst_geom );
}
}
break;
case 'morph':
if ( geometries[ controller.morph.source ] ) {
var inst_geom = new InstanceGeometry();
inst_geom.url = controller.morph.source;
inst_geom.instance_material = node.controllers[ i ].instance_material;
node.geometries.push( inst_geom );
morphController = node.controllers[ i ];
}
console.log( 'ColladaLoader: Morph-controller partially supported.' );
default:
break;
}
}
// FIXME: multi-material mesh?
// geometries
var double_sided_materials = {};
for ( i = 0; i < node.geometries.length; i ++ ) {
var instance_geometry = node.geometries[i];
var instance_materials = instance_geometry.instance_material;
var geometry = geometries[ instance_geometry.url ];
var used_materials = {};
var used_materials_array = [];
var num_materials = 0;
var first_material;
if ( geometry ) {
if ( !geometry.mesh || !geometry.mesh.primitives )
continue;
if ( obj.name.length == 0 ) {
obj.name = geometry.id;
}
// collect used fx for this geometry-instance
if ( instance_materials ) {
for ( j = 0; j < instance_materials.length; j ++ ) {
var instance_material = instance_materials[ j ];
var mat = materials[ instance_material.target ];
var effect_id = mat.instance_effect.url;
var shader = effects[ effect_id ].shader;
var material3js = shader.material;
if ( geometry.doubleSided ) {
if ( !( material3js in double_sided_materials ) ) {
var _copied_material = material3js.clone();
_copied_material.side = THREE.DoubleSide;
double_sided_materials[ material3js ] = _copied_material;
}
material3js = double_sided_materials[ material3js ];
}
material3js.opacity = !material3js.opacity ? 1 : material3js.opacity;
used_materials[ instance_material.symbol ] = num_materials;
used_materials_array.push( material3js );
first_material = material3js;
first_material.name = mat.name == null || mat.name === '' ? mat.id : mat.name;
num_materials ++;
}
}
var mesh;
var material = first_material || new THREE.MeshLambertMaterial( { color: 0xdddddd, shading: THREE.FlatShading, side: geometry.doubleSided ? THREE.DoubleSide : THREE.FrontSide } );
var geom = geometry.mesh.geometry3js;
if ( num_materials > 1 ) {
material = new THREE.MeshFaceMaterial( used_materials_array );
for ( j = 0; j < geom.faces.length; j ++ ) {
var face = geom.faces[ j ];
face.materialIndex = used_materials[ face.daeMaterial ]
}
}
if ( skinController !== undefined ) {
applySkin( geom, skinController );
material.morphTargets = true;
mesh = new THREE.SkinnedMesh( geom, material, false );
mesh.skeleton = skinController.skeleton;
mesh.skinController = controllers[ skinController.url ];
mesh.skinInstanceController = skinController;
mesh.name = 'skin_' + skins.length;
skins.push( mesh );
} else if ( morphController !== undefined ) {
createMorph( geom, morphController );
material.morphTargets = true;
mesh = new THREE.Mesh( geom, material );
mesh.name = 'morph_' + morphs.length;
morphs.push( mesh );
} else {
mesh = new THREE.Mesh( geom, material );
// mesh.geom.name = geometry.id;
}
node.geometries.length > 1 ? obj.add( mesh ) : obj = mesh;
}
}
for ( i = 0; i < node.cameras.length; i ++ ) {
var params = cameras[node.cameras[i].url];
obj = new THREE.PerspectiveCamera(params.fov, params.aspect_ratio, params.znear, params.zfar);
}
for ( i = 0; i < node.lights.length; i ++ ) {
var params = lights[node.lights[i].url];
switch ( params.technique ) {
case 'ambient':
obj = new THREE.AmbientLight(params.color);
break;
case 'point':
obj = new THREE.PointLight(params.color);
break;
case 'directional':
obj = new THREE.DirectionalLight(params.color);
break;
}
}
obj.name = node.name || node.id || "";
obj.matrix = node.matrix;
var props = node.matrix.decompose();
obj.position = props[ 0 ];
obj.quaternion = props[ 1 ];
obj.useQuaternion = true;
obj.scale = props[ 2 ];
if ( options.centerGeometry && obj.geometry ) {
var delta = THREE.GeometryUtils.center( obj.geometry );
delta.multiply( obj.scale );
delta.applyQuaternion( obj.quaternion );
obj.position.sub( delta );
}
for ( i = 0; i < node.nodes.length; i ++ ) {
obj.add( createSceneGraph( node.nodes[i], node ) );
}
return obj;
};
function getJointId( skin, id ) {
for ( var i = 0; i < skin.joints.length; i ++ ) {
if ( skin.joints[ i ] == id ) {
return i;
}
}
};
function getLibraryNode( id ) {
return COLLADA.evaluate( './/dae:library_nodes//dae:node[@id=\'' + id + '\']', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
};
function getChannelsForNode (node ) {
var channels = [];
var startTime = 1000000;
var endTime = -1000000;
for ( var id in animations ) {
var animation = animations[id];
for ( var i = 0; i < animation.channel.length; i ++ ) {
var channel = animation.channel[i];
var sampler = animation.sampler[i];
var id = channel.target.split('/')[0];
if ( id == node.id ) {
sampler.create();
channel.sampler = sampler;
startTime = Math.min(startTime, sampler.startTime);
endTime = Math.max(endTime, sampler.endTime);
channels.push(channel);
}
}
}
if ( channels.length ) {
node.startTime = startTime;
node.endTime = endTime;
}
return channels;
};
function calcFrameDuration( node ) {
var minT = 10000000;
for ( var i = 0; i < node.channels.length; i ++ ) {
var sampler = node.channels[i].sampler;
for ( var j = 0; j < sampler.input.length - 1; j ++ ) {
var t0 = sampler.input[ j ];
var t1 = sampler.input[ j + 1 ];
minT = Math.min( minT, t1 - t0 );
}
}
return minT;
};
function calcMatrixAt( node, t ) {
var animated = {};
var i, j;
for ( i = 0; i < node.channels.length; i ++ ) {
var channel = node.channels[ i ];
animated[ channel.sid ] = channel;
}
var matrix = new THREE.Matrix4();
for ( i = 0; i < node.transforms.length; i ++ ) {
var transform = node.transforms[ i ];
var channel = animated[ transform.sid ];
if ( channel !== undefined ) {
var sampler = channel.sampler;
var value;
for ( j = 0; j < sampler.input.length - 1; j ++ ) {
if ( sampler.input[ j + 1 ] > t ) {
value = sampler.output[ j ];
//console.log(value.flatten)
break;
}
}
if ( value !== undefined ) {
if ( value instanceof THREE.Matrix4 ) {
matrix.multiplyMatrices( matrix, value );
} else {
// FIXME: handle other types
matrix.multiplyMatrices( matrix, transform.matrix );
}
} else {
matrix.multiplyMatrices( matrix, transform.matrix );
}
} else {
matrix.multiplyMatrices( matrix, transform.matrix );
}
}
return matrix;
};
function bakeAnimations ( node ) {
if ( node.channels && node.channels.length ) {
var keys = [],
sids = [];
for ( var i = 0, il = node.channels.length; i < il; i++ ) {
var channel = node.channels[i],
fullSid = channel.fullSid,
sampler = channel.sampler,
input = sampler.input,
transform = node.getTransformBySid( channel.sid ),
member;
if ( channel.arrIndices ) {
member = [];
for ( var j = 0, jl = channel.arrIndices.length; j < jl; j++ ) {
member[ j ] = getConvertedIndex( channel.arrIndices[ j ] );
}
} else {
member = getConvertedMember( channel.member );
}
if ( transform ) {
if ( sids.indexOf( fullSid ) === -1 ) {
sids.push( fullSid );
}
for ( var j = 0, jl = input.length; j < jl; j++ ) {
var time = input[j],
data = sampler.getData( transform.type, j ),
key = findKey( keys, time );
if ( !key ) {
key = new Key( time );
var timeNdx = findTimeNdx( keys, time );
keys.splice( timeNdx == -1 ? keys.length : timeNdx, 0, key );
}
key.addTarget( fullSid, transform, member, data );
}
} else {
console.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id );
}
}
// post process
for ( var i = 0; i < sids.length; i++ ) {
var sid = sids[ i ];
for ( var j = 0; j < keys.length; j++ ) {
var key = keys[ j ];
if ( !key.hasTarget( sid ) ) {
interpolateKeys( keys, key, j, sid );
}
}
}
node.keys = keys;
node.sids = sids;
}
};
function findKey ( keys, time) {
var retVal = null;
for ( var i = 0, il = keys.length; i < il && retVal == null; i++ ) {
var key = keys[i];
if ( key.time === time ) {
retVal = key;
} else if ( key.time > time ) {
break;
}
}
return retVal;
};
function findTimeNdx ( keys, time) {
var ndx = -1;
for ( var i = 0, il = keys.length; i < il && ndx == -1; i++ ) {
var key = keys[i];
if ( key.time >= time ) {
ndx = i;
}
}
return ndx;
};
function interpolateKeys ( keys, key, ndx, fullSid ) {
var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx-1 : 0 ),
nextKey = getNextKeyWith( keys, fullSid, ndx+1 );
if ( prevKey && nextKey ) {
var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time),
prevTarget = prevKey.getTarget( fullSid ),
nextData = nextKey.getTarget( fullSid ).data,
prevData = prevTarget.data,
data;
if ( prevTarget.type === 'matrix' ) {
data = prevData;
} else if ( prevData.length ) {
data = [];
for ( var i = 0; i < prevData.length; ++i ) {
data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale;
}
} else {
data = prevData + ( nextData - prevData ) * scale;
}
key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data );
}
};
// Get next key with given sid
function getNextKeyWith( keys, fullSid, ndx ) {
for ( ; ndx < keys.length; ndx++ ) {
var key = keys[ ndx ];
if ( key.hasTarget( fullSid ) ) {
return key;
}
}
return null;
};
// Get previous key with given sid
function getPrevKeyWith( keys, fullSid, ndx ) {
ndx = ndx >= 0 ? ndx : ndx + keys.length;
for ( ; ndx >= 0; ndx-- ) {
var key = keys[ ndx ];
if ( key.hasTarget( fullSid ) ) {
return key;
}
}
return null;
};
function _Image() {
this.id = "";
this.init_from = "";
};
_Image.prototype.parse = function(element) {
this.id = element.getAttribute('id');
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeName == 'init_from' ) {
this.init_from = child.textContent;
}
}
return this;
};
function Controller() {
this.id = "";
this.name = "";
this.type = "";
this.skin = null;
this.morph = null;
};
Controller.prototype.parse = function( element ) {
this.id = element.getAttribute('id');
this.name = element.getAttribute('name');
this.type = "none";
for ( var i = 0; i < element.childNodes.length; i++ ) {
var child = element.childNodes[ i ];
switch ( child.nodeName ) {
case 'skin':
this.skin = (new Skin()).parse(child);
this.type = child.nodeName;
break;
case 'morph':
this.morph = (new Morph()).parse(child);
this.type = child.nodeName;
break;
default:
break;
}
}
return this;
};
function Morph() {
this.method = null;
this.source = null;
this.targets = null;
this.weights = null;
};
Morph.prototype.parse = function( element ) {
var sources = {};
var inputs = [];
var i;
this.method = element.getAttribute( 'method' );
this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
for ( i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'source':
var source = ( new Source() ).parse( child );
sources[ source.id ] = source;
break;
case 'targets':
inputs = this.parseInputs( child );
break;
default:
console.log( child.nodeName );
break;
}
}
for ( i = 0; i < inputs.length; i ++ ) {
var input = inputs[ i ];
var source = sources[ input.source ];
switch ( input.semantic ) {
case 'MORPH_TARGET':
this.targets = source.read();
break;
case 'MORPH_WEIGHT':
this.weights = source.read();
break;
default:
break;
}
}
return this;
};
Morph.prototype.parseInputs = function(element) {
var inputs = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[i];
if ( child.nodeType != 1) continue;
switch ( child.nodeName ) {
case 'input':
inputs.push( (new Input()).parse(child) );
break;
default:
break;
}
}
return inputs;
};
function Skin() {
this.source = "";
this.bindShapeMatrix = null;
this.invBindMatrices = [];
this.joints = [];
this.weights = [];
};
Skin.prototype.parse = function( element ) {
var sources = {};
var joints, weights;
this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
this.invBindMatrices = [];
this.joints = [];
this.weights = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[i];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'bind_shape_matrix':
var f = _floats(child.textContent);
this.bindShapeMatrix = getConvertedMat4( f );
break;
case 'source':
var src = new Source().parse(child);
sources[ src.id ] = src;
break;
case 'joints':
joints = child;
break;
case 'vertex_weights':
weights = child;
break;
default:
console.log( child.nodeName );
break;
}
}
this.parseJoints( joints, sources );
this.parseWeights( weights, sources );
return this;
};
Skin.prototype.parseJoints = function ( element, sources ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'input':
var input = ( new Input() ).parse( child );
var source = sources[ input.source ];
if ( input.semantic == 'JOINT' ) {
this.joints = source.read();
} else if ( input.semantic == 'INV_BIND_MATRIX' ) {
this.invBindMatrices = source.read();
}
break;
default:
break;
}
}
};
Skin.prototype.parseWeights = function ( element, sources ) {
var v, vcount, inputs = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'input':
inputs.push( ( new Input() ).parse( child ) );
break;
case 'v':
v = _ints( child.textContent );
break;
case 'vcount':
vcount = _ints( child.textContent );
break;
default:
break;
}
}
var index = 0;
for ( var i = 0; i < vcount.length; i ++ ) {
var numBones = vcount[i];
var vertex_weights = [];
for ( var j = 0; j < numBones; j++ ) {
var influence = {};
for ( var k = 0; k < inputs.length; k ++ ) {
var input = inputs[ k ];
var value = v[ index + input.offset ];
switch ( input.semantic ) {
case 'JOINT':
influence.joint = value;//this.joints[value];
break;
case 'WEIGHT':
influence.weight = sources[ input.source ].data[ value ];
break;
default:
break;
}
}
vertex_weights.push( influence );
index += inputs.length;
}
for ( var j = 0; j < vertex_weights.length; j ++ ) {
vertex_weights[ j ].index = i;
}
this.weights.push( vertex_weights );
}
};
function VisualScene () {
this.id = "";
this.name = "";
this.nodes = [];
this.scene = new THREE.Object3D();
};
VisualScene.prototype.getChildById = function( id, recursive ) {
for ( var i = 0; i < this.nodes.length; i ++ ) {
var node = this.nodes[ i ].getChildById( id, recursive );
if ( node ) {
return node;
}
}
return null;
};
VisualScene.prototype.getChildBySid = function( sid, recursive ) {
for ( var i = 0; i < this.nodes.length; i ++ ) {
var node = this.nodes[ i ].getChildBySid( sid, recursive );
if ( node ) {
return node;
}
}
return null;
};
VisualScene.prototype.parse = function( element ) {
this.id = element.getAttribute( 'id' );
this.name = element.getAttribute( 'name' );
this.nodes = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'node':
this.nodes.push( ( new Node() ).parse( child ) );
break;
default:
break;
}
}
return this;
};
function Node() {
this.id = "";
this.name = "";
this.sid = "";
this.nodes = [];
this.controllers = [];
this.transforms = [];
this.geometries = [];
this.channels = [];
this.matrix = new THREE.Matrix4();
};
Node.prototype.getChannelForTransform = function( transformSid ) {
for ( var i = 0; i < this.channels.length; i ++ ) {
var channel = this.channels[i];
var parts = channel.target.split('/');
var id = parts.shift();
var sid = parts.shift();
var dotSyntax = (sid.indexOf(".") >= 0);
var arrSyntax = (sid.indexOf("(") >= 0);
var arrIndices;
var member;
if ( dotSyntax ) {
parts = sid.split(".");
sid = parts.shift();
member = parts.shift();
} else if ( arrSyntax ) {
arrIndices = sid.split("(");
sid = arrIndices.shift();
for ( var j = 0; j < arrIndices.length; j ++ ) {
arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
}
}
if ( sid == transformSid ) {
channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
return channel;
}
}
return null;
};
Node.prototype.getChildById = function ( id, recursive ) {
if ( this.id == id ) {
return this;
}
if ( recursive ) {
for ( var i = 0; i < this.nodes.length; i ++ ) {
var n = this.nodes[ i ].getChildById( id, recursive );
if ( n ) {
return n;
}
}
}
return null;
};
Node.prototype.getChildBySid = function ( sid, recursive ) {
if ( this.sid == sid ) {
return this;
}
if ( recursive ) {
for ( var i = 0; i < this.nodes.length; i ++ ) {
var n = this.nodes[ i ].getChildBySid( sid, recursive );
if ( n ) {
return n;
}
}
}
return null;
};
Node.prototype.getTransformBySid = function ( sid ) {
for ( var i = 0; i < this.transforms.length; i ++ ) {
if ( this.transforms[ i ].sid == sid ) return this.transforms[ i ];
}
return null;
};
Node.prototype.parse = function( element ) {
var url;
this.id = element.getAttribute('id');
this.sid = element.getAttribute('sid');
this.name = element.getAttribute('name');
this.type = element.getAttribute('type');
this.type = this.type == 'JOINT' ? this.type : 'NODE';
this.nodes = [];
this.transforms = [];
this.geometries = [];
this.cameras = [];
this.lights = [];
this.controllers = [];
this.matrix = new THREE.Matrix4();
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'node':
this.nodes.push( ( new Node() ).parse( child ) );
break;
case 'instance_camera':
this.cameras.push( ( new InstanceCamera() ).parse( child ) );
break;
case 'instance_light':
this.lights.push( ( new InstanceLight() ).parse( child ) );
break;
case 'instance_controller':
this.controllers.push( ( new InstanceController() ).parse( child ) );
break;
case 'instance_geometry':
this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
break;
case 'instance_node':
url = child.getAttribute( 'url' ).replace( /^#/, '' );
var iNode = getLibraryNode( url );
if ( iNode ) {
this.nodes.push( ( new Node() ).parse( iNode )) ;
}
break;
case 'rotate':
case 'translate':
case 'scale':
case 'matrix':
case 'lookat':
case 'skew':
this.transforms.push( ( new Transform() ).parse( child ) );
break;
case 'extra':
break;
default:
console.log( child.nodeName );
break;
}
}
this.channels = getChannelsForNode( this );
bakeAnimations( this );
this.updateMatrix();
return this;
};
Node.prototype.updateMatrix = function () {
this.matrix.identity();
for ( var i = 0; i < this.transforms.length; i ++ ) {
this.transforms[ i ].apply( this.matrix );
}
};
function Transform () {
this.sid = "";
this.type = "";
this.data = [];
this.obj = null;
};
Transform.prototype.parse = function ( element ) {
this.sid = element.getAttribute( 'sid' );
this.type = element.nodeName;
this.data = _floats( element.textContent );
this.convert();
return this;
};
Transform.prototype.convert = function () {
switch ( this.type ) {
case 'matrix':
this.obj = getConvertedMat4( this.data );
break;
case 'rotate':
this.angle = THREE.Math.degToRad( this.data[3] );
case 'translate':
fixCoords( this.data, -1 );
this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
break;
case 'scale':
fixCoords( this.data, 1 );
this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
break;
default:
console.log( 'Can not convert Transform of type ' + this.type );
break;
}
};
Transform.prototype.apply = function () {
var m1 = new THREE.Matrix4();
return function ( matrix ) {
switch ( this.type ) {
case 'matrix':
matrix.multiply( this.obj );
break;
case 'translate':
matrix.multiply( m1.makeTranslation( this.obj.x, this.obj.y, this.obj.z ) );
break;
case 'rotate':
matrix.multiply( m1.makeRotationAxis( this.obj, this.angle ) );
break;
case 'scale':
matrix.scale( this.obj );
break;
}
};
}();
Transform.prototype.update = function ( data, member ) {
var members = [ 'X', 'Y', 'Z', 'ANGLE' ];
switch ( this.type ) {
case 'matrix':
if ( ! member ) {
this.obj.copy( data );
} else if ( member.length === 1 ) {
switch ( member[ 0 ] ) {
case 0:
this.obj.n11 = data[ 0 ];
this.obj.n21 = data[ 1 ];
this.obj.n31 = data[ 2 ];
this.obj.n41 = data[ 3 ];
break;
case 1:
this.obj.n12 = data[ 0 ];
this.obj.n22 = data[ 1 ];
this.obj.n32 = data[ 2 ];
this.obj.n42 = data[ 3 ];
break;
case 2:
this.obj.n13 = data[ 0 ];
this.obj.n23 = data[ 1 ];
this.obj.n33 = data[ 2 ];
this.obj.n43 = data[ 3 ];
break;
case 3:
this.obj.n14 = data[ 0 ];
this.obj.n24 = data[ 1 ];
this.obj.n34 = data[ 2 ];
this.obj.n44 = data[ 3 ];
break;
}
} else if ( member.length === 2 ) {
var propName = 'n' + ( member[ 0 ] + 1 ) + ( member[ 1 ] + 1 );
this.obj[ propName ] = data;
} else {
console.log('Incorrect addressing of matrix in transform.');
}
break;
case 'translate':
case 'scale':
if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
member = members[ member[ 0 ] ];
}
switch ( member ) {
case 'X':
this.obj.x = data;
break;
case 'Y':
this.obj.y = data;
break;
case 'Z':
this.obj.z = data;
break;
default:
this.obj.x = data[ 0 ];
this.obj.y = data[ 1 ];
this.obj.z = data[ 2 ];
break;
}
break;
case 'rotate':
if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
member = members[ member[ 0 ] ];
}
switch ( member ) {
case 'X':
this.obj.x = data;
break;
case 'Y':
this.obj.y = data;
break;
case 'Z':
this.obj.z = data;
break;
case 'ANGLE':
this.angle = THREE.Math.degToRad( data );
break;
default:
this.obj.x = data[ 0 ];
this.obj.y = data[ 1 ];
this.obj.z = data[ 2 ];
this.angle = THREE.Math.degToRad( data[ 3 ] );
break;
}
break;
}
};
function InstanceController() {
this.url = "";
this.skeleton = [];
this.instance_material = [];
};
InstanceController.prototype.parse = function ( element ) {
this.url = element.getAttribute('url').replace(/^#/, '');
this.skeleton = [];
this.instance_material = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType !== 1 ) continue;
switch ( child.nodeName ) {
case 'skeleton':
this.skeleton.push( child.textContent.replace(/^#/, '') );
break;
case 'bind_material':
var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
if ( instances ) {
var instance = instances.iterateNext();
while ( instance ) {
this.instance_material.push( (new InstanceMaterial()).parse(instance) );
instance = instances.iterateNext();
}
}
break;
case 'extra':
break;
default:
break;
}
}
return this;
};
function InstanceMaterial () {
this.symbol = "";
this.target = "";
};
InstanceMaterial.prototype.parse = function ( element ) {
this.symbol = element.getAttribute('symbol');
this.target = element.getAttribute('target').replace(/^#/, '');
return this;
};
function InstanceGeometry() {
this.url = "";
this.instance_material = [];
};
InstanceGeometry.prototype.parse = function ( element ) {
this.url = element.getAttribute('url').replace(/^#/, '');
this.instance_material = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[i];
if ( child.nodeType != 1 ) continue;
if ( child.nodeName == 'bind_material' ) {
var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
if ( instances ) {
var instance = instances.iterateNext();
while ( instance ) {
this.instance_material.push( (new InstanceMaterial()).parse(instance) );
instance = instances.iterateNext();
}
}
break;
}
}
return this;
};
function Geometry() {
this.id = "";
this.mesh = null;
};
Geometry.prototype.parse = function ( element ) {
this.id = element.getAttribute('id');
extractDoubleSided( this, element );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[i];
switch ( child.nodeName ) {
case 'mesh':
this.mesh = (new Mesh(this)).parse(child);
break;
case 'extra':
// console.log( child );
break;
default:
break;
}
}
return this;
};
function Mesh( geometry ) {
this.geometry = geometry.id;
this.primitives = [];
this.vertices = null;
this.geometry3js = null;
};
Mesh.prototype.parse = function( element ) {
this.primitives = [];
var i, j;
for ( i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
switch ( child.nodeName ) {
case 'source':
_source( child );
break;
case 'vertices':
this.vertices = ( new Vertices() ).parse( child );
break;
case 'triangles':
this.primitives.push( ( new Triangles().parse( child ) ) );
break;
case 'polygons':
this.primitives.push( ( new Polygons().parse( child ) ) );
break;
case 'polylist':
this.primitives.push( ( new Polylist().parse( child ) ) );
break;
default:
break;
}
}
this.geometry3js = new THREE.Geometry();
var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
for ( i = 0; i < vertexData.length; i += 3 ) {
this.geometry3js.vertices.push( getConvertedVec3( vertexData, i ).clone() );
}
for ( i = 0; i < this.primitives.length; i ++ ) {
var primitive = this.primitives[ i ];
primitive.setVertices( this.vertices );
this.handlePrimitive( primitive, this.geometry3js );
}
this.geometry3js.computeCentroids();
this.geometry3js.computeFaceNormals();
if ( this.geometry3js.calcNormals ) {
this.geometry3js.computeVertexNormals();
delete this.geometry3js.calcNormals;
}
this.geometry3js.computeBoundingBox();
return this;
};
Mesh.prototype.handlePrimitive = function( primitive, geom ) {
var j, k, pList = primitive.p, inputs = primitive.inputs;
var input, index, idx32;
var source, numParams;
var vcIndex = 0, vcount = 3, maxOffset = 0;
var texture_sets = [];
for ( j = 0; j < inputs.length; j ++ ) {
input = inputs[ j ];
var offset = input.offset + 1;
maxOffset = (maxOffset < offset)? offset : maxOffset;
switch ( input.semantic ) {
case 'TEXCOORD':
texture_sets.push( input.set );
break;
}
}
for ( var pCount = 0; pCount < pList.length; ++pCount ) {
var p = pList[ pCount ], i = 0;
while ( i < p.length ) {
var vs = [];
var ns = [];
var ts = null;
var cs = [];
if ( primitive.vcount ) {
vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
} else {
vcount = p.length / maxOffset;
}
for ( j = 0; j < vcount; j ++ ) {
for ( k = 0; k < inputs.length; k ++ ) {
input = inputs[ k ];
source = sources[ input.source ];
index = p[ i + ( j * maxOffset ) + input.offset ];
numParams = source.accessor.params.length;
idx32 = index * numParams;
switch ( input.semantic ) {
case 'VERTEX':
vs.push( index );
break;
case 'NORMAL':
ns.push( getConvertedVec3( source.data, idx32 ) );
break;
case 'TEXCOORD':
ts = ts || { };
if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
// invert the V
ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], source.data[ idx32 + 1 ] ) );
break;
case 'COLOR':
cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
break;
default:
break;
}
}
}
if ( ns.length == 0 ) {
// check the vertices inputs
input = this.vertices.input.NORMAL;
if ( input ) {
source = sources[ input.source ];
numParams = source.accessor.params.length;
for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) {
ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
}
} else {
geom.calcNormals = true;
}
}
if ( !ts ) {
ts = { };
// check the vertices inputs
input = this.vertices.input.TEXCOORD;
if ( input ) {
texture_sets.push( input.set );
source = sources[ input.source ];
numParams = source.accessor.params.length;
for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) {
idx32 = vs[ ndx ] * numParams;
if ( ts[ input.set ] === undefined ) ts[ input.set ] = [ ];
// invert the V
ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
}
}
}
if ( cs.length == 0 ) {
// check the vertices inputs
input = this.vertices.input.COLOR;
if ( input ) {
source = sources[ input.source ];
numParams = source.accessor.params.length;
for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) {
idx32 = vs[ ndx ] * numParams;
cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
}
}
}
var face = null, faces = [], uv, uvArr;
if ( vcount === 3 ) {
faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
} else if ( vcount === 4 ) {
faces.push( new THREE.Face4( vs[0], vs[1], vs[2], vs[3], ns, cs.length ? cs : new THREE.Color() ) );
} else if ( vcount > 4 && options.subdivideFaces ) {
var clr = cs.length ? cs : new THREE.Color(),
vec1, vec2, vec3, v1, v2, norm;
// subdivide into multiple Face3s
for ( k = 1; k < vcount - 1; ) {
// FIXME: normals don't seem to be quite right
faces.push( new THREE.Face3( vs[0], vs[k], vs[k+1], [ ns[0], ns[k++], ns[k] ], clr ) );
}
}
if ( faces.length ) {
for ( var ndx = 0, len = faces.length; ndx < len; ndx ++ ) {
face = faces[ndx];
face.daeMaterial = primitive.material;
geom.faces.push( face );
for ( k = 0; k < texture_sets.length; k++ ) {
uv = ts[ texture_sets[k] ];
if ( vcount > 4 ) {
// Grab the right UVs for the vertices in this face
uvArr = [ uv[0], uv[ndx+1], uv[ndx+2] ];
} else if ( vcount === 4 ) {
uvArr = [ uv[0], uv[1], uv[2], uv[3] ];
} else {
uvArr = [ uv[0], uv[1], uv[2] ];
}
if ( !geom.faceVertexUvs[k] ) {
geom.faceVertexUvs[k] = [];
}
geom.faceVertexUvs[k].push( uvArr );
}
}
} else {
console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
}
i += maxOffset * vcount;
}
}
};
function Polygons () {
this.material = "";
this.count = 0;
this.inputs = [];
this.vcount = null;
this.p = [];
this.geometry = new THREE.Geometry();
};
Polygons.prototype.setVertices = function ( vertices ) {
for ( var i = 0; i < this.inputs.length; i ++ ) {
if ( this.inputs[ i ].source == vertices.id ) {
this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
}
}
};
Polygons.prototype.parse = function ( element ) {
this.material = element.getAttribute( 'material' );
this.count = _attr_as_int( element, 'count', 0 );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
switch ( child.nodeName ) {
case 'input':
this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
break;
case 'vcount':
this.vcount = _ints( child.textContent );
break;
case 'p':
this.p.push( _ints( child.textContent ) );
break;
case 'ph':
console.warn( 'polygon holes not yet supported!' );
break;
default:
break;
}
}
return this;
};
function Polylist () {
Polygons.call( this );
this.vcount = [];
};
Polylist.prototype = Object.create( Polygons.prototype );
function Triangles () {
Polygons.call( this );
this.vcount = 3;
};
Triangles.prototype = Object.create( Polygons.prototype );
function Accessor() {
this.source = "";
this.count = 0;
this.stride = 0;
this.params = [];
};
Accessor.prototype.parse = function ( element ) {
this.params = [];
this.source = element.getAttribute( 'source' );
this.count = _attr_as_int( element, 'count', 0 );
this.stride = _attr_as_int( element, 'stride', 0 );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeName == 'param' ) {
var param = {};
param[ 'name' ] = child.getAttribute( 'name' );
param[ 'type' ] = child.getAttribute( 'type' );
this.params.push( param );
}
}
return this;
};
function Vertices() {
this.input = {};
};
Vertices.prototype.parse = function ( element ) {
this.id = element.getAttribute('id');
for ( var i = 0; i < element.childNodes.length; i ++ ) {
if ( element.childNodes[i].nodeName == 'input' ) {
var input = ( new Input() ).parse( element.childNodes[ i ] );
this.input[ input.semantic ] = input;
}
}
return this;
};
function Input () {
this.semantic = "";
this.offset = 0;
this.source = "";
this.set = 0;
};
Input.prototype.parse = function ( element ) {
this.semantic = element.getAttribute('semantic');
this.source = element.getAttribute('source').replace(/^#/, '');
this.set = _attr_as_int(element, 'set', -1);
this.offset = _attr_as_int(element, 'offset', 0);
if ( this.semantic == 'TEXCOORD' && this.set < 0 ) {
this.set = 0;
}
return this;
};
function Source ( id ) {
this.id = id;
this.type = null;
};
Source.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[i];
switch ( child.nodeName ) {
case 'bool_array':
this.data = _bools( child.textContent );
this.type = child.nodeName;
break;
case 'float_array':
this.data = _floats( child.textContent );
this.type = child.nodeName;
break;
case 'int_array':
this.data = _ints( child.textContent );
this.type = child.nodeName;
break;
case 'IDREF_array':
case 'Name_array':
this.data = _strings( child.textContent );
this.type = child.nodeName;
break;
case 'technique_common':
for ( var j = 0; j < child.childNodes.length; j ++ ) {
if ( child.childNodes[ j ].nodeName == 'accessor' ) {
this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
break;
}
}
break;
default:
// console.log(child.nodeName);
break;
}
}
return this;
};
Source.prototype.read = function () {
var result = [];
//for (var i = 0; i < this.accessor.params.length; i++) {
var param = this.accessor.params[ 0 ];
//console.log(param.name + " " + param.type);
switch ( param.type ) {
case 'IDREF':
case 'Name': case 'name':
case 'float':
return this.data;
case 'float4x4':
for ( var j = 0; j < this.data.length; j += 16 ) {
var s = this.data.slice( j, j + 16 );
var m = getConvertedMat4( s );
result.push( m );
}
break;
default:
console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
break;
}
//}
return result;
};
function Material () {
this.id = "";
this.name = "";
this.instance_effect = null;
};
Material.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
this.name = element.getAttribute( 'name' );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
if ( element.childNodes[ i ].nodeName == 'instance_effect' ) {
this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
break;
}
}
return this;
};
function ColorOrTexture () {
this.color = new THREE.Color();
this.color.setRGB( Math.random(), Math.random(), Math.random() );
this.color.a = 1.0;
this.texture = null;
this.texcoord = null;
this.texOpts = null;
};
ColorOrTexture.prototype.isColor = function () {
return ( this.texture == null );
};
ColorOrTexture.prototype.isTexture = function () {
return ( this.texture != null );
};
ColorOrTexture.prototype.parse = function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'color':
var rgba = _floats( child.textContent );
this.color = new THREE.Color();
this.color.setRGB( rgba[0], rgba[1], rgba[2] );
this.color.a = rgba[3];
break;
case 'texture':
this.texture = child.getAttribute('texture');
this.texcoord = child.getAttribute('texcoord');
// Defaults from:
// https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
this.texOpts = {
offsetU: 0,
offsetV: 0,
repeatU: 1,
repeatV: 1,
wrapU: 1,
wrapV: 1,
};
this.parseTexture( child );
break;
default:
break;
}
}
return this;
};
ColorOrTexture.prototype.parseTexture = function ( element ) {
if ( ! element.childNodes ) return this;
// This should be supported by Maya, 3dsMax, and MotionBuilder
if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
element = element.childNodes[1];
if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
element = element.childNodes[1];
}
}
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
switch ( child.nodeName ) {
case 'offsetU':
case 'offsetV':
case 'repeatU':
case 'repeatV':
this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
break;
case 'wrapU':
case 'wrapV':
this.texOpts[ child.nodeName ] = parseInt( child.textContent );
break;
default:
this.texOpts[ child.nodeName ] = child.textContent;
break;
}
}
return this;
};
function Shader ( type, effect ) {
this.type = type;
this.effect = effect;
this.material = null;
};
Shader.prototype.parse = function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'ambient':
case 'emission':
case 'diffuse':
case 'specular':
case 'transparent':
this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
break;
case 'shininess':
case 'reflectivity':
case 'index_of_refraction':
case 'transparency':
var f = evaluateXPath( child, './/dae:float' );
if ( f.length > 0 )
this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
break;
default:
break;
}
}
this.create();
return this;
};
Shader.prototype.create = function() {
var props = {};
var transparent = ( this['transparency'] !== undefined && this['transparency'] < 1.0 );
for ( var prop in this ) {
switch ( prop ) {
case 'ambient':
case 'emission':
case 'diffuse':
case 'specular':
var cot = this[ prop ];
if ( cot instanceof ColorOrTexture ) {
if ( cot.isTexture() ) {
var samplerId = cot.texture;
var surfaceId = this.effect.sampler[samplerId].source;
if ( surfaceId ) {
var surface = this.effect.surface[surfaceId];
var image = images[surface.init_from];
if (image) {
var texture = THREE.ImageUtils.loadTexture(baseUrl + image.init_from);
texture.wrapS = cot.texOpts.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
texture.wrapT = cot.texOpts.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
texture.offset.x = cot.texOpts.offsetU;
texture.offset.y = cot.texOpts.offsetV;
texture.repeat.x = cot.texOpts.repeatU;
texture.repeat.y = cot.texOpts.repeatV;
props['map'] = texture;
// Texture with baked lighting?
if (prop === 'emission') props['emissive'] = 0xffffff;
}
}
} else if ( prop === 'diffuse' || !transparent ) {
if ( prop === 'emission' ) {
props[ 'emissive' ] = cot.color.getHex();
} else {
props[ prop ] = cot.color.getHex();
}
}
}
break;
case 'shininess':
props[ prop ] = this[ prop ];
break;
case 'reflectivity':
props[ prop ] = this[ prop ];
if( props[ prop ] > 0.0 ) props['envMap'] = options.defaultEnvMap;
props['combine'] = THREE.MixOperation; //mix regular shading with reflective component
break;
case 'index_of_refraction':
props[ 'refractionRatio' ] = this[ prop ]; //TODO: "index_of_refraction" becomes "refractionRatio" in shader, but I'm not sure if the two are actually comparable
if ( this[ prop ] !== 1.0 ) props['envMap'] = options.defaultEnvMap;
break;
case 'transparency':
if ( transparent ) {
props[ 'transparent' ] = true;
props[ 'opacity' ] = this[ prop ];
transparent = true;
}
break;
default:
break;
}
}
props[ 'shading' ] = preferredShading;
props[ 'side' ] = this.effect.doubleSided ? THREE.DoubleSide : THREE.FrontSide;
switch ( this.type ) {
case 'constant':
if (props.emissive != undefined) props.color = props.emissive;
this.material = new THREE.MeshBasicMaterial( props );
break;
case 'phong':
case 'blinn':
if (props.diffuse != undefined) props.color = props.diffuse;
this.material = new THREE.MeshPhongMaterial( props );
break;
case 'lambert':
default:
if (props.diffuse != undefined) props.color = props.diffuse;
this.material = new THREE.MeshLambertMaterial( props );
break;
}
return this.material;
};
function Surface ( effect ) {
this.effect = effect;
this.init_from = null;
this.format = null;
};
Surface.prototype.parse = function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'init_from':
this.init_from = child.textContent;
break;
case 'format':
this.format = child.textContent;
break;
default:
console.log( "unhandled Surface prop: " + child.nodeName );
break;
}
}
return this;
};
function Sampler2D ( effect ) {
this.effect = effect;
this.source = null;
this.wrap_s = null;
this.wrap_t = null;
this.minfilter = null;
this.magfilter = null;
this.mipfilter = null;
};
Sampler2D.prototype.parse = function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'source':
this.source = child.textContent;
break;
case 'minfilter':
this.minfilter = child.textContent;
break;
case 'magfilter':
this.magfilter = child.textContent;
break;
case 'mipfilter':
this.mipfilter = child.textContent;
break;
case 'wrap_s':
this.wrap_s = child.textContent;
break;
case 'wrap_t':
this.wrap_t = child.textContent;
break;
default:
console.log( "unhandled Sampler2D prop: " + child.nodeName );
break;
}
}
return this;
};
function Effect () {
this.id = "";
this.name = "";
this.shader = null;
this.surface = {};
this.sampler = {};
};
Effect.prototype.create = function () {
if ( this.shader == null ) {
return null;
}
};
Effect.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
this.name = element.getAttribute( 'name' );
extractDoubleSided( this, element );
this.shader = null;
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'profile_COMMON':
this.parseTechnique( this.parseProfileCOMMON( child ) );
break;
default:
break;
}
}
return this;
};
Effect.prototype.parseNewparam = function ( element ) {
var sid = element.getAttribute( 'sid' );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'surface':
this.surface[sid] = ( new Surface( this ) ).parse( child );
break;
case 'sampler2D':
this.sampler[sid] = ( new Sampler2D( this ) ).parse( child );
break;
case 'extra':
break;
default:
console.log( child.nodeName );
break;
}
}
};
Effect.prototype.parseProfileCOMMON = function ( element ) {
var technique;
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'profile_COMMON':
this.parseProfileCOMMON( child );
break;
case 'technique':
technique = child;
break;
case 'newparam':
this.parseNewparam( child );
break;
case 'image':
var _image = ( new _Image() ).parse( child );
images[ _image.id ] = _image;
break;
case 'extra':
break;
default:
console.log( child.nodeName );
break;
}
}
return technique;
};
Effect.prototype.parseTechnique= function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[i];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'constant':
case 'lambert':
case 'blinn':
case 'phong':
this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
break;
default:
break;
}
}
};
function InstanceEffect () {
this.url = "";
};
InstanceEffect.prototype.parse = function ( element ) {
this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
return this;
};
function Animation() {
this.id = "";
this.name = "";
this.source = {};
this.sampler = [];
this.channel = [];
};
Animation.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
this.name = element.getAttribute( 'name' );
this.source = {};
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'animation':
var anim = ( new Animation() ).parse( child );
for ( var src in anim.source ) {
this.source[ src ] = anim.source[ src ];
}
for ( var j = 0; j < anim.channel.length; j ++ ) {
this.channel.push( anim.channel[ j ] );
this.sampler.push( anim.sampler[ j ] );
}
break;
case 'source':
var src = ( new Source() ).parse( child );
this.source[ src.id ] = src;
break;
case 'sampler':
this.sampler.push( ( new Sampler( this ) ).parse( child ) );
break;
case 'channel':
this.channel.push( ( new Channel( this ) ).parse( child ) );
break;
default:
break;
}
}
return this;
};
function Channel( animation ) {
this.animation = animation;
this.source = "";
this.target = "";
this.fullSid = null;
this.sid = null;
this.dotSyntax = null;
this.arrSyntax = null;
this.arrIndices = null;
this.member = null;
};
Channel.prototype.parse = function ( element ) {
this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
this.target = element.getAttribute( 'target' );
var parts = this.target.split( '/' );
var id = parts.shift();
var sid = parts.shift();
var dotSyntax = ( sid.indexOf(".") >= 0 );
var arrSyntax = ( sid.indexOf("(") >= 0 );
if ( dotSyntax ) {
parts = sid.split(".");
this.sid = parts.shift();
this.member = parts.shift();
} else if ( arrSyntax ) {
var arrIndices = sid.split("(");
this.sid = arrIndices.shift();
for (var j = 0; j < arrIndices.length; j ++ ) {
arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
}
this.arrIndices = arrIndices;
} else {
this.sid = sid;
}
this.fullSid = sid;
this.dotSyntax = dotSyntax;
this.arrSyntax = arrSyntax;
return this;
};
function Sampler ( animation ) {
this.id = "";
this.animation = animation;
this.inputs = [];
this.input = null;
this.output = null;
this.strideOut = null;
this.interpolation = null;
this.startTime = null;
this.endTime = null;
this.duration = 0;
};
Sampler.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
this.inputs = [];
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'input':
this.inputs.push( (new Input()).parse( child ) );
break;
default:
break;
}
}
return this;
};
Sampler.prototype.create = function () {
for ( var i = 0; i < this.inputs.length; i ++ ) {
var input = this.inputs[ i ];
var source = this.animation.source[ input.source ];
switch ( input.semantic ) {
case 'INPUT':
this.input = source.read();
break;
case 'OUTPUT':
this.output = source.read();
this.strideOut = source.accessor.stride;
break;
case 'INTERPOLATION':
this.interpolation = source.read();
break;
case 'IN_TANGENT':
break;
case 'OUT_TANGENT':
break;
default:
console.log(input.semantic);
break;
}
}
this.startTime = 0;
this.endTime = 0;
this.duration = 0;
if ( this.input.length ) {
this.startTime = 100000000;
this.endTime = -100000000;
for ( var i = 0; i < this.input.length; i ++ ) {
this.startTime = Math.min( this.startTime, this.input[ i ] );
this.endTime = Math.max( this.endTime, this.input[ i ] );
}
this.duration = this.endTime - this.startTime;
}
};
Sampler.prototype.getData = function ( type, ndx ) {
var data;
if ( type === 'matrix' && this.strideOut === 16 ) {
data = this.output[ ndx ];
} else if ( this.strideOut > 1 ) {
data = [];
ndx *= this.strideOut;
for ( var i = 0; i < this.strideOut; ++i ) {
data[ i ] = this.output[ ndx + i ];
}
if ( this.strideOut === 3 ) {
switch ( type ) {
case 'rotate':
case 'translate':
fixCoords( data, -1 );
break;
case 'scale':
fixCoords( data, 1 );
break;
}
} else if ( this.strideOut === 4 && type === 'matrix' ) {
fixCoords( data, -1 );
}
} else {
data = this.output[ ndx ];
}
return data;
};
function Key ( time ) {
this.targets = [];
this.time = time;
};
Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
this.targets.push( {
sid: fullSid,
member: member,
transform: transform,
data: data
} );
};
Key.prototype.apply = function ( opt_sid ) {
for ( var i = 0; i < this.targets.length; ++i ) {
var target = this.targets[ i ];
if ( !opt_sid || target.sid === opt_sid ) {
target.transform.update( target.data, target.member );
}
}
};
Key.prototype.getTarget = function ( fullSid ) {
for ( var i = 0; i < this.targets.length; ++i ) {
if ( this.targets[ i ].sid === fullSid ) {
return this.targets[ i ];
}
}
return null;
};
Key.prototype.hasTarget = function ( fullSid ) {
for ( var i = 0; i < this.targets.length; ++i ) {
if ( this.targets[ i ].sid === fullSid ) {
return true;
}
}
return false;
};
// TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
Key.prototype.interpolate = function ( nextKey, time ) {
for ( var i = 0; i < this.targets.length; ++i ) {
var target = this.targets[ i ],
nextTarget = nextKey.getTarget( target.sid ),
data;
if ( target.transform.type !== 'matrix' && nextTarget ) {
var scale = ( time - this.time ) / ( nextKey.time - this.time ),
nextData = nextTarget.data,
prevData = target.data;
// check scale error
if ( scale < 0 || scale > 1 ) {
console.log( "Key.interpolate: Warning! Scale out of bounds:" + scale );
scale = scale < 0 ? 0 : 1;
}
if ( prevData.length ) {
data = [];
for ( var j = 0; j < prevData.length; ++j ) {
data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
}
} else {
data = prevData + ( nextData - prevData ) * scale;
}
} else {
data = target.data;
}
target.transform.update( data, target.member );
}
};
// Camera
function Camera() {
this.id = "";
this.name = "";
this.technique = "";
};
Camera.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
this.name = element.getAttribute( 'name' );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'optics':
this.parseOptics( child );
break;
}
}
return this;
};
Camera.prototype.parseOptics = function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
if ( element.childNodes[ i ].nodeName == 'technique_common' ) {
var technique = element.childNodes[ i ];
for ( var j = 0; j < technique.childNodes.length; j ++ ) {
this.technique = technique.childNodes[ j ].nodeName;
if ( this.technique == 'perspective' ) {
var perspective = technique.childNodes[ j ];
for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
var param = perspective.childNodes[ k ];
switch ( param.nodeName ) {
case 'yfov':
this.yfov = param.textContent;
break;
case 'xfov':
this.xfov = param.textContent;
break;
case 'znear':
this.znear = param.textContent;
break;
case 'zfar':
this.zfar = param.textContent;
break;
case 'aspect_ratio':
this.aspect_ratio = param.textContent;
break;
}
}
} else if ( this.technique == 'orthographic' ) {
var orthographic = technique.childNodes[ j ];
for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
var param = orthographic.childNodes[ k ];
switch ( param.nodeName ) {
case 'xmag':
this.xmag = param.textContent;
break;
case 'ymag':
this.ymag = param.textContent;
break;
case 'znear':
this.znear = param.textContent;
break;
case 'zfar':
this.zfar = param.textContent;
break;
case 'aspect_ratio':
this.aspect_ratio = param.textContent;
break;
}
}
}
}
}
}
return this;
};
function InstanceCamera() {
this.url = "";
};
InstanceCamera.prototype.parse = function ( element ) {
this.url = element.getAttribute('url').replace(/^#/, '');
return this;
};
// Light
function Light() {
this.id = "";
this.name = "";
this.technique = "";
};
Light.prototype.parse = function ( element ) {
this.id = element.getAttribute( 'id' );
this.name = element.getAttribute( 'name' );
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
if ( child.nodeType != 1 ) continue;
switch ( child.nodeName ) {
case 'technique_common':
this.parseTechnique( child );
break;
}
}
return this;
};
Light.prototype.parseTechnique = function ( element ) {
for ( var i = 0; i < element.childNodes.length; i ++ ) {
var child = element.childNodes[ i ];
switch ( child.nodeName ) {
case 'ambient':
case 'point':
case 'directional':
this.technique = child.nodeName;
for ( var k = 0; k < child.childNodes.length; k ++ ) {
var param = child.childNodes[ k ];
switch ( param.nodeName ) {
case 'color':
var vector = new THREE.Vector3().fromArray( _floats( param.textContent ) );
this.color = new THREE.Color().setRGB( vector.x, vector.y, vector.z );
break;
}
}
break;
}
}
};
function InstanceLight() {
this.url = "";
};
InstanceLight.prototype.parse = function ( element ) {
this.url = element.getAttribute('url').replace(/^#/, '');
return this;
};
function _source( element ) {
var id = element.getAttribute( 'id' );
if ( sources[ id ] != undefined ) {
return sources[ id ];
}
sources[ id ] = ( new Source(id )).parse( element );
return sources[ id ];
};
function _nsResolver( nsPrefix ) {
if ( nsPrefix == "dae" ) {
return "http://www.collada.org/2005/11/COLLADASchema";
}
return null;
};
function _bools( str ) {
var raw = _strings( str );
var data = [];
for ( var i = 0, l = raw.length; i < l; i ++ ) {
data.push( (raw[i] == 'true' || raw[i] == '1') ? true : false );
}
return data;
};
function _floats( str ) {
var raw = _strings(str);
var data = [];
for ( var i = 0, l = raw.length; i < l; i ++ ) {
data.push( parseFloat( raw[ i ] ) );
}
return data;
};
function _ints( str ) {
var raw = _strings( str );
var data = [];
for ( var i = 0, l = raw.length; i < l; i ++ ) {
data.push( parseInt( raw[ i ], 10 ) );
}
return data;
};
function _strings( str ) {
return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
};
function _trimString( str ) {
return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
};
function _attr_as_float( element, name, defaultValue ) {
if ( element.hasAttribute( name ) ) {
return parseFloat( element.getAttribute( name ) );
} else {
return defaultValue;
}
};
function _attr_as_int( element, name, defaultValue ) {
if ( element.hasAttribute( name ) ) {
return parseInt( element.getAttribute( name ), 10) ;
} else {
return defaultValue;
}
};
function _attr_as_string( element, name, defaultValue ) {
if ( element.hasAttribute( name ) ) {
return element.getAttribute( name );
} else {
return defaultValue;
}
};
function _format_float( f, num ) {
if ( f === undefined ) {
var s = '0.';
while ( s.length < num + 2 ) {
s += '0';
}
return s;
}
num = num || 2;
var parts = f.toString().split( '.' );
parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
while( parts[ 1 ].length < num ) {
parts[ 1 ] += '0';
}
return parts.join( '.' );
};
function evaluateXPath( node, query ) {
var instances = COLLADA.evaluate( query, node, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
var inst = instances.iterateNext();
var result = [];
while ( inst ) {
result.push( inst );
inst = instances.iterateNext();
}
return result;
};
function extractDoubleSided( obj, element ) {
obj.doubleSided = false;
var node = COLLADA.evaluate( './/dae:extra//dae:double_sided', element, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
if ( node ) {
node = node.iterateNext();
if ( node && parseInt( node.textContent, 10 ) === 1 ) {
obj.doubleSided = true;
}
}
};
// Up axis conversion
function setUpConversion() {
if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
upConversion = null;
} else {
switch ( colladaUp ) {
case 'X':
upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
break;
case 'Y':
upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
break;
case 'Z':
upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
break;
}
}
};
function fixCoords( data, sign ) {
if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
return;
}
switch ( upConversion ) {
case 'XtoY':
var tmp = data[ 0 ];
data[ 0 ] = sign * data[ 1 ];
data[ 1 ] = tmp;
break;
case 'XtoZ':
var tmp = data[ 2 ];
data[ 2 ] = data[ 1 ];
data[ 1 ] = data[ 0 ];
data[ 0 ] = tmp;
break;
case 'YtoX':
var tmp = data[ 0 ];
data[ 0 ] = data[ 1 ];
data[ 1 ] = sign * tmp;
break;
case 'YtoZ':
var tmp = data[ 1 ];
data[ 1 ] = sign * data[ 2 ];
data[ 2 ] = tmp;
break;
case 'ZtoX':
var tmp = data[ 0 ];
data[ 0 ] = data[ 1 ];
data[ 1 ] = data[ 2 ];
data[ 2 ] = tmp;
break;
case 'ZtoY':
var tmp = data[ 1 ];
data[ 1 ] = data[ 2 ];
data[ 2 ] = sign * tmp;
break;
}
};
function getConvertedVec3( data, offset ) {
var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
fixCoords( arr, -1 );
return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
};
function getConvertedMat4( data ) {
if ( options.convertUpAxis ) {
// First fix rotation and scale
// Columns first
var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
fixCoords( arr, -1 );
data[ 0 ] = arr[ 0 ];
data[ 4 ] = arr[ 1 ];
data[ 8 ] = arr[ 2 ];
arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
fixCoords( arr, -1 );
data[ 1 ] = arr[ 0 ];
data[ 5 ] = arr[ 1 ];
data[ 9 ] = arr[ 2 ];
arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
fixCoords( arr, -1 );
data[ 2 ] = arr[ 0 ];
data[ 6 ] = arr[ 1 ];
data[ 10 ] = arr[ 2 ];
// Rows second
arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
fixCoords( arr, -1 );
data[ 0 ] = arr[ 0 ];
data[ 1 ] = arr[ 1 ];
data[ 2 ] = arr[ 2 ];
arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
fixCoords( arr, -1 );
data[ 4 ] = arr[ 0 ];
data[ 5 ] = arr[ 1 ];
data[ 6 ] = arr[ 2 ];
arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
fixCoords( arr, -1 );
data[ 8 ] = arr[ 0 ];
data[ 9 ] = arr[ 1 ];
data[ 10 ] = arr[ 2 ];
// Now fix translation
arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
fixCoords( arr, -1 );
data[ 3 ] = arr[ 0 ];
data[ 7 ] = arr[ 1 ];
data[ 11 ] = arr[ 2 ];
}
return new THREE.Matrix4(
data[0], data[1], data[2], data[3],
data[4], data[5], data[6], data[7],
data[8], data[9], data[10], data[11],
data[12], data[13], data[14], data[15]
);
};
function getConvertedIndex( index ) {
if ( index > -1 && index < 3 ) {
var members = ['X', 'Y', 'Z'],
indices = { X: 0, Y: 1, Z: 2 };
index = getConvertedMember( members[ index ] );
index = indices[ index ];
}
return index;
};
function getConvertedMember( member ) {
if ( options.convertUpAxis ) {
switch ( member ) {
case 'X':
switch ( upConversion ) {
case 'XtoY':
case 'XtoZ':
case 'YtoX':
member = 'Y';
break;
case 'ZtoX':
member = 'Z';
break;
}
break;
case 'Y':
switch ( upConversion ) {
case 'XtoY':
case 'YtoX':
case 'ZtoX':
member = 'X';
break;
case 'XtoZ':
case 'YtoZ':
case 'ZtoY':
member = 'Z';
break;
}
break;
case 'Z':
switch ( upConversion ) {
case 'XtoZ':
member = 'X';
break;
case 'YtoZ':
case 'ZtoX':
case 'ZtoY':
member = 'Y';
break;
}
break;
}
}
return member;
};
return {
load: load,
parse: parse,
setPreferredShading: setPreferredShading,
applySkin: applySkin,
geometries : geometries,
options: options
};
};
|
define(['exports'], function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var App = exports.App = function () {
function App() {
_classCallCheck(this, App);
this.firstName = 'John';
this.lastName = 'Doe';
}
App.prototype.mouseMove = function mouseMove(e) {
this.mouseX = e.clientX;
this.mouseY = e.clientY;
};
App.prototype.mouseMove200 = function mouseMove200(e) {
this.mouse200X = e.clientX;
this.mouse200Y = e.clientY;
};
App.prototype.mouseMove800 = function mouseMove800(e) {
this.mouse800X = e.clientX;
this.mouse800Y = e.clientY;
};
return App;
}();
}); |
'use strict';
module.exports = function renderMenu(props) {
if (!props.menu) {
return;
}
return props.menu({
className: 'z-header-menu-column',
gridColumns: props.columns
});
}; |
( function ( $ ) {
'use strict';
var asInScript2 = {
id: 'as-inscript2',
name: 'ইনস্ক্ৰিপ্ট ২',
description: 'Enhanced InScript keyboard for Assamese language',
date: '2013-02-09',
URL: 'http://github.com/wikimedia/jquery.ime',
author: 'Parag Nemade',
license: 'GPLv3',
version: '1.0',
patterns: [
[ '\\!', 'অ্যা' ],
[ '1', '১' ],
[ '2', '২' ],
[ '\\#', '্ৰ' ],
[ '3', '৩' ],
[ '\\$', 'ৰ্' ],
[ '4', '৪' ],
[ '\\%', 'জ্ঞ' ],
[ '5', '৫' ],
[ '\\^', 'ত্র' ],
[ '6', '৬' ],
[ '\\&', 'ক্ষ' ],
[ '7', '৭' ],
[ '\\*', 'শ্র' ],
[ '8', '৮' ],
[ '9', '৯' ],
[ '\\(', '(' ],
[ '\\)', ')' ],
[ '0', '০' ],
[ '\"', 'ঠ' ],
[ '\'', 'ট' ],
[ ',', ',' ],
[ '-', '-' ],
[ '\\.', '.' ],
[ '/', 'য়' ],
[ ':', 'ছ' ],
[ ';', 'চ' ],
[ '\\<', 'ষ' ],
[ '\\=', 'ৃ' ],
[ '\\+', 'ঋ' ],
[ '\\>', '।' ],
[ '\\?', 'য' ],
[ 'A', 'ও' ],
[ 'C', 'ণ' ],
[ 'D', 'অ' ],
[ 'E', 'আ' ],
[ 'F', 'ই' ],
[ 'G', 'উ' ],
[ 'H', 'ফ' ],
[ 'I', 'ঘ' ],
[ 'K', 'খ' ],
[ 'L', 'থ' ],
[ 'M', 'শ' ],
[ 'O', 'ধ' ],
[ 'P', 'ঝ' ],
[ 'Q', 'ঔ' ],
[ 'R', 'ঈ' ],
[ 'S', 'এ' ],
[ 'T', 'ঊ' ],
[ 'U', 'ঙ' ],
[ 'W', 'ঐ' ],
[ 'X', 'ঁ' ],
[ 'Y', 'ভ' ],
[ '\\{', 'ঢ' ],
[ '\\[', 'ড' ],
[ '\\}', 'ঞ' ],
[ '\\]', '়' ],
[ '\\_', 'ঃ' ],
[ 'a', 'ো' ],
[ 'b', 'ৱ' ],
[ 'c', 'ম' ],
[ 'd', '্' ],
[ 'e', 'া' ],
[ 'f', 'ি' ],
[ 'g', 'ু' ],
[ 'h', 'প' ],
[ 'i', 'গ' ],
[ 'j', 'ৰ' ],
[ 'k', 'ক' ],
[ 'l', 'ত' ],
[ 'm', 'স' ],
[ 'n', 'ল' ],
[ 'o', 'দ' ],
[ 'p', 'জ' ],
[ 'q', 'ৌ' ],
[ 'r', 'ী' ],
[ 's', 'ে' ],
[ 't', 'ূ' ],
[ 'u', 'হ' ],
[ 'v', 'ন' ],
[ 'w', 'ৈ' ],
[ 'x', 'ং' ],
[ 'y', 'ব' ],
[ 'z', 'ʼ' ]
],
patterns_x: [
[ '\\!', '৴' ],
[ '1', '\u200d' ],
[ '\\@', '৵' ],
[ '2', '\u200c' ],
[ '\\#', '৶' ],
[ '\\$', '৷' ],
[ '4', '₹' ],
[ '\\%', '৸' ],
[ '\\^', '৹' ],
[ ',', '৳' ],
[ '\\.', '॥' ],
[ '/', '্য' ],
[ '\\<', '৲' ],
[ '\\=', 'ৄ' ],
[ '\\+', 'ৠ' ],
[ '\\>', 'ঽ' ],
[ 'F', 'ঌ' ],
[ 'R', 'ৡ' ],
[ '\\{', 'ঢ়' ],
[ '\\[', 'ড়' ],
[ 'f', 'ৢ' ],
[ 'l', 'ৎ' ],
[ 'r', 'ৣ' ],
[ 'x', '৺' ]
]
};
$.ime.register( asInScript2 );
}( jQuery ) );
|
var config = require('../config')
var gulp = require('gulp')
var gulpSequence = require('gulp-sequence')
var getEnabledTasks = require('../lib/getEnabledTasks')
var productionTask = function(cb) {
var tasks = getEnabledTasks('production')
gulpSequence('clean', tasks.assetTasks, tasks.codeTasks, 'rev', 'static', cb)
}
gulp.task('production', productionTask)
module.exports = productionTask
|
/* global SnippetedMessages */
Template.snippetedMessages.helpers({
hasMessages() {
return SnippetedMessages.find({ snippeted:true, rid: this.rid }, { sort: { ts: -1 } }).count() > 0;
},
messages() {
return SnippetedMessages.find({ snippeted: true, rid: this.rid }, { sort: { ts: -1 } });
},
message() {
return _.extend(this, { customClass: 'snippeted' });
},
hasMore() {
return Template.instance().hasMore.get();
}
});
Template.snippetedMessages.onCreated(function() {
this.hasMore = new ReactiveVar(true);
this.limit = new ReactiveVar(50);
const self = this;
this.autorun(function() {
const data = Template.currentData();
self.subscribe('snippetedMessages', data.rid, self.limit.get(), function() {
if (SnippetedMessages.find({ snippeted: true, rid: data.rid }).count() < self.limit.get()) {
return self.hasMore.set(false);
}
});
});
});
|
'use strict';
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = require('./shams');
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
|
// # Update Checking Service
//
// Makes a request to Ghost.org to check if there is a new version of Ghost available.
// The service is provided in return for users opting in to anonymous usage data collection.
//
// Blog owners can opt-out of update checks by setting `privacy: { useUpdateCheck: false }` in their config.js
//
// The data collected is as follows:
//
// - blog id - a hash of the blog hostname, pathname and dbHash. No identifiable info is stored.
// - ghost version
// - node version
// - npm version
// - env - production or development
// - database type - SQLite, MySQL, PostgreSQL
// - email transport - mail.options.service, or otherwise mail.transport
// - created date - database creation date
// - post count - total number of posts
// - user count - total number of users
// - theme - name of the currently active theme
// - apps - names of any active apps
var crypto = require('crypto'),
exec = require('child_process').exec,
https = require('http'),
moment = require('moment'),
semver = require('semver'),
Promise = require('bluebird'),
_ = require('lodash'),
url = require('url'),
api = require('./api'),
config = require('./config'),
errors = require('./errors'),
internal = {context: {internal: true}},
allowedCheckEnvironments = ['development', 'production'],
checkEndpoint = 'updates.ghostchina.com',
currentVersion = config.ghostVersion;
function updateCheckError(error) {
api.settings.edit(
{settings: [{key: 'nextUpdateCheck', value: Math.round(Date.now() / 1000 + 24 * 3600)}]},
internal
).catch(errors.rejectError);
errors.logError(
error,
'Checking for updates failed, your blog will continue to function.',
'If you get this error repeatedly, please seek help from https://ghost.org/forum.'
);
}
function updateCheckData() {
var data = {},
ops = [],
mailConfig = config.mail;
ops.push(api.settings.read(_.extend({key: 'dbHash'}, internal)).catch(errors.rejectError));
ops.push(api.settings.read(_.extend({key: 'activeTheme'}, internal)).catch(errors.rejectError));
ops.push(api.settings.read(_.extend({key: 'activeApps'}, internal))
.then(function (response) {
var apps = response.settings[0];
try {
apps = JSON.parse(apps.value);
} catch (e) {
return errors.rejectError(e);
}
return _.reduce(apps, function (memo, item) { return memo === '' ? memo + item : memo + ', ' + item; }, '');
}).catch(errors.rejectError));
ops.push(api.posts.browse().catch(errors.rejectError));
ops.push(api.users.browse(internal).catch(errors.rejectError));
ops.push(Promise.promisify(exec)('npm -v').catch(errors.rejectError));
data.ghost_version = currentVersion;
data.node_version = process.versions.node;
data.env = process.env.NODE_ENV;
data.database_type = config.database.client;
data.email_transport = mailConfig && (mailConfig.options && mailConfig.options.service ? mailConfig.options.service : mailConfig.transport);
return Promise.settle(ops).then(function (descriptors) {
var hash = descriptors[0].value().settings[0],
theme = descriptors[1].value().settings[0],
apps = descriptors[2].value(),
posts = descriptors[3].value(),
users = descriptors[4].value(),
npm = descriptors[5].value(),
blogUrl = url.parse(config.url),
blogId = blogUrl.hostname + blogUrl.pathname.replace(/\//, '') + hash.value;
data.blog_id = crypto.createHash('md5').update(blogId).digest('hex');
data.theme = theme ? theme.value : '';
data.apps = apps || '';
data.post_count = posts && posts.meta && posts.meta.pagination ? posts.meta.pagination.total : 0;
data.user_count = users && users.users && users.users.length ? users.users.length : 0;
data.blog_created_at = users && users.users && users.users[0] && users.users[0].created_at ? moment(users.users[0].created_at).unix() : '';
data.npm_version = _.isArray(npm) && npm[0] ? npm[0].toString().replace(/\n/, '') : '';
data.storage = (config.storage && config.storage.provider) || 'local-file-store';
data.blog_url = config.url;
return data;
}).catch(updateCheckError);
}
function updateCheckRequest() {
return updateCheckData().then(function then(reqData) {
var resData = '',
headers,
req;
reqData = JSON.stringify(reqData);
headers = {
'Content-Length': reqData.length
};
return new Promise(function p(resolve, reject) {
req = https.request({
hostname: checkEndpoint,
method: 'POST',
headers: headers
}, function handler(res) {
res.on('error', function onError(error) { reject(error); });
res.on('data', function onData(chunk) { resData += chunk; });
res.on('end', function onEnd() {
try {
resData = JSON.parse(resData);
resolve(resData);
} catch (e) {
reject('Unable to decode update response');
}
});
});
req.on('socket', function onSocket(socket) {
// Wait a maximum of 10seconds
socket.setTimeout(10000);
socket.on('timeout', function onTimeout() {
req.abort();
});
});
req.on('error', function onError(error) {
reject(error);
});
req.write(reqData);
req.end();
});
});
}
// ## Update Check Response
// Handles the response from the update check
// Does two things with the information received:
// 1. Updates the time we can next make a check
// 2. Checks if the version in the response is new, and updates the notification setting
function updateCheckResponse(response) {
var ops = [];
ops.push(
api.settings.edit(
{settings: [{key: 'nextUpdateCheck', value: response.next_check}]},
internal
).catch(errors.rejectError),
api.settings.edit(
{settings: [{key: 'displayUpdateNotification', value: response.version}]},
internal
).catch(errors.rejectError)
);
return Promise.settle(ops).then(function then(descriptors) {
descriptors.forEach(function forEach(d) {
if (d.isRejected()) {
errors.rejectError(d.reason());
}
});
});
}
function updateCheck() {
// The check will not happen if:
// 1. updateCheck is defined as false in config.js
// 2. we've already done a check this session
// 3. we're not in production or development mode
// TODO: need to remove config.updateCheck in favor of config.privacy.updateCheck in future version (it is now deprecated)
if (config.updateCheck === false || config.isPrivacyDisabled('useUpdateCheck') || _.indexOf(allowedCheckEnvironments, process.env.NODE_ENV) === -1) {
// No update check
return Promise.resolve();
} else {
return api.settings.read(_.extend({key: 'nextUpdateCheck'}, internal)).then(function then(result) {
var nextUpdateCheck = result.settings[0];
if (nextUpdateCheck && nextUpdateCheck.value && nextUpdateCheck.value > moment().unix()) {
// It's not time to check yet
return;
} else {
// We need to do a check
return updateCheckRequest()
.then(updateCheckResponse)
.catch(updateCheckError);
}
}).catch(updateCheckError);
}
}
function showUpdateNotification() {
return api.settings.read(_.extend({key: 'displayUpdateNotification'}, internal)).then(function then(response) {
var display = response.settings[0];
// Version 0.4 used boolean to indicate the need for an update. This special case is
// translated to the version string.
// TODO: remove in future version.
if (display.value === 'false' || display.value === 'true' || display.value === '1' || display.value === '0') {
display.value = '0.4.0';
}
if (display && display.value && currentVersion && semver.gt(display.value, currentVersion)) {
return display.value;
}
return false;
});
}
module.exports = updateCheck;
module.exports.showUpdateNotification = showUpdateNotification;
|
/**
* lodash 3.0.3 (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** `Object#toString` result references. */
var boolTag = '[object Boolean]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* Checks if `value` is classified as a boolean primitive or object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isBoolean(false);
* // => true
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return value === true || value === false ||
(isObjectLike(value) && objectToString.call(value) == boolTag);
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
module.exports = isBoolean;
|
/*
* Foundation Responsive Library
* http://foundation.zurb.com
* Copyright 2015, ZURB
* Free to use under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*/
(function ($, window, document, undefined) {
'use strict';
var header_helpers = function (class_array) {
var head = $('head');
head.prepend($.map(class_array, function (class_name) {
if (head.has('.' + class_name).length === 0) {
return '<meta class="' + class_name + '" />';
}
}));
};
header_helpers([
'foundation-mq-small',
'foundation-mq-small-only',
'foundation-mq-medium',
'foundation-mq-medium-only',
'foundation-mq-large',
'foundation-mq-large-only',
'foundation-mq-xlarge',
'foundation-mq-xlarge-only',
'foundation-mq-xxlarge',
'foundation-data-attribute-namespace']);
// Enable FastClick if present
$(function () {
if (typeof FastClick !== 'undefined') {
// Don't attach to body if undefined
if (typeof document.body !== 'undefined') {
FastClick.attach(document.body);
}
}
});
// private Fast Selector wrapper,
// returns jQuery object. Only use where
// getElementById is not available.
var S = function (selector, context) {
if (typeof selector === 'string') {
if (context) {
var cont;
if (context.jquery) {
cont = context[0];
if (!cont) {
return context;
}
} else {
cont = context;
}
return $(cont.querySelectorAll(selector));
}
return $(document.querySelectorAll(selector));
}
return $(selector, context);
};
// Namespace functions.
var attr_name = function (init) {
var arr = [];
if (!init) {
arr.push('data');
}
if (this.namespace.length > 0) {
arr.push(this.namespace);
}
arr.push(this.name);
return arr.join('-');
};
var add_namespace = function (str) {
var parts = str.split('-'),
i = parts.length,
arr = [];
while (i--) {
if (i !== 0) {
arr.push(parts[i]);
} else {
if (this.namespace.length > 0) {
arr.push(this.namespace, parts[i]);
} else {
arr.push(parts[i]);
}
}
}
return arr.reverse().join('-');
};
// Event binding and data-options updating.
var bindings = function (method, options) {
var self = this,
bind = function(){
var $this = S(this),
should_bind_events = !S(self).data(self.attr_name(true) + '-init');
$this.data(self.attr_name(true) + '-init', $.extend({}, self.settings, (options || method), self.data_options($this)));
if (should_bind_events) {
self.events(this);
}
};
if (S(this.scope).is('[' + this.attr_name() +']')) {
bind.call(this.scope);
} else {
S('[' + this.attr_name() +']', this.scope).each(bind);
}
// # Patch to fix #5043 to move this *after* the if/else clause in order for Backbone and similar frameworks to have improved control over event binding and data-options updating.
if (typeof method === 'string') {
return this[method].call(this, options);
}
};
var single_image_loaded = function (image, callback) {
function loaded () {
callback(image[0]);
}
function bindLoad () {
this.one('load', loaded);
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
var src = this.attr( 'src' ),
param = src.match( /\?/ ) ? '&' : '?';
param += 'random=' + (new Date()).getTime();
this.attr('src', src + param);
}
}
if (!image.attr('src')) {
loaded();
return;
}
if (image[0].complete || image[0].readyState === 4) {
loaded();
} else {
bindLoad.call(image);
}
};
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas, David Knight. Dual MIT/BSD license */
window.matchMedia || (window.matchMedia = function() {
"use strict";
// For browsers that support matchMedium api such as IE 9 and webkit
var styleMedia = (window.styleMedia || window.media);
// For those that don't support matchMedium
if (!styleMedia) {
var style = document.createElement('style'),
script = document.getElementsByTagName('script')[0],
info = null;
style.type = 'text/css';
style.id = 'matchmediajs-test';
script.parentNode.insertBefore(style, script);
// 'style.currentStyle' is used by IE <= 8 and 'window.getComputedStyle' for all other browsers
info = ('getComputedStyle' in window) && window.getComputedStyle(style, null) || style.currentStyle;
styleMedia = {
matchMedium: function(media) {
var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }';
// 'style.styleSheet' is used by IE <= 8 and 'style.textContent' for all other browsers
if (style.styleSheet) {
style.styleSheet.cssText = text;
} else {
style.textContent = text;
}
// Test if media query is true or false
return info.width === '1px';
}
};
}
return function(media) {
return {
matches: styleMedia.matchMedium(media || 'all'),
media: media || 'all'
};
};
}());
/*
* jquery.requestAnimationFrame
* https://github.com/gnarf37/jquery-requestAnimationFrame
* Requires jQuery 1.8+
*
* Copyright (c) 2012 Corey Frang
* Licensed under the MIT license.
*/
(function(jQuery) {
// requestAnimationFrame polyfill adapted from Erik Möller
// fixes from Paul Irish and Tino Zijdel
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
var animating,
lastTime = 0,
vendors = ['webkit', 'moz'],
requestAnimationFrame = window.requestAnimationFrame,
cancelAnimationFrame = window.cancelAnimationFrame,
jqueryFxAvailable = 'undefined' !== typeof jQuery.fx;
for (; lastTime < vendors.length && !requestAnimationFrame; lastTime++) {
requestAnimationFrame = window[ vendors[lastTime] + 'RequestAnimationFrame' ];
cancelAnimationFrame = cancelAnimationFrame ||
window[ vendors[lastTime] + 'CancelAnimationFrame' ] ||
window[ vendors[lastTime] + 'CancelRequestAnimationFrame' ];
}
function raf() {
if (animating) {
requestAnimationFrame(raf);
if (jqueryFxAvailable) {
jQuery.fx.tick();
}
}
}
if (requestAnimationFrame) {
// use rAF
window.requestAnimationFrame = requestAnimationFrame;
window.cancelAnimationFrame = cancelAnimationFrame;
if (jqueryFxAvailable) {
jQuery.fx.timer = function (timer) {
if (timer() && jQuery.timers.push(timer) && !animating) {
animating = true;
raf();
}
};
jQuery.fx.stop = function () {
animating = false;
};
}
} else {
// polyfill
window.requestAnimationFrame = function (callback) {
var currTime = new Date().getTime(),
timeToCall = Math.max(0, 16 - (currTime - lastTime)),
id = window.setTimeout(function () {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
window.cancelAnimationFrame = function (id) {
clearTimeout(id);
};
}
}( $ ));
function removeQuotes (string) {
if (typeof string === 'string' || string instanceof String) {
string = string.replace(/^['\\/"]+|(;\s?})+|['\\/"]+$/g, '');
}
return string;
}
function MediaQuery(selector) {
this.selector = selector;
this.query = '';
}
MediaQuery.prototype.toString = function () {
return this.query || (this.query = S(this.selector).css('font-family').replace(/^[\/\\'"]+|(;\s?})+|[\/\\'"]+$/g, ''));
};
window.Foundation = {
name : 'Foundation',
version : '{{VERSION}}',
media_queries : {
'small' : new MediaQuery('.foundation-mq-small'),
'small-only' : new MediaQuery('.foundation-mq-small-only'),
'medium' : new MediaQuery('.foundation-mq-medium'),
'medium-only' : new MediaQuery('.foundation-mq-medium-only'),
'large' : new MediaQuery('.foundation-mq-large'),
'large-only' : new MediaQuery('.foundation-mq-large-only'),
'xlarge' : new MediaQuery('.foundation-mq-xlarge'),
'xlarge-only' : new MediaQuery('.foundation-mq-xlarge-only'),
'xxlarge' : new MediaQuery('.foundation-mq-xxlarge')
},
stylesheet : $('<style></style>').appendTo('head')[0].sheet,
global : {
namespace : undefined
},
init : function (scope, libraries, method, options, response) {
var args = [scope, method, options, response],
responses = [];
// check RTL
this.rtl = /rtl/i.test(S('html').attr('dir'));
// set foundation global scope
this.scope = scope || this.scope;
this.set_namespace();
if (libraries && typeof libraries === 'string' && !/reflow/i.test(libraries)) {
if (this.libs.hasOwnProperty(libraries)) {
responses.push(this.init_lib(libraries, args));
}
} else {
for (var lib in this.libs) {
responses.push(this.init_lib(lib, libraries));
}
}
S(window).on('load', function () {
S(window)
.trigger('resize.fndtn.clearing')
.trigger('resize.fndtn.dropdown')
.trigger('resize.fndtn.equalizer')
.trigger('resize.fndtn.interchange')
.trigger('resize.fndtn.joyride')
.trigger('resize.fndtn.magellan')
.trigger('resize.fndtn.topbar')
.trigger('resize.fndtn.slider');
});
return scope;
},
init_lib : function (lib, args) {
if (this.libs.hasOwnProperty(lib)) {
this.patch(this.libs[lib]);
if (args && args.hasOwnProperty(lib)) {
if (typeof this.libs[lib].settings !== 'undefined') {
$.extend(true, this.libs[lib].settings, args[lib]);
} else if (typeof this.libs[lib].defaults !== 'undefined') {
$.extend(true, this.libs[lib].defaults, args[lib]);
}
return this.libs[lib].init.apply(this.libs[lib], [this.scope, args[lib]]);
}
args = args instanceof Array ? args : new Array(args);
return this.libs[lib].init.apply(this.libs[lib], args);
}
return function () {};
},
patch : function (lib) {
lib.scope = this.scope;
lib.namespace = this.global.namespace;
lib.rtl = this.rtl;
lib['data_options'] = this.utils.data_options;
lib['attr_name'] = attr_name;
lib['add_namespace'] = add_namespace;
lib['bindings'] = bindings;
lib['S'] = this.utils.S;
},
inherit : function (scope, methods) {
var methods_arr = methods.split(' '),
i = methods_arr.length;
while (i--) {
if (this.utils.hasOwnProperty(methods_arr[i])) {
scope[methods_arr[i]] = this.utils[methods_arr[i]];
}
}
},
set_namespace : function () {
// Description:
// Don't bother reading the namespace out of the meta tag
// if the namespace has been set globally in javascript
//
// Example:
// Foundation.global.namespace = 'my-namespace';
// or make it an empty string:
// Foundation.global.namespace = '';
//
//
// If the namespace has not been set (is undefined), try to read it out of the meta element.
// Otherwise use the globally defined namespace, even if it's empty ('')
var namespace = ( this.global.namespace === undefined ) ? $('.foundation-data-attribute-namespace').css('font-family') : this.global.namespace;
// Finally, if the namsepace is either undefined or false, set it to an empty string.
// Otherwise use the namespace value.
this.global.namespace = ( namespace === undefined || /false/i.test(namespace) ) ? '' : namespace;
},
libs : {},
// methods that can be inherited in libraries
utils : {
// Description:
// Fast Selector wrapper returns jQuery object. Only use where getElementById
// is not available.
//
// Arguments:
// Selector (String): CSS selector describing the element(s) to be
// returned as a jQuery object.
//
// Scope (String): CSS selector describing the area to be searched. Default
// is document.
//
// Returns:
// Element (jQuery Object): jQuery object containing elements matching the
// selector within the scope.
S : S,
// Description:
// Executes a function a max of once every n milliseconds
//
// Arguments:
// Func (Function): Function to be throttled.
//
// Delay (Integer): Function execution threshold in milliseconds.
//
// Returns:
// Lazy_function (Function): Function with throttling applied.
throttle : function (func, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
if (timer == null) {
timer = setTimeout(function () {
func.apply(context, args);
timer = null;
}, delay);
}
};
},
// Description:
// Executes a function when it stops being invoked for n seconds
// Modified version of _.debounce() http://underscorejs.org
//
// Arguments:
// Func (Function): Function to be debounced.
//
// Delay (Integer): Function execution threshold in milliseconds.
//
// Immediate (Bool): Whether the function should be called at the beginning
// of the delay instead of the end. Default is false.
//
// Returns:
// Lazy_function (Function): Function with debouncing applied.
debounce : function (func, delay, immediate) {
var timeout, result;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, delay);
if (callNow) {
result = func.apply(context, args);
}
return result;
};
},
// Description:
// Parses data-options attribute
//
// Arguments:
// El (jQuery Object): Element to be parsed.
//
// Returns:
// Options (Javascript Object): Contents of the element's data-options
// attribute.
data_options : function (el, data_attr_name) {
data_attr_name = data_attr_name || 'options';
var opts = {}, ii, p, opts_arr,
data_options = function (el) {
var namespace = Foundation.global.namespace;
if (namespace.length > 0) {
return el.data(namespace + '-' + data_attr_name);
}
return el.data(data_attr_name);
};
var cached_options = data_options(el);
if (typeof cached_options === 'object') {
return cached_options;
}
opts_arr = (cached_options || ':').split(';');
ii = opts_arr.length;
function isNumber (o) {
return !isNaN (o - 0) && o !== null && o !== '' && o !== false && o !== true;
}
function trim (str) {
if (typeof str === 'string') {
return $.trim(str);
}
return str;
}
while (ii--) {
p = opts_arr[ii].split(':');
p = [p[0], p.slice(1).join(':')];
if (/true/i.test(p[1])) {
p[1] = true;
}
if (/false/i.test(p[1])) {
p[1] = false;
}
if (isNumber(p[1])) {
if (p[1].indexOf('.') === -1) {
p[1] = parseInt(p[1], 10);
} else {
p[1] = parseFloat(p[1]);
}
}
if (p.length === 2 && p[0].length > 0) {
opts[trim(p[0])] = trim(p[1]);
}
}
return opts;
},
// Description:
// Adds JS-recognizable media queries
//
// Arguments:
// Media (String): Key string for the media query to be stored as in
// Foundation.media_queries
//
// Class (String): Class name for the generated <meta> tag
register_media : function (media, media_class) {
if (Foundation.media_queries[media] === undefined) {
$('head').append('<meta class="' + media_class + '"/>');
Foundation.media_queries[media] = removeQuotes($('.' + media_class).css('font-family'));
}
},
// Description:
// Add custom CSS within a JS-defined media query
//
// Arguments:
// Rule (String): CSS rule to be appended to the document.
//
// Media (String): Optional media query string for the CSS rule to be
// nested under.
add_custom_rule : function (rule, media) {
if (media === undefined && Foundation.stylesheet) {
Foundation.stylesheet.insertRule(rule, Foundation.stylesheet.cssRules.length);
} else {
var query = Foundation.media_queries[media];
if (query !== undefined) {
Foundation.stylesheet.insertRule('@media ' +
Foundation.media_queries[media] + '{ ' + rule + ' }', Foundation.stylesheet.cssRules.length);
}
}
},
// Description:
// Performs a callback function when an image is fully loaded
//
// Arguments:
// Image (jQuery Object): Image(s) to check if loaded.
//
// Callback (Function): Function to execute when image is fully loaded.
image_loaded : function (images, callback) {
var self = this,
unloaded = images.length;
function pictures_has_height(images) {
var pictures_number = images.length;
for (var i = pictures_number - 1; i >= 0; i--) {
if(images.attr('height') === undefined) {
return false;
};
};
return true;
}
if (unloaded === 0 || pictures_has_height(images)) {
callback(images);
}
images.each(function () {
single_image_loaded(self.S(this), function () {
unloaded -= 1;
if (unloaded === 0) {
callback(images);
}
});
});
},
// Description:
// Returns a random, alphanumeric string
//
// Arguments:
// Length (Integer): Length of string to be generated. Defaults to random
// integer.
//
// Returns:
// Rand (String): Pseudo-random, alphanumeric string.
random_str : function () {
if (!this.fidx) {
this.fidx = 0;
}
this.prefix = this.prefix || [(this.name || 'F'), (+new Date).toString(36)].join('-');
return this.prefix + (this.fidx++).toString(36);
},
// Description:
// Helper for window.matchMedia
//
// Arguments:
// mq (String): Media query
//
// Returns:
// (Boolean): Whether the media query passes or not
match : function (mq) {
return window.matchMedia(mq).matches;
},
// Description:
// Helpers for checking Foundation default media queries with JS
//
// Returns:
// (Boolean): Whether the media query passes or not
is_small_up : function () {
return this.match(Foundation.media_queries.small);
},
is_medium_up : function () {
return this.match(Foundation.media_queries.medium);
},
is_large_up : function () {
return this.match(Foundation.media_queries.large);
},
is_xlarge_up : function () {
return this.match(Foundation.media_queries.xlarge);
},
is_xxlarge_up : function () {
return this.match(Foundation.media_queries.xxlarge);
},
is_small_only : function () {
return !this.is_medium_up() && !this.is_large_up() && !this.is_xlarge_up() && !this.is_xxlarge_up();
},
is_medium_only : function () {
return this.is_medium_up() && !this.is_large_up() && !this.is_xlarge_up() && !this.is_xxlarge_up();
},
is_large_only : function () {
return this.is_medium_up() && this.is_large_up() && !this.is_xlarge_up() && !this.is_xxlarge_up();
},
is_xlarge_only : function () {
return this.is_medium_up() && this.is_large_up() && this.is_xlarge_up() && !this.is_xxlarge_up();
},
is_xxlarge_only : function () {
return this.is_medium_up() && this.is_large_up() && this.is_xlarge_up() && this.is_xxlarge_up();
}
}
};
$.fn.foundation = function () {
var args = Array.prototype.slice.call(arguments, 0);
return this.each(function () {
Foundation.init.apply(Foundation, [this].concat(args));
return this;
});
};
}(jQuery, window, window.document));
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'newpage', 'da', {
toolbar: 'Ny side'
} );
|
export * from './calendar';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHVibGljX2FwaS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9hcHAvY29tcG9uZW50cy9jYWxlbmRhci9wdWJsaWNfYXBpLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLGNBQWMsWUFBWSxDQUFDIiwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0ICogZnJvbSAnLi9jYWxlbmRhcic7Il19 |
exports.BattleAbilities = {
"cutecharm": {
inherit: true,
onAfterDamage: function(damage, target, source, move) {
if (move && move.isContact) {
if (this.random(3) < 1) {
source.addVolatile('attract', target);
}
}
}
},
"effectspore": {
inherit: true,
onAfterDamage: function(damage, target, source, move) {
if (move && move.isContact && !source.status) {
var r = this.random(300);
if (r < 10) source.setStatus('slp');
else if (r < 20) source.setStatus('par');
else if (r < 30) source.setStatus('psn');
}
}
},
"flamebody": {
inherit: true,
onAfterDamage: function(damage, target, source, move) {
if (move && move.isContact) {
if (this.random(3) < 1) {
source.trySetStatus('brn', target, move);
}
}
}
},
"flashfire": {
inherit: true,
onTryHit: function(target, source, move) {
if (target !== source && move.type === 'Fire') {
if (move.id === 'willowisp' && (target.hasType('Fire') || target.status || target.volatiles['substitute'])) {
return;
}
if (!target.addVolatile('flashfire')) {
this.add('-immune', target, '[msg]');
}
return null;
}
}
},
"lightningrod": {
desc: "During double battles, this Pokemon draws any single-target Electric-type attack to itself. If an opponent uses an Electric-type attack that affects multiple Pokemon, those targets will be hit. This ability does not affect Electric Hidden Power or Judgment. The user is immune to Electric and its Special Attack is increased one stage when hit by one.",
shortDesc: "This Pokemon draws opposing Electric moves to itself.",
onFoeRedirectTargetPriority: 1,
onFoeRedirectTarget: function(target, source, source2, move) {
if (move.type !== 'Electric') return;
if (this.validTarget(this.effectData.target, source, move.target)) {
return this.effectData.target;
}
},
id: "lightningrod",
name: "Lightningrod",
rating: 3.5,
num: 32
},
"pickup": {
inherit: true,
onResidualOrder: null,
onResidualSubOrder: null,
onResidual: null
},
"poisonpoint": {
inherit: true,
onAfterDamage: function(damage, target, source, move) {
if (move && move.isContact) {
if (this.random(3) < 1) {
source.trySetStatus('psn', target, move);
}
}
}
},
"pressure": {
inherit: true,
onStart: null
},
"rockhead": {
inherit: true,
onModifyMove: function(move) {
if (move.id !== 'struggle') delete move.recoil;
}
},
"roughskin": {
inherit: true,
onAfterDamage: function(damage, target, source, move) {
if (source && source !== target && move && move.isContact) {
this.damage(source.maxhp/16, source, target);
}
}
},
"shadowtag": {
inherit: true,
onFoeModifyPokemon: function(pokemon) {
pokemon.trapped = true;
}
},
"static": {
inherit: true,
onAfterDamage: function(damage, target, source, effect) {
if (effect && effect.isContact) {
if (this.random(3) < 1) {
source.trySetStatus('par', target, effect);
}
}
}
},
"stench": {
inherit: true,
onModifyMove: function(){}
},
"sturdy": {
inherit: true,
onDamage: function(damage, target, source, effect) {
if (effect && effect.ohko) {
this.add('-activate',target,'Sturdy');
return 0;
}
}
},
"synchronize": {
inherit: true,
onAfterSetStatus: function(status, target, source) {
if (!source || source === target) return;
var status = status.id;
if (status === 'slp' || status === 'frz') return;
if (status === 'tox') status = 'psn';
source.trySetStatus(status);
}
},
"trace": {
inherit: true,
onUpdate: function(pokemon) {
var target = pokemon.side.foe.randomActive();
if (!target || target.fainted) return;
var ability = this.getAbility(target.ability);
var bannedAbilities = {forecast:1, multitype:1, trace:1};
if (bannedAbilities[target.ability]) {
return;
}
if (ability === 'Intimidate')
{
if (pokemon.setAbility('Illuminate')) { //Temporary fix so Intimidate doesn't activate in third gen when traced
this.add('-ability',pokemon, ability,'[from] ability: Trace','[of] '+target);
}
}
else if (pokemon.setAbility(ability)) {
this.add('-ability',pokemon, ability,'[from] ability: Trace','[of] '+target);
}
}
},
"voltabsorb": {
inherit: true,
onTryHit: function(target, source, move) {
if (target !== source && move.type === 'Electric' && move.id !== 'thunderwave') {
if (!this.heal(target.maxhp/4)) {
this.add('-immune', target, '[msg]');
}
return null;
}
}
}
};
|
define([
"dojo/_base/declare", // declare
"dojo/Deferred",
"dojo/_base/kernel", // kernel.deprecated
"dojo/_base/lang", // lang.mixin
"dojo/store/util/QueryResults",
"./_AutoCompleterMixin",
"./_ComboBoxMenu",
"../_HasDropDown",
"dojo/text!./templates/DropDownBox.html"
], function(declare, Deferred, kernel, lang, QueryResults, _AutoCompleterMixin, _ComboBoxMenu, _HasDropDown, template){
// module:
// dijit/form/ComboBoxMixin
return declare("dijit.form.ComboBoxMixin", [_HasDropDown, _AutoCompleterMixin], {
// summary:
// Provides main functionality of ComboBox widget
// dropDownClass: [protected extension] Function String
// Dropdown widget class used to select a date/time.
// Subclasses should specify this.
dropDownClass: _ComboBoxMenu,
// hasDownArrow: Boolean
// Set this textbox to have a down arrow button, to display the drop down list.
// Defaults to true.
hasDownArrow: true,
templateString: template,
baseClass: "dijitTextBox dijitComboBox",
/*=====
// store: [const] dojo/store/api/Store|dojo/data/api/Read
// Reference to data provider object used by this ComboBox.
//
// Should be dojo/store/api/Store, but dojo/data/api/Read supported
// for backwards compatibility.
store: null,
=====*/
// Set classes like dijitDownArrowButtonHover depending on
// mouse action over button node
cssStateNodes: {
"_buttonNode": "dijitDownArrowButton"
},
_setHasDownArrowAttr: function(/*Boolean*/ val){
this._set("hasDownArrow", val);
this._buttonNode.style.display = val ? "" : "none";
},
_showResultList: function(){
// hide the tooltip
this.displayMessage("");
this.inherited(arguments);
},
_setStoreAttr: function(store){
// For backwards-compatibility, accept dojo.data store in addition to dojo/store/api/Store. Remove in 2.0.
if(!store.get){
lang.mixin(store, {
_oldAPI: true,
get: function(id){
// summary:
// Retrieves an object by it's identity. This will trigger a fetchItemByIdentity.
// Like dojo/store/DataStore.get() except returns native item.
var deferred = new Deferred();
this.fetchItemByIdentity({
identity: id,
onItem: function(object){
deferred.resolve(object);
},
onError: function(error){
deferred.reject(error);
}
});
return deferred.promise;
},
query: function(query, options){
// summary:
// Queries the store for objects. Like dojo/store/DataStore.query()
// except returned Deferred contains array of native items.
var deferred = new Deferred(function(){ fetchHandle.abort && fetchHandle.abort(); });
deferred.total = new Deferred();
var fetchHandle = this.fetch(lang.mixin({
query: query,
onBegin: function(count){
deferred.total.resolve(count);
},
onComplete: function(results){
deferred.resolve(results);
},
onError: function(error){
deferred.reject(error);
}
}, options));
return QueryResults(deferred);
}
});
}
this._set("store", store);
},
postMixInProperties: function(){
// Since _setValueAttr() depends on this.store, _setStoreAttr() needs to execute first.
// Unfortunately, without special code, it ends up executing second.
var store = this.params.store || this.store;
if(store){
this._setStoreAttr(store);
}
this.inherited(arguments);
// User may try to access this.store.getValue() etc. in a custom labelFunc() function.
// It's not available with the new data store for handling inline <option> tags, so add it.
if(!this.params.store && !this.store._oldAPI){
var clazz = this.declaredClass;
lang.mixin(this.store, {
getValue: function(item, attr){
kernel.deprecated(clazz + ".store.getValue(item, attr) is deprecated for builtin store. Use item.attr directly", "", "2.0");
return item[attr];
},
getLabel: function(item){
kernel.deprecated(clazz + ".store.getLabel(item) is deprecated for builtin store. Use item.label directly", "", "2.0");
return item.name;
},
fetch: function(args){
kernel.deprecated(clazz + ".store.fetch() is deprecated for builtin store.", "Use store.query()", "2.0");
var shim = ["dojo/data/ObjectStore"]; // indirection so it doesn't get rolled into a build
require(shim, lang.hitch(this, function(ObjectStore){
new ObjectStore({objectStore: this}).fetch(args);
}));
}
});
}
}
});
});
|
var arrayAggregator = require('./_arrayAggregator'),
baseAggregator = require('./_baseAggregator'),
baseIteratee = require('./_baseIteratee'),
isArray = require('./isArray');
/**
* Creates a function like `_.groupBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} [initializer] The accumulator object initializer.
* @returns {Function} Returns the new aggregator function.
*/
function createAggregator(setter, initializer) {
return function(collection, iteratee) {
var func = isArray(collection) ? arrayAggregator : baseAggregator,
accumulator = initializer ? initializer() : {};
return func(collection, setter, baseIteratee(iteratee, 2), accumulator);
};
}
module.exports = createAggregator;
|
angular.module('listDemo1', ['ngMaterial'])
.config(function($mdIconProvider) {
$mdIconProvider
.iconSet('communication', 'img/icons/sets/communication-icons.svg', 24);
})
.controller('AppCtrl', function($scope) {
var imagePath = 'img/60.jpeg';
$scope.phones = [
{
type: 'Home',
number: '(555) 251-1234',
options: {
icon: 'communication:phone'
}
},
{
type: 'Cell',
number: '(555) 786-9841',
options: {
icon: 'communication:phone',
avatarIcon: true
}
},
{
type: 'Office',
number: '(555) 314-1592',
options: {
face : imagePath
}
},
{
type: 'Offset',
number: '(555) 192-2010',
options: {
offset: true,
actionIcon: 'communication:phone'
}
}
];
$scope.todos = [
{
face : imagePath,
what: 'My quirky, joyful porg',
who: 'Kaguya w/ #qjporg',
when: '3:08PM',
notes: " I was lucky to find a quirky, joyful porg!"
},
{
face : imagePath,
what: 'Brunch this weekend?',
who: 'Min Li Chan',
when: '3:08PM',
notes: " I'll be in your neighborhood doing errands"
},
{
face : imagePath,
what: 'Brunch this weekend?',
who: 'Min Li Chan',
when: '3:08PM',
notes: " I'll be in your neighborhood doing errands"
},
{
face : imagePath,
what: 'Brunch this weekend?',
who: 'Min Li Chan',
when: '3:08PM',
notes: " I'll be in your neighborhood doing errands"
},
{
face : imagePath,
what: 'Brunch this weekend?',
who: 'Min Li Chan',
when: '3:08PM',
notes: " I'll be in your neighborhood doing errands"
},
];
});
|
import React from 'react'
import { Router, Route, hashHistory } from 'react-router'
import Home from './components/ui/Home'
import About from './components/ui/About'
import MemberList from './components/ui/MemberList'
import { Left, Right, Whoops404 } from './components'
const routes = (
<Router history={hashHistory}>
<Route path="/" component={Home} />
<Route path="/" component={Left}>
<Route path="about" component={About} />
<Route path="members" component={MemberList} />
</Route>
<Route path="*" component={Whoops404} />
</Router>
)
export default routes |
/**
* FTScroller: touch and mouse-based scrolling for DOM elements larger than their containers.
*
* While this is a rewrite, it is heavily inspired by two projects:
* 1) Uxebu TouchScroll (https://github.com/davidaurelio/TouchScroll), BSD licensed:
* Copyright (c) 2010 uxebu Consulting Ltd. & Co. KG
* Copyright (c) 2010 David Aurelio
* 2) Zynga Scroller (https://github.com/zynga/scroller), MIT licensed:
* Copyright 2011, Zynga Inc.
* Copyright 2011, Deutsche Telekom AG
*
* Includes CubicBezier:
*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
* Copyright (C) 2010 David Aurelio. All Rights Reserved.
* Copyright (C) 2010 uxebu Consulting Ltd. & Co. KG. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC., DAVID AURELIO, AND UXEBU
* CONSULTING LTD. & CO. KG ``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 APPLE INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @copyright The Financial Times Ltd [All rights reserved]
* @codingstandard ftlabs-jslint
* @version 0.2.0
*/
/**
* @license FTScroller is (c) 2012 The Financial Times Ltd [All rights reserved] and licensed under the MIT license.
*
* Inspired by Uxebu TouchScroll, (c) 2010 uxebu Consulting Ltd. & Co. KG and David Aurelio, which is BSD licensed (https://github.com/davidaurelio/TouchScroll)
* Inspired by Zynga Scroller, (c) 2011 Zynga Inc and Deutsche Telekom AG, which is MIT licensed (https://github.com/zynga/scroller)
* Includes CubicBezier, (c) 2008 Apple Inc [All rights reserved], (c) 2010 David Aurelio and uxebu Consulting Ltd. & Co. KG. [All rights reserved], which is 2-clause BSD licensed (see above or https://github.com/davidaurelio/TouchScroll).
*/
/*jslint nomen: true, vars: true, browser: true, node: true, es5: true, continue: true, white: true*/
/*globals FTScrollerOptions*/
var FTScroller, CubicBezier;
(function () {
'use strict';
// Global flag to determine if any scroll is currently active. This prevents
// issues when using multiple scrollers, particularly when they're nested.
var _ftscrollerMoving = false;
// Determine whether pointer events or touch events can be used
var _trackPointerEvents = window.navigator.msPointerEnabled;
var _trackTouchEvents = !_trackPointerEvents && document.hasOwnProperty('ontouchstart');
// Determine whether to use modern hardware acceleration rules or dynamic/toggleable rules.
// Certain older browsers - particularly Android browsers - have problems with hardware
// acceleration, so being able to toggle the behaviour dynamically via a CSS cascade is desirable.
var _useToggleableHardwareAcceleration = !window.hasOwnProperty('ArrayBuffer');
// Feature detection
var _canClearSelection = (window.Selection && window.Selection.prototype.removeAllRanges);
// Determine the browser engine and prefix, trying to use the unprefixed version where available.
var _vendorCSSPrefix, _vendorStylePropertyPrefix, _vendorTransformLookup;
if (document.createElement('div').style.transform !== undefined) {
_vendorCSSPrefix = '';
_vendorStylePropertyPrefix = '';
_vendorTransformLookup = 'transform';
} else if (window.opera && Object.prototype.toString.call(window.opera) === '[object Opera]') {
_vendorCSSPrefix = '-o-';
_vendorStylePropertyPrefix = 'O';
_vendorTransformLookup = 'OTransform';
} else if (document.documentElement.style.MozTransform !== undefined) {
_vendorCSSPrefix = '-moz-';
_vendorStylePropertyPrefix = 'Moz';
_vendorTransformLookup = 'MozTransform';
} else if (document.documentElement.style.webkitTransform !== undefined) {
_vendorCSSPrefix = '-webkit-';
_vendorStylePropertyPrefix = 'webkit';
_vendorTransformLookup = '-webkit-transform';
} else if (typeof navigator.cpuClass === 'string') {
_vendorCSSPrefix = '-ms-';
_vendorStylePropertyPrefix = 'ms';
_vendorTransformLookup = '-ms-transform';
}
// If hardware acceleration is using the standard path, but perspective doesn't seem to be supported,
// 3D transforms likely aren't supported either
if (!_useToggleableHardwareAcceleration && document.createElement('div').style[_vendorStylePropertyPrefix + (_vendorStylePropertyPrefix ? 'P' : 'p') + 'erspective'] === undefined) {
_useToggleableHardwareAcceleration = true;
}
// Style prefixes
var _transformProperty = _vendorStylePropertyPrefix + (_vendorStylePropertyPrefix ? 'T' : 't') + 'ransform';
var _transitionProperty = _vendorStylePropertyPrefix + (_vendorStylePropertyPrefix ? 'T' : 't') + 'ransition';
var _translateRulePrefix = _useToggleableHardwareAcceleration ? 'translate(' : 'translate3d(';
var _transformPrefixes = { x: '', y: '0,' };
var _transformSuffixes = { x: ',0' + (_useToggleableHardwareAcceleration ? ')' : ',0)'), y: (_useToggleableHardwareAcceleration ? ')' : ',0)') };
// Constants. Note that the bezier curve should be changed along with the friction!
var _kFriction = 0.998;
var _kMinimumSpeed = 0.01;
// Create a global stylesheet to set up stylesheet rules and track dynamic entries
(function () {
var stylesheetContainerNode = document.getElementsByTagName('head')[0] || document.documentElement;
var newStyleNode = document.createElement('style');
var hardwareAccelerationRule;
var _styleText;
newStyleNode.type = 'text/css';
// Determine the hardware acceleration logic to use
if (_useToggleableHardwareAcceleration) {
hardwareAccelerationRule = _vendorCSSPrefix + 'transform-style: preserve-3d;';
} else {
hardwareAccelerationRule = _vendorCSSPrefix + 'transform: translateZ(0);';
}
// Add our rules
_styleText = [
'.ftscroller_scrolling { ' + _vendorCSSPrefix + 'user-select: none; cursor: all-scroll !important }',
'.ftscroller_container { overflow: hidden; position: relative; max-height: 100%; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); -ms-touch-action: none }',
'.ftscroller_hwaccelerated { ' + hardwareAccelerationRule + ' }',
'.ftscroller_x, .ftscroller_y { position: relative; min-width: 100%; min-height: 100%; overflow: hidden }',
'.ftscroller_x { display: inline-block }',
'.ftscroller_scrollbar { pointer-events: none; position: absolute; width: 5px; height: 5px; border: 1px solid rgba(255, 255, 255, 0.15); -webkit-border-radius: 3px; border-radius: 6px; opacity: 0; ' + _vendorCSSPrefix + 'transition: opacity 350ms; z-index: 10 }',
'.ftscroller_scrollbarx { bottom: 2px; left: 2px }',
'.ftscroller_scrollbary { right: 2px; top: 2px }',
'.ftscroller_scrollbarinner { height: 100%; background: rgba(0,0,0,0.5); -webkit-border-radius: 2px; border-radius: 4px / 6px }',
'.ftscroller_scrolling .ftscroller_scrollbar { opacity: 1; ' + _vendorCSSPrefix + 'transition: none; -o-transition: all 0 none }',
'.ftscroller_scrolling .ftscroller_container .ftscroller_scrollbar { opacity: 0 }'
];
if (newStyleNode.styleSheet) {
newStyleNode.styleSheet.cssText = _styleText.join('\n');
} else {
newStyleNode.appendChild(document.createTextNode(_styleText.join('\n')));
}
// Add the stylesheet
stylesheetContainerNode.insertBefore(newStyleNode, stylesheetContainerNode.firstChild);
}());
/**
* Master constructor for the scrolling function, including which element to
* construct the scroller in, and any scrolling options.
* Note that app-wide options can also be set using a global FTScrollerOptions
* object.
*/
FTScroller = function (domNode, options) {
var key;
var destroy, setSnapSize, scrollTo, scrollBy, updateDimensions, addEventListener, removeEventListener, _startScroll, _updateScroll, _endScroll, _finalizeScroll, _interruptScroll, _flingScroll, _snapScroll, _getSnapPositionForPosition, _initializeDOM, _existingDOMValid, _domChanged, _updateDimensions, _updateScrollbarDimensions, _updateElementPosition, _updateSegments, _setAxisPosition, _scheduleAxisPosition, _fireEvent, _childFocused, _modifyDistanceBeyondBounds, _distancesBeyondBounds, _startAnimation, _scheduleRender, _cancelAnimation, _toggleEventHandlers, _onTouchStart, _onTouchMove, _onTouchEnd, _onMouseDown, _onMouseMove, _onMouseUp, _onPointerDown, _onPointerMove, _onPointerUp, _onPointerCancel, _onPointerCaptureEnd, _onClick, _onMouseScroll, _captureInput, _releaseInputCapture, _getBoundingRect;
/* Note that actual object instantiation occurs at the end of the closure to avoid jslint errors */
/* Options */
var _instanceOptions = {
// Whether to display scrollbars as appropriate
scrollbars: true,
// Enable scrolling on the X axis if content is available
scrollingX: true,
// Enable scrolling on the Y axis if content is available
scrollingY: true,
// The initial movement required to trigger a scroll, in pixels; this is the point at which
// the scroll is exclusive to this particular FTScroller instance.
scrollBoundary: 1,
// The initial movement required to trigger a visual indication that scrolling is occurring,
// in pixels. This is enforced to be less than or equal to the scrollBoundary, and is used to
// define when the scroller starts drawing changes in response to an input, even if the scroll
// is not treated as having begun/locked yet.
scrollResponseBoundary: 1,
// Whether to always enable scrolling, even if the content of the scroller does not
// require the scroller to function. This makes the scroller behave more like an
// element set to "overflow: scroll", with bouncing always occurring if enabled.
alwaysScroll: false,
// The content width to use when determining scroller dimensions. If this
// is false, the width will be detected based on the actual content.
contentWidth: undefined,
// The content height to use when determining scroller dimensions. If this
// is false, the height will be detected based on the actual content.
contentHeight: undefined,
// Enable snapping of content to 'pages' or a pixel grid
snapping: false,
// Define the horizontal interval of the pixel grid; snapping must be enabled for this to
// take effect. If this is not defined, snapping will use intervals based on container size.
snapSizeX: undefined,
// Define the vertical interval of the pixel grid; snapping must be enabled for this to
// take effect. If this is not defined, snapping will use intervals based on container size.
snapSizeY: undefined,
// Control whether snapping should be fully paginated, only ever flicking to the next page
// and not beyond. Snapping needs to be enabled for this to take effect.
paginatedSnap: false,
// Allow scroll bouncing and elasticity near the ends and grid
bouncing: true,
// Automatically detects changes to the contained markup and
// updates its dimensions whenever the content changes. This is
// set to false if a contentWidth or contentHeight are supplied.
updateOnChanges: true,
// Automatically catches changes to the window size and updates
// its dimensions.
updateOnWindowResize: false,
// The alignment to use if the content is smaller than the container;
// this also applies to initial positioning of scrollable content.
// Valid alignments are -1 (top or left), 0 (center), and 1 (bottom or right).
baseAlignments: { x: -1, y: -1 },
// Whether to use a window scroll flag, eg window.foo, to control whether
// to allow scrolling to start or now. If the window flag is set to true,
// this element will not start scrolling; this element will also toggle
// the variable while scrolling
windowScrollingActiveFlag: undefined,
// Instead of always using translate3d for transforms, a mix of translate3d
// and translate with a hardware acceleration class used to trigger acceleration
// is used; this is to allow CSS inheritance to be used to allow dynamic
// disabling of backing layers on older platforms.
hwAccelerationClass: 'ftscroller_hwaccelerated',
// While use of requestAnimationFrame is highly recommended on platforms
// which support it, it can result in the animation being a further half-frame
// behind the input method, increasing perceived lag slightly. To disable this,
// set this property to false.
enableRequestAnimationFrameSupport: true,
// Set the maximum time (ms) that a fling can take to complete; if
// this is not set, flings will complete instantly
maxFlingDuration: 1000
};
/* Local variables */
// Cache the DOM node and set up variables for other nodes
var _publicSelf;
var _self = this;
var _scrollableMasterNode = domNode;
var _containerNode;
var _contentParentNode;
var _scrollNodes = { x: null, y: null };
var _scrollbarNodes = { x: null, y: null };
// Dimensions of the container element and the content element
var _metrics = {
container: { x: null, y: null },
content: { x: null, y: null, rawX: null, rawY: null },
scrollEnd: { x: null, y: null }
};
// Snapping details
var _snapGridSize = {
x: false,
y: false,
userX: false,
userY: false
};
var _baseSegment = { x: 0, y: 0 };
var _activeSegment = { x: 0, y: 0 };
// Track the identifier of any input being tracked
var _inputIdentifier = false;
var _inputIndex = 0;
var _inputCaptured = false;
// Current scroll positions and tracking
var _isScrolling = false;
var _isDisplayingScroll = false;
var _isAnimating = false;
var _scrollbarsVisible = false;
var _baseScrollPosition = { x: 0, y: 0 };
var _lastScrollPosition = { x: 0, y: 0 };
var _scrollAtExtremity = { x: null, y: null };
var _preventClick = false;
var _timeouts = [];
var _hasBeenScrolled = false;
// Gesture details
var _baseScrollableAxes = {};
var _scrollableAxes = { x: true, y: true };
var _gestureStart = { x: 0, y: 0, t: 0 };
var _cumulativeScroll = { x: 0, y: 0 };
var _eventHistory = [];
var _kFlingBezier = new CubicBezier(0.1, 0.4, 0.3, 1);
var _kBounceBezier = new CubicBezier(0.7, 0, 0.9, 0.6);
var _kFlingTruncatedBezier = _kFlingBezier.divideAtT(0.97)[0];
var _kDecelerateBezier = new CubicBezier(0, 0.5, 0.5, 1);
// Allow certain events to be debounced
var _domChangeDebouncer = false;
var _scrollWheelEndDebouncer = false;
// Performance switches on browsers supporting requestAnimationFrame
var _animationFrameRequest = false;
var _animationTargetPosition = { x: 0, y: 0 };
var _reqAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || false;
var _cancelAnimationFrame = window.cancelAnimationFrame || window.cancelRequestAnimationFrame || window.mozCancelAnimationFrame || window.mozCancelRequestAnimationFrame || window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame || window.msCancelAnimationFrame || window.msCancelRequestAnimationFrame || false;
// Event listeners
var _eventListeners = {
'scrollstart': [],
'scroll': [],
'scrollend': [],
'segmentwillchange': [],
'segmentdidchange': [],
'reachedstart': [],
'reachedend': []
};
// MutationObserver instance, when supported and if DOM change sniffing is enabled
var _mutationObserver;
/* Parsing supplied options */
// Override default instance options with global - or closure'd - options
if (typeof FTScrollerOptions === 'object' && FTScrollerOptions) {
for (key in FTScrollerOptions) {
if (FTScrollerOptions.hasOwnProperty(key) && _instanceOptions.hasOwnProperty(key)) {
_instanceOptions[key] = FTScrollerOptions[key];
}
}
}
// Override default and global options with supplied options
if (options) {
for (key in options) {
if (options.hasOwnProperty(key) && _instanceOptions.hasOwnProperty(key)) {
_instanceOptions[key] = options[key];
}
}
// If snap grid size options were supplied, store them
if (options.hasOwnProperty('snapSizeX') && !isNaN(options.snapSizeX)) {
_snapGridSize.userX = _snapGridSize.x = options.snapSizeX;
}
if (options.hasOwnProperty('snapSizeY') && !isNaN(options.snapSizeY)) {
_snapGridSize.userY = _snapGridSize.y = options.snapSizeY;
}
// If content width and height were defined, disable updateOnChanges for performance
if (options.contentWidth && options.contentHeight) {
options.updateOnChanges = false;
}
}
// Validate the scroll response parameter
_instanceOptions.scrollResponseBoundary = Math.min(_instanceOptions.scrollBoundary, _instanceOptions.scrollResponseBoundary);
// Update base scrollable axes
if (_instanceOptions.scrollingX) {
_baseScrollableAxes.x = true;
}
if (_instanceOptions.scrollingY) {
_baseScrollableAxes.y = true;
}
/* Scoped Functions */
/**
* Unbinds all event listeners to prevent circular references preventing items
* from being deallocated, and clean up references to dom elements. Pass in
* "removeElements" to also remove FTScroller DOM elements for special reuse cases.
*/
destroy = function destroy(removeElements) {
var i, l;
_toggleEventHandlers(false);
_cancelAnimation();
if (_domChangeDebouncer) {
window.clearTimeout(_domChangeDebouncer);
_domChangeDebouncer = false;
}
for (i = 0, l = _timeouts.length; i < l; i = i + 1) {
window.clearTimeout(_timeouts[i]);
}
_timeouts.length = 0;
// Destroy DOM elements if required
if (removeElements && _scrollableMasterNode) {
while (_contentParentNode.firstChild) {
_scrollableMasterNode.appendChild(_contentParentNode.firstChild);
}
_scrollableMasterNode.removeChild(_containerNode);
}
_scrollableMasterNode = null;
_containerNode = null;
_contentParentNode = null;
_scrollNodes.x = null;
_scrollNodes.y = null;
_scrollbarNodes.x = null;
_scrollbarNodes.y = null;
for (i in _eventListeners) {
if (_eventListeners.hasOwnProperty(i)) {
_eventListeners[i].length = 0;
}
}
// If this is currently tracked as a scrolling instance, clear the flag
if (_ftscrollerMoving && _ftscrollerMoving === _self) {
_ftscrollerMoving = false;
if (_instanceOptions.windowScrollingActiveFlag) {
window[_instanceOptions.windowScrollingActiveFlag] = false;
}
}
};
/**
* Configures the snapping boundaries within the scrolling element if
* snapping is active. If this is never called, snapping defaults to
* using the bounding box, eg page-at-a-time.
*/
setSnapSize = function setSnapSize(width, height) {
_snapGridSize.userX = width;
_snapGridSize.userY = height;
_snapGridSize.x = width;
_snapGridSize.y = height;
// Ensure the content dimensions conform to the grid
_metrics.content.x = Math.ceil(_metrics.content.rawX / width) * width;
_metrics.content.y = Math.ceil(_metrics.content.rawY / height) * height;
_metrics.scrollEnd.x = _metrics.container.x - _metrics.content.x;
_metrics.scrollEnd.y = _metrics.container.y - _metrics.content.y;
_updateScrollbarDimensions();
// Snap to the new grid if necessary
_snapScroll();
_updateSegments(true);
};
/**
* Scroll to a supplied position, including whether or not to animate the
* scroll and how fast to perform the animation (pass in true to select a
* dynamic duration). The inputs will be constrained to bounds and snapped.
* If false is supplied for a position, that axis will not be scrolled.
*/
scrollTo = function scrollTo(left, top, animationDuration) {
var targetPosition, duration, positions, axis, maxDuration = 0, scrollPositionsToApply = {};
// If a manual scroll is in progress, cancel it
_endScroll(Date.now());
// Move supplied coordinates into an object for iteration, also inverting the values into
// our coordinate system
positions = {
x: -left,
y: -top
};
for (axis in _baseScrollableAxes) {
if (_baseScrollableAxes.hasOwnProperty(axis)) {
targetPosition = positions[axis];
if (targetPosition === false) {
continue;
}
// Constrain to bounds
targetPosition = Math.min(0, Math.max(_metrics.scrollEnd[axis], targetPosition));
// Snap if appropriate
if (_instanceOptions.snapping && _snapGridSize[axis]) {
targetPosition = Math.round(targetPosition / _snapGridSize[axis]) * _snapGridSize[axis];
}
// Get a duration
duration = animationDuration || 0;
if (duration === true) {
duration = Math.sqrt(Math.abs(_baseScrollPosition[axis] - targetPosition)) * 20;
}
// Trigger the position change
_setAxisPosition(axis, targetPosition, duration);
scrollPositionsToApply[axis] = targetPosition;
maxDuration = Math.max(maxDuration, duration);
}
}
// If the scroll had resulted in a change in position, perform some additional actions:
if (_baseScrollPosition.x !== positions.x || _baseScrollPosition.y !== positions.y) {
// Mark a scroll as having ever occurred
_hasBeenScrolled = true;
// If an animation duration is present, fire a scroll start event
_fireEvent('scrollstart', { scrollLeft: -_baseScrollPosition.x, scrollTop: -_baseScrollPosition.y });
}
if (maxDuration) {
_timeouts.push(setTimeout(function () {
var axis;
for (axis in scrollPositionsToApply) {
if (scrollPositionsToApply.hasOwnProperty(axis)) {
_lastScrollPosition[axis] = scrollPositionsToApply[axis];
}
}
_finalizeScroll();
}, maxDuration));
} else {
_finalizeScroll();
}
_fireEvent('scroll', { scrollLeft: -_baseScrollPosition.x, scrollTop: -_baseScrollPosition.y });
};
/**
* Alter the current scroll position, including whether or not to animate
* the scroll and how fast to perform the animation (pass in true to
* select a dynamic duration). The inputs will be checked against the
* current position.
*/
scrollBy = function scrollBy(horizontal, vertical, animationDuration) {
// Wrap the scrollTo function for simplicity
scrollTo(parseFloat(horizontal) - _baseScrollPosition.x, parseFloat(vertical) - _baseScrollPosition.y, animationDuration);
};
/**
* Provide a public method to detect changes in dimensions for either the content or the
* container.
*/
updateDimensions = function updateDimensions(contentWidth, contentHeight, ignoreSnapScroll) {
options.contentWidth = contentWidth || options.contentWidth;
options.contentHeight = contentHeight || options.contentHeight;
// Currently just wrap the private API
_updateDimensions(!!ignoreSnapScroll);
};
/**
* Add an event handler for a supported event. Current events include:
* scroll - fired whenever the scroll position changes
* scrollstart - fired when a scroll movement starts
* scrollend - fired when a scroll movement ends
* segmentwillchange - fired whenever the segment changes, including during scrolling
* segmentdidchange - fired when a segment has conclusively changed, after scrolling.
*/
addEventListener = function addEventListener(eventname, eventlistener) {
// Ensure this is a valid event
if (!_eventListeners.hasOwnProperty(eventname)) {
return false;
}
// Add the listener
_eventListeners[eventname].push(eventlistener);
return true;
};
/**
* Remove an event handler for a supported event. The listener must be exactly the same as
* an added listener to be removed.
*/
removeEventListener = function removeEventListener(eventname, eventlistener) {
var i;
// Ensure this is a valid event
if (!_eventListeners.hasOwnProperty(eventname)) {
return false;
}
for (i = _eventListeners[eventname].length; i >= 0; i = i - 1) {
if (_eventListeners[eventname][i] === eventlistener) {
_eventListeners[eventname].splice(i, 1);
}
}
return true;
};
/**
* Start a scroll tracking input - this could be mouse, webkit-style touch,
* or ms-style pointer events.
*/
_startScroll = function _startScroll(inputX, inputY, inputTime, rawEvent) {
var triggerScrollInterrupt = _isAnimating;
// Opera fix
if (inputTime <= 0) {
inputTime = Date.now();
}
// If a window scrolling flag is set, and evaluates to true, don't start checking touches
if (_instanceOptions.windowScrollingActiveFlag && window[_instanceOptions.windowScrollingActiveFlag]) {
return false;
}
// If an animation is in progress, stop the scroll.
if (triggerScrollInterrupt) {
_interruptScroll();
} else {
// Allow clicks again, but only if a scroll was not interrupted
_preventClick = false;
}
// Store the initial event coordinates
_gestureStart.x = inputX;
_gestureStart.y = inputY;
_gestureStart.t = inputTime;
_animationTargetPosition.x = _lastScrollPosition.x;
_animationTargetPosition.y = _lastScrollPosition.y;
// Clear event history and add the start touch
_eventHistory.length = 0;
_eventHistory.push({ x: inputX, y: inputY, t: inputTime });
if (triggerScrollInterrupt) {
_updateScroll(inputX, inputY, inputTime, rawEvent, triggerScrollInterrupt);
}
return true;
};
/**
* Continue a scroll as a result of an updated position
*/
_updateScroll = function _updateScroll(inputX, inputY, inputTime, rawEvent, scrollInterrupt) {
var axis, otherScrollerActive;
var initialScroll = false;
var gesture = {
x: inputX - _gestureStart.x,
y: inputY - _gestureStart.y
};
var targetPositions = { x: _baseScrollPosition.x + gesture.x, y: _baseScrollPosition.y + gesture.y };
var distancesBeyondBounds = _distancesBeyondBounds(targetPositions);
// Opera fix
if (inputTime <= 0) {
inputTime = Date.now();
}
// If scrolling has not yet locked to this scroller, check whether to stop scrolling
if (!_isScrolling) {
// Check the internal flag to determine if another FTScroller is scrolling
if (_ftscrollerMoving && _ftscrollerMoving !== _self) {
otherScrollerActive = true;
}
// Otherwise, check the window scrolling flag to see if anything else has claimed scrolling
else if (_instanceOptions.windowScrollingActiveFlag && window[_instanceOptions.windowScrollingActiveFlag]) {
otherScrollerActive = true;
}
// If another scroller was active, clean up and stop processing.
if (otherScrollerActive) {
_inputIdentifier = false;
_releaseInputCapture();
if (_scrollbarsVisible) {
_cancelAnimation();
if (!_snapScroll(true)) {
_finalizeScroll(true);
}
}
return;
}
}
// If not yet displaying a scroll, determine whether that triggering boundary
// has been exceeded
if (!_isDisplayingScroll) {
// Determine whether to prevent the default scroll event - if the scroll could still
// be triggered, prevent the default to avoid problems (particularly on PlayBook)
if (_instanceOptions.bouncing || scrollInterrupt || (_scrollableAxes.x && gesture.x && distancesBeyondBounds.x < 0) || (_scrollableAxes.y && gesture.y && distancesBeyondBounds.y < 0)) {
rawEvent.preventDefault();
}
// Check scrolled distance against the boundary limit to see if scrolling can be triggered.
// If snapping is active and the scroll has been interrupted, trigger at once
if (!(scrollInterrupt && _instanceOptions.snapping) && (!_scrollableAxes.x || Math.abs(gesture.x) < _instanceOptions.scrollResponseBoundary) && (!_scrollableAxes.y || Math.abs(gesture.y) < _instanceOptions.scrollResponseBoundary)) {
return;
}
// If bouncing is disabled, and already at an edge and scrolling beyond the edge, ignore the scroll for
// now - this allows other scrollers to claim if appropriate, allowing nicer nested scrolls.
if (!_instanceOptions.bouncing && !scrollInterrupt && (!_scrollableAxes.x || !gesture.x || distancesBeyondBounds.x > 0) && (!_scrollableAxes.y || !gesture.y || distancesBeyondBounds.y > 0)) {
// Prevent the original click now that scrolling would be triggered
_preventClick = true;
return;
}
// Trigger the start of visual scrolling
_startAnimation();
_isDisplayingScroll = true;
_hasBeenScrolled = true;
_isAnimating = true;
initialScroll = true;
_scrollbarsVisible = true;
} else {
// Prevent the event default. It is safe to call this in IE10 because the event is never
// a window.event, always a "true" event.
rawEvent.preventDefault();
}
// If not yet locked to a scroll, determine whether to do so
if (!_isScrolling) {
// If the gesture distance has exceeded the scroll lock distance, or snapping is active
// and the scroll has been interrupted, enture exclusive scrolling.
if ((scrollInterrupt && _instanceOptions.snapping)
|| (_scrollableAxes.x && Math.abs(gesture.x) >= _instanceOptions.scrollBoundary)
|| (_scrollableAxes.y && Math.abs(gesture.y) >= _instanceOptions.scrollBoundary)) {
_isScrolling = true;
_ftscrollerMoving = _self;
if (_instanceOptions.windowScrollingActiveFlag) {
window[_instanceOptions.windowScrollingActiveFlag] = _self;
}
_fireEvent('scrollstart', { scrollLeft: -_baseScrollPosition.x, scrollTop: -_baseScrollPosition.y });
}
}
// Cancel text selections while dragging a cursor
if (_canClearSelection) {
window.getSelection().removeAllRanges();
}
// Update axes if appropriate
for (axis in _scrollableAxes) {
if (_scrollableAxes.hasOwnProperty(axis)) {
if (targetPositions[axis] > 0) {
targetPositions[axis] = _modifyDistanceBeyondBounds(targetPositions[axis], axis);
} else if (targetPositions[axis] < _metrics.scrollEnd[axis]) {
targetPositions[axis] = _metrics.scrollEnd[axis] + _modifyDistanceBeyondBounds(targetPositions[axis] - _metrics.scrollEnd[axis], axis);
}
if (_reqAnimationFrame) {
_animationTargetPosition[axis] = targetPositions[axis];
} else {
_setAxisPosition(axis, targetPositions[axis]);
}
}
}
// To aid render/draw coalescing, perform other one-off actions here
if (initialScroll) {
if (_containerNode.className.indexOf('ftscroller_scrolling') === -1) {
_containerNode.className += ' ftscroller_scrolling';
}
}
// If full, locked scrolling has enabled, fire any scroll and segment change events
if (_isScrolling) {
_fireEvent('scroll', { scrollLeft: -targetPositions.x, scrollTop: -targetPositions.y });
_updateSegments(false);
}
// Add an event to the event history, keeping it around twenty events long
_eventHistory.push({ x: inputX, y: inputY, t: inputTime });
if (_eventHistory.length > 30) {
_eventHistory.splice(0, 15);
}
};
/**
* Complete a scroll with a final event time if available (it may
* not be, depending on the input type); this may continue the scroll
* with a fling and/or bounceback depending on options.
*/
_endScroll = function _endScroll(inputTime, rawEvent) {
_inputIdentifier = false;
_releaseInputCapture();
_cancelAnimation();
if (!_isScrolling) {
if (!_snapScroll(true) && _scrollbarsVisible) {
_finalizeScroll(true);
}
return;
}
// Modify the last movement event to include the end event time
_eventHistory[_eventHistory.length - 1].t = inputTime;
// Update flags
_isScrolling = false;
_isDisplayingScroll = false;
_ftscrollerMoving = false;
if (_instanceOptions.windowScrollingActiveFlag) {
window[_instanceOptions.windowScrollingActiveFlag] = false;
}
// Prevent clicks and stop the event default. It is safe to call this in IE10 because
// the event is never a window.event, always a "true" event.
_preventClick = true;
if (rawEvent) {
rawEvent.preventDefault();
}
// Trigger a fling or bounceback if necessary
if (!_flingScroll() && !_snapScroll()) {
_finalizeScroll();
}
};
/**
* Remove the scrolling class, cleaning up display.
*/
_finalizeScroll = function _finalizeScroll(scrollCancelled) {
var i, l, axis;
_isAnimating = false;
_scrollbarsVisible = false;
_isDisplayingScroll = false;
// Remove scrolling class
_containerNode.className = _containerNode.className.replace(/ ?ftscroller_scrolling/g, '');
// Store final position if scrolling occurred
_baseScrollPosition.x = _lastScrollPosition.x;
_baseScrollPosition.y = _lastScrollPosition.y;
if (!scrollCancelled) {
_fireEvent('scroll', { scrollLeft: -_baseScrollPosition.x, scrollTop: -_baseScrollPosition.y });
_updateSegments(true);
_fireEvent('scrollend', { scrollLeft: -_baseScrollPosition.x, scrollTop: -_baseScrollPosition.y });
}
// Restore transitions
for (axis in _scrollableAxes) {
if (_scrollableAxes.hasOwnProperty(axis)) {
_scrollNodes[axis].style[_transitionProperty] = '';
if (_instanceOptions.scrollbars) {
_scrollbarNodes[axis].style[_transitionProperty] = '';
}
}
}
// Clear any remaining timeouts
for (i = 0, l = _timeouts.length; i < l; i = i + 1) {
window.clearTimeout(_timeouts[i]);
}
_timeouts.length = 0;
};
/**
* Interrupt a current scroll, allowing a start scroll during animation to trigger a new scroll
*/
_interruptScroll = function _interruptScroll() {
var axis, i, l;
_isAnimating = false;
// Update the stored base position
_updateElementPosition();
// Ensure the parsed positions are set, also clearing transitions
for (axis in _scrollableAxes) {
if (_scrollableAxes.hasOwnProperty(axis)) {
_setAxisPosition(axis, _baseScrollPosition[axis]);
}
}
// Update segment tracking if snapping is active
_updateSegments(false);
// Clear any remaining timeouts
for (i = 0, l = _timeouts.length; i < l; i = i + 1) {
window.clearTimeout(_timeouts[i]);
}
_timeouts.length = 0;
};
/**
* Determine whether a scroll fling or bounceback is required, and set up the styles and
* timeouts required.
*/
_flingScroll = function _flingScroll() {
var i, axis, movementSpeed, lastPosition, comparisonPosition, flingDuration, flingDistance, flingPosition, bounceDelay, bounceDistance, bounceDuration, bounceTarget, boundsBounce, modifiedDistance, flingBezier, timeProportion, boundsCrossDelay, flingStartSegment, beyondBoundsFlingDistance, baseFlingComponent;
var maxAnimationTime = 0;
var moveRequired = false;
var scrollPositionsToApply = {};
// If we only have the start event available, or are scrolling, no action required.
if (_eventHistory.length === 1 || _inputIdentifier === 'scrollwheel') {
return false;
}
for (axis in _scrollableAxes) {
if (_scrollableAxes.hasOwnProperty(axis)) {
bounceDuration = 350;
bounceDistance = 0;
boundsBounce = false;
bounceTarget = false;
boundsCrossDelay = undefined;
// Re-set a default bezier curve for the animation, with the end lopped off for min speed
flingBezier = _kFlingTruncatedBezier;
// Get the last movement speed, in pixels per millisecond. To do this, look at the events
// in the last 100ms and average out the speed, using a minimum number of two points.
lastPosition = _eventHistory[_eventHistory.length - 1];
comparisonPosition = _eventHistory[_eventHistory.length - 2];
for (i = _eventHistory.length - 3; i >= 0; i = i - 1) {
if (lastPosition.t - _eventHistory[i].t > 100) {
break;
}
comparisonPosition = _eventHistory[i];
}
movementSpeed = (lastPosition[axis] - comparisonPosition[axis]) / (lastPosition.t - comparisonPosition.t);
// If there is little speed, no further action required except for a bounceback, below.
if (Math.abs(movementSpeed) < _kMinimumSpeed) {
flingDuration = 0;
flingDistance = 0;
} else {
/* Calculate the fling duration. As per TouchScroll, the speed at any particular
point in time can be calculated as:
{ speed } = { initial speed } * ({ friction } to the power of { duration })
...assuming all values are in equal pixels/millisecond measurements. As we know the
minimum target speed, this can be altered to:
{ duration } = log( { speed } / { initial speed } ) / log( { friction } )
*/
flingDuration = Math.log(_kMinimumSpeed / Math.abs(movementSpeed)) / Math.log(_kFriction);
/* Calculate the fling distance (before any bouncing or snapping). As per
TouchScroll, the total distance covered can be approximated by summing
the distance per millisecond, per millisecond of duration - a divergent series,
and so rather tricky to model otherwise!
So using values in pixels per millisecond:
{ distance } = { initial speed } * (1 - ({ friction } to the power
of { duration + 1 }) / (1 - { friction })
*/
flingDistance = movementSpeed * (1 - Math.pow(_kFriction, flingDuration + 1)) / (1 - _kFriction);
}
// Determine a target fling position
flingPosition = Math.floor(_lastScrollPosition[axis] + flingDistance);
// If bouncing is disabled, and the last scroll position and fling position are both at a bound,
// reset the fling position to the bound
if (!_instanceOptions.bouncing) {
if (_lastScrollPosition[axis] === 0 && flingPosition > 0) {
flingPosition = 0;
} else if (_lastScrollPosition[axis] === _metrics.scrollEnd[axis] && flingPosition < _lastScrollPosition[axis]) {
flingPosition = _lastScrollPosition[axis];
}
}
// In paginated snapping mode, determine the page to snap to - maximum
// one page in either direction from the current page.
if (_instanceOptions.paginatedSnap && _instanceOptions.snapping) {
flingStartSegment = -_lastScrollPosition[axis] / _snapGridSize[axis];
if (_baseSegment[axis] < flingStartSegment) {
flingStartSegment = Math.floor(flingStartSegment);
} else {
flingStartSegment = Math.ceil(flingStartSegment);
}
// If the target position will end up beyond another page, target that page edge
if (flingPosition > -(flingStartSegment - 1) * _snapGridSize[axis]) {
bounceDistance = flingPosition + (flingStartSegment - 1) * _snapGridSize[axis];
} else if (flingPosition < -(flingStartSegment + 1) * _snapGridSize[axis]) {
bounceDistance = flingPosition + (flingStartSegment + 1) * _snapGridSize[axis];
// Otherwise, if the movement speed was above the minimum velocity, continue
// in the move direction.
} else if (Math.abs(movementSpeed) > _kMinimumSpeed) {
// Determine the target segment
if (movementSpeed < 0) {
flingPosition = Math.floor(_lastScrollPosition[axis] / _snapGridSize[axis]) * _snapGridSize[axis];
} else {
flingPosition = Math.ceil(_lastScrollPosition[axis] / _snapGridSize[axis]) * _snapGridSize[axis];
}
flingDuration = Math.min(_instanceOptions.maxFlingDuration, flingDuration * (flingPosition - _lastScrollPosition[axis]) / flingDistance);
}
// In non-paginated snapping mode, snap to the nearest grid location to the target
} else if (_instanceOptions.snapping) {
bounceDistance = flingPosition - (Math.round(flingPosition / _snapGridSize[axis]) * _snapGridSize[axis]);
}
// Deal with cases where the target is beyond the bounds
if (flingPosition - bounceDistance > 0) {
bounceDistance = flingPosition;
boundsBounce = true;
} else if (flingPosition - bounceDistance < _metrics.scrollEnd[axis]) {
bounceDistance = flingPosition - _metrics.scrollEnd[axis];
boundsBounce = true;
}
// Amend the positions and bezier curve if necessary
if (bounceDistance) {
// If the fling moves the scroller beyond the normal scroll bounds, and
// the bounce is snapping the scroll back after the fling:
if (boundsBounce && _instanceOptions.bouncing && flingDistance) {
flingDistance = Math.floor(flingDistance);
if (flingPosition > 0) {
beyondBoundsFlingDistance = flingPosition - Math.max(0, _lastScrollPosition[axis]);
} else {
beyondBoundsFlingDistance = flingPosition - Math.min(_metrics.scrollEnd[axis], _lastScrollPosition[axis]);
}
baseFlingComponent = flingDistance - beyondBoundsFlingDistance;
// Determine the time proportion the original bound is along the fling curve
if (!flingDistance || !flingDuration) {
timeProportion = 0;
} else {
timeProportion = flingBezier._getCoordinateForT(flingBezier.getTForY((flingDistance - beyondBoundsFlingDistance) / flingDistance, 1 / flingDuration), flingBezier._p1.x, flingBezier._p2.x);
boundsCrossDelay = timeProportion * flingDuration;
}
// Eighth the distance beyonds the bounds
modifiedDistance = Math.ceil(beyondBoundsFlingDistance / 8);
// Further limit the bounce to half the container dimensions
if (Math.abs(modifiedDistance) > _metrics.container[axis] / 2) {
if (modifiedDistance < 0) {
modifiedDistance = -Math.floor(_metrics.container[axis] / 2);
} else {
modifiedDistance = Math.floor(_metrics.container[axis] / 2);
}
}
if (flingPosition > 0) {
bounceTarget = 0;
} else {
bounceTarget = _metrics.scrollEnd[axis];
}
// If the entire fling is a bounce, modify appropriately
if (timeProportion === 0) {
flingDuration = flingDuration / 6;
flingPosition = _lastScrollPosition[axis] + baseFlingComponent + modifiedDistance;
bounceDelay = flingDuration;
// Otherwise, take a new curve and add it to the timeout stack for the bounce
} else {
// The new bounce delay is the pre-boundary fling duration, plus a
// sixth of the post-boundary fling.
bounceDelay = (timeProportion + ((1 - timeProportion) / 6)) * flingDuration;
_scheduleAxisPosition(axis, (_lastScrollPosition[axis] + baseFlingComponent + modifiedDistance), ((1 - timeProportion) * flingDuration / 6), _kDecelerateBezier, boundsCrossDelay);
// Modify the fling to match, clipping to prevent over-fling
flingBezier = flingBezier.divideAtX(bounceDelay / flingDuration, 1 / flingDuration)[0];
flingDuration = bounceDelay;
flingPosition = (_lastScrollPosition[axis] + baseFlingComponent + modifiedDistance);
}
// If the fling requires snapping to a snap location, and the bounce needs to
// reverse the fling direction after the fling completes:
} else if ((flingDistance < 0 && bounceDistance < flingDistance) || (flingDistance > 0 && bounceDistance > flingDistance)) {
// Shorten the original fling duration to reflect the bounce
flingPosition = flingPosition - Math.floor(flingDistance / 2);
bounceDistance = bounceDistance - Math.floor(flingDistance / 2);
bounceDuration = Math.sqrt(Math.abs(bounceDistance)) * 50;
bounceTarget = flingPosition - bounceDistance;
flingDuration = 350;
bounceDelay = flingDuration * 0.97;
// If the bounce is truncating the fling, or continuing the fling on in the same
// direction to hit the next boundary:
} else {
flingPosition = flingPosition - bounceDistance;
// If there was no fling distance originally, use the bounce details
if (!flingDistance) {
flingDuration = bounceDuration;
// If truncating the fling at a snapping edge:
} else if ((flingDistance < 0 && bounceDistance < 0) || (flingDistance > 0 && bounceDistance > 0)) {
timeProportion = flingBezier._getCoordinateForT(flingBezier.getTForY((Math.abs(flingDistance) - Math.abs(bounceDistance)) / Math.abs(flingDistance), 1 / flingDuration), flingBezier._p1.x, flingBezier._p2.x);
flingBezier = flingBezier.divideAtX(timeProportion, 1 / flingDuration)[0];
flingDuration = Math.round(flingDuration * timeProportion);
// If extending the fling to reach the next snapping boundary, no further
// action is required.
}
bounceDistance = 0;
bounceDuration = 0;
}
}
// If no fling or bounce is required, continue
if (flingPosition === _lastScrollPosition[axis] && !bounceDistance) {
continue;
}
moveRequired = true;
// Perform the fling
_setAxisPosition(axis, flingPosition, flingDuration, flingBezier, boundsCrossDelay);
// Schedule a bounce if appropriate
if (bounceDistance && bounceDuration) {
_scheduleAxisPosition(axis, bounceTarget, bounceDuration, _kBounceBezier, bounceDelay);
}
maxAnimationTime = Math.max(maxAnimationTime, bounceDistance ? (bounceDelay + bounceDuration) : flingDuration);
scrollPositionsToApply[axis] = (bounceTarget === false) ? flingPosition : bounceTarget;
}
}
if (moveRequired && maxAnimationTime) {
_timeouts.push(setTimeout(function () {
var axis;
// Update the stored scroll position ready for finalising
for (axis in scrollPositionsToApply) {
if (scrollPositionsToApply.hasOwnProperty(axis)) {
_lastScrollPosition[axis] = scrollPositionsToApply[axis];
}
}
_finalizeScroll();
}, maxAnimationTime));
}
return moveRequired;
};
/**
* Bounce back into bounds if necessary, or snap to a grid location.
*/
_snapScroll = function _snapScroll(scrollCancelled) {
var axis;
var snapDuration = scrollCancelled ? 100 : 350;
// Get the current position and see if a snap is required
var targetPosition = _getSnapPositionForPosition(_lastScrollPosition);
var snapRequired = false;
for (axis in _baseScrollableAxes) {
if (_baseScrollableAxes.hasOwnProperty(axis)) {
if (targetPosition[axis] !== _lastScrollPosition[axis]) {
snapRequired = true;
}
}
}
if (!snapRequired) {
return false;
}
// Perform the snap
for (axis in _baseScrollableAxes) {
if (_baseScrollableAxes.hasOwnProperty(axis)) {
_setAxisPosition(axis, targetPosition[axis], snapDuration);
}
}
_timeouts.push(setTimeout(function () {
// Update the stored scroll position ready for finalizing
_lastScrollPosition = targetPosition;
_finalizeScroll(scrollCancelled);
}, snapDuration));
return true;
};
/**
* Get an appropriate snap point for a supplied point. This will respect the edge of the
* element, and any grid if configured.
*/
_getSnapPositionForPosition = function _getSnapPositionForPosition(coordinates) {
var axis;
var coordinatesToReturn = { x: 0, y: 0 };
for (axis in _scrollableAxes) {
if (_scrollableAxes.hasOwnProperty(axis)) {
// If the coordinate is beyond the edges of the scroller, use the closest edge
if (coordinates[axis] > 0) {
coordinatesToReturn[axis] = 0;
continue;
}
if (coordinates[axis] < _metrics.scrollEnd[axis]) {
coordinatesToReturn[axis] = _metrics.scrollEnd[axis];
continue;
}
// If a grid is present, find the nearest grid delineator.
if (_instanceOptions.snapping && _snapGridSize[axis]) {
coordinatesToReturn[axis] = Math.round(coordinates[axis] / _snapGridSize[axis]) * _snapGridSize[axis];
continue;
}
// Otherwise use the supplied coordinate.
coordinatesToReturn[axis] = coordinates[axis];
}
}
return coordinatesToReturn;
};
/**
* Sets up the DOM around the node to be scrolled.
*/
_initializeDOM = function _initializeDOM() {
var offscreenFragment, offscreenNode, scrollYParent;
// Check whether the DOM is already present and valid - if so, no further action required.
if (_existingDOMValid()) {
return;
}
// Otherwise, the DOM needs to be created inside the originally supplied node. The node
// has a container inserted inside it - which acts as an anchor element with constraints -
// and then the scrollable layers as appropriate.
// Create a new document fragment to temporarily hold the scrollable content
offscreenFragment = _scrollableMasterNode.ownerDocument.createDocumentFragment();
offscreenNode = document.createElement('DIV');
offscreenFragment.appendChild(offscreenNode);
// Drop in the wrapping HTML
offscreenNode.innerHTML = FTScroller.prototype.getPrependedHTML(!_instanceOptions.scrollingX, !_instanceOptions.scrollingY, _instanceOptions.hwAccelerationClass) + FTScroller.prototype.getAppendedHTML(!_instanceOptions.scrollingX, !_instanceOptions.scrollingY, _instanceOptions.hwAccelerationClass, _instanceOptions.scrollbars);
// Update references as appropriate
_containerNode = offscreenNode.firstElementChild;
scrollYParent = _containerNode;
if (_instanceOptions.scrollingX) {
_scrollNodes.x = _containerNode.firstElementChild;
scrollYParent = _scrollNodes.x;
if (_instanceOptions.scrollbars) {
_scrollbarNodes.x = _containerNode.getElementsByClassName('ftscroller_scrollbarx')[0];
}
}
if (_instanceOptions.scrollingY) {
_scrollNodes.y = scrollYParent.firstElementChild;
if (_instanceOptions.scrollbars) {
_scrollbarNodes.y = _containerNode.getElementsByClassName('ftscroller_scrollbary')[0];
}
_contentParentNode = _scrollNodes.y;
} else {
_contentParentNode = _scrollNodes.x;
}
// Take the contents of the scrollable element, and copy them into the new container
while (_scrollableMasterNode.firstChild) {
_contentParentNode.appendChild(_scrollableMasterNode.firstChild);
}
// Move the wrapped elements back into the document
_scrollableMasterNode.appendChild(_containerNode);
};
/**
* Attempts to use any existing DOM scroller nodes if possible, returning true if so;
* updates all internal element references.
*/
_existingDOMValid = function _existingDOMValid() {
var scrollerContainer, layerX, layerY, yParent, scrollerX, scrollerY, candidates, i, l;
// Check that there's an initial child node, and make sure it's the container class
scrollerContainer = _scrollableMasterNode.firstElementChild;
if (!scrollerContainer || scrollerContainer.className.indexOf('ftscroller_container') === -1) {
return;
}
// If x-axis scrolling is enabled, find and verify the x scroller layer
if (_instanceOptions.scrollingX) {
// Find and verify the x scroller layer
layerX = scrollerContainer.firstElementChild;
if (!layerX || layerX.className.indexOf('ftscroller_x') === -1) {
return;
}
yParent = layerX;
// Find and verify the x scrollbar if enabled
if (_instanceOptions.scrollbars) {
candidates = scrollerContainer.getElementsByClassName('ftscroller_scrollbarx');
if (candidates) {
for (i = 0, l = candidates.length; i < l; i = i + 1) {
if (candidates[i].parentNode === scrollerContainer) {
scrollerX = candidates[i];
break;
}
}
}
if (!scrollerX) {
return;
}
}
} else {
yParent = scrollerContainer;
}
// If y-axis scrolling is enabled, find and verify the y scroller layer
if (_instanceOptions.scrollingY) {
// Find and verify the x scroller layer
layerY = yParent.firstElementChild;
if (!layerY || layerY.className.indexOf('ftscroller_y') === -1) {
return;
}
// Find and verify the y scrollbar if enabled
if (_instanceOptions.scrollbars) {
candidates = scrollerContainer.getElementsByClassName('ftscroller_scrollbary');
if (candidates) {
for (i = 0, l = candidates.length; i < l; i = i + 1) {
if (candidates[i].parentNode === scrollerContainer) {
scrollerY = candidates[i];
break;
}
}
}
if (!scrollerY) {
return;
}
}
}
// Elements found and verified - update the references and return success
_containerNode = scrollerContainer;
if (layerX) {
_scrollNodes.x = layerX;
}
if (layerY) {
_scrollNodes.y = layerY;
}
if (scrollerX) {
_scrollbarNodes.x = scrollerX;
}
if (scrollerY) {
_scrollbarNodes.y = scrollerY;
}
if (_instanceOptions.scrollingY) {
_contentParentNode = layerY;
} else {
_contentParentNode = layerX;
}
return true;
};
_domChanged = function _domChanged() {
// If the timer is active, clear it
if (_domChangeDebouncer) {
window.clearTimeout(_domChangeDebouncer);
}
// Set up the DOM changed timer
_domChangeDebouncer = setTimeout(function () {
_updateDimensions();
}, 100);
};
_updateDimensions = function _updateDimensions(ignoreSnapScroll) {
var axis;
// Only update dimensions if the container node exists (DOM elements can go away if
// the scroller instance is not destroyed correctly)
if (!_containerNode || !_contentParentNode) {
return false;
}
if (_domChangeDebouncer) {
window.clearTimeout(_domChangeDebouncer);
_domChangeDebouncer = false;
}
var containerWidth, containerHeight, startAlignments;
// If a manual scroll is in progress, cancel it
_endScroll(Date.now());
// Calculate the starting alignment for comparison later
startAlignments = { x: false, y: false };
for (axis in startAlignments) {
if (startAlignments.hasOwnProperty(axis)) {
if (_lastScrollPosition[axis] === 0) {
startAlignments[axis] = -1;
} else if (_lastScrollPosition[axis] <= _metrics.scrollEnd[axis]) {
startAlignments[axis] = 1;
} else if (_lastScrollPosition[axis] * 2 <= _metrics.scrollEnd[axis] + 5 && _lastScrollPosition[axis] * 2 >= _metrics.scrollEnd[axis] - 5) {
startAlignments[axis] = 0;
}
}
}
containerWidth = _containerNode.offsetWidth;
containerHeight = _containerNode.offsetHeight;
// Grab the dimensions
var rawScrollWidth = options.contentWidth || _contentParentNode.offsetWidth;
var rawScrollHeight = options.contentHeight || _contentParentNode.offsetHeight;
var scrollWidth = rawScrollWidth;
var scrollHeight = rawScrollHeight;
var targetPosition = { x: false, y: false };
// Update snap grid
if (!_snapGridSize.userX) {
_snapGridSize.x = containerWidth;
}
if (!_snapGridSize.userY) {
_snapGridSize.y = containerHeight;
}
// If there is a grid, conform to the grid
if (_instanceOptions.snapping) {
if (_snapGridSize.userX) {
scrollWidth = Math.ceil(scrollWidth / _snapGridSize.userX) * _snapGridSize.userX;
} else {
scrollWidth = Math.ceil(scrollWidth / _snapGridSize.x) * _snapGridSize.x;
}
if (_snapGridSize.userY) {
scrollHeight = Math.ceil(scrollHeight / _snapGridSize.userY) * _snapGridSize.userY;
} else {
scrollHeight = Math.ceil(scrollHeight / _snapGridSize.y) * _snapGridSize.y;
}
}
// If no details have changed, return.
if (_metrics.container.x === containerWidth && _metrics.container.y === containerHeight && _metrics.content.x === scrollWidth && _metrics.content.y === scrollHeight) {
return;
}
// Update the sizes
_metrics.container.x = containerWidth;
_metrics.container.y = containerHeight;
_metrics.content.x = scrollWidth;
_metrics.content.rawX = rawScrollWidth;
_metrics.content.y = scrollHeight;
_metrics.content.rawY = rawScrollHeight;
_metrics.scrollEnd.x = containerWidth - scrollWidth;
_metrics.scrollEnd.y = containerHeight - scrollHeight;
_updateScrollbarDimensions();
// Apply base alignment if appropriate
for (axis in targetPosition) {
if (targetPosition.hasOwnProperty(axis)) {
// If the container is smaller than the content, determine whether to apply the
// alignment. This occurs if a scroll has never taken place, or if the position
// was previously at the correct "end" and can be maintained.
if (_metrics.container[axis] < _metrics.content[axis]) {
if (_hasBeenScrolled && _instanceOptions.baseAlignments[axis] !== startAlignments[axis]) {
continue;
}
}
// Apply the alignment
if (_instanceOptions.baseAlignments[axis] === 1) {
targetPosition[axis] = _metrics.scrollEnd[axis];
} else if (_instanceOptions.baseAlignments[axis] === 0) {
targetPosition[axis] = Math.floor(_metrics.scrollEnd[axis] / 2);
} else if (_instanceOptions.baseAlignments[axis] === -1) {
targetPosition[axis] = 0;
}
}
}
if (_instanceOptions.scrollingX && targetPosition.x !== false) {
_setAxisPosition('x', targetPosition.x, 0);
_baseScrollPosition.x = targetPosition.x;
}
if (_instanceOptions.scrollingY && targetPosition.y !== false) {
_setAxisPosition('y', targetPosition.y, 0);
_baseScrollPosition.y = targetPosition.y;
}
// Ensure bounds are correct
if (!ignoreSnapScroll && _snapScroll()) {
_updateSegments(true);
}
};
_updateScrollbarDimensions = function _updateScrollbarDimensions() {
// Update scrollbar sizes
if (_instanceOptions.scrollbars) {
if (_instanceOptions.scrollingX) {
_scrollbarNodes.x.style.width = Math.max(6, Math.round(_metrics.container.x * (_metrics.container.x / _metrics.content.x) - 4)) + 'px';
}
if (_instanceOptions.scrollingY) {
_scrollbarNodes.y.style.height = Math.max(6, Math.round(_metrics.container.y * (_metrics.container.y / _metrics.content.y) - 4)) + 'px';
}
}
// Update scroll caches
_scrollableAxes = {};
if (_instanceOptions.scrollingX && (_metrics.content.x > _metrics.container.x || _instanceOptions.alwaysScroll)) {
_scrollableAxes.x = true;
}
if (_instanceOptions.scrollingY && (_metrics.content.y > _metrics.container.y || _instanceOptions.alwaysScroll)) {
_scrollableAxes.y = true;
}
};
_updateElementPosition = function _updateElementPosition() {
var axis, computedStyle, splitStyle;
// Retrieve the current position of each active axis.
// Custom parsing is used instead of native matrix support for speed and for
// backwards compatibility.
for (axis in _scrollableAxes) {
if (_scrollableAxes.hasOwnProperty(axis)) {
computedStyle = window.getComputedStyle(_scrollNodes[axis], null)[_vendorTransformLookup];
splitStyle = computedStyle.split(', ');
// For 2d-style transforms, pull out elements four or five
if (splitStyle.length === 6) {
_baseScrollPosition[axis] = parseInt(splitStyle[(axis === 'y') ? 5 : 4], 10);
// For 3d-style transforms, pull out elements twelve or thirteen
} else {
_baseScrollPosition[axis] = parseInt(splitStyle[(axis === 'y') ? 13 : 12], 10);
}
_lastScrollPosition[axis] = _baseScrollPosition[axis];
}
}
};
_updateSegments = function _updateSegments(scrollFinalised) {
var axis;
var newSegment = { x: 0, y: 0 };
// If snapping is disabled, return without any further action required
if (!_instanceOptions.snapping) {
return;
}
// Calculate the new segments
for (axis in _scrollableAxes) {
if (_scrollableAxes.hasOwnProperty(axis)) {
newSegment[axis] = Math.max(0, Math.min(Math.ceil(_metrics.content[axis] / _snapGridSize[axis]) - 1, Math.round(-_lastScrollPosition[axis] / _snapGridSize[axis])));
}
}
// In all cases update the active segment if appropriate
if (newSegment.x !== _activeSegment.x || newSegment.y !== _activeSegment.y) {
_activeSegment.x = newSegment.x;
_activeSegment.y = newSegment.y;
_fireEvent('segmentwillchange', { segmentX: newSegment.x, segmentY: newSegment.y });
}
// If the scroll has been finalised, also update the base segment
if (scrollFinalised) {
if (newSegment.x !== _baseSegment.x || newSegment.y !== _baseSegment.y) {
_baseSegment.x = newSegment.x;
_baseSegment.y = newSegment.y;
_fireEvent('segmentdidchange', { segmentX: newSegment.x, segmentY: newSegment.y });
}
}
};
_setAxisPosition = function _setAxisPosition(axis, position, animationDuration, animationBezier, boundsCrossDelay) {
var transitionCSSString, newPositionAtExtremity = null;
// Only update position if the axis node exists (DOM elements can go away if
// the scroller instance is not destroyed correctly)
if (!_scrollNodes[axis]) {
return false;
}
// Determine the transition property to apply to both the scroll element and the scrollbar
if (animationDuration) {
if (!animationBezier) {
animationBezier = _kFlingTruncatedBezier;
}
transitionCSSString = _vendorCSSPrefix + 'transform ' + animationDuration + 'ms ' + animationBezier.toString();
} else {
transitionCSSString = '';
}
// Apply the transition property to elements
_scrollNodes[axis].style[_transitionProperty] = transitionCSSString;
if (_instanceOptions.scrollbars) {
_scrollbarNodes[axis].style[_transitionProperty] = transitionCSSString;
}
// Update the positions
_scrollNodes[axis].style[_transformProperty] = _translateRulePrefix + _transformPrefixes[axis] + position + 'px' + _transformSuffixes[axis];
if (_instanceOptions.scrollbars) {
_scrollbarNodes[axis].style[_transformProperty] = _translateRulePrefix + _transformPrefixes[axis] + (-position * _metrics.container[axis] / _metrics.content[axis]) + 'px' + _transformSuffixes[axis];
}
// Determine whether the scroll is at an extremity.
if (position >= 0) {
newPositionAtExtremity = 'start';
} else if (position <= _metrics.scrollEnd[axis]) {
newPositionAtExtremity = 'end';
}
// If the extremity status has changed, fire an appropriate event
if (newPositionAtExtremity !== _scrollAtExtremity[axis]) {
if (newPositionAtExtremity !== null) {
if (animationDuration) {
_timeouts.push(setTimeout(function() {
_fireEvent('reached' + newPositionAtExtremity, { axis: axis });
}, boundsCrossDelay || animationDuration));
} else {
_fireEvent('reached' + newPositionAtExtremity, { axis: axis });
}
}
_scrollAtExtremity[axis] = newPositionAtExtremity;
}
// Update the recorded position if there's no duration
if (!animationDuration) {
_lastScrollPosition[axis] = position;
}
};
_scheduleAxisPosition = function _scheduleAxisPosition(axis, position, animationDuration, animationBezier, afterDelay) {
_timeouts.push(setTimeout(function () {
_setAxisPosition(axis, position, animationDuration, animationBezier);
}, afterDelay));
};
_fireEvent = function _fireEvent(eventName, eventObject) {
var i, l;
eventObject.srcObject = _publicSelf;
// Iterate through any listeners
for (i = 0, l = _eventListeners[eventName].length; i < l; i = i + 1) {
// Execute each in a try/catch
try {
_eventListeners[eventName][i](eventObject);
} catch (error) {
if (window.console && window.console.error) {
window.console.error(error.message + ' (' + error.sourceURL + ', line ' + error.line + ')');
}
}
}
};
/**
* Update the scroll position so that the child element is in view.
*/
_childFocused = function _childFocused(event) {
var offset, axis;
var focusedNodeRect = _getBoundingRect(event.target);
var containerRect = _getBoundingRect(_containerNode);
var edgeMap = { x: 'left', y: 'top' };
var dimensionMap = { x: 'width', y: 'height' };
// If an input is currently being tracked, ignore the focus event
if (_inputIdentifier !== false) {
return;
}
for (axis in _scrollableAxes) {
if (_scrollableAxes.hasOwnProperty(axis)) {
// Set the target offset to be in the middle of the container, or as close as bounds permit
offset = -Math.round((focusedNodeRect[dimensionMap[axis]] / 2) - _lastScrollPosition[axis] + focusedNodeRect[edgeMap[axis]] - containerRect[edgeMap[axis]] - (containerRect[dimensionMap[axis]] / 2));
offset = Math.min(0, Math.max(_metrics.scrollEnd[axis], offset));
// Perform the scroll
_setAxisPosition(axis, offset, 0);
_baseScrollPosition[axis] = offset;
}
}
};
/**
* Given a relative distance beyond the element bounds, returns a modified version to
* simulate bouncy/springy edges.
*/
_modifyDistanceBeyondBounds = function _modifyDistanceBeyondBounds(distance, axis) {
if (!_instanceOptions.bouncing) {
return 0;
}
var e = Math.exp(distance / _metrics.container[axis]);
return Math.round(_metrics.container[axis] * 0.6 * (e - 1) / (e + 1));
};
/**
* Given positions for each enabled axis, returns an object showing how far each axis is beyond
* bounds. If within bounds, -1 is returned; if at the bounds, 0 is returned.
*/
_distancesBeyondBounds = function _distancesBeyondBounds(positions) {
var axis, position;
var distances = {};
for (axis in positions) {
if (positions.hasOwnProperty(axis)) {
position = positions[axis];
// If the position is to the left/top, no further modification required
if (position >= 0) {
distances[axis] = position;
// If it's within the bounds, use -1
} else if (position > _metrics.scrollEnd[axis]) {
distances[axis] = -1;
// Otherwise, amend by the distance of the maximum edge
} else {
distances[axis] = _metrics.scrollEnd[axis] - position;
}
}
}
return distances;
};
/**
* On platforms which support it, use RequestAnimationFrame to group
* position updates for speed. Starts the render process.
*/
_startAnimation = function _startAnimation() {
if (_reqAnimationFrame) {
_cancelAnimation();
_animationFrameRequest = _reqAnimationFrame(_scheduleRender);
}
};
/**
* On platforms which support RequestAnimationFrame, provide the rendering loop.
* Takes two arguments; the first is the render/position update function to
* be called, and the second is a string controlling the render type to
* allow previous changes to be cancelled - should be 'pan' or 'scroll'.
*/
_scheduleRender = function _scheduleRender() {
var axis;
// Request the next update at once
_animationFrameRequest = _reqAnimationFrame(_scheduleRender);
// Perform the draw.
for (axis in _scrollableAxes) {
if (_scrollableAxes.hasOwnProperty(axis) && _animationTargetPosition[axis] !== _lastScrollPosition[axis]) {
_setAxisPosition(axis, _animationTargetPosition[axis]);
}
}
};
/**
* Stops the animation process.
*/
_cancelAnimation = function _cancelAnimation() {
if (_animationFrameRequest === false || !_cancelAnimationFrame) {
return;
}
_cancelAnimationFrame(_animationFrameRequest);
_animationFrameRequest = false;
};
/**
* Register or unregister event handlers as appropriate
*/
_toggleEventHandlers = function _toggleEventHandlers(enable) {
var MutationObserver;
// Only remove the event if the node exists (DOM elements can go away)
if (!_containerNode) {
return;
}
if (enable) {
_containerNode._ftscrollerToggle = _containerNode.addEventListener;
} else {
_containerNode._ftscrollerToggle = _containerNode.removeEventListener;
}
if (_trackPointerEvents) {
_containerNode._ftscrollerToggle('MSPointerDown', _onPointerDown, true);
_containerNode._ftscrollerToggle('MSPointerMove', _onPointerMove, true);
_containerNode._ftscrollerToggle('MSPointerUp', _onPointerUp, true);
_containerNode._ftscrollerToggle('MSPointerCancel', _onPointerCancel, true);
} else if (_trackTouchEvents) {
_containerNode._ftscrollerToggle('touchstart', _onTouchStart, true);
_containerNode._ftscrollerToggle('touchmove', _onTouchMove, true);
_containerNode._ftscrollerToggle('touchend', _onTouchEnd, true);
_containerNode._ftscrollerToggle('touchcancel', _onTouchEnd, true);
} else {
_containerNode._ftscrollerToggle('mousedown', _onMouseDown, true);
if (!enable) {
document.removeEventListener('mousemove', _onMouseMove, true);
document.removeEventListener('mouseup', _onMouseUp, true);
}
}
_containerNode._ftscrollerToggle('DOMMouseScroll', _onMouseScroll, false);
_containerNode._ftscrollerToggle('mousewheel', _onMouseScroll, false);
// Add a click listener. On IE, add the listener to the document, to allow
// clicks to be cancelled if a scroll ends outside the bounds of the container; on
// other platforms, add to the container node.
if (_trackPointerEvents) {
if (enable) {
document.addEventListener('click', _onClick, true);
} else {
document.removeEventListener('click', _onClick, true);
}
} else {
_containerNode._ftscrollerToggle('click', _onClick, true);
}
// Watch for changes inside the contained element to update bounds - de-bounced slightly.
if (enable) {
_contentParentNode.addEventListener('focus', _childFocused, true);
if (_instanceOptions.updateOnChanges) {
// Try and reuse the old, disconnected observer instance if available
// Otherwise, check for support before proceeding
if (!_mutationObserver) {
MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window[_vendorStylePropertyPrefix + 'MutationObserver'];
if (MutationObserver) {
_mutationObserver = new MutationObserver(_domChanged);
}
}
if (_mutationObserver) {
_mutationObserver.observe(_contentParentNode, {
childList: true,
characterData: true,
subtree: true
});
} else {
_contentParentNode.addEventListener('DOMSubtreeModified', function (e) {
// Ignore changes to nested FT Scrollers - even updating a transform style
// can trigger a DOMSubtreeModified in IE, causing nested scrollers to always
// favour the deepest scroller as parent scrollers 'resize'/end scrolling.
if (e && (e.srcElement === _contentParentNode || e.srcElement.className.indexOf('ftscroller_') !== -1)) {
return;
}
_domChanged();
}, true);
}
_contentParentNode.addEventListener('load', _domChanged, true);
}
if (_instanceOptions.updateOnWindowResize) {
window.addEventListener('resize', _domChanged, true);
}
} else {
_contentParentNode.removeEventListener('focus', _childFocused, true);
if (_mutationObserver) {
_mutationObserver.disconnect();
} else {
_contentParentNode.removeEventListener('DOMSubtreeModified', _domChanged, true);
}
_contentParentNode.removeEventListener('load', _domChanged, true);
window.removeEventListener('resize', _domChanged, true);
}
delete _containerNode._ftscrollerToggle;
};
/**
* Touch event handlers
*/
_onTouchStart = function _onTouchStart(startEvent) {
var i, l, touchEvent;
// If a touch is already active, ensure that the index
// is mapped to the correct finger, and return.
if (_inputIdentifier) {
for (i = 0, l = startEvent.touches.length; i < l; i = i + 1) {
if (startEvent.touches[i].identifier === _inputIdentifier) {
_inputIndex = i;
}
}
return;
}
// Track the new touch's identifier, reset index, and pass
// the coordinates to the scroll start function.
touchEvent = startEvent.touches[0];
_inputIdentifier = touchEvent.identifier;
_inputIndex = 0;
_startScroll(touchEvent.clientX, touchEvent.clientY, startEvent.timeStamp, startEvent);
};
_onTouchMove = function _onTouchMove(moveEvent) {
if (_inputIdentifier === false) {
return;
}
// Get the coordinates from the appropriate touch event and
// pass them on to the scroll handler
var touchEvent = moveEvent.touches[_inputIndex];
_updateScroll(touchEvent.clientX, touchEvent.clientY, moveEvent.timeStamp, moveEvent);
};
_onTouchEnd = function _onTouchEnd(endEvent) {
var i, l;
// Check whether the original touch event is still active,
// if it is, update the index and return.
if (endEvent.touches) {
for (i = 0, l = endEvent.touches.length; i < l; i = i + 1) {
if (endEvent.touches[i].identifier === _inputIdentifier) {
_inputIndex = i;
return;
}
}
}
// Complete the scroll. Note that touch end events
// don't capture coordinates.
_endScroll(endEvent.timeStamp, endEvent);
};
/**
* Mouse event handlers
*/
_onMouseDown = function _onMouseDown(startEvent) {
// Don't track the right mouse buttons, or a context menu
if ((startEvent.button && startEvent.button === 2) || startEvent.ctrlKey) {
return;
}
// Capture if possible
if (_containerNode.setCapture) {
_containerNode.setCapture();
}
// Add move & up handlers to the *document* to allow handling outside the element
document.addEventListener('mousemove', _onMouseMove, true);
document.addEventListener('mouseup', _onMouseUp, true);
_inputIdentifier = startEvent.button || 1;
_inputIndex = 0;
_startScroll(startEvent.clientX, startEvent.clientY, startEvent.timeStamp, startEvent);
};
_onMouseMove = function _onMouseMove(moveEvent) {
if (!_inputIdentifier) {
return;
}
_updateScroll(moveEvent.clientX, moveEvent.clientY, moveEvent.timeStamp, moveEvent);
};
_onMouseUp = function _onMouseUp(endEvent) {
if (endEvent.button && endEvent.button !== _inputIdentifier) {
return;
}
document.removeEventListener('mousemove', _onMouseMove, true);
document.removeEventListener('mouseup', _onMouseUp, true);
// Release capture if possible
if (_containerNode.releaseCapture) {
_containerNode.releaseCapture();
}
_endScroll(endEvent.timeStamp, endEvent);
};
/**
* Pointer event handlers
*/
_onPointerDown = function _onPointerDown(startEvent) {
// If there is already a pointer event being tracked, ignore subsequent.
if (_inputIdentifier) {
return;
}
_inputIdentifier = startEvent.pointerId;
_captureInput();
_startScroll(startEvent.clientX, startEvent.clientY, startEvent.timeStamp, startEvent);
};
_onPointerMove = function _onPointerMove(moveEvent) {
if (_inputIdentifier !== moveEvent.pointerId) {
return;
}
_updateScroll(moveEvent.clientX, moveEvent.clientY, moveEvent.timeStamp, moveEvent);
};
_onPointerUp = function _onPointerUp(endEvent) {
if (_inputIdentifier !== endEvent.pointerId) {
return;
}
_endScroll(endEvent.timeStamp, endEvent);
};
_onPointerCancel = function _onPointerCancel(endEvent) {
_endScroll(endEvent.timeStamp, endEvent);
};
_onPointerCaptureEnd = function _onPointerCaptureEnd(event) {
_endScroll(event.timeStamp, event);
};
/**
* Prevents click actions if appropriate
*/
_onClick = function _onClick(clickEvent) {
// If a scroll action hasn't resulted in the next scroll being prevented, and a scroll
// isn't currently in progress with a different identifier, allow the click
if (!_preventClick && !_inputIdentifier) {
return true;
}
// Prevent clicks using the preventDefault() and stopPropagation() handlers on the event;
// this is safe even in IE10 as this is always a "true" event, never a window.event.
clickEvent.preventDefault();
clickEvent.stopPropagation();
if (!_inputIdentifier) {
_preventClick = false;
}
return false;
};
/**
* Process scroll wheel/input actions as scroller scrolls
*/
_onMouseScroll = function _onMouseScroll(event) {
var scrollDeltaX, scrollDeltaY;
if (_inputIdentifier !== 'scrollwheel') {
if (_inputIdentifier !== false) {
return true;
}
_inputIdentifier = 'scrollwheel';
_cumulativeScroll.x = 0;
_cumulativeScroll.y = 0;
// Start a scroll event
if (!_startScroll(event.clientX, event.clientY, Date.now(), event)) {
return;
}
}
// Convert the scrollwheel values to a scroll value
if (event.wheelDelta) {
if (event.wheelDeltaX) {
scrollDeltaX = event.wheelDeltaX / 2;
scrollDeltaY = event.wheelDeltaY / 2;
} else {
scrollDeltaX = 0;
scrollDeltaY = event.wheelDelta / 2;
}
} else {
if (event.axis && event.axis === event.HORIZONTAL_AXIS) {
scrollDeltaX = event.detail * -10;
scrollDeltaY = 0;
} else {
scrollDeltaX = 0;
scrollDeltaY = event.detail * -10;
}
}
// If the scroller is constrained to an x axis, convert y scroll to allow single-axis scroll
// wheels to scroll constrained content.
if (!_instanceOptions.scrollingY && !scrollDeltaX) {
scrollDeltaX = scrollDeltaY;
scrollDeltaY = 0;
}
_cumulativeScroll.x = Math.round(_cumulativeScroll.x + scrollDeltaX);
_cumulativeScroll.y = Math.round(_cumulativeScroll.y + scrollDeltaY);
_updateScroll(_gestureStart.x + _cumulativeScroll.x, _gestureStart.y + _cumulativeScroll.y, event.timeStamp, event);
// End scrolling state
if (_scrollWheelEndDebouncer) {
clearTimeout(_scrollWheelEndDebouncer);
}
_scrollWheelEndDebouncer = setTimeout(function () {
_inputIdentifier = false;
_releaseInputCapture();
_isScrolling = false;
_isDisplayingScroll = false;
_ftscrollerMoving = false;
if (_instanceOptions.windowScrollingActiveFlag) {
window[_instanceOptions.windowScrollingActiveFlag] = false;
}
_cancelAnimation();
if (!_snapScroll()) {
_finalizeScroll();
}
}, 300);
};
/**
* Capture and release input support, particularly allowing tracking
* of Metro pointers outside the docked view.
*/
_captureInput = function _captureInput() {
if (_inputCaptured || _inputIdentifier === false || _inputIdentifier === 'scrollwheel') {
return;
}
if (_trackPointerEvents) {
_containerNode.msSetPointerCapture(_inputIdentifier);
_containerNode.addEventListener('MSLostPointerCapture', _onPointerCaptureEnd, false);
}
_inputCaptured = true;
};
_releaseInputCapture = function _releaseInputCapture() {
if (!_inputCaptured) {
return;
}
if (_trackPointerEvents) {
_containerNode.removeEventListener('MSLostPointerCapture', _onPointerCaptureEnd, false);
_containerNode.msReleasePointerCapture(_inputIdentifier);
}
_inputCaptured = false;
};
/**
* Utility function acting as a getBoundingClientRect polyfill.
*/
_getBoundingRect = function _getBoundingRect(anElement) {
if (anElement.getBoundingClientRect) {
return anElement.getBoundingClientRect();
}
var x = 0, y = 0, eachElement = anElement;
while (eachElement) {
x = x + eachElement.offsetLeft - eachElement.scrollLeft;
y = y + eachElement.offsetTop - eachElement.scrollTop;
eachElement = eachElement.offsetParent;
}
return { left: x, top: y, width: anElement.offsetWidth, height: anElement.offsetHeight };
};
/* Instantiation */
// Set up the DOM node if appropriate
_initializeDOM();
// Update sizes
_updateDimensions();
// Set up the event handlers
_toggleEventHandlers(true);
// Define a public API to be returned at the bottom - this is the public-facing interface.
_publicSelf = {
destroy: destroy,
setSnapSize: setSnapSize,
scrollTo: scrollTo,
scrollBy: scrollBy,
updateDimensions: updateDimensions,
addEventListener: addEventListener,
removeEventListener: removeEventListener,
get scrollHeight () { return _metrics.content.y; },
set scrollHeight (value) { throw new SyntaxError('scrollHeight is currently read-only - ignoring ' + value); },
get scrollLeft () { return -_lastScrollPosition.x; },
set scrollLeft (value) { scrollTo(value, false, false); return -_lastScrollPosition.x; },
get scrollTop () { return -_lastScrollPosition.y; },
set scrollTop (value) { scrollTo(false, value, false); return -_lastScrollPosition.y; },
get scrollWidth () { return _metrics.content.x; },
set scrollWidth (value) { throw new SyntaxError('scrollWidth is currently read-only - ignoring ' + value); },
get segmentCount () {
if (!_instanceOptions.snapping) {
return { x: NaN, y: NaN };
}
return {
x: Math.ceil(_metrics.content.x / _snapGridSize.x),
y: Math.ceil(_metrics.content.y / _snapGridSize.y)
};
},
set segmentCount (value) { throw new SyntaxError('segmentCount is currently read-only - ignoring ' + value); },
get currentSegment () { return { x: _activeSegment.x, y: _activeSegment.y }; },
set currentSegment (value) { throw new SyntaxError('currentSegment is currently read-only - ignoring ' + value); },
get contentContainerNode () { return _contentParentNode; },
set contentContainerNode (value) { throw new SyntaxError('contentContainerNode is currently read-only - ignoring ' + value); }
};
// Return the public interface.
return _publicSelf;
};
/* Prototype Functions and Properties */
/**
* The HTML to prepend to the scrollable content to wrap it. Used internally,
* and may be used to pre-wrap scrollable content. Axes can optionally
* be excluded for speed improvements.
*/
FTScroller.prototype.getPrependedHTML = function (excludeXAxis, excludeYAxis, hwAccelerationClass) {
if (!hwAccelerationClass) {
if (typeof FTScrollerOptions === 'object' && FTScrollerOptions.hwAccelerationClass) {
hwAccelerationClass = FTScrollerOptions.hwAccelerationClass;
} else {
hwAccelerationClass = 'ftscroller_hwaccelerated';
}
}
var output = '<div class="ftscroller_container">';
if (!excludeXAxis) {
output += '<div class="ftscroller_x ' + hwAccelerationClass + '">';
}
if (!excludeYAxis) {
output += '<div class="ftscroller_y ' + hwAccelerationClass + '">';
}
return output;
};
/**
* The HTML to append to the scrollable content to wrap it; again, used internally,
* and may be used to pre-wrap scrollable content.
*/
FTScroller.prototype.getAppendedHTML = function (excludeXAxis, excludeYAxis, hwAccelerationClass, scrollbars) {
if (!hwAccelerationClass) {
if (typeof FTScrollerOptions === 'object' && FTScrollerOptions.hwAccelerationClass) {
hwAccelerationClass = FTScrollerOptions.hwAccelerationClass;
} else {
hwAccelerationClass = 'ftscroller_hwaccelerated';
}
}
var output = '';
if (!excludeXAxis) {
output += '</div>';
}
if (!excludeYAxis) {
output += '</div>';
}
if (scrollbars) {
if (!excludeXAxis) {
output += '<div class="ftscroller_scrollbar ftscroller_scrollbarx ' + hwAccelerationClass + '"><div class="ftscroller_scrollbarinner"></div></div>';
}
if (!excludeYAxis) {
output += '<div class="ftscroller_scrollbar ftscroller_scrollbary ' + hwAccelerationClass + '"><div class="ftscroller_scrollbarinner"></div></div>';
}
}
output += '</div>';
return output;
};
}());
(function () {
'use strict';
/**
* Represents a two-dimensional cubic bezier curve with the starting
* point (0, 0) and the end point (1, 1). The two control points p1 and p2
* have x and y coordinates between 0 and 1.
*
* This type of bezier curves can be used as CSS transform timing functions.
*/
CubicBezier = function (p1x, p1y, p2x, p2y) {
if (!(p1x >= 0 && p1x <= 1)) {
throw new RangeError('"p1x" must be a number between 0 and 1. ' + 'Got ' + p1x + 'instead.');
}
if (!(p1y >= 0 && p1y <= 1)) {
throw new RangeError('"p1y" must be a number between 0 and 1. ' + 'Got ' + p1y + 'instead.');
}
if (!(p2x >= 0 && p2x <= 1)) {
throw new RangeError('"p2x" must be a number between 0 and 1. ' + 'Got ' + p2x + 'instead.');
}
if (!(p2y >= 0 && p2y <= 1)) {
throw new RangeError('"p2y" must be a number between 0 and 1. ' + 'Got ' + p2y + 'instead.');
}
// Control points
this._p1 = { x: p1x, y: p1y };
this._p2 = { x: p2x, y: p2y };
};
CubicBezier.prototype._getCoordinateForT = function (t, p1, p2) {
var c = 3 * p1,
b = 3 * (p2 - p1) - c,
a = 1 - c - b;
return ((a * t + b) * t + c) * t;
};
CubicBezier.prototype._getCoordinateDerivateForT = function (t, p1, p2) {
var c = 3 * p1,
b = 3 * (p2 - p1) - c,
a = 1 - c - b;
return (3 * a * t + 2 * b) * t + c;
};
CubicBezier.prototype._getTForCoordinate = function (c, p1, p2, epsilon) {
if (!isFinite(epsilon) || epsilon <= 0) {
throw new RangeError('"epsilon" must be a number greater than 0.');
}
var t2, i, c2, d2;
// First try a few iterations of Newton's method -- normally very fast.
for (t2 = c, i = 0; i < 8; i = i + 1) {
c2 = this._getCoordinateForT(t2, p1, p2) - c;
if (Math.abs(c2) < epsilon) {
return t2;
}
d2 = this._getCoordinateDerivateForT(t2, p1, p2);
if (Math.abs(d2) < 1e-6) {
break;
}
t2 = t2 - c2 / d2;
}
// Fall back to the bisection method for reliability.
t2 = c;
var t0 = 0,
t1 = 1;
if (t2 < t0) {
return t0;
}
if (t2 > t1) {
return t1;
}
while (t0 < t1) {
c2 = this._getCoordinateForT(t2, p1, p2);
if (Math.abs(c2 - c) < epsilon) {
return t2;
}
if (c > c2) {
t0 = t2;
} else {
t1 = t2;
}
t2 = (t1 - t0) * 0.5 + t0;
}
// Failure.
return t2;
};
/**
* Computes the point for a given t value.
*
* @param {number} t
* @returns {Object} Returns an object with x and y properties
*/
CubicBezier.prototype.getPointForT = function (t) {
// Special cases: starting and ending points
if (t === 0 || t === 1) {
return { x: t, y: t };
}
// Check for correct t value (must be between 0 and 1)
if (t < 0 || t > 1) {
throw new RangeError('"t" must be a number between 0 and 1' + 'Got ' + t + ' instead.');
}
return {
x: this._getCoordinateForT(t, this._p1.x, this._p2.x),
y: this._getCoordinateForT(t, this._p1.y, this._p2.y)
};
};
CubicBezier.prototype.getTForX = function (x, epsilon) {
return this._getTForCoordinate(x, this._p1.x, this._p2.x, epsilon);
};
CubicBezier.prototype.getTForY = function (y, epsilon) {
return this._getTForCoordinate(y, this._p1.y, this._p2.y, epsilon);
};
/**
* Computes auxiliary points using De Casteljau's algorithm.
*
* @param {number} t must be greater than 0 and lower than 1.
* @returns {Object} with members i0, i1, i2 (first iteration),
* j1, j2 (second iteration) and k (the exact point for t)
*/
CubicBezier.prototype._getAuxPoints = function (t) {
if (t <= 0 || t >= 1) {
throw new RangeError('"t" must be greater than 0 and lower than 1');
}
/* First series of auxiliary points */
// First control point of the left curve
var i0 = {
x: t * this._p1.x,
y: t * this._p1.y
},
i1 = {
x: this._p1.x + t * (this._p2.x - this._p1.x),
y: this._p1.y + t * (this._p2.y - this._p1.y)
},
// Second control point of the right curve
i2 = {
x: this._p2.x + t * (1 - this._p2.x),
y: this._p2.y + t * (1 - this._p2.y)
};
/* Second series of auxiliary points */
// Second control point of the left curve
var j0 = {
x: i0.x + t * (i1.x - i0.x),
y: i0.y + t * (i1.y - i0.y)
},
// First control point of the right curve
j1 = {
x: i1.x + t * (i2.x - i1.x),
y: i1.y + t * (i2.y - i1.y)
};
// The division point (ending point of left curve, starting point of right curve)
var k = {
x: j0.x + t * (j1.x - j0.x),
y: j0.y + t * (j1.y - j0.y)
};
return {
i0: i0,
i1: i1,
i2: i2,
j0: j0,
j1: j1,
k: k
};
};
/**
* Divides the bezier curve into two bezier functions.
*
* De Casteljau's algorithm is used to compute the new starting, ending, and
* control points.
*
* @param {number} t must be greater than 0 and lower than 1.
* t === 1 or t === 0 are the starting/ending points of the curve, so no
* division is needed.
*
* @returns {CubicBezier[]} Returns an array containing two bezier curves
* to the left and the right of t.
*/
CubicBezier.prototype.divideAtT = function (t) {
if (t < 0 || t > 1) {
throw new RangeError('"t" must be a number between 0 and 1. ' + 'Got ' + t + ' instead.');
}
// Special cases t = 0, t = 1: Curve can be cloned for one side, the other
// side is a linear curve (with duration 0)
if (t === 0 || t === 1) {
var curves = [];
curves[t] = CubicBezier.linear();
curves[1 - t] = this.clone();
return curves;
}
var left = {},
right = {},
points = this._getAuxPoints(t);
var i0 = points.i0,
i2 = points.i2,
j0 = points.j0,
j1 = points.j1,
k = points.k;
// Normalize derived points, so that the new curves starting/ending point
// coordinates are (0, 0) respectively (1, 1)
var factorX = k.x,
factorY = k.y;
left.p1 = {
x: i0.x / factorX,
y: i0.y / factorY
};
left.p2 = {
x: j0.x / factorX,
y: j0.y / factorY
};
right.p1 = {
x: (j1.x - factorX) / (1 - factorX),
y: (j1.y - factorY) / (1 - factorY)
};
right.p2 = {
x: (i2.x - factorX) / (1 - factorX),
y: (i2.y - factorY) / (1 - factorY)
};
return [
new CubicBezier(left.p1.x, left.p1.y, left.p2.x, left.p2.y),
new CubicBezier(right.p1.x, right.p1.y, right.p2.x, right.p2.y)
];
};
CubicBezier.prototype.divideAtX = function (x, epsilon) {
if (x < 0 || x > 1) {
throw new RangeError('"x" must be a number between 0 and 1. ' + 'Got ' + x + ' instead.');
}
var t = this.getTForX(x, epsilon);
return this.divideAtT(t);
};
CubicBezier.prototype.divideAtY = function (y, epsilon) {
if (y < 0 || y > 1) {
throw new RangeError('"y" must be a number between 0 and 1. ' + 'Got ' + y + ' instead.');
}
var t = this.getTForY(y, epsilon);
return this.divideAtT(t);
};
CubicBezier.prototype.clone = function () {
return new CubicBezier(this._p1.x, this._p1.y, this._p2.x, this._p2.y);
};
CubicBezier.prototype.toString = function () {
return "cubic-bezier(" + [
this._p1.x,
this._p1.y,
this._p2.x,
this._p2.y
].join(", ") + ")";
};
CubicBezier.linear = function () {
return new CubicBezier();
};
CubicBezier.ease = function () {
return new CubicBezier(0.25, 0.1, 0.25, 1.0);
};
CubicBezier.linear = function () {
return new CubicBezier(0.0, 0.0, 1.0, 1.0);
};
CubicBezier.easeIn = function () {
return new CubicBezier(0.42, 0, 1.0, 1.0);
};
CubicBezier.easeOut = function () {
return new CubicBezier(0, 0, 0.58, 1.0);
};
CubicBezier.easeInOut = function () {
return new CubicBezier(0.42, 0, 0.58, 1.0);
};
}());
// If a CommonJS environment is present, add our exports; make the check in a jslint-compatible method.
if (typeof module === 'object' && module.exports) {
module.exports = function(domNode, options) {
'use strict';
return new FTScroller(domNode, options);
};
module.exports.FTScroller = FTScroller;
module.exports.CubicBezier = CubicBezier;
} |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getTableBodyUtilityClass = getTableBodyUtilityClass;
exports.default = void 0;
var _unstyled = require("@material-ui/unstyled");
function getTableBodyUtilityClass(slot) {
return (0, _unstyled.generateUtilityClass)('MuiTableBody', slot);
}
const tableBodyClasses = (0, _unstyled.generateUtilityClasses)('MuiTableBody', ['root']);
var _default = tableBodyClasses;
exports.default = _default; |
var assert = require('assert');
var R = require('..');
describe('mapObjIndexed', function() {
var times2 = function(x) {return x * 2;};
var addIndexed = function(x, key) {return x + key;};
var squareVowels = function(x, key) {
var vowels = ['a', 'e', 'i', 'o', 'u'];
return R.contains(key, vowels) ? x * x : x;
};
it('works just like a normal mapObj', function() {
assert.deepEqual(R.mapObjIndexed(times2, {a: 1, b: 2, c: 3, d: 4}), {a: 2, b: 4, c: 6, d: 8});
});
it('passes the index as a second parameter to the callback', function() {
assert.deepEqual(R.mapObjIndexed(addIndexed, {a: 8, b: 6, c: 7, d: 5, e: 3, f: 0, g: 9}),
{a: '8a', b: '6b', c: '7c', d: '5d', e: '3e', f: '0f', g: '9g'});
});
it('passes the entire list as a third parameter to the callback', function() {
assert.deepEqual(R.mapObjIndexed(squareVowels, {a: 8, b: 6, c: 7, d: 5, e: 3, f: 0, g: 9}),
{a: 64, b: 6, c: 7, d: 5, e: 9, f: 0, g: 9});
});
it('is curried', function() {
var makeSquareVowels = R.mapObjIndexed(squareVowels);
assert.deepEqual(makeSquareVowels({a: 8, b: 6, c: 7, d: 5, e: 3, f: 0, g: 9}),
{a: 64, b: 6, c: 7, d: 5, e: 9, f: 0, g: 9});
});
});
|
var convert = require('./convert'),
func = convert('wrapperLodash', require('../wrapperLodash'), require('./_falseOptions'));
func.placeholder = require('./placeholder');
module.exports = func;
|
loadjs = (function () {
/**
* Global dependencies.
* @global {Object} document - DOM
*/
var devnull = function() {},
bundleIdCache = {},
bundleResultCache = {},
bundleCallbackQueue = {};
/**
* Subscribe to bundle load event.
* @param {string[]} bundleIds - Bundle ids
* @param {Function} callbackFn - The callback function
*/
function subscribe(bundleIds, callbackFn) {
// listify
bundleIds = bundleIds.push ? bundleIds : [bundleIds];
var depsNotFound = [],
i = bundleIds.length,
numWaiting = i,
fn,
bundleId,
r,
q;
// define callback function
fn = function (bundleId, pathsNotFound) {
if (pathsNotFound.length) depsNotFound.push(bundleId);
numWaiting--;
if (!numWaiting) callbackFn(depsNotFound);
};
// register callback
while (i--) {
bundleId = bundleIds[i];
// execute callback if in result cache
r = bundleResultCache[bundleId];
if (r) {
fn(bundleId, r);
continue;
}
// add to callback queue
q = bundleCallbackQueue[bundleId] = bundleCallbackQueue[bundleId] || [];
q.push(fn);
}
}
/**
* Publish bundle load event.
* @param {string} bundleId - Bundle id
* @param {string[]} pathsNotFound - List of files not found
*/
function publish(bundleId, pathsNotFound) {
// exit if id isn't defined
if (!bundleId) return;
var q = bundleCallbackQueue[bundleId];
// cache result
bundleResultCache[bundleId] = pathsNotFound;
// exit if queue is empty
if (!q) return;
// empty callback queue
while (q.length) {
q[0](bundleId, pathsNotFound);
q.splice(0, 1);
}
}
/**
* Load individual file.
* @param {string} path - The file path
* @param {Function} callbackFn - The callback function
*/
function loadFile(path, callbackFn, args, numTries) {
var doc = document,
async = args.async,
maxTries = (args.numRetries || 0) + 1,
beforeCallbackFn = args.before || devnull,
isCss,
e;
numTries = numTries || 0;
if (/\.css$/.test(path)) {
isCss = true;
// css
e = doc.createElement('link');
e.rel = 'stylesheet';
e.href = path;
} else {
// javascript
e = doc.createElement('script');
e.src = path;
e.async = async === undefined ? true : async;
}
e.onload = e.onerror = e.onbeforeload = function (ev) {
var result = ev.type[0];
// Note: The following code isolates IE using `hideFocus` and treats empty
// stylesheets as failures to get around lack of onerror support
if (isCss && 'hideFocus' in e) {
try {
if (!e.sheet.cssText.length) result = 'e';
} catch (x) {
// sheets objects created from load errors don't allow access to
// `cssText`
result = 'e';
}
}
// handle retries in case of load failure
if (result == 'e') {
// increment counter
numTries += 1;
// exit function and try again
if (numTries < maxTries) {
return loadFile(path, callbackFn, args, numTries);
}
}
// execute callback
callbackFn(path, result, ev.defaultPrevented);
};
// execute before callback
beforeCallbackFn(path, e);
// add to document
doc.head.appendChild(e);
}
/**
* Load multiple files.
* @param {string[]} paths - The file paths
* @param {Function} callbackFn - The callback function
*/
function loadFiles(paths, callbackFn, args) {
// listify paths
paths = paths.push ? paths : [paths];
var numWaiting = paths.length,
x = numWaiting,
pathsNotFound = [],
fn,
i;
// define callback function
fn = function(path, result, defaultPrevented) {
// handle error
if (result == 'e') pathsNotFound.push(path);
// handle beforeload event. If defaultPrevented then that means the load
// will be blocked (ex. Ghostery/ABP on Safari)
if (result == 'b') {
if (defaultPrevented) pathsNotFound.push(path);
else return;
}
numWaiting--;
if (!numWaiting) callbackFn(pathsNotFound);
};
// load scripts
for (i=0; i < x; i++) loadFile(paths[i], fn, args);
}
/**
* Initiate script load and register bundle.
* @param {(string|string[])} paths - The file paths
* @param {(string|Function)} [arg1] - The bundleId or success callback
* @param {Function} [arg2] - The success or error callback
* @param {Function} [arg3] - The error callback
*/
function loadjs(paths, arg1, arg2) {
var bundleId,
args;
// bundleId (if string)
if (arg1 && arg1.trim) bundleId = arg1;
// args (default is {})
args = (bundleId ? arg2 : arg1) || {};
// throw error if bundle is already defined
if (bundleId) {
if (bundleId in bundleIdCache) {
throw "LoadJS";
} else {
bundleIdCache[bundleId] = true;
}
}
// load scripts
loadFiles(paths, function (pathsNotFound) {
// success and error callbacks
if (pathsNotFound.length) (args.error || devnull)(pathsNotFound);
else (args.success || devnull)();
// publish bundle load event
publish(bundleId, pathsNotFound);
}, args);
}
/**
* Execute callbacks when dependencies have been satisfied.
* @param {(string|string[])} deps - List of bundle ids
* @param {Object} args - success/error arguments
*/
loadjs.ready = function ready(deps, args) {
// subscribe to bundle load event
subscribe(deps, function (depsNotFound) {
// execute callbacks
if (depsNotFound.length) (args.error || devnull)(depsNotFound);
else (args.success || devnull)();
});
return loadjs;
};
/**
* Manually satisfy bundle dependencies.
* @param {string} bundleId - The bundle id
*/
loadjs.done = function done(bundleId) {
publish(bundleId, []);
};
/**
* Reset loadjs dependencies statuses
*/
loadjs.reset = function reset() {
bundleIdCache = {};
bundleResultCache = {};
bundleCallbackQueue = {};
};
/**
* Determine if bundle has already been defined
* @param String} bundleId - The bundle id
*/
loadjs.isDefined = function isDefined(bundleId) {
return bundleId in bundleIdCache;
};
// export
return loadjs;
})();
|
(function() {
"use strict";
window.GOVUK = window.GOVUK || {};
// For usage and initialisation see:
// https://github.com/alphagov/govuk_frontend_toolkit/blob/master/docs/analytics.md#create-an-analytics-tracker
var Tracker = function(config) {
this.trackers = [];
if (typeof config.universalId != 'undefined') {
this.trackers.push(new GOVUK.GoogleAnalyticsUniversalTracker(config.universalId, config.cookieDomain));
}
if (typeof config.classicId != 'undefined') {
this.trackers.push(new GOVUK.GoogleAnalyticsClassicTracker(config.classicId, config.cookieDomain));
}
};
Tracker.load = function() {
GOVUK.GoogleAnalyticsClassicTracker.load();
GOVUK.GoogleAnalyticsUniversalTracker.load();
};
Tracker.prototype.trackPageview = function(path, title) {
for (var i=0; i < this.trackers.length; i++) {
this.trackers[i].trackPageview(path, title);
}
};
/*
https://developers.google.com/analytics/devguides/collection/analyticsjs/events
options.label – Useful for categorizing events (eg nav buttons)
options.value – Values must be non-negative. Useful to pass counts
options.nonInteraction – Prevent event from impacting bounce rate
*/
Tracker.prototype.trackEvent = function(category, action, options) {
for (var i=0; i < this.trackers.length; i++) {
this.trackers[i].trackEvent(category, action, options);
}
};
Tracker.prototype.trackShare = function(network) {
var target = location.pathname;
for (var i=0; i < this.trackers.length; i++) {
this.trackers[i].trackSocial(network, 'share', target);
}
};
/*
Assumes that the index of the dimension is the same for both classic and universal.
Check this for your app before using this
*/
Tracker.prototype.setDimension = function(index, value, name, scope) {
for (var i=0; i < this.trackers.length; i++) {
this.trackers[i].setDimension(index, value, name, scope);
}
};
/*
Add a beacon to track a page in another GA account on another domain.
*/
Tracker.prototype.addLinkedTrackerDomain = function(trackerId, name, domain) {
for (var i=0; i < this.trackers.length; i++) {
this.trackers[i].addLinkedTrackerDomain(trackerId, name, domain);
}
};
GOVUK.Tracker = Tracker;
})();
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["ReduxLittleRouter"] = factory(require("react"));
else
root["ReduxLittleRouter"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_30__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.GO_BACK = exports.GO_FORWARD = exports.GO = exports.REPLACE = exports.PUSH = exports.LOCATION_CHANGED = exports.createMatcher = exports.Link = exports.routerReducer = exports.routerMiddleware = exports.createStoreWithRouter = undefined;
var _storeEnhancer = __webpack_require__(1);
var _storeEnhancer2 = _interopRequireDefault(_storeEnhancer);
var _middleware = __webpack_require__(28);
var _middleware2 = _interopRequireDefault(_middleware);
var _reducer = __webpack_require__(26);
var _reducer2 = _interopRequireDefault(_reducer);
var _link = __webpack_require__(29);
var _link2 = _interopRequireDefault(_link);
var _createMatcher = __webpack_require__(16);
var _createMatcher2 = _interopRequireDefault(_createMatcher);
var _actionTypes = __webpack_require__(27);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.createStoreWithRouter = _storeEnhancer2.default;
exports.routerMiddleware = _middleware2.default;
exports.routerReducer = _reducer2.default;
exports.Link = _link2.default;
exports.createMatcher = _createMatcher2.default;
exports.LOCATION_CHANGED = _actionTypes.LOCATION_CHANGED;
exports.PUSH = _actionTypes.PUSH;
exports.REPLACE = _actionTypes.REPLACE;
exports.GO = _actionTypes.GO;
exports.GO_FORWARD = _actionTypes.GO_FORWARD;
exports.GO_BACK = _actionTypes.GO_BACK;
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _redux = __webpack_require__(2);
var _createMatcher = __webpack_require__(16);
var _createMatcher2 = _interopRequireDefault(_createMatcher);
var _reducer = __webpack_require__(26);
var _reducer2 = _interopRequireDefault(_reducer);
var _middleware = __webpack_require__(28);
var _middleware2 = _interopRequireDefault(_middleware);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
exports.default = function (_ref) {
var middleware = _ref.middleware;
var routes = _ref.routes;
var history = _ref.history;
var _ref$createMatcher = _ref.createMatcher;
var createMatcher = _ref$createMatcher === undefined ? _createMatcher2.default : _ref$createMatcher;
return function (createStore) {
return function (reducer, initialState) {
var enhancedReducer = function enhancedReducer(state, action) {
var vanillaState = _extends({}, state);
delete vanillaState.router;
return _extends({}, reducer(vanillaState, action), {
router: (0, _reducer2.default)(routes, createMatcher)(state.router, action)
});
};
return createStore(enhancedReducer, initialState, _redux.applyMiddleware.apply(undefined, [(0, _middleware2.default)(history)].concat(_toConsumableArray(middleware))));
};
};
};
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
exports.__esModule = true;
exports.compose = exports.applyMiddleware = exports.bindActionCreators = exports.combineReducers = exports.createStore = undefined;
var _createStore = __webpack_require__(4);
var _createStore2 = _interopRequireDefault(_createStore);
var _combineReducers = __webpack_require__(11);
var _combineReducers2 = _interopRequireDefault(_combineReducers);
var _bindActionCreators = __webpack_require__(13);
var _bindActionCreators2 = _interopRequireDefault(_bindActionCreators);
var _applyMiddleware = __webpack_require__(14);
var _applyMiddleware2 = _interopRequireDefault(_applyMiddleware);
var _compose = __webpack_require__(15);
var _compose2 = _interopRequireDefault(_compose);
var _warning = __webpack_require__(12);
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/*
* This is a dummy function to check if the function name has been altered by minification.
* If the function has been minified and NODE_ENV !== 'production', warn the user.
*/
function isCrushed() {}
if (process.env.NODE_ENV !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') {
(0, _warning2["default"])('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.');
}
exports.createStore = _createStore2["default"];
exports.combineReducers = _combineReducers2["default"];
exports.bindActionCreators = _bindActionCreators2["default"];
exports.applyMiddleware = _applyMiddleware2["default"];
exports.compose = _compose2["default"];
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 3 */
/***/ function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.ActionTypes = undefined;
exports["default"] = createStore;
var _isPlainObject = __webpack_require__(5);
var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
var _symbolObservable = __webpack_require__(9);
var _symbolObservable2 = _interopRequireDefault(_symbolObservable);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* These are private action types reserved by Redux.
* For any unknown actions, you must return the current state.
* If the current state is undefined, you must return the initial state.
* Do not reference these action types directly in your code.
*/
var ActionTypes = exports.ActionTypes = {
INIT: '@@redux/INIT'
};
/**
* Creates a Redux store that holds the state tree.
* The only way to change the data in the store is to call `dispatch()` on it.
*
* There should only be a single store in your app. To specify how different
* parts of the state tree respond to actions, you may combine several reducers
* into a single reducer function by using `combineReducers`.
*
* @param {Function} reducer A function that returns the next state tree, given
* the current state tree and the action to handle.
*
* @param {any} [initialState] The initial state. You may optionally specify it
* to hydrate the state from the server in universal apps, or to restore a
* previously serialized user session.
* If you use `combineReducers` to produce the root reducer function, this must be
* an object with the same shape as `combineReducers` keys.
*
* @param {Function} enhancer The store enhancer. You may optionally specify it
* to enhance the store with third-party capabilities such as middleware,
* time travel, persistence, etc. The only store enhancer that ships with Redux
* is `applyMiddleware()`.
*
* @returns {Store} A Redux store that lets you read the state, dispatch actions
* and subscribe to changes.
*/
function createStore(reducer, initialState, enhancer) {
var _ref2;
if (typeof initialState === 'function' && typeof enhancer === 'undefined') {
enhancer = initialState;
initialState = undefined;
}
if (typeof enhancer !== 'undefined') {
if (typeof enhancer !== 'function') {
throw new Error('Expected the enhancer to be a function.');
}
return enhancer(createStore)(reducer, initialState);
}
if (typeof reducer !== 'function') {
throw new Error('Expected the reducer to be a function.');
}
var currentReducer = reducer;
var currentState = initialState;
var currentListeners = [];
var nextListeners = currentListeners;
var isDispatching = false;
function ensureCanMutateNextListeners() {
if (nextListeners === currentListeners) {
nextListeners = currentListeners.slice();
}
}
/**
* Reads the state tree managed by the store.
*
* @returns {any} The current state tree of your application.
*/
function getState() {
return currentState;
}
/**
* Adds a change listener. It will be called any time an action is dispatched,
* and some part of the state tree may potentially have changed. You may then
* call `getState()` to read the current state tree inside the callback.
*
* You may call `dispatch()` from a change listener, with the following
* caveats:
*
* 1. The subscriptions are snapshotted just before every `dispatch()` call.
* If you subscribe or unsubscribe while the listeners are being invoked, this
* will not have any effect on the `dispatch()` that is currently in progress.
* However, the next `dispatch()` call, whether nested or not, will use a more
* recent snapshot of the subscription list.
*
* 2. The listener should not expect to see all state changes, as the state
* might have been updated multiple times during a nested `dispatch()` before
* the listener is called. It is, however, guaranteed that all subscribers
* registered before the `dispatch()` started will be called with the latest
* state by the time it exits.
*
* @param {Function} listener A callback to be invoked on every dispatch.
* @returns {Function} A function to remove this change listener.
*/
function subscribe(listener) {
if (typeof listener !== 'function') {
throw new Error('Expected listener to be a function.');
}
var isSubscribed = true;
ensureCanMutateNextListeners();
nextListeners.push(listener);
return function unsubscribe() {
if (!isSubscribed) {
return;
}
isSubscribed = false;
ensureCanMutateNextListeners();
var index = nextListeners.indexOf(listener);
nextListeners.splice(index, 1);
};
}
/**
* Dispatches an action. It is the only way to trigger a state change.
*
* The `reducer` function, used to create the store, will be called with the
* current state tree and the given `action`. Its return value will
* be considered the **next** state of the tree, and the change listeners
* will be notified.
*
* The base implementation only supports plain object actions. If you want to
* dispatch a Promise, an Observable, a thunk, or something else, you need to
* wrap your store creating function into the corresponding middleware. For
* example, see the documentation for the `redux-thunk` package. Even the
* middleware will eventually dispatch plain object actions using this method.
*
* @param {Object} action A plain object representing “what changed”. It is
* a good idea to keep actions serializable so you can record and replay user
* sessions, or use the time travelling `redux-devtools`. An action must have
* a `type` property which may not be `undefined`. It is a good idea to use
* string constants for action types.
*
* @returns {Object} For convenience, the same action object you dispatched.
*
* Note that, if you use a custom middleware, it may wrap `dispatch()` to
* return something else (for example, a Promise you can await).
*/
function dispatch(action) {
if (!(0, _isPlainObject2["default"])(action)) {
throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.');
}
if (typeof action.type === 'undefined') {
throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?');
}
if (isDispatching) {
throw new Error('Reducers may not dispatch actions.');
}
try {
isDispatching = true;
currentState = currentReducer(currentState, action);
} finally {
isDispatching = false;
}
var listeners = currentListeners = nextListeners;
for (var i = 0; i < listeners.length; i++) {
listeners[i]();
}
return action;
}
/**
* Replaces the reducer currently used by the store to calculate the state.
*
* You might need this if your app implements code splitting and you want to
* load some of the reducers dynamically. You might also need this if you
* implement a hot reloading mechanism for Redux.
*
* @param {Function} nextReducer The reducer for the store to use instead.
* @returns {void}
*/
function replaceReducer(nextReducer) {
if (typeof nextReducer !== 'function') {
throw new Error('Expected the nextReducer to be a function.');
}
currentReducer = nextReducer;
dispatch({ type: ActionTypes.INIT });
}
/**
* Interoperability point for observable/reactive libraries.
* @returns {observable} A minimal observable of state changes.
* For more information, see the observable proposal:
* https://github.com/zenparsing/es-observable
*/
function observable() {
var _ref;
var outerSubscribe = subscribe;
return _ref = {
/**
* The minimal observable subscription method.
* @param {Object} observer Any object that can be used as an observer.
* The observer object should have a `next` method.
* @returns {subscription} An object with an `unsubscribe` method that can
* be used to unsubscribe the observable from the store, and prevent further
* emission of values from the observable.
*/
subscribe: function subscribe(observer) {
if (typeof observer !== 'object') {
throw new TypeError('Expected the observer to be an object.');
}
function observeState() {
if (observer.next) {
observer.next(getState());
}
}
observeState();
var unsubscribe = outerSubscribe(observeState);
return { unsubscribe: unsubscribe };
}
}, _ref[_symbolObservable2["default"]] = function () {
return this;
}, _ref;
}
// When a store is created, an "INIT" action is dispatched so that every
// reducer returns their initial state. This effectively populates
// the initial state tree.
dispatch({ type: ActionTypes.INIT });
return _ref2 = {
dispatch: dispatch,
subscribe: subscribe,
getState: getState,
replaceReducer: replaceReducer
}, _ref2[_symbolObservable2["default"]] = observable, _ref2;
}
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
var getPrototype = __webpack_require__(6),
isHostObject = __webpack_require__(7),
isObjectLike = __webpack_require__(8);
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object,
* else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) ||
objectToString.call(value) != objectTag || isHostObject(value)) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return (typeof Ctor == 'function' &&
Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
}
module.exports = isPlainObject;
/***/ },
/* 6 */
/***/ function(module, exports) {
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetPrototype = Object.getPrototypeOf;
/**
* Gets the `[[Prototype]]` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {null|Object} Returns the `[[Prototype]]`.
*/
function getPrototype(value) {
return nativeGetPrototype(Object(value));
}
module.exports = getPrototype;
/***/ },
/* 7 */
/***/ function(module, exports) {
/**
* Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
*/
function isHostObject(value) {
// Many host objects are `Object` objects that can coerce to strings
// despite having improperly defined `toString` methods.
var result = false;
if (value != null && typeof value.toString != 'function') {
try {
result = !!(value + '');
} catch (e) {}
}
return result;
}
module.exports = isHostObject;
/***/ },
/* 8 */
/***/ function(module, exports) {
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
module.exports = isObjectLike;
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {/* global window */
'use strict';
module.exports = __webpack_require__(10)(global || window || this);
/* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
/***/ },
/* 10 */
/***/ function(module, exports) {
'use strict';
module.exports = function symbolObservablePonyfill(root) {
var result;
var Symbol = root.Symbol;
if (typeof Symbol === 'function') {
if (Symbol.observable) {
result = Symbol.observable;
} else {
if (typeof Symbol.for === 'function') {
result = Symbol.for('observable');
} else {
result = Symbol('observable');
}
Symbol.observable = result;
}
} else {
result = '@@observable';
}
return result;
};
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {'use strict';
exports.__esModule = true;
exports["default"] = combineReducers;
var _createStore = __webpack_require__(4);
var _isPlainObject = __webpack_require__(5);
var _isPlainObject2 = _interopRequireDefault(_isPlainObject);
var _warning = __webpack_require__(12);
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function getUndefinedStateErrorMessage(key, action) {
var actionType = action && action.type;
var actionName = actionType && '"' + actionType.toString() + '"' || 'an action';
return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state.';
}
function getUnexpectedStateShapeWarningMessage(inputState, reducers, action) {
var reducerKeys = Object.keys(reducers);
var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'initialState argument passed to createStore' : 'previous state received by the reducer';
if (reducerKeys.length === 0) {
return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
}
if (!(0, _isPlainObject2["default"])(inputState)) {
return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"');
}
var unexpectedKeys = Object.keys(inputState).filter(function (key) {
return !reducers.hasOwnProperty(key);
});
if (unexpectedKeys.length > 0) {
return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.');
}
}
function assertReducerSanity(reducers) {
Object.keys(reducers).forEach(function (key) {
var reducer = reducers[key];
var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT });
if (typeof initialState === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.');
}
var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.');
if (typeof reducer(undefined, { type: type }) === 'undefined') {
throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.');
}
});
}
/**
* Turns an object whose values are different reducer functions, into a single
* reducer function. It will call every child reducer, and gather their results
* into a single state object, whose keys correspond to the keys of the passed
* reducer functions.
*
* @param {Object} reducers An object whose values correspond to different
* reducer functions that need to be combined into one. One handy way to obtain
* it is to use ES6 `import * as reducers` syntax. The reducers may never return
* undefined for any action. Instead, they should return their initial state
* if the state passed to them was undefined, and the current state for any
* unrecognized action.
*
* @returns {Function} A reducer function that invokes every reducer inside the
* passed object, and builds a state object with the same shape.
*/
function combineReducers(reducers) {
var reducerKeys = Object.keys(reducers);
var finalReducers = {};
for (var i = 0; i < reducerKeys.length; i++) {
var key = reducerKeys[i];
if (typeof reducers[key] === 'function') {
finalReducers[key] = reducers[key];
}
}
var finalReducerKeys = Object.keys(finalReducers);
var sanityError;
try {
assertReducerSanity(finalReducers);
} catch (e) {
sanityError = e;
}
return function combination() {
var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var action = arguments[1];
if (sanityError) {
throw sanityError;
}
if (process.env.NODE_ENV !== 'production') {
var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action);
if (warningMessage) {
(0, _warning2["default"])(warningMessage);
}
}
var hasChanged = false;
var nextState = {};
for (var i = 0; i < finalReducerKeys.length; i++) {
var key = finalReducerKeys[i];
var reducer = finalReducers[key];
var previousStateForKey = state[key];
var nextStateForKey = reducer(previousStateForKey, action);
if (typeof nextStateForKey === 'undefined') {
var errorMessage = getUndefinedStateErrorMessage(key, action);
throw new Error(errorMessage);
}
nextState[key] = nextStateForKey;
hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
}
return hasChanged ? nextState : state;
};
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ },
/* 12 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports["default"] = warning;
/**
* Prints a warning in the console if it exists.
*
* @param {String} message The warning message.
* @returns {void}
*/
function warning(message) {
/* eslint-disable no-console */
if (typeof console !== 'undefined' && typeof console.error === 'function') {
console.error(message);
}
/* eslint-enable no-console */
try {
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
/* eslint-disable no-empty */
} catch (e) {}
/* eslint-enable no-empty */
}
/***/ },
/* 13 */
/***/ function(module, exports) {
'use strict';
exports.__esModule = true;
exports["default"] = bindActionCreators;
function bindActionCreator(actionCreator, dispatch) {
return function () {
return dispatch(actionCreator.apply(undefined, arguments));
};
}
/**
* Turns an object whose values are action creators, into an object with the
* same keys, but with every function wrapped into a `dispatch` call so they
* may be invoked directly. This is just a convenience method, as you can call
* `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
*
* For convenience, you can also pass a single function as the first argument,
* and get a function in return.
*
* @param {Function|Object} actionCreators An object whose values are action
* creator functions. One handy way to obtain it is to use ES6 `import * as`
* syntax. You may also pass a single function.
*
* @param {Function} dispatch The `dispatch` function available on your Redux
* store.
*
* @returns {Function|Object} The object mimicking the original object, but with
* every action creator wrapped into the `dispatch` call. If you passed a
* function as `actionCreators`, the return value will also be a single
* function.
*/
function bindActionCreators(actionCreators, dispatch) {
if (typeof actionCreators === 'function') {
return bindActionCreator(actionCreators, dispatch);
}
if (typeof actionCreators !== 'object' || actionCreators === null) {
throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');
}
var keys = Object.keys(actionCreators);
var boundActionCreators = {};
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var actionCreator = actionCreators[key];
if (typeof actionCreator === 'function') {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
}
}
return boundActionCreators;
}
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports["default"] = applyMiddleware;
var _compose = __webpack_require__(15);
var _compose2 = _interopRequireDefault(_compose);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/**
* Creates a store enhancer that applies middleware to the dispatch method
* of the Redux store. This is handy for a variety of tasks, such as expressing
* asynchronous actions in a concise manner, or logging every action payload.
*
* See `redux-thunk` package as an example of the Redux middleware.
*
* Because middleware is potentially asynchronous, this should be the first
* store enhancer in the composition chain.
*
* Note that each middleware will be given the `dispatch` and `getState` functions
* as named arguments.
*
* @param {...Function} middlewares The middleware chain to be applied.
* @returns {Function} A store enhancer applying the middleware.
*/
function applyMiddleware() {
for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) {
middlewares[_key] = arguments[_key];
}
return function (createStore) {
return function (reducer, initialState, enhancer) {
var store = createStore(reducer, initialState, enhancer);
var _dispatch = store.dispatch;
var chain = [];
var middlewareAPI = {
getState: store.getState,
dispatch: function dispatch(action) {
return _dispatch(action);
}
};
chain = middlewares.map(function (middleware) {
return middleware(middlewareAPI);
});
_dispatch = _compose2["default"].apply(undefined, chain)(store.dispatch);
return _extends({}, store, {
dispatch: _dispatch
});
};
};
}
/***/ },
/* 15 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
exports["default"] = compose;
/**
* Composes single-argument functions from right to left. The rightmost
* function can take multiple arguments as it provides the signature for
* the resulting composite function.
*
* @param {...Function} funcs The functions to compose.
* @returns {Function} A function obtained by composing the argument functions
* from right to left. For example, compose(f, g, h) is identical to doing
* (...args) => f(g(h(...args))).
*/
function compose() {
for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) {
funcs[_key] = arguments[_key];
}
if (funcs.length === 0) {
return function (arg) {
return arg;
};
} else {
var _ret = function () {
var last = funcs[funcs.length - 1];
var rest = funcs.slice(0, -1);
return {
v: function v() {
return rest.reduceRight(function (composed, f) {
return f(composed);
}, last.apply(undefined, arguments));
}
};
}();
if (typeof _ret === "object") return _ret.v;
}
}
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _urlPattern = __webpack_require__(17);
var _urlPattern2 = _interopRequireDefault(_urlPattern);
var _lodash = __webpack_require__(19);
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (routes) {
var routeCache = Object.keys(routes).map(function (key) {
return {
pattern: new _urlPattern2.default(key),
result: routes[key]
};
});
return function (incomingRoute) {
var match = (0, _lodash2.default)(routeCache, function (route) {
return route.pattern.match(incomingRoute);
}) || null;
return match ? {
params: match.pattern.match(incomingRoute),
result: match.result
} : null;
};
};
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Generated by CoffeeScript 1.10.0
var slice = [].slice;
(function(root, factory) {
if (('function' === "function") && (__webpack_require__(18) != null)) {
return !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (typeof exports !== "undefined" && exports !== null) {
return module.exports = factory();
} else {
return root.UrlPattern = factory();
}
})(this, function() {
var P, UrlPattern, astNodeContainsSegmentsForProvidedParams, astNodeToNames, astNodeToRegexString, baseAstNodeToRegexString, concatMap, defaultOptions, escapeForRegex, getParam, keysAndValuesToObject, newParser, regexGroupCount, stringConcatMap, stringify;
escapeForRegex = function(string) {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
concatMap = function(array, f) {
var i, length, results;
results = [];
i = -1;
length = array.length;
while (++i < length) {
results = results.concat(f(array[i]));
}
return results;
};
stringConcatMap = function(array, f) {
var i, length, result;
result = '';
i = -1;
length = array.length;
while (++i < length) {
result += f(array[i]);
}
return result;
};
regexGroupCount = function(regex) {
return (new RegExp(regex.toString() + '|')).exec('').length - 1;
};
keysAndValuesToObject = function(keys, values) {
var i, key, length, object, value;
object = {};
i = -1;
length = keys.length;
while (++i < length) {
key = keys[i];
value = values[i];
if (value == null) {
continue;
}
if (object[key] != null) {
if (!Array.isArray(object[key])) {
object[key] = [object[key]];
}
object[key].push(value);
} else {
object[key] = value;
}
}
return object;
};
P = {};
P.Result = function(value, rest) {
this.value = value;
this.rest = rest;
};
P.Tagged = function(tag, value) {
this.tag = tag;
this.value = value;
};
P.tag = function(tag, parser) {
return function(input) {
var result, tagged;
result = parser(input);
if (result == null) {
return;
}
tagged = new P.Tagged(tag, result.value);
return new P.Result(tagged, result.rest);
};
};
P.regex = function(regex) {
return function(input) {
var matches, result;
matches = regex.exec(input);
if (matches == null) {
return;
}
result = matches[0];
return new P.Result(result, input.slice(result.length));
};
};
P.sequence = function() {
var parsers;
parsers = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return function(input) {
var i, length, parser, rest, result, values;
i = -1;
length = parsers.length;
values = [];
rest = input;
while (++i < length) {
parser = parsers[i];
result = parser(rest);
if (result == null) {
return;
}
values.push(result.value);
rest = result.rest;
}
return new P.Result(values, rest);
};
};
P.pick = function() {
var indexes, parsers;
indexes = arguments[0], parsers = 2 <= arguments.length ? slice.call(arguments, 1) : [];
return function(input) {
var array, result;
result = P.sequence.apply(P, parsers)(input);
if (result == null) {
return;
}
array = result.value;
result.value = array[indexes];
return result;
};
};
P.string = function(string) {
var length;
length = string.length;
return function(input) {
if (input.slice(0, length) === string) {
return new P.Result(string, input.slice(length));
}
};
};
P.lazy = function(fn) {
var cached;
cached = null;
return function(input) {
if (cached == null) {
cached = fn();
}
return cached(input);
};
};
P.baseMany = function(parser, end, stringResult, atLeastOneResultRequired, input) {
var endResult, parserResult, rest, results;
rest = input;
results = stringResult ? '' : [];
while (true) {
if (end != null) {
endResult = end(rest);
if (endResult != null) {
break;
}
}
parserResult = parser(rest);
if (parserResult == null) {
break;
}
if (stringResult) {
results += parserResult.value;
} else {
results.push(parserResult.value);
}
rest = parserResult.rest;
}
if (atLeastOneResultRequired && results.length === 0) {
return;
}
return new P.Result(results, rest);
};
P.many1 = function(parser) {
return function(input) {
return P.baseMany(parser, null, false, true, input);
};
};
P.concatMany1Till = function(parser, end) {
return function(input) {
return P.baseMany(parser, end, true, true, input);
};
};
P.firstChoice = function() {
var parsers;
parsers = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return function(input) {
var i, length, parser, result;
i = -1;
length = parsers.length;
while (++i < length) {
parser = parsers[i];
result = parser(input);
if (result != null) {
return result;
}
}
};
};
newParser = function(options) {
var U;
U = {};
U.wildcard = P.tag('wildcard', P.string(options.wildcardChar));
U.optional = P.tag('optional', P.pick(1, P.string(options.optionalSegmentStartChar), P.lazy(function() {
return U.pattern;
}), P.string(options.optionalSegmentEndChar)));
U.name = P.regex(new RegExp("^[" + options.segmentNameCharset + "]+"));
U.named = P.tag('named', P.pick(1, P.string(options.segmentNameStartChar), P.lazy(function() {
return U.name;
})));
U.escapedChar = P.pick(1, P.string(options.escapeChar), P.regex(/^./));
U["static"] = P.tag('static', P.concatMany1Till(P.firstChoice(P.lazy(function() {
return U.escapedChar;
}), P.regex(/^./)), P.firstChoice(P.string(options.segmentNameStartChar), P.string(options.optionalSegmentStartChar), P.string(options.optionalSegmentEndChar), U.wildcard)));
U.token = P.lazy(function() {
return P.firstChoice(U.wildcard, U.optional, U.named, U["static"]);
});
U.pattern = P.many1(P.lazy(function() {
return U.token;
}));
return U;
};
defaultOptions = {
escapeChar: '\\',
segmentNameStartChar: ':',
segmentValueCharset: 'a-zA-Z0-9-_~ %',
segmentNameCharset: 'a-zA-Z0-9',
optionalSegmentStartChar: '(',
optionalSegmentEndChar: ')',
wildcardChar: '*'
};
baseAstNodeToRegexString = function(astNode, segmentValueCharset) {
if (Array.isArray(astNode)) {
return stringConcatMap(astNode, function(node) {
return baseAstNodeToRegexString(node, segmentValueCharset);
});
}
switch (astNode.tag) {
case 'wildcard':
return '(.*?)';
case 'named':
return "([" + segmentValueCharset + "]+)";
case 'static':
return escapeForRegex(astNode.value);
case 'optional':
return '(?:' + baseAstNodeToRegexString(astNode.value, segmentValueCharset) + ')?';
}
};
astNodeToRegexString = function(astNode, segmentValueCharset) {
if (segmentValueCharset == null) {
segmentValueCharset = defaultOptions.segmentValueCharset;
}
return '^' + baseAstNodeToRegexString(astNode, segmentValueCharset) + '$';
};
astNodeToNames = function(astNode) {
if (Array.isArray(astNode)) {
return concatMap(astNode, astNodeToNames);
}
switch (astNode.tag) {
case 'wildcard':
return ['_'];
case 'named':
return [astNode.value];
case 'static':
return [];
case 'optional':
return astNodeToNames(astNode.value);
}
};
getParam = function(params, key, nextIndexes, sideEffects) {
var index, maxIndex, result, value;
if (sideEffects == null) {
sideEffects = false;
}
value = params[key];
if (value == null) {
if (sideEffects) {
throw new Error("no values provided for key `" + key + "`");
} else {
return;
}
}
index = nextIndexes[key] || 0;
maxIndex = Array.isArray(value) ? value.length - 1 : 0;
if (index > maxIndex) {
if (sideEffects) {
throw new Error("too few values provided for key `" + key + "`");
} else {
return;
}
}
result = Array.isArray(value) ? value[index] : value;
if (sideEffects) {
nextIndexes[key] = index + 1;
}
return result;
};
astNodeContainsSegmentsForProvidedParams = function(astNode, params, nextIndexes) {
var i, length;
if (Array.isArray(astNode)) {
i = -1;
length = astNode.length;
while (++i < length) {
if (astNodeContainsSegmentsForProvidedParams(astNode[i], params, nextIndexes)) {
return true;
}
}
return false;
}
switch (astNode.tag) {
case 'wildcard':
return getParam(params, '_', nextIndexes, false) != null;
case 'named':
return getParam(params, astNode.value, nextIndexes, false) != null;
case 'static':
return false;
case 'optional':
return astNodeContainsSegmentsForProvidedParams(astNode.value, params, nextIndexes);
}
};
stringify = function(astNode, params, nextIndexes) {
if (Array.isArray(astNode)) {
return stringConcatMap(astNode, function(node) {
return stringify(node, params, nextIndexes);
});
}
switch (astNode.tag) {
case 'wildcard':
return getParam(params, '_', nextIndexes, true);
case 'named':
return getParam(params, astNode.value, nextIndexes, true);
case 'static':
return astNode.value;
case 'optional':
if (astNodeContainsSegmentsForProvidedParams(astNode.value, params, nextIndexes)) {
return stringify(astNode.value, params, nextIndexes);
} else {
return '';
}
}
};
UrlPattern = function(arg1, arg2) {
var groupCount, options, parsed, parser, withoutWhitespace;
if (arg1 instanceof UrlPattern) {
this.isRegex = arg1.isRegex;
this.regex = arg1.regex;
this.ast = arg1.ast;
this.names = arg1.names;
return;
}
this.isRegex = arg1 instanceof RegExp;
if (!(('string' === typeof arg1) || this.isRegex)) {
throw new TypeError('argument must be a regex or a string');
}
if (this.isRegex) {
this.regex = arg1;
if (arg2 != null) {
if (!Array.isArray(arg2)) {
throw new Error('if first argument is a regex the second argument may be an array of group names but you provided something else');
}
groupCount = regexGroupCount(this.regex);
if (arg2.length !== groupCount) {
throw new Error("regex contains " + groupCount + " groups but array of group names contains " + arg2.length);
}
this.names = arg2;
}
return;
}
if (arg1 === '') {
throw new Error('argument must not be the empty string');
}
withoutWhitespace = arg1.replace(/\s+/g, '');
if (withoutWhitespace !== arg1) {
throw new Error('argument must not contain whitespace');
}
options = {
escapeChar: (arg2 != null ? arg2.escapeChar : void 0) || defaultOptions.escapeChar,
segmentNameStartChar: (arg2 != null ? arg2.segmentNameStartChar : void 0) || defaultOptions.segmentNameStartChar,
segmentNameCharset: (arg2 != null ? arg2.segmentNameCharset : void 0) || defaultOptions.segmentNameCharset,
segmentValueCharset: (arg2 != null ? arg2.segmentValueCharset : void 0) || defaultOptions.segmentValueCharset,
optionalSegmentStartChar: (arg2 != null ? arg2.optionalSegmentStartChar : void 0) || defaultOptions.optionalSegmentStartChar,
optionalSegmentEndChar: (arg2 != null ? arg2.optionalSegmentEndChar : void 0) || defaultOptions.optionalSegmentEndChar,
wildcardChar: (arg2 != null ? arg2.wildcardChar : void 0) || defaultOptions.wildcardChar
};
parser = newParser(options);
parsed = parser.pattern(arg1);
if (parsed == null) {
throw new Error("couldn't parse pattern");
}
if (parsed.rest !== '') {
throw new Error("could only partially parse pattern");
}
this.ast = parsed.value;
this.regex = new RegExp(astNodeToRegexString(this.ast, options.segmentValueCharset));
this.names = astNodeToNames(this.ast);
};
UrlPattern.prototype.match = function(url) {
var groups, match;
match = this.regex.exec(url);
if (match == null) {
return null;
}
groups = match.slice(1);
if (this.names) {
return keysAndValuesToObject(this.names, groups);
} else {
return groups;
}
};
UrlPattern.prototype.stringify = function(params) {
if (params == null) {
params = {};
}
if (this.isRegex) {
throw new Error("can't stringify patterns generated from a regex");
}
if (params !== Object(params)) {
throw new Error("argument must be an object or undefined");
}
return stringify(this.ast, params, {});
};
UrlPattern.escapeForRegex = escapeForRegex;
UrlPattern.concatMap = concatMap;
UrlPattern.stringConcatMap = stringConcatMap;
UrlPattern.regexGroupCount = regexGroupCount;
UrlPattern.keysAndValuesToObject = keysAndValuesToObject;
UrlPattern.P = P;
UrlPattern.newParser = newParser;
UrlPattern.defaultOptions = defaultOptions;
UrlPattern.astNodeToRegexString = astNodeToRegexString;
UrlPattern.astNodeToNames = astNodeToNames;
UrlPattern.getParam = getParam;
UrlPattern.astNodeContainsSegmentsForProvidedParams = astNodeContainsSegmentsForProvidedParams;
UrlPattern.stringify = stringify;
return UrlPattern;
});
/***/ },
/* 18 */
/***/ function(module, exports) {
/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__;
/* WEBPACK VAR INJECTION */}.call(exports, {}))
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
/**
* lodash 4.3.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
var baseEach = __webpack_require__(20),
baseFind = __webpack_require__(21),
baseFindIndex = __webpack_require__(22),
baseIteratee = __webpack_require__(23);
/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to search.
* @param {Array|Function|Object|string} [predicate=_.identity]
* The function invoked per iteration.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
* _.find(users, function(o) { return o.age < 40; });
* // => object for 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.find(users, { 'age': 1, 'active': true });
* // => object for 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.find(users, ['active', false]);
* // => object for 'fred'
*
* // The `_.property` iteratee shorthand.
* _.find(users, 'active');
* // => object for 'barney'
*/
function find(collection, predicate) {
predicate = baseIteratee(predicate, 3);
if (isArray(collection)) {
var index = baseFindIndex(collection, predicate);
return index > -1 ? collection[index] : undefined;
}
return baseFind(collection, predicate, baseEach);
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @type {Function}
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
module.exports = find;
/***/ },
/* 20 */
/***/ function(module, exports) {
/**
* lodash 4.1.2 (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
stringTag = '[object String]';
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetPrototype = Object.getPrototypeOf,
nativeKeys = Object.keys;
/**
* The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEach = createBaseEach(baseForOwn);
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` invoking `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return object && baseFor(object, iteratee, keys);
}
/**
* The base implementation of `_.has` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHas(object, key) {
// Avoid a bug in IE 10-11 where objects with a [[Prototype]] of `null`,
// that are composed entirely of index properties, return `false` for
// `hasOwnProperty` checks of them.
return hasOwnProperty.call(object, key) ||
(typeof object == 'object' && key in object && getPrototype(object) === null);
}
/**
* The base implementation of `_.keys` which doesn't skip the constructor
* property of prototypes or treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
return nativeKeys(Object(object));
}
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length,
index = fromRight ? length : -1,
iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a
* [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) that affects
* Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Gets the `[[Prototype]]` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {null|Object} Returns the `[[Prototype]]`.
*/
function getPrototype(value) {
return nativeGetPrototype(Object(value));
}
/**
* Creates an array of index keys for `object` values of arrays,
* `arguments` objects, and strings, otherwise `null` is returned.
*
* @private
* @param {Object} object The object to query.
* @returns {Array|null} Returns index keys, else `null`.
*/
function indexKeys(object) {
var length = object ? object.length : undefined;
if (isLength(length) &&
(isArray(object) || isString(object) || isArguments(object))) {
return baseTimes(length, String);
}
return null;
}
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
// Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode.
return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
(!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @type {Function}
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value)) && !isFunction(value);
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 8 which returns 'object' for typed array and weak map constructors,
// and PhantomJS 1.9 which returns 'function' for `NodeList` instances.
var tag = isObject(value) ? objectToString.call(value) : '';
return tag == funcTag || tag == genTag;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length,
* else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag);
}
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
var isProto = isPrototype(object);
if (!(isProto || isArrayLike(object))) {
return baseKeys(object);
}
var indexes = indexKeys(object),
skipIndexes = !!indexes,
result = indexes || [],
length = result.length;
for (var key in object) {
if (baseHas(object, key) &&
!(skipIndexes && (key == 'length' || isIndex(key, length))) &&
!(isProto && key == 'constructor')) {
result.push(key);
}
}
return result;
}
module.exports = baseEach;
/***/ },
/* 21 */
/***/ function(module, exports) {
/**
* lodash 3.0.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`,
* without support for callback shorthands and `this` binding, which iterates
* over `collection` using the provided `eachFunc`.
*
* @private
* @param {Array|Object|string} collection The collection to search.
* @param {Function} predicate The function invoked per iteration.
* @param {Function} eachFunc The function to iterate over `collection`.
* @param {boolean} [retKey] Specify returning the key of the found element
* instead of the element itself.
* @returns {*} Returns the found element or its key, else `undefined`.
*/
function baseFind(collection, predicate, eachFunc, retKey) {
var result;
eachFunc(collection, function(value, key, collection) {
if (predicate(value, key, collection)) {
result = retKey ? key : value;
return false;
}
});
return result;
}
module.exports = baseFind;
/***/ },
/* 22 */
/***/ function(module, exports) {
/**
* lodash 3.6.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for callback shorthands and `this` binding.
*
* @private
* @param {Array} array The array to search.
* @param {Function} predicate The function invoked per iteration.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromRight) {
var length = array.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
module.exports = baseFindIndex;
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module, global) {/**
* lodash 4.6.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
var stringToPath = __webpack_require__(25);
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used to compose bitmasks for comparison styles. */
var UNORDERED_COMPARE_FLAG = 1,
PARTIAL_COMPARE_FLAG = 2;
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/;
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/** Used to determine if values are of the language type `Object`. */
var objectTypes = {
'function': true,
'object': true
};
/** Detect free variable `exports`. */
var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType)
? exports
: undefined;
/** Detect free variable `module`. */
var freeModule = (objectTypes[typeof module] && module && !module.nodeType)
? module
: undefined;
/** Detect free variable `global` from Node.js. */
var freeGlobal = checkGlobal(freeExports && freeModule && typeof global == 'object' && global);
/** Detect free variable `self`. */
var freeSelf = checkGlobal(objectTypes[typeof self] && self);
/** Detect free variable `window`. */
var freeWindow = checkGlobal(objectTypes[typeof window] && window);
/** Detect `this` as the global object. */
var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
/**
* Used as a reference to the global object.
*
* The `this` value is used if it's the global object to avoid Greasemonkey's
* restricted `window` object, otherwise the `window` object is used.
*/
var root = freeGlobal ||
((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) ||
freeSelf || thisGlobal || Function('return this')();
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
* of key-value pairs for `object` corresponding to the property names of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the new array of key-value pairs.
*/
function baseToPairs(object, props) {
return arrayMap(props, function(key) {
return [key, object[key]];
});
}
/**
* Checks if `value` is a global object.
*
* @private
* @param {*} value The value to check.
* @returns {null|Object} Returns `value` if it's a global object, else `null`.
*/
function checkGlobal(value) {
return (value && value.Object === Object) ? value : null;
}
/**
* Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
*/
function isHostObject(value) {
// Many host objects are `Object` objects that can coerce to strings
// despite having improperly defined `toString` methods.
var result = false;
if (value != null && typeof value.toString != 'function') {
try {
result = !!(value + '');
} catch (e) {}
}
return result;
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
/**
* Converts `map` to an array.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the converted array.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
/**
* Converts `set` to an array.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the converted array.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
/** Used for built-in method references. */
var arrayProto = Array.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/** Built-in value references. */
var Symbol = root.Symbol,
Uint8Array = root.Uint8Array,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayProto.splice;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetPrototype = Object.getPrototypeOf,
nativeKeys = Object.keys;
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView'),
Map = getNative(root, 'Map'),
Promise = getNative(root, 'Promise'),
Set = getNative(root, 'Set'),
WeakMap = getNative(root, 'WeakMap'),
nativeCreate = getNative(Object, 'create');
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a hash object.
*
* @private
* @constructor
* @returns {Object} Returns the new hash object.
*/
function Hash() {}
/**
* Removes `key` and its value from the hash.
*
* @private
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(hash, key) {
return hashHas(hash, key) && delete hash[key];
}
/**
* Gets the hash value for `key`.
*
* @private
* @param {Object} hash The hash to query.
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(hash, key) {
if (nativeCreate) {
var result = hash[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(hash, key) ? hash[key] : undefined;
}
/**
* Checks if a hash value for `key` exists.
*
* @private
* @param {Object} hash The hash to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(hash, key) {
return nativeCreate ? hash[key] !== undefined : hasOwnProperty.call(hash, key);
}
/**
* Sets the hash `key` to `value`.
*
* @private
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
*/
function hashSet(hash, key, value) {
hash[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
}
// Avoid inheriting from `Object.prototype` when possible.
Hash.prototype = nativeCreate ? nativeCreate(null) : objectProto;
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function MapCache(values) {
var index = -1,
length = values ? values.length : 0;
this.clear();
while (++index < length) {
var entry = values[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapClear() {
this.__data__ = {
'hash': new Hash,
'map': Map ? new Map : [],
'string': new Hash
};
}
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapDelete(key) {
var data = this.__data__;
if (isKeyable(key)) {
return hashDelete(typeof key == 'string' ? data.string : data.hash, key);
}
return Map ? data.map['delete'](key) : assocDelete(data.map, key);
}
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapGet(key) {
var data = this.__data__;
if (isKeyable(key)) {
return hashGet(typeof key == 'string' ? data.string : data.hash, key);
}
return Map ? data.map.get(key) : assocGet(data.map, key);
}
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapHas(key) {
var data = this.__data__;
if (isKeyable(key)) {
return hashHas(typeof key == 'string' ? data.string : data.hash, key);
}
return Map ? data.map.has(key) : assocHas(data.map, key);
}
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapSet(key, value) {
var data = this.__data__;
if (isKeyable(key)) {
hashSet(typeof key == 'string' ? data.string : data.hash, key, value);
} else if (Map) {
data.map.set(key, value);
} else {
assocSet(data.map, key, value);
}
return this;
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapClear;
MapCache.prototype['delete'] = mapDelete;
MapCache.prototype.get = mapGet;
MapCache.prototype.has = mapHas;
MapCache.prototype.set = mapSet;
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function Stack(values) {
var index = -1,
length = values ? values.length : 0;
this.clear();
while (++index < length) {
var entry = values[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = { 'array': [], 'map': null };
}
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
array = data.array;
return array ? assocDelete(array, key) : data.map['delete'](key);
}
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
var data = this.__data__,
array = data.array;
return array ? assocGet(array, key) : data.map.get(key);
}
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
var data = this.__data__,
array = data.array;
return array ? assocHas(array, key) : data.map.has(key);
}
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__,
array = data.array;
if (array) {
if (array.length < (LARGE_ARRAY_SIZE - 1)) {
assocSet(array, key, value);
} else {
data.array = null;
data.map = new MapCache(array);
}
}
var map = data.map;
if (map) {
map.set(key, value);
}
return this;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
/**
* Removes `key` and its value from the associative array.
*
* @private
* @param {Array} array The array to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function assocDelete(array, key) {
var index = assocIndexOf(array, key);
if (index < 0) {
return false;
}
var lastIndex = array.length - 1;
if (index == lastIndex) {
array.pop();
} else {
splice.call(array, index, 1);
}
return true;
}
/**
* Gets the associative array value for `key`.
*
* @private
* @param {Array} array The array to query.
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function assocGet(array, key) {
var index = assocIndexOf(array, key);
return index < 0 ? undefined : array[index][1];
}
/**
* Checks if an associative array value for `key` exists.
*
* @private
* @param {Array} array The array to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function assocHas(array, key) {
return assocIndexOf(array, key) > -1;
}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to search.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
/**
* Sets the associative array `key` to `value`.
*
* @private
* @param {Array} array The array to modify.
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
*/
function assocSet(array, key, value) {
var index = assocIndexOf(array, key);
if (index < 0) {
array.push([key, value]);
} else {
array[index][1] = value;
}
}
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @returns {Array} Returns the cast property path array.
*/
function baseCastPath(value) {
return isArray(value) ? value : stringToPath(value);
}
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path) {
path = isKey(path, object) ? [path] : baseCastPath(path);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[path[index++]];
}
return (index && index == length) ? object : undefined;
}
/**
* The base implementation of `_.has` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHas(object, key) {
// Avoid a bug in IE 10-11 where objects with a [[Prototype]] of `null`,
// that are composed entirely of index properties, return `false` for
// `hasOwnProperty` checks of them.
return hasOwnProperty.call(object, key) ||
(typeof object == 'object' && key in object && getPrototype(object) === null);
}
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHasIn(object, key) {
return key in Object(object);
}
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparisons.
* @param {boolean} [bitmask] The bitmask of comparison flags.
* The bitmask may be composed of the following flags:
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, customizer, bitmask, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack);
}
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparisons.
* @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = arrayTag,
othTag = arrayTag;
if (!objIsArr) {
objTag = getTag(object);
objTag = objTag == argsTag ? objectTag : objTag;
}
if (!othIsArr) {
othTag = getTag(other);
othTag = othTag == argsTag ? objectTag : othTag;
}
var objIsObj = objTag == objectTag && !isHostObject(object),
othIsObj = othTag == objectTag && !isHostObject(other),
isSameTag = objTag == othTag;
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, equalFunc, customizer, bitmask, stack)
: equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack);
}
if (!(bitmask & PARTIAL_COMPARE_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, equalFunc, customizer, bitmask, stack);
}
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var stack = new Stack;
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined
? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack)
: result
)) {
return false;
}
}
}
return true;
}
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/
function baseIteratee(value) {
// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if (typeof value == 'function') {
return value;
}
if (value == null) {
return identity;
}
if (typeof value == 'object') {
return isArray(value)
? baseMatchesProperty(value[0], value[1])
: baseMatches(value);
}
return property(value);
}
/**
* The base implementation of `_.keys` which doesn't skip the constructor
* property of prototypes or treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
return nativeKeys(Object(object));
}
/**
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new function.
*/
function baseMatches(source) {
var matchData = getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
return matchesStrictComparable(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || baseIsMatch(object, source, matchData);
};
}
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new function.
*/
function baseMatchesProperty(path, srcValue) {
if (isKey(path) && isStrictComparable(srcValue)) {
return matchesStrictComparable(path, srcValue);
}
return function(object) {
var objValue = get(object, path);
return (objValue === undefined && objValue === srcValue)
? hasIn(object, path)
: baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG);
};
}
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new function.
*/
function basePropertyDeep(path) {
return function(object) {
return baseGet(object, path);
};
}
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} customizer The function to customize comparisons.
* @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, equalFunc, customizer, bitmask, stack) {
var index = -1,
isPartial = bitmask & PARTIAL_COMPARE_FLAG,
isUnordered = bitmask & UNORDERED_COMPARE_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(array);
if (stacked) {
return stacked == other;
}
var result = true;
stack.set(array, other);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (isUnordered) {
if (!arraySome(other, function(othValue) {
return arrValue === othValue ||
equalFunc(arrValue, othValue, customizer, bitmask, stack);
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, customizer, bitmask, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
return result;
}
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} customizer The function to customize comparisons.
* @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
// 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 +object == +other;
case errorTag:
return object.name == other.name && object.message == other.message;
case numberTag:
// Treat `NaN` vs. `NaN` as equal.
return (object != +object) ? other != +other : object == +other;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/6.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & PARTIAL_COMPARE_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= UNORDERED_COMPARE_FLAG;
stack.set(object, other);
// Recursively compare objects (susceptible to call stack limits).
return equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack);
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} customizer The function to customize comparisons.
* @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, equalFunc, customizer, bitmask, stack) {
var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
objProps = keys(object),
objLength = objProps.length,
othProps = keys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : baseHas(other, key))) {
return false;
}
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
var result = true;
stack.set(object, other);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
return result;
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a
* [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) that affects
* Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = toPairs(object),
length = result.length;
while (length--) {
result[length][2] = isStrictComparable(result[length][1]);
}
return result;
}
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = object[key];
return isNative(value) ? value : undefined;
}
/**
* Gets the `[[Prototype]]` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {null|Object} Returns the `[[Prototype]]`.
*/
function getPrototype(value) {
return nativeGetPrototype(Object(value));
}
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function getTag(value) {
return objectToString.call(value);
}
// Fallback for data views, maps, sets, and weak maps in IE 11,
// for data views in Edge, and promises in Node.js.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = objectToString.call(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : undefined;
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath(object, path, hasFunc) {
path = isKey(path, object) ? [path] : baseCastPath(path);
var result,
index = -1,
length = path.length;
while (++index < length) {
var key = path[index];
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result) {
return result;
}
var length = object ? object.length : 0;
return !!length && isLength(length) && isIndex(key, length) &&
(isArray(object) || isString(object) || isArguments(object));
}
/**
* Creates an array of index keys for `object` values of arrays,
* `arguments` objects, and strings, otherwise `null` is returned.
*
* @private
* @param {Object} object The object to query.
* @returns {Array|null} Returns index keys, else `null`.
*/
function indexKeys(object) {
var length = object ? object.length : undefined;
if (isLength(length) &&
(isArray(object) || isString(object) || isArguments(object))) {
return baseTimes(length, String);
}
return null;
}
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
var type = typeof value;
if (type == 'number' || type == 'symbol') {
return true;
}
return !isArray(value) &&
(isSymbol(value) || reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object)));
}
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return type == 'number' || type == 'boolean' ||
(type == 'string' && value != '__proto__') || value == null;
}
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject(value);
}
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to process.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'user': 'fred' };
* var other = { 'user': 'fred' };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
// Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode.
return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
(!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @type {Function}
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value)) && !isFunction(value);
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 8 which returns 'object' for typed array and weak map constructors,
// and PhantomJS 1.9 which returns 'function' for `NodeList` instances.
var tag = isObject(value) ? objectToString.call(value) : '';
return tag == funcTag || tag == genTag;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length,
* else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/6.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (!isObject(value)) {
return false;
}
var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag);
}
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && objectToString.call(value) == symbolTag);
}
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
function isTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
}
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is used in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/
function hasIn(object, path) {
return object != null && hasPath(object, path, baseHasIn);
}
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
var isProto = isPrototype(object);
if (!(isProto || isArrayLike(object))) {
return baseKeys(object);
}
var indexes = indexKeys(object),
skipIndexes = !!indexes,
result = indexes || [],
length = result.length;
for (var key in object) {
if (baseHas(object, key) &&
!(skipIndexes && (key == 'length' || isIndex(key, length))) &&
!(isProto && key == 'constructor')) {
result.push(key);
}
}
return result;
}
/**
* Creates an array of own enumerable string keyed-value pairs for `object`
* which can be consumed by `_.fromPairs`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias entries
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the new array of key-value pairs.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.toPairs(new Foo);
* // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
*/
function toPairs(object) {
return baseToPairs(object, keys(object));
}
/**
* This method returns the first argument given to it.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'user': 'fred' };
*
* _.identity(object) === object;
* // => true
*/
function identity(value) {
return value;
}
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/
function property(path) {
return isKey(path) ? baseProperty(path) : basePropertyDeep(path);
}
module.exports = baseIteratee;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(24)(module), (function() { return this; }())))
/***/ },
/* 24 */
/***/ function(module, exports) {
module.exports = function(module) {
if(!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
module.children = [];
module.webpackPolyfill = 1;
}
return module;
}
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module, global) {/**
* lodash 4.7.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/** `Object#toString` result references. */
var funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
symbolTag = '[object Symbol]';
/** Used to match property names within property paths. */
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]/g;
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used to determine if values are of the language type `Object`. */
var objectTypes = {
'function': true,
'object': true
};
/** Detect free variable `exports`. */
var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType)
? exports
: undefined;
/** Detect free variable `module`. */
var freeModule = (objectTypes[typeof module] && module && !module.nodeType)
? module
: undefined;
/** Detect free variable `global` from Node.js. */
var freeGlobal = checkGlobal(freeExports && freeModule && typeof global == 'object' && global);
/** Detect free variable `self`. */
var freeSelf = checkGlobal(objectTypes[typeof self] && self);
/** Detect free variable `window`. */
var freeWindow = checkGlobal(objectTypes[typeof window] && window);
/** Detect `this` as the global object. */
var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
/**
* Used as a reference to the global object.
*
* The `this` value is used if it's the global object to avoid Greasemonkey's
* restricted `window` object, otherwise the `window` object is used.
*/
var root = freeGlobal ||
((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) ||
freeSelf || thisGlobal || Function('return this')();
/**
* Checks if `value` is a global object.
*
* @private
* @param {*} value The value to check.
* @returns {null|Object} Returns `value` if it's a global object, else `null`.
*/
function checkGlobal(value) {
return (value && value.Object === Object) ? value : null;
}
/**
* Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
*/
function isHostObject(value) {
// Many host objects are `Object` objects that can coerce to strings
// despite having improperly defined `toString` methods.
var result = false;
if (value != null && typeof value.toString != 'function') {
try {
result = !!(value + '');
} catch (e) {}
}
return result;
}
/** Used for built-in method references. */
var arrayProto = Array.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/** Built-in value references. */
var Symbol = root.Symbol,
splice = arrayProto.splice;
/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map'),
nativeCreate = getNative(Object, 'create');
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/**
* Creates a hash object.
*
* @private
* @constructor
* @returns {Object} Returns the new hash object.
*/
function Hash() {}
/**
* Removes `key` and its value from the hash.
*
* @private
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(hash, key) {
return hashHas(hash, key) && delete hash[key];
}
/**
* Gets the hash value for `key`.
*
* @private
* @param {Object} hash The hash to query.
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(hash, key) {
if (nativeCreate) {
var result = hash[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(hash, key) ? hash[key] : undefined;
}
/**
* Checks if a hash value for `key` exists.
*
* @private
* @param {Object} hash The hash to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(hash, key) {
return nativeCreate ? hash[key] !== undefined : hasOwnProperty.call(hash, key);
}
/**
* Sets the hash `key` to `value`.
*
* @private
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
*/
function hashSet(hash, key, value) {
hash[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
}
// Avoid inheriting from `Object.prototype` when possible.
Hash.prototype = nativeCreate ? nativeCreate(null) : objectProto;
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function MapCache(values) {
var index = -1,
length = values ? values.length : 0;
this.clear();
while (++index < length) {
var entry = values[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapClear() {
this.__data__ = {
'hash': new Hash,
'map': Map ? new Map : [],
'string': new Hash
};
}
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapDelete(key) {
var data = this.__data__;
if (isKeyable(key)) {
return hashDelete(typeof key == 'string' ? data.string : data.hash, key);
}
return Map ? data.map['delete'](key) : assocDelete(data.map, key);
}
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapGet(key) {
var data = this.__data__;
if (isKeyable(key)) {
return hashGet(typeof key == 'string' ? data.string : data.hash, key);
}
return Map ? data.map.get(key) : assocGet(data.map, key);
}
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapHas(key) {
var data = this.__data__;
if (isKeyable(key)) {
return hashHas(typeof key == 'string' ? data.string : data.hash, key);
}
return Map ? data.map.has(key) : assocHas(data.map, key);
}
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapSet(key, value) {
var data = this.__data__;
if (isKeyable(key)) {
hashSet(typeof key == 'string' ? data.string : data.hash, key, value);
} else if (Map) {
data.map.set(key, value);
} else {
assocSet(data.map, key, value);
}
return this;
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapClear;
MapCache.prototype['delete'] = mapDelete;
MapCache.prototype.get = mapGet;
MapCache.prototype.has = mapHas;
MapCache.prototype.set = mapSet;
/**
* Removes `key` and its value from the associative array.
*
* @private
* @param {Array} array The array to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function assocDelete(array, key) {
var index = assocIndexOf(array, key);
if (index < 0) {
return false;
}
var lastIndex = array.length - 1;
if (index == lastIndex) {
array.pop();
} else {
splice.call(array, index, 1);
}
return true;
}
/**
* Gets the associative array value for `key`.
*
* @private
* @param {Array} array The array to query.
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function assocGet(array, key) {
var index = assocIndexOf(array, key);
return index < 0 ? undefined : array[index][1];
}
/**
* Checks if an associative array value for `key` exists.
*
* @private
* @param {Array} array The array to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function assocHas(array, key) {
return assocIndexOf(array, key) > -1;
}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to search.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
/**
* Sets the associative array `key` to `value`.
*
* @private
* @param {Array} array The array to modify.
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
*/
function assocSet(array, key, value) {
var index = assocIndexOf(array, key);
if (index < 0) {
array.push([key, value]);
} else {
array[index][1] = value;
}
}
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = object[key];
return isNative(value) ? value : undefined;
}
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return type == 'number' || type == 'boolean' ||
(type == 'string' && value != '__proto__') || value == null;
}
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = memoize(function(string) {
var result = [];
toString(string).replace(rePropName, function(match, number, quote, string) {
result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to process.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object)
* method interface of `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoizing function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result);
return result;
};
memoized.cache = new (memoize.Cache || MapCache);
return memoized;
}
// Assign cache to `_.memoize`.
memoize.Cache = MapCache;
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'user': 'fred' };
* var other = { 'user': 'fred' };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 8 which returns 'object' for typed array and weak map constructors,
// and PhantomJS 1.9 which returns 'function' for `NodeList` instances.
var tag = isObject(value) ? objectToString.call(value) : '';
return tag == funcTag || tag == genTag;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/6.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (!isObject(value)) {
return false;
}
var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && objectToString.call(value) == symbolTag);
}
/**
* Converts `value` to a string if it's not one. An empty string is returned
* for `null` and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {string} Returns the string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (value == null) {
return '';
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
module.exports = stringToPath;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(24)(module), (function() { return this; }())))
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _actionTypes = __webpack_require__(27);
var _createMatcher = __webpack_require__(16);
var _createMatcher2 = _interopRequireDefault(_createMatcher);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (routes) {
var createMatcher = arguments.length <= 1 || arguments[1] === undefined ? _createMatcher2.default : arguments[1];
var matchRoute = createMatcher(routes);
return function () {
var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var action = arguments[1];
if (action.type === _actionTypes.LOCATION_CHANGED) {
return {
current: _extends({}, matchRoute(action.payload.url), action.payload),
previous: state.current
};
}
return state;
};
};
/***/ },
/* 27 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var LOCATION_CHANGED = exports.LOCATION_CHANGED = 'ROUTER_LOCATION_CHANGED';
var PUSH = exports.PUSH = 'ROUTER_PUSH';
var REPLACE = exports.REPLACE = 'ROUTER_REPLACE';
var GO = exports.GO = 'ROUTER_GO';
var GO_BACK = exports.GO_BACK = 'ROUTER_GO_BACK';
var GO_FORWARD = exports.GO_FORWARD = 'ROUTER_GO_FORWARD';
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _actionTypes = __webpack_require__(27);
var locationDidChange = function locationDidChange(location) {
var basename = location.basename;
var pathname = location.pathname;
var action = location.action;
var state = location.state;
return {
type: _actionTypes.LOCATION_CHANGED,
payload: {
action: action,
state: state,
url: ('' + (basename || '') + pathname).replace(/\/$/, '') // remove trailing slash
}
};
};
var locationListener = void 0;
exports.default = function (history) {
return function () {
return function (next) {
return function (action) {
if (!locationListener) {
locationListener = history.listen(function (location) {
if (location) {
next(locationDidChange(location));
}
});
}
switch (action.type) {
case _actionTypes.PUSH:
history.push(action.payload);
break;
case _actionTypes.REPLACE:
history.replace(action.payload);
break;
case _actionTypes.GO:
history.go(action.payload);
break;
case _actionTypes.GO_BACK:
history.goBack();
break;
case _actionTypes.GO_FORWARD:
history.goForward();
break;
case _actionTypes.LOCATION_CHANGED:
break;
default:
next(action);
}
};
};
};
};
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(30);
var _react2 = _interopRequireDefault(_react);
var _actionTypes = __webpack_require__(27);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Link = function (_Component) {
_inherits(Link, _Component);
function Link() {
_classCallCheck(this, Link);
return _possibleConstructorReturn(this, Object.getPrototypeOf(Link).apply(this, arguments));
}
_createClass(Link, [{
key: 'onClick',
value: function onClick(event) {
event.preventDefault();
var _props = this.props;
var replaceState = _props.replaceState;
var dispatch = _props.dispatch;
dispatch({
type: replaceState ? _actionTypes.REPLACE : _actionTypes.PUSH,
payload: {
pathname: this.props.href
}
});
}
}, {
key: 'render',
value: function render() {
var _props2 = this.props;
var href = _props2.href;
var history = _props2.history;
var children = _props2.children;
return _react2.default.createElement(
'a',
_extends({}, this.props, {
href: history ? history.createHref(href) : href,
onClick: this.onClick.bind(this)
}),
children
);
}
}]);
return Link;
}(_react.Component);
exports.default = Link;
Link.propTypes = {
href: _react.PropTypes.string,
children: _react.PropTypes.node,
dispatch: _react.PropTypes.func,
history: _react.PropTypes.object,
replaceState: _react.PropTypes.bool
};
/***/ },
/* 30 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_30__;
/***/ }
/******/ ])
});
;
//# sourceMappingURL=redux-little-router.js.map |
"use strict";
/**
* @license
* Copyright 2017 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var utils = require("tsutils");
var ts = require("typescript");
var Lint = require("../index");
var Rule = (function (_super) {
tslib_1.__extends(Rule, _super);
function Rule() {
return _super !== null && _super.apply(this, arguments) || this;
}
/* tslint:enable:object-literal-sort-keys */
Rule.FAILURE_STRING = function (name) {
return "Qualifier is unnecessary since '" + name + "' is in scope.";
};
Rule.prototype.applyWithProgram = function (sourceFile, program) {
return this.applyWithFunction(sourceFile, function (ctx) { return walk(ctx, program.getTypeChecker()); });
};
return Rule;
}(Lint.Rules.TypedRule));
/* tslint:disable:object-literal-sort-keys */
Rule.metadata = {
ruleName: "no-unnecessary-qualifier",
description: "Warns when a namespace qualifier (`A.x`) is unnecessary.",
hasFix: true,
optionsDescription: "Not configurable.",
options: null,
optionExamples: [true],
type: "style",
typescriptOnly: true,
requiresTypeInfo: true,
};
exports.Rule = Rule;
function walk(ctx, checker) {
var namespacesInScope = [];
ts.forEachChild(ctx.sourceFile, cb);
function cb(node) {
switch (node.kind) {
case ts.SyntaxKind.ModuleDeclaration:
case ts.SyntaxKind.EnumDeclaration:
namespacesInScope.push(node);
ts.forEachChild(node, cb);
namespacesInScope.pop();
break;
case ts.SyntaxKind.QualifiedName:
var _a = node, left = _a.left, right = _a.right;
visitNamespaceAccess(node, left, right);
break;
case ts.SyntaxKind.PropertyAccessExpression:
var _b = node, expression = _b.expression, name = _b.name;
if (utils.isEntityNameExpression(expression)) {
visitNamespaceAccess(node, expression, name);
break;
}
// falls through
default:
ts.forEachChild(node, cb);
}
}
function visitNamespaceAccess(node, qualifier, name) {
if (qualifierIsUnnecessary(qualifier, name)) {
var fix = Lint.Replacement.deleteFromTo(qualifier.getStart(), name.getStart());
ctx.addFailureAtNode(qualifier, Rule.FAILURE_STRING(qualifier.getText()), fix);
}
else {
// Only look for nested qualifier errors if we didn't already fail on the outer qualifier.
ts.forEachChild(node, cb);
}
}
function qualifierIsUnnecessary(qualifier, name) {
var namespaceSymbol = checker.getSymbolAtLocation(qualifier);
if (namespaceSymbol === undefined || !symbolIsNamespaceInScope(namespaceSymbol)) {
return false;
}
var accessedSymbol = checker.getSymbolAtLocation(name);
if (accessedSymbol === undefined) {
return false;
}
// If the symbol in scope is different, the qualifier is necessary.
var fromScope = getSymbolInScope(qualifier, accessedSymbol.flags, name.text);
return fromScope === undefined || fromScope === accessedSymbol;
}
function getSymbolInScope(node, flags, name) {
// TODO:PERF `getSymbolsInScope` gets a long list. Is there a better way?
var scope = checker.getSymbolsInScope(node, flags);
return scope.find(function (scopeSymbol) { return scopeSymbol.name === name; });
}
function symbolIsNamespaceInScope(symbol) {
var symbolDeclarations = symbol.getDeclarations();
if (symbolDeclarations == null) {
return false;
}
else if (symbolDeclarations.some(function (decl) { return namespacesInScope.some(function (ns) { return ns === decl; }); })) {
return true;
}
var alias = tryGetAliasedSymbol(symbol, checker);
return alias !== undefined && symbolIsNamespaceInScope(alias);
}
}
function tryGetAliasedSymbol(symbol, checker) {
return Lint.isSymbolFlagSet(symbol, ts.SymbolFlags.Alias) ? checker.getAliasedSymbol(symbol) : undefined;
}
|
/* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*jshint globalstrict: false */
/* globals PDFJS, PDFViewer, PDFPageView, TextLayerBuilder, PDFLinkService,
DefaultTextLayerFactory, AnnotationLayerBuilder, PDFHistory,
DefaultAnnotationLayerFactory, DownloadManager, ProgressBar */
// Initializing PDFJS global object (if still undefined)
if (typeof PDFJS === 'undefined') {
(typeof window !== 'undefined' ? window : this).PDFJS = {};
}
(function pdfViewerWrapper() {
'use strict';
var CSS_UNITS = 96.0 / 72.0;
var DEFAULT_SCALE_VALUE = 'auto';
var DEFAULT_SCALE = 1.0;
var UNKNOWN_SCALE = 0;
var MAX_AUTO_SCALE = 1.25;
var SCROLLBAR_PADDING = 40;
var VERTICAL_PADDING = 5;
/**
* Returns scale factor for the canvas. It makes sense for the HiDPI displays.
* @return {Object} The object with horizontal (sx) and vertical (sy)
scales. The scaled property is set to false if scaling is
not required, true otherwise.
*/
function getOutputScale(ctx) {
var devicePixelRatio = window.devicePixelRatio || 1;
var backingStoreRatio = ctx.webkitBackingStorePixelRatio ||
ctx.mozBackingStorePixelRatio ||
ctx.msBackingStorePixelRatio ||
ctx.oBackingStorePixelRatio ||
ctx.backingStorePixelRatio || 1;
var pixelRatio = devicePixelRatio / backingStoreRatio;
return {
sx: pixelRatio,
sy: pixelRatio,
scaled: pixelRatio !== 1
};
}
/**
* Scrolls specified element into view of its parent.
* @param {Object} element - The element to be visible.
* @param {Object} spot - An object with optional top and left properties,
* specifying the offset from the top left edge.
* @param {boolean} skipOverflowHiddenElements - Ignore elements that have
* the CSS rule `overflow: hidden;` set. The default is false.
*/
function scrollIntoView(element, spot, skipOverflowHiddenElements) {
// Assuming offsetParent is available (it's not available when viewer is in
// hidden iframe or object). We have to scroll: if the offsetParent is not set
// producing the error. See also animationStartedClosure.
var parent = element.offsetParent;
if (!parent) {
console.error('offsetParent is not set -- cannot scroll');
return;
}
var checkOverflow = skipOverflowHiddenElements || false;
var offsetY = element.offsetTop + element.clientTop;
var offsetX = element.offsetLeft + element.clientLeft;
while (parent.clientHeight === parent.scrollHeight ||
(checkOverflow && getComputedStyle(parent).overflow === 'hidden')) {
if (parent.dataset._scaleY) {
offsetY /= parent.dataset._scaleY;
offsetX /= parent.dataset._scaleX;
}
offsetY += parent.offsetTop;
offsetX += parent.offsetLeft;
parent = parent.offsetParent;
if (!parent) {
return; // no need to scroll
}
}
if (spot) {
if (spot.top !== undefined) {
offsetY += spot.top;
}
if (spot.left !== undefined) {
offsetX += spot.left;
parent.scrollLeft = offsetX;
}
}
parent.scrollTop = offsetY;
}
/**
* Helper function to start monitoring the scroll event and converting them into
* PDF.js friendly one: with scroll debounce and scroll direction.
*/
function watchScroll(viewAreaElement, callback) {
var debounceScroll = function debounceScroll(evt) {
if (rAF) {
return;
}
// schedule an invocation of scroll for next animation frame.
rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
rAF = null;
var currentY = viewAreaElement.scrollTop;
var lastY = state.lastY;
if (currentY !== lastY) {
state.down = currentY > lastY;
}
state.lastY = currentY;
callback(state);
});
};
var state = {
down: true,
lastY: viewAreaElement.scrollTop,
_eventHandler: debounceScroll
};
var rAF = null;
viewAreaElement.addEventListener('scroll', debounceScroll, true);
return state;
}
/**
* Helper function to parse query string (e.g. ?param1=value&parm2=...).
*/
function parseQueryString(query) {
var parts = query.split('&');
var params = {};
for (var i = 0, ii = parts.length; i < ii; ++i) {
var param = parts[i].split('=');
var key = param[0].toLowerCase();
var value = param.length > 1 ? param[1] : null;
params[decodeURIComponent(key)] = decodeURIComponent(value);
}
return params;
}
/**
* Use binary search to find the index of the first item in a given array which
* passes a given condition. The items are expected to be sorted in the sense
* that if the condition is true for one item in the array, then it is also true
* for all following items.
*
* @returns {Number} Index of the first array element to pass the test,
* or |items.length| if no such element exists.
*/
function binarySearchFirstItem(items, condition) {
var minIndex = 0;
var maxIndex = items.length - 1;
if (items.length === 0 || !condition(items[maxIndex])) {
return items.length;
}
if (condition(items[minIndex])) {
return minIndex;
}
while (minIndex < maxIndex) {
var currentIndex = (minIndex + maxIndex) >> 1;
var currentItem = items[currentIndex];
if (condition(currentItem)) {
maxIndex = currentIndex;
} else {
minIndex = currentIndex + 1;
}
}
return minIndex; /* === maxIndex */
}
/**
* Approximates float number as a fraction using Farey sequence (max order
* of 8).
* @param {number} x - Positive float number.
* @returns {Array} Estimated fraction: the first array item is a numerator,
* the second one is a denominator.
*/
function approximateFraction(x) {
// Fast paths for int numbers or their inversions.
if (Math.floor(x) === x) {
return [x, 1];
}
var xinv = 1 / x;
var limit = 8;
if (xinv > limit) {
return [1, limit];
} else if (Math.floor(xinv) === xinv) {
return [1, xinv];
}
var x_ = x > 1 ? xinv : x;
// a/b and c/d are neighbours in Farey sequence.
var a = 0, b = 1, c = 1, d = 1;
// Limiting search to order 8.
while (true) {
// Generating next term in sequence (order of q).
var p = a + c, q = b + d;
if (q > limit) {
break;
}
if (x_ <= p / q) {
c = p; d = q;
} else {
a = p; b = q;
}
}
// Select closest of the neighbours to x.
if (x_ - a / b < c / d - x_) {
return x_ === x ? [a, b] : [b, a];
} else {
return x_ === x ? [c, d] : [d, c];
}
}
function roundToDivide(x, div) {
var r = x % div;
return r === 0 ? x : Math.round(x - r + div);
}
/**
* Generic helper to find out what elements are visible within a scroll pane.
*/
function getVisibleElements(scrollEl, views, sortByVisibility) {
var top = scrollEl.scrollTop, bottom = top + scrollEl.clientHeight;
var left = scrollEl.scrollLeft, right = left + scrollEl.clientWidth;
function isElementBottomBelowViewTop(view) {
var element = view.div;
var elementBottom =
element.offsetTop + element.clientTop + element.clientHeight;
return elementBottom > top;
}
var visible = [], view, element;
var currentHeight, viewHeight, hiddenHeight, percentHeight;
var currentWidth, viewWidth;
var firstVisibleElementInd = (views.length === 0) ? 0 :
binarySearchFirstItem(views, isElementBottomBelowViewTop);
for (var i = firstVisibleElementInd, ii = views.length; i < ii; i++) {
view = views[i];
element = view.div;
currentHeight = element.offsetTop + element.clientTop;
viewHeight = element.clientHeight;
if (currentHeight > bottom) {
break;
}
currentWidth = element.offsetLeft + element.clientLeft;
viewWidth = element.clientWidth;
if (currentWidth + viewWidth < left || currentWidth > right) {
continue;
}
hiddenHeight = Math.max(0, top - currentHeight) +
Math.max(0, currentHeight + viewHeight - bottom);
percentHeight = ((viewHeight - hiddenHeight) * 100 / viewHeight) | 0;
visible.push({
id: view.id,
x: currentWidth,
y: currentHeight,
view: view,
percent: percentHeight
});
}
var first = visible[0];
var last = visible[visible.length - 1];
if (sortByVisibility) {
visible.sort(function(a, b) {
var pc = a.percent - b.percent;
if (Math.abs(pc) > 0.001) {
return -pc;
}
return a.id - b.id; // ensure stability
});
}
return {first: first, last: last, views: visible};
}
/**
* Event handler to suppress context menu.
*/
function noContextMenuHandler(e) {
e.preventDefault();
}
/**
* Returns the filename or guessed filename from the url (see issue 3455).
* url {String} The original PDF location.
* @return {String} Guessed PDF file name.
*/
function getPDFFileNameFromURL(url) {
var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
// SCHEME HOST 1.PATH 2.QUERY 3.REF
// Pattern to get last matching NAME.pdf
var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
var splitURI = reURI.exec(url);
var suggestedFilename = reFilename.exec(splitURI[1]) ||
reFilename.exec(splitURI[2]) ||
reFilename.exec(splitURI[3]);
if (suggestedFilename) {
suggestedFilename = suggestedFilename[0];
if (suggestedFilename.indexOf('%') !== -1) {
// URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
try {
suggestedFilename =
reFilename.exec(decodeURIComponent(suggestedFilename))[0];
} catch(e) { // Possible (extremely rare) errors:
// URIError "Malformed URI", e.g. for "%AA.pdf"
// TypeError "null has no properties", e.g. for "%2F.pdf"
}
}
}
return suggestedFilename || 'document.pdf';
}
var ProgressBar = (function ProgressBarClosure() {
function clamp(v, min, max) {
return Math.min(Math.max(v, min), max);
}
function ProgressBar(id, opts) {
this.visible = true;
// Fetch the sub-elements for later.
this.div = document.querySelector(id + ' .progress');
// Get the loading bar element, so it can be resized to fit the viewer.
this.bar = this.div.parentNode;
// Get options, with sensible defaults.
this.height = opts.height || 100;
this.width = opts.width || 100;
this.units = opts.units || '%';
// Initialize heights.
this.div.style.height = this.height + this.units;
this.percent = 0;
}
ProgressBar.prototype = {
updateBar: function ProgressBar_updateBar() {
if (this._indeterminate) {
this.div.classList.add('indeterminate');
this.div.style.width = this.width + this.units;
return;
}
this.div.classList.remove('indeterminate');
var progressSize = this.width * this._percent / 100;
this.div.style.width = progressSize + this.units;
},
get percent() {
return this._percent;
},
set percent(val) {
this._indeterminate = isNaN(val);
this._percent = clamp(val, 0, 100);
this.updateBar();
},
setWidth: function ProgressBar_setWidth(viewer) {
if (viewer) {
var container = viewer.parentNode;
var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
if (scrollbarWidth > 0) {
this.bar.setAttribute('style', 'width: calc(100% - ' +
scrollbarWidth + 'px);');
}
}
},
hide: function ProgressBar_hide() {
if (!this.visible) {
return;
}
this.visible = false;
this.bar.classList.add('hidden');
document.body.classList.remove('loadingInProgress');
},
show: function ProgressBar_show() {
if (this.visible) {
return;
}
this.visible = true;
document.body.classList.add('loadingInProgress');
this.bar.classList.remove('hidden');
}
};
return ProgressBar;
})();
/**
* Performs navigation functions inside PDF, such as opening specified page,
* or destination.
* @class
* @implements {IPDFLinkService}
*/
var PDFLinkService = (function () {
/**
* @constructs PDFLinkService
*/
function PDFLinkService() {
this.baseUrl = null;
this.pdfDocument = null;
this.pdfViewer = null;
this.pdfHistory = null;
this._pagesRefCache = null;
}
PDFLinkService.prototype = {
setDocument: function PDFLinkService_setDocument(pdfDocument, baseUrl) {
this.baseUrl = baseUrl;
this.pdfDocument = pdfDocument;
this._pagesRefCache = Object.create(null);
},
setViewer: function PDFLinkService_setViewer(pdfViewer) {
this.pdfViewer = pdfViewer;
},
setHistory: function PDFLinkService_setHistory(pdfHistory) {
this.pdfHistory = pdfHistory;
},
/**
* @returns {number}
*/
get pagesCount() {
return this.pdfDocument.numPages;
},
/**
* @returns {number}
*/
get page() {
return this.pdfViewer.currentPageNumber;
},
/**
* @param {number} value
*/
set page(value) {
this.pdfViewer.currentPageNumber = value;
},
/**
* @param dest - The PDF destination object.
*/
navigateTo: function PDFLinkService_navigateTo(dest) {
var destString = '';
var self = this;
var goToDestination = function(destRef) {
// dest array looks like that: <page-ref> </XYZ|FitXXX> <args..>
var pageNumber = destRef instanceof Object ?
self._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
(destRef + 1);
if (pageNumber) {
if (pageNumber > self.pagesCount) {
pageNumber = self.pagesCount;
}
self.pdfViewer.scrollPageIntoView(pageNumber, dest);
if (self.pdfHistory) {
// Update the browsing history.
self.pdfHistory.push({
dest: dest,
hash: destString,
page: pageNumber
});
}
} else {
self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
var pageNum = pageIndex + 1;
var cacheKey = destRef.num + ' ' + destRef.gen + ' R';
self._pagesRefCache[cacheKey] = pageNum;
goToDestination(destRef);
});
}
};
var destinationPromise;
if (typeof dest === 'string') {
destString = dest;
destinationPromise = this.pdfDocument.getDestination(dest);
} else {
destinationPromise = Promise.resolve(dest);
}
destinationPromise.then(function(destination) {
dest = destination;
if (!(destination instanceof Array)) {
return; // invalid destination
}
goToDestination(destination[0]);
});
},
/**
* @param dest - The PDF destination object.
* @returns {string} The hyperlink to the PDF object.
*/
getDestinationHash: function PDFLinkService_getDestinationHash(dest) {
if (typeof dest === 'string') {
return this.getAnchorUrl('#' + escape(dest));
}
if (dest instanceof Array) {
var destRef = dest[0]; // see navigateTo method for dest format
var pageNumber = destRef instanceof Object ?
this._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R'] :
(destRef + 1);
if (pageNumber) {
var pdfOpenParams = this.getAnchorUrl('#page=' + pageNumber);
var destKind = dest[1];
if (typeof destKind === 'object' && 'name' in destKind &&
destKind.name === 'XYZ') {
var scale = (dest[4] || this.pdfViewer.currentScaleValue);
var scaleNumber = parseFloat(scale);
if (scaleNumber) {
scale = scaleNumber * 100;
}
pdfOpenParams += '&zoom=' + scale;
if (dest[2] || dest[3]) {
pdfOpenParams += ',' + (dest[2] || 0) + ',' + (dest[3] || 0);
}
}
return pdfOpenParams;
}
}
return this.getAnchorUrl('');
},
/**
* Prefix the full url on anchor links to make sure that links are resolved
* relative to the current URL instead of the one defined in <base href>.
* @param {String} anchor The anchor hash, including the #.
* @returns {string} The hyperlink to the PDF object.
*/
getAnchorUrl: function PDFLinkService_getAnchorUrl(anchor) {
return (this.baseUrl || '') + anchor;
},
/**
* @param {string} hash
*/
setHash: function PDFLinkService_setHash(hash) {
if (hash.indexOf('=') >= 0) {
var params = parseQueryString(hash);
// borrowing syntax from "Parameters for Opening PDF Files"
if ('nameddest' in params) {
if (this.pdfHistory) {
this.pdfHistory.updateNextHashParam(params.nameddest);
}
this.navigateTo(params.nameddest);
return;
}
var pageNumber, dest;
if ('page' in params) {
pageNumber = (params.page | 0) || 1;
}
if ('zoom' in params) {
// Build the destination array.
var zoomArgs = params.zoom.split(','); // scale,left,top
var zoomArg = zoomArgs[0];
var zoomArgNumber = parseFloat(zoomArg);
if (zoomArg.indexOf('Fit') === -1) {
// If the zoomArg is a number, it has to get divided by 100. If it's
// a string, it should stay as it is.
dest = [null, { name: 'XYZ' },
zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null,
zoomArgs.length > 2 ? (zoomArgs[2] | 0) : null,
(zoomArgNumber ? zoomArgNumber / 100 : zoomArg)];
} else {
if (zoomArg === 'Fit' || zoomArg === 'FitB') {
dest = [null, { name: zoomArg }];
} else if ((zoomArg === 'FitH' || zoomArg === 'FitBH') ||
(zoomArg === 'FitV' || zoomArg === 'FitBV')) {
dest = [null, { name: zoomArg },
zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null];
} else if (zoomArg === 'FitR') {
if (zoomArgs.length !== 5) {
console.error('PDFLinkService_setHash: ' +
'Not enough parameters for \'FitR\'.');
} else {
dest = [null, { name: zoomArg },
(zoomArgs[1] | 0), (zoomArgs[2] | 0),
(zoomArgs[3] | 0), (zoomArgs[4] | 0)];
}
} else {
console.error('PDFLinkService_setHash: \'' + zoomArg +
'\' is not a valid zoom value.');
}
}
}
if (dest) {
this.pdfViewer.scrollPageIntoView(pageNumber || this.page, dest);
} else if (pageNumber) {
this.page = pageNumber; // simple page
}
if ('pagemode' in params) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagemode', true, true, {
mode: params.pagemode,
});
this.pdfViewer.container.dispatchEvent(event);
}
} else if (/^\d+$/.test(hash)) { // page number
this.page = hash;
} else { // named destination
if (this.pdfHistory) {
this.pdfHistory.updateNextHashParam(unescape(hash));
}
this.navigateTo(unescape(hash));
}
},
/**
* @param {string} action
*/
executeNamedAction: function PDFLinkService_executeNamedAction(action) {
// See PDF reference, table 8.45 - Named action
switch (action) {
case 'GoBack':
if (this.pdfHistory) {
this.pdfHistory.back();
}
break;
case 'GoForward':
if (this.pdfHistory) {
this.pdfHistory.forward();
}
break;
case 'NextPage':
this.page++;
break;
case 'PrevPage':
this.page--;
break;
case 'LastPage':
this.page = this.pagesCount;
break;
case 'FirstPage':
this.page = 1;
break;
default:
break; // No action according to spec
}
var event = document.createEvent('CustomEvent');
event.initCustomEvent('namedaction', true, true, {
action: action
});
this.pdfViewer.container.dispatchEvent(event);
},
/**
* @param {number} pageNum - page number.
* @param {Object} pageRef - reference to the page.
*/
cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) {
var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
this._pagesRefCache[refStr] = pageNum;
}
};
return PDFLinkService;
})();
var PresentationModeState = {
UNKNOWN: 0,
NORMAL: 1,
CHANGING: 2,
FULLSCREEN: 3,
};
var IGNORE_CURRENT_POSITION_ON_ZOOM = false;
var DEFAULT_CACHE_SIZE = 10;
var CLEANUP_TIMEOUT = 30000;
var RenderingStates = {
INITIAL: 0,
RUNNING: 1,
PAUSED: 2,
FINISHED: 3
};
/**
* Controls rendering of the views for pages and thumbnails.
* @class
*/
var PDFRenderingQueue = (function PDFRenderingQueueClosure() {
/**
* @constructs
*/
function PDFRenderingQueue() {
this.pdfViewer = null;
this.pdfThumbnailViewer = null;
this.onIdle = null;
this.highestPriorityPage = null;
this.idleTimeout = null;
this.printing = false;
this.isThumbnailViewEnabled = false;
}
PDFRenderingQueue.prototype = /** @lends PDFRenderingQueue.prototype */ {
/**
* @param {PDFViewer} pdfViewer
*/
setViewer: function PDFRenderingQueue_setViewer(pdfViewer) {
this.pdfViewer = pdfViewer;
},
/**
* @param {PDFThumbnailViewer} pdfThumbnailViewer
*/
setThumbnailViewer:
function PDFRenderingQueue_setThumbnailViewer(pdfThumbnailViewer) {
this.pdfThumbnailViewer = pdfThumbnailViewer;
},
/**
* @param {IRenderableView} view
* @returns {boolean}
*/
isHighestPriority: function PDFRenderingQueue_isHighestPriority(view) {
return this.highestPriorityPage === view.renderingId;
},
renderHighestPriority: function
PDFRenderingQueue_renderHighestPriority(currentlyVisiblePages) {
if (this.idleTimeout) {
clearTimeout(this.idleTimeout);
this.idleTimeout = null;
}
// Pages have a higher priority than thumbnails, so check them first.
if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
return;
}
// No pages needed rendering so check thumbnails.
if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) {
if (this.pdfThumbnailViewer.forceRendering()) {
return;
}
}
if (this.printing) {
// If printing is currently ongoing do not reschedule cleanup.
return;
}
if (this.onIdle) {
this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
}
},
getHighestPriority: function
PDFRenderingQueue_getHighestPriority(visible, views, scrolledDown) {
// The state has changed figure out which page has the highest priority to
// render next (if any).
// Priority:
// 1 visible pages
// 2 if last scrolled down page after the visible pages
// 2 if last scrolled up page before the visible pages
var visibleViews = visible.views;
var numVisible = visibleViews.length;
if (numVisible === 0) {
return false;
}
for (var i = 0; i < numVisible; ++i) {
var view = visibleViews[i].view;
if (!this.isViewFinished(view)) {
return view;
}
}
// All the visible views have rendered, try to render next/previous pages.
if (scrolledDown) {
var nextPageIndex = visible.last.id;
// ID's start at 1 so no need to add 1.
if (views[nextPageIndex] &&
!this.isViewFinished(views[nextPageIndex])) {
return views[nextPageIndex];
}
} else {
var previousPageIndex = visible.first.id - 2;
if (views[previousPageIndex] &&
!this.isViewFinished(views[previousPageIndex])) {
return views[previousPageIndex];
}
}
// Everything that needs to be rendered has been.
return null;
},
/**
* @param {IRenderableView} view
* @returns {boolean}
*/
isViewFinished: function PDFRenderingQueue_isViewFinished(view) {
return view.renderingState === RenderingStates.FINISHED;
},
/**
* Render a page or thumbnail view. This calls the appropriate function
* based on the views state. If the view is already rendered it will return
* false.
* @param {IRenderableView} view
*/
renderView: function PDFRenderingQueue_renderView(view) {
var state = view.renderingState;
switch (state) {
case RenderingStates.FINISHED:
return false;
case RenderingStates.PAUSED:
this.highestPriorityPage = view.renderingId;
view.resume();
break;
case RenderingStates.RUNNING:
this.highestPriorityPage = view.renderingId;
break;
case RenderingStates.INITIAL:
this.highestPriorityPage = view.renderingId;
var continueRendering = function () {
this.renderHighestPriority();
}.bind(this);
view.draw().then(continueRendering, continueRendering);
break;
}
return true;
},
};
return PDFRenderingQueue;
})();
var TEXT_LAYER_RENDER_DELAY = 200; // ms
/**
* @typedef {Object} PDFPageViewOptions
* @property {HTMLDivElement} container - The viewer element.
* @property {number} id - The page unique ID (normally its number).
* @property {number} scale - The page scale display.
* @property {PageViewport} defaultViewport - The page viewport.
* @property {PDFRenderingQueue} renderingQueue - The rendering queue object.
* @property {IPDFTextLayerFactory} textLayerFactory
* @property {IPDFAnnotationLayerFactory} annotationLayerFactory
*/
/**
* @class
* @implements {IRenderableView}
*/
var PDFPageView = (function PDFPageViewClosure() {
/**
* @constructs PDFPageView
* @param {PDFPageViewOptions} options
*/
function PDFPageView(options) {
var container = options.container;
var id = options.id;
var scale = options.scale;
var defaultViewport = options.defaultViewport;
var renderingQueue = options.renderingQueue;
var textLayerFactory = options.textLayerFactory;
var annotationLayerFactory = options.annotationLayerFactory;
this.id = id;
this.renderingId = 'page' + id;
this.rotation = 0;
this.scale = scale || DEFAULT_SCALE;
this.viewport = defaultViewport;
this.pdfPageRotate = defaultViewport.rotation;
this.hasRestrictedScaling = false;
this.renderingQueue = renderingQueue;
this.textLayerFactory = textLayerFactory;
this.annotationLayerFactory = annotationLayerFactory;
this.renderingState = RenderingStates.INITIAL;
this.resume = null;
this.onBeforeDraw = null;
this.onAfterDraw = null;
this.textLayer = null;
this.zoomLayer = null;
this.annotationLayer = null;
var div = document.createElement('div');
div.id = 'pageContainer' + this.id;
div.className = 'page';
div.style.width = Math.floor(this.viewport.width) + 'px';
div.style.height = Math.floor(this.viewport.height) + 'px';
div.setAttribute('data-page-number', this.id);
this.div = div;
container.appendChild(div);
}
PDFPageView.prototype = {
setPdfPage: function PDFPageView_setPdfPage(pdfPage) {
this.pdfPage = pdfPage;
this.pdfPageRotate = pdfPage.rotate;
var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
this.viewport = pdfPage.getViewport(this.scale * CSS_UNITS,
totalRotation);
this.stats = pdfPage.stats;
this.reset();
},
destroy: function PDFPageView_destroy() {
this.zoomLayer = null;
this.reset();
if (this.pdfPage) {
this.pdfPage.cleanup();
}
},
reset: function PDFPageView_reset(keepZoomLayer, keepAnnotations) {
if (this.renderTask) {
this.renderTask.cancel();
}
this.resume = null;
this.renderingState = RenderingStates.INITIAL;
var div = this.div;
div.style.width = Math.floor(this.viewport.width) + 'px';
div.style.height = Math.floor(this.viewport.height) + 'px';
var childNodes = div.childNodes;
var currentZoomLayerNode = (keepZoomLayer && this.zoomLayer) || null;
var currentAnnotationNode = (keepAnnotations && this.annotationLayer &&
this.annotationLayer.div) || null;
for (var i = childNodes.length - 1; i >= 0; i--) {
var node = childNodes[i];
if (currentZoomLayerNode === node || currentAnnotationNode === node) {
continue;
}
div.removeChild(node);
}
div.removeAttribute('data-loaded');
if (currentAnnotationNode) {
// Hide annotationLayer until all elements are resized
// so they are not displayed on the already-resized page
this.annotationLayer.hide();
} else {
this.annotationLayer = null;
}
if (this.canvas && !currentZoomLayerNode) {
// Zeroing the width and height causes Firefox to release graphics
// resources immediately, which can greatly reduce memory consumption.
this.canvas.width = 0;
this.canvas.height = 0;
delete this.canvas;
}
this.loadingIconDiv = document.createElement('div');
this.loadingIconDiv.className = 'loadingIcon';
div.appendChild(this.loadingIconDiv);
},
update: function PDFPageView_update(scale, rotation) {
this.scale = scale || this.scale;
if (typeof rotation !== 'undefined') {
this.rotation = rotation;
}
var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
this.viewport = this.viewport.clone({
scale: this.scale * CSS_UNITS,
rotation: totalRotation
});
var isScalingRestricted = false;
if (this.canvas && PDFJS.maxCanvasPixels > 0) {
var outputScale = this.outputScale;
var pixelsInViewport = this.viewport.width * this.viewport.height;
var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
if (((Math.floor(this.viewport.width) * outputScale.sx) | 0) *
((Math.floor(this.viewport.height) * outputScale.sy) | 0) >
PDFJS.maxCanvasPixels) {
isScalingRestricted = true;
}
}
if (this.canvas) {
if (PDFJS.useOnlyCssZoom ||
(this.hasRestrictedScaling && isScalingRestricted)) {
this.cssTransform(this.canvas, true);
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagerendered', true, true, {
pageNumber: this.id,
cssTransform: true,
});
this.div.dispatchEvent(event);
return;
}
if (!this.zoomLayer) {
this.zoomLayer = this.canvas.parentNode;
this.zoomLayer.style.position = 'absolute';
}
}
if (this.zoomLayer) {
this.cssTransform(this.zoomLayer.firstChild);
}
this.reset(/* keepZoomLayer = */ true, /* keepAnnotations = */ true);
},
/**
* Called when moved in the parent's container.
*/
updatePosition: function PDFPageView_updatePosition() {
if (this.textLayer) {
this.textLayer.render(TEXT_LAYER_RENDER_DELAY);
}
},
cssTransform: function PDFPageView_transform(canvas, redrawAnnotations) {
var CustomStyle = PDFJS.CustomStyle;
// Scale canvas, canvas wrapper, and page container.
var width = this.viewport.width;
var height = this.viewport.height;
var div = this.div;
canvas.style.width = canvas.parentNode.style.width = div.style.width =
Math.floor(width) + 'px';
canvas.style.height = canvas.parentNode.style.height = div.style.height =
Math.floor(height) + 'px';
// The canvas may have been originally rotated, rotate relative to that.
var relativeRotation = this.viewport.rotation - canvas._viewport.rotation;
var absRotation = Math.abs(relativeRotation);
var scaleX = 1, scaleY = 1;
if (absRotation === 90 || absRotation === 270) {
// Scale x and y because of the rotation.
scaleX = height / width;
scaleY = width / height;
}
var cssTransform = 'rotate(' + relativeRotation + 'deg) ' +
'scale(' + scaleX + ',' + scaleY + ')';
CustomStyle.setProp('transform', canvas, cssTransform);
if (this.textLayer) {
// Rotating the text layer is more complicated since the divs inside the
// the text layer are rotated.
// TODO: This could probably be simplified by drawing the text layer in
// one orientation then rotating overall.
var textLayerViewport = this.textLayer.viewport;
var textRelativeRotation = this.viewport.rotation -
textLayerViewport.rotation;
var textAbsRotation = Math.abs(textRelativeRotation);
var scale = width / textLayerViewport.width;
if (textAbsRotation === 90 || textAbsRotation === 270) {
scale = width / textLayerViewport.height;
}
var textLayerDiv = this.textLayer.textLayerDiv;
var transX, transY;
switch (textAbsRotation) {
case 0:
transX = transY = 0;
break;
case 90:
transX = 0;
transY = '-' + textLayerDiv.style.height;
break;
case 180:
transX = '-' + textLayerDiv.style.width;
transY = '-' + textLayerDiv.style.height;
break;
case 270:
transX = '-' + textLayerDiv.style.width;
transY = 0;
break;
default:
console.error('Bad rotation value.');
break;
}
CustomStyle.setProp('transform', textLayerDiv,
'rotate(' + textAbsRotation + 'deg) ' +
'scale(' + scale + ', ' + scale + ') ' +
'translate(' + transX + ', ' + transY + ')');
CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');
}
if (redrawAnnotations && this.annotationLayer) {
this.annotationLayer.render(this.viewport, 'display');
}
},
get width() {
return this.viewport.width;
},
get height() {
return this.viewport.height;
},
getPagePoint: function PDFPageView_getPagePoint(x, y) {
return this.viewport.convertToPdfPoint(x, y);
},
draw: function PDFPageView_draw() {
if (this.renderingState !== RenderingStates.INITIAL) {
console.error('Must be in new state before drawing');
}
this.renderingState = RenderingStates.RUNNING;
var pdfPage = this.pdfPage;
var viewport = this.viewport;
var div = this.div;
// Wrap the canvas so if it has a css transform for highdpi the overflow
// will be hidden in FF.
var canvasWrapper = document.createElement('div');
canvasWrapper.style.width = div.style.width;
canvasWrapper.style.height = div.style.height;
canvasWrapper.classList.add('canvasWrapper');
var canvas = document.createElement('canvas');
canvas.id = 'page' + this.id;
// Keep the canvas hidden until the first draw callback, or until drawing
// is complete when `!this.renderingQueue`, to prevent black flickering.
canvas.setAttribute('hidden', 'hidden');
var isCanvasHidden = true;
canvasWrapper.appendChild(canvas);
if (this.annotationLayer && this.annotationLayer.div) {
// annotationLayer needs to stay on top
div.insertBefore(canvasWrapper, this.annotationLayer.div);
} else {
div.appendChild(canvasWrapper);
}
this.canvas = canvas;
var ctx = canvas.getContext('2d', {alpha: false});
var outputScale = getOutputScale(ctx);
this.outputScale = outputScale;
if (PDFJS.useOnlyCssZoom) {
var actualSizeViewport = viewport.clone({scale: CSS_UNITS});
// Use a scale that will make the canvas be the original intended size
// of the page.
outputScale.sx *= actualSizeViewport.width / viewport.width;
outputScale.sy *= actualSizeViewport.height / viewport.height;
outputScale.scaled = true;
}
if (PDFJS.maxCanvasPixels > 0) {
var pixelsInViewport = viewport.width * viewport.height;
var maxScale = Math.sqrt(PDFJS.maxCanvasPixels / pixelsInViewport);
if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
outputScale.sx = maxScale;
outputScale.sy = maxScale;
outputScale.scaled = true;
this.hasRestrictedScaling = true;
} else {
this.hasRestrictedScaling = false;
}
}
var sfx = approximateFraction(outputScale.sx);
var sfy = approximateFraction(outputScale.sy);
canvas.width = roundToDivide(viewport.width * outputScale.sx, sfx[0]);
canvas.height = roundToDivide(viewport.height * outputScale.sy, sfy[0]);
canvas.style.width = roundToDivide(viewport.width, sfx[1]) + 'px';
canvas.style.height = roundToDivide(viewport.height, sfy[1]) + 'px';
// Add the viewport so it's known what it was originally drawn with.
canvas._viewport = viewport;
var textLayerDiv = null;
var textLayer = null;
if (this.textLayerFactory) {
textLayerDiv = document.createElement('div');
textLayerDiv.className = 'textLayer';
textLayerDiv.style.width = canvasWrapper.style.width;
textLayerDiv.style.height = canvasWrapper.style.height;
if (this.annotationLayer && this.annotationLayer.div) {
// annotationLayer needs to stay on top
div.insertBefore(textLayerDiv, this.annotationLayer.div);
} else {
div.appendChild(textLayerDiv);
}
textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv,
this.id - 1,
this.viewport);
}
this.textLayer = textLayer;
var resolveRenderPromise, rejectRenderPromise;
var promise = new Promise(function (resolve, reject) {
resolveRenderPromise = resolve;
rejectRenderPromise = reject;
});
// Rendering area
var self = this;
function pageViewDrawCallback(error) {
// The renderTask may have been replaced by a new one, so only remove
// the reference to the renderTask if it matches the one that is
// triggering this callback.
if (renderTask === self.renderTask) {
self.renderTask = null;
}
if (error === 'cancelled') {
rejectRenderPromise(error);
return;
}
self.renderingState = RenderingStates.FINISHED;
if (isCanvasHidden) {
self.canvas.removeAttribute('hidden');
isCanvasHidden = false;
}
if (self.loadingIconDiv) {
div.removeChild(self.loadingIconDiv);
delete self.loadingIconDiv;
}
if (self.zoomLayer) {
// Zeroing the width and height causes Firefox to release graphics
// resources immediately, which can greatly reduce memory consumption.
var zoomLayerCanvas = self.zoomLayer.firstChild;
zoomLayerCanvas.width = 0;
zoomLayerCanvas.height = 0;
div.removeChild(self.zoomLayer);
self.zoomLayer = null;
}
self.error = error;
self.stats = pdfPage.stats;
if (self.onAfterDraw) {
self.onAfterDraw();
}
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagerendered', true, true, {
pageNumber: self.id,
cssTransform: false,
});
div.dispatchEvent(event);
if (!error) {
resolveRenderPromise(undefined);
} else {
rejectRenderPromise(error);
}
}
var renderContinueCallback = null;
if (this.renderingQueue) {
renderContinueCallback = function renderContinueCallback(cont) {
if (!self.renderingQueue.isHighestPriority(self)) {
self.renderingState = RenderingStates.PAUSED;
self.resume = function resumeCallback() {
self.renderingState = RenderingStates.RUNNING;
cont();
};
return;
}
if (isCanvasHidden) {
self.canvas.removeAttribute('hidden');
isCanvasHidden = false;
}
cont();
};
}
var transform = !outputScale.scaled ? null :
[outputScale.sx, 0, 0, outputScale.sy, 0, 0];
var renderContext = {
canvasContext: ctx,
transform: transform,
viewport: this.viewport,
// intent: 'default', // === 'display'
};
var renderTask = this.renderTask = this.pdfPage.render(renderContext);
renderTask.onContinue = renderContinueCallback;
this.renderTask.promise.then(
function pdfPageRenderCallback() {
pageViewDrawCallback(null);
if (textLayer) {
self.pdfPage.getTextContent({ normalizeWhitespace: true }).then(
function textContentResolved(textContent) {
textLayer.setTextContent(textContent);
textLayer.render(TEXT_LAYER_RENDER_DELAY);
}
);
}
},
function pdfPageRenderError(error) {
pageViewDrawCallback(error);
}
);
if (this.annotationLayerFactory) {
if (!this.annotationLayer) {
this.annotationLayer = this.annotationLayerFactory.
createAnnotationLayerBuilder(div, this.pdfPage);
}
this.annotationLayer.render(this.viewport, 'display');
}
div.setAttribute('data-loaded', true);
if (self.onBeforeDraw) {
self.onBeforeDraw();
}
return promise;
},
beforePrint: function PDFPageView_beforePrint() {
var CustomStyle = PDFJS.CustomStyle;
var pdfPage = this.pdfPage;
var viewport = pdfPage.getViewport(1);
// Use the same hack we use for high dpi displays for printing to get
// better output until bug 811002 is fixed in FF.
var PRINT_OUTPUT_SCALE = 2;
var canvas = document.createElement('canvas');
// The logical size of the canvas.
canvas.width = Math.floor(viewport.width) * PRINT_OUTPUT_SCALE;
canvas.height = Math.floor(viewport.height) * PRINT_OUTPUT_SCALE;
// The rendered size of the canvas, relative to the size of canvasWrapper.
canvas.style.width = (PRINT_OUTPUT_SCALE * 100) + '%';
canvas.style.height = (PRINT_OUTPUT_SCALE * 100) + '%';
var cssScale = 'scale(' + (1 / PRINT_OUTPUT_SCALE) + ', ' +
(1 / PRINT_OUTPUT_SCALE) + ')';
CustomStyle.setProp('transform' , canvas, cssScale);
CustomStyle.setProp('transformOrigin' , canvas, '0% 0%');
var printContainer = document.getElementById('printContainer');
var canvasWrapper = document.createElement('div');
canvasWrapper.style.width = viewport.width + 'pt';
canvasWrapper.style.height = viewport.height + 'pt';
canvasWrapper.appendChild(canvas);
printContainer.appendChild(canvasWrapper);
canvas.mozPrintCallback = function(obj) {
var ctx = obj.context;
ctx.save();
ctx.fillStyle = 'rgb(255, 255, 255)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.restore();
// Used by the mozCurrentTransform polyfill in src/display/canvas.js.
ctx._transformMatrix =
[PRINT_OUTPUT_SCALE, 0, 0, PRINT_OUTPUT_SCALE, 0, 0];
ctx.scale(PRINT_OUTPUT_SCALE, PRINT_OUTPUT_SCALE);
var renderContext = {
canvasContext: ctx,
viewport: viewport,
intent: 'print'
};
pdfPage.render(renderContext).promise.then(function() {
// Tell the printEngine that rendering this canvas/page has finished.
obj.done();
}, function(error) {
console.error(error);
// Tell the printEngine that rendering this canvas/page has failed.
// This will make the print proces stop.
if ('abort' in obj) {
obj.abort();
} else {
obj.done();
}
});
};
},
};
return PDFPageView;
})();
/**
* @typedef {Object} TextLayerBuilderOptions
* @property {HTMLDivElement} textLayerDiv - The text layer container.
* @property {number} pageIndex - The page index.
* @property {PageViewport} viewport - The viewport of the text layer.
* @property {PDFFindController} findController
*/
/**
* TextLayerBuilder provides text-selection functionality for the PDF.
* It does this by creating overlay divs over the PDF text. These divs
* contain text that matches the PDF text they are overlaying. This object
* also provides a way to highlight text that is being searched for.
* @class
*/
var TextLayerBuilder = (function TextLayerBuilderClosure() {
function TextLayerBuilder(options) {
this.textLayerDiv = options.textLayerDiv;
this.renderingDone = false;
this.divContentDone = false;
this.pageIdx = options.pageIndex;
this.pageNumber = this.pageIdx + 1;
this.matches = [];
this.viewport = options.viewport;
this.textDivs = [];
this.findController = options.findController || null;
this.textLayerRenderTask = null;
this._bindMouse();
}
TextLayerBuilder.prototype = {
_finishRendering: function TextLayerBuilder_finishRendering() {
this.renderingDone = true;
var endOfContent = document.createElement('div');
endOfContent.className = 'endOfContent';
this.textLayerDiv.appendChild(endOfContent);
var event = document.createEvent('CustomEvent');
event.initCustomEvent('textlayerrendered', true, true, {
pageNumber: this.pageNumber
});
this.textLayerDiv.dispatchEvent(event);
},
/**
* Renders the text layer.
* @param {number} timeout (optional) if specified, the rendering waits
* for specified amount of ms.
*/
render: function TextLayerBuilder_render(timeout) {
if (!this.divContentDone || this.renderingDone) {
return;
}
if (this.textLayerRenderTask) {
this.textLayerRenderTask.cancel();
this.textLayerRenderTask = null;
}
this.textDivs = [];
var textLayerFrag = document.createDocumentFragment();
this.textLayerRenderTask = PDFJS.renderTextLayer({
textContent: this.textContent,
container: textLayerFrag,
viewport: this.viewport,
textDivs: this.textDivs,
timeout: timeout
});
this.textLayerRenderTask.promise.then(function () {
this.textLayerDiv.appendChild(textLayerFrag);
this._finishRendering();
this.updateMatches();
}.bind(this), function (reason) {
// canceled or failed to render text layer -- skipping errors
});
},
setTextContent: function TextLayerBuilder_setTextContent(textContent) {
if (this.textLayerRenderTask) {
this.textLayerRenderTask.cancel();
this.textLayerRenderTask = null;
}
this.textContent = textContent;
this.divContentDone = true;
},
convertMatches: function TextLayerBuilder_convertMatches(matches) {
var i = 0;
var iIndex = 0;
var bidiTexts = this.textContent.items;
var end = bidiTexts.length - 1;
var queryLen = (this.findController === null ?
0 : this.findController.state.query.length);
var ret = [];
for (var m = 0, len = matches.length; m < len; m++) {
// Calculate the start position.
var matchIdx = matches[m];
// Loop over the divIdxs.
while (i !== end && matchIdx >= (iIndex + bidiTexts[i].str.length)) {
iIndex += bidiTexts[i].str.length;
i++;
}
if (i === bidiTexts.length) {
console.error('Could not find a matching mapping');
}
var match = {
begin: {
divIdx: i,
offset: matchIdx - iIndex
}
};
// Calculate the end position.
matchIdx += queryLen;
// Somewhat the same array as above, but use > instead of >= to get
// the end position right.
while (i !== end && matchIdx > (iIndex + bidiTexts[i].str.length)) {
iIndex += bidiTexts[i].str.length;
i++;
}
match.end = {
divIdx: i,
offset: matchIdx - iIndex
};
ret.push(match);
}
return ret;
},
renderMatches: function TextLayerBuilder_renderMatches(matches) {
// Early exit if there is nothing to render.
if (matches.length === 0) {
return;
}
var bidiTexts = this.textContent.items;
var textDivs = this.textDivs;
var prevEnd = null;
var pageIdx = this.pageIdx;
var isSelectedPage = (this.findController === null ?
false : (pageIdx === this.findController.selected.pageIdx));
var selectedMatchIdx = (this.findController === null ?
-1 : this.findController.selected.matchIdx);
var highlightAll = (this.findController === null ?
false : this.findController.state.highlightAll);
var infinity = {
divIdx: -1,
offset: undefined
};
function beginText(begin, className) {
var divIdx = begin.divIdx;
textDivs[divIdx].textContent = '';
appendTextToDiv(divIdx, 0, begin.offset, className);
}
function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
var div = textDivs[divIdx];
var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
var node = document.createTextNode(content);
if (className) {
var span = document.createElement('span');
span.className = className;
span.appendChild(node);
div.appendChild(span);
return;
}
div.appendChild(node);
}
var i0 = selectedMatchIdx, i1 = i0 + 1;
if (highlightAll) {
i0 = 0;
i1 = matches.length;
} else if (!isSelectedPage) {
// Not highlighting all and this isn't the selected page, so do nothing.
return;
}
for (var i = i0; i < i1; i++) {
var match = matches[i];
var begin = match.begin;
var end = match.end;
var isSelected = (isSelectedPage && i === selectedMatchIdx);
var highlightSuffix = (isSelected ? ' selected' : '');
if (this.findController) {
this.findController.updateMatchPosition(pageIdx, i, textDivs,
begin.divIdx, end.divIdx);
}
// Match inside new div.
if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
// If there was a previous div, then add the text at the end.
if (prevEnd !== null) {
appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
}
// Clear the divs and set the content until the starting point.
beginText(begin);
} else {
appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
}
if (begin.divIdx === end.divIdx) {
appendTextToDiv(begin.divIdx, begin.offset, end.offset,
'highlight' + highlightSuffix);
} else {
appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
'highlight begin' + highlightSuffix);
for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
textDivs[n0].className = 'highlight middle' + highlightSuffix;
}
beginText(end, 'highlight end' + highlightSuffix);
}
prevEnd = end;
}
if (prevEnd) {
appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
}
},
updateMatches: function TextLayerBuilder_updateMatches() {
// Only show matches when all rendering is done.
if (!this.renderingDone) {
return;
}
// Clear all matches.
var matches = this.matches;
var textDivs = this.textDivs;
var bidiTexts = this.textContent.items;
var clearedUntilDivIdx = -1;
// Clear all current matches.
for (var i = 0, len = matches.length; i < len; i++) {
var match = matches[i];
var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
for (var n = begin, end = match.end.divIdx; n <= end; n++) {
var div = textDivs[n];
div.textContent = bidiTexts[n].str;
div.className = '';
}
clearedUntilDivIdx = match.end.divIdx + 1;
}
if (this.findController === null || !this.findController.active) {
return;
}
// Convert the matches on the page controller into the match format
// used for the textLayer.
this.matches = this.convertMatches(this.findController === null ?
[] : (this.findController.pageMatches[this.pageIdx] || []));
this.renderMatches(this.matches);
},
/**
* Fixes text selection: adds additional div where mouse was clicked.
* This reduces flickering of the content if mouse slowly dragged down/up.
* @private
*/
_bindMouse: function TextLayerBuilder_bindMouse() {
var div = this.textLayerDiv;
div.addEventListener('mousedown', function (e) {
var end = div.querySelector('.endOfContent');
if (!end) {
return;
}
// On non-Firefox browsers, the selection will feel better if the height
// of the endOfContent div will be adjusted to start at mouse click
// location -- this will avoid flickering when selections moves up.
// However it does not work when selection started on empty space.
var adjustTop = e.target !== div;
if (adjustTop) {
var divBounds = div.getBoundingClientRect();
var r = Math.max(0, (e.pageY - divBounds.top) / divBounds.height);
end.style.top = (r * 100).toFixed(2) + '%';
}
end.classList.add('active');
});
div.addEventListener('mouseup', function (e) {
var end = div.querySelector('.endOfContent');
if (!end) {
return;
}
end.style.top = '';
end.classList.remove('active');
});
},
};
return TextLayerBuilder;
})();
/**
* @constructor
* @implements IPDFTextLayerFactory
*/
function DefaultTextLayerFactory() {}
DefaultTextLayerFactory.prototype = {
/**
* @param {HTMLDivElement} textLayerDiv
* @param {number} pageIndex
* @param {PageViewport} viewport
* @returns {TextLayerBuilder}
*/
createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
return new TextLayerBuilder({
textLayerDiv: textLayerDiv,
pageIndex: pageIndex,
viewport: viewport
});
}
};
/**
* @typedef {Object} AnnotationLayerBuilderOptions
* @property {HTMLDivElement} pageDiv
* @property {PDFPage} pdfPage
* @property {IPDFLinkService} linkService
* @property {DownloadManager} downloadManager
*/
/**
* @class
*/
var AnnotationLayerBuilder = (function AnnotationLayerBuilderClosure() {
/**
* @param {AnnotationLayerBuilderOptions} options
* @constructs AnnotationLayerBuilder
*/
function AnnotationLayerBuilder(options) {
this.pageDiv = options.pageDiv;
this.pdfPage = options.pdfPage;
this.linkService = options.linkService;
this.downloadManager = options.downloadManager;
this.div = null;
}
AnnotationLayerBuilder.prototype =
/** @lends AnnotationLayerBuilder.prototype */ {
/**
* @param {PageViewport} viewport
* @param {string} intent (default value is 'display')
*/
render: function AnnotationLayerBuilder_render(viewport, intent) {
var self = this;
var parameters = {
intent: (intent === undefined ? 'display' : intent),
};
this.pdfPage.getAnnotations(parameters).then(function (annotations) {
viewport = viewport.clone({ dontFlip: true });
parameters = {
viewport: viewport,
div: self.div,
annotations: annotations,
page: self.pdfPage,
linkService: self.linkService,
downloadManager: self.downloadManager
};
if (self.div) {
// If an annotationLayer already exists, refresh its children's
// transformation matrices.
PDFJS.AnnotationLayer.update(parameters);
} else {
// Create an annotation layer div and render the annotations
// if there is at least one annotation.
if (annotations.length === 0) {
return;
}
self.div = document.createElement('div');
self.div.className = 'annotationLayer';
self.pageDiv.appendChild(self.div);
parameters.div = self.div;
PDFJS.AnnotationLayer.render(parameters);
if (typeof mozL10n !== 'undefined') {
mozL10n.translate(self.div);
}
}
});
},
hide: function AnnotationLayerBuilder_hide() {
if (!this.div) {
return;
}
this.div.setAttribute('hidden', 'true');
}
};
return AnnotationLayerBuilder;
})();
/**
* @constructor
* @implements IPDFAnnotationLayerFactory
*/
function DefaultAnnotationLayerFactory() {}
DefaultAnnotationLayerFactory.prototype = {
/**
* @param {HTMLDivElement} pageDiv
* @param {PDFPage} pdfPage
* @returns {AnnotationLayerBuilder}
*/
createAnnotationLayerBuilder: function (pageDiv, pdfPage) {
return new AnnotationLayerBuilder({
pageDiv: pageDiv,
pdfPage: pdfPage,
linkService: new SimpleLinkService(),
});
}
};
/**
* @typedef {Object} PDFViewerOptions
* @property {HTMLDivElement} container - The container for the viewer element.
* @property {HTMLDivElement} viewer - (optional) The viewer element.
* @property {IPDFLinkService} linkService - The navigation/linking service.
* @property {DownloadManager} downloadManager - (optional) The download
* manager component.
* @property {PDFRenderingQueue} renderingQueue - (optional) The rendering
* queue object.
* @property {boolean} removePageBorders - (optional) Removes the border shadow
* around the pages. The default is false.
*/
/**
* Simple viewer control to display PDF content/pages.
* @class
* @implements {IRenderableView}
*/
var PDFViewer = (function pdfViewer() {
function PDFPageViewBuffer(size) {
var data = [];
this.push = function cachePush(view) {
var i = data.indexOf(view);
if (i >= 0) {
data.splice(i, 1);
}
data.push(view);
if (data.length > size) {
data.shift().destroy();
}
};
this.resize = function (newSize) {
size = newSize;
while (data.length > size) {
data.shift().destroy();
}
};
}
function isSameScale(oldScale, newScale) {
if (newScale === oldScale) {
return true;
}
if (Math.abs(newScale - oldScale) < 1e-15) {
// Prevent unnecessary re-rendering of all pages when the scale
// changes only because of limited numerical precision.
return true;
}
return false;
}
/**
* @constructs PDFViewer
* @param {PDFViewerOptions} options
*/
function PDFViewer(options) {
this.container = options.container;
this.viewer = options.viewer || options.container.firstElementChild;
this.linkService = options.linkService || new SimpleLinkService();
this.downloadManager = options.downloadManager || null;
this.removePageBorders = options.removePageBorders || false;
this.defaultRenderingQueue = !options.renderingQueue;
if (this.defaultRenderingQueue) {
// Custom rendering queue is not specified, using default one
this.renderingQueue = new PDFRenderingQueue();
this.renderingQueue.setViewer(this);
} else {
this.renderingQueue = options.renderingQueue;
}
this.scroll = watchScroll(this.container, this._scrollUpdate.bind(this));
this.updateInProgress = false;
this.presentationModeState = PresentationModeState.UNKNOWN;
this._resetView();
if (this.removePageBorders) {
this.viewer.classList.add('removePageBorders');
}
}
PDFViewer.prototype = /** @lends PDFViewer.prototype */{
get pagesCount() {
return this._pages.length;
},
getPageView: function (index) {
return this._pages[index];
},
get currentPageNumber() {
return this._currentPageNumber;
},
set currentPageNumber(val) {
if (!this.pdfDocument) {
this._currentPageNumber = val;
return;
}
var event = document.createEvent('UIEvents');
event.initUIEvent('pagechange', true, true, window, 0);
event.updateInProgress = this.updateInProgress;
if (!(0 < val && val <= this.pagesCount)) {
event.pageNumber = this._currentPageNumber;
event.previousPageNumber = val;
this.container.dispatchEvent(event);
return;
}
event.previousPageNumber = this._currentPageNumber;
this._currentPageNumber = val;
event.pageNumber = val;
this.container.dispatchEvent(event);
// Check if the caller is `PDFViewer_update`, to avoid breaking scrolling.
if (this.updateInProgress) {
return;
}
this.scrollPageIntoView(val);
},
/**
* @returns {number}
*/
get currentScale() {
return this._currentScale !== UNKNOWN_SCALE ? this._currentScale :
DEFAULT_SCALE;
},
/**
* @param {number} val - Scale of the pages in percents.
*/
set currentScale(val) {
if (isNaN(val)) {
throw new Error('Invalid numeric scale');
}
if (!this.pdfDocument) {
this._currentScale = val;
this._currentScaleValue = val !== UNKNOWN_SCALE ? val.toString() : null;
return;
}
this._setScale(val, false);
},
/**
* @returns {string}
*/
get currentScaleValue() {
return this._currentScaleValue;
},
/**
* @param val - The scale of the pages (in percent or predefined value).
*/
set currentScaleValue(val) {
if (!this.pdfDocument) {
this._currentScale = isNaN(val) ? UNKNOWN_SCALE : val;
this._currentScaleValue = val;
return;
}
this._setScale(val, false);
},
/**
* @returns {number}
*/
get pagesRotation() {
return this._pagesRotation;
},
/**
* @param {number} rotation - The rotation of the pages (0, 90, 180, 270).
*/
set pagesRotation(rotation) {
this._pagesRotation = rotation;
for (var i = 0, l = this._pages.length; i < l; i++) {
var pageView = this._pages[i];
pageView.update(pageView.scale, rotation);
}
this._setScale(this._currentScaleValue, true);
if (this.defaultRenderingQueue) {
this.update();
}
},
/**
* @param pdfDocument {PDFDocument}
*/
setDocument: function (pdfDocument) {
if (this.pdfDocument) {
this._resetView();
}
this.pdfDocument = pdfDocument;
if (!pdfDocument) {
return;
}
var pagesCount = pdfDocument.numPages;
var self = this;
var resolvePagesPromise;
var pagesPromise = new Promise(function (resolve) {
resolvePagesPromise = resolve;
});
this.pagesPromise = pagesPromise;
pagesPromise.then(function () {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagesloaded', true, true, {
pagesCount: pagesCount
});
self.container.dispatchEvent(event);
});
var isOnePageRenderedResolved = false;
var resolveOnePageRendered = null;
var onePageRendered = new Promise(function (resolve) {
resolveOnePageRendered = resolve;
});
this.onePageRendered = onePageRendered;
var bindOnAfterAndBeforeDraw = function (pageView) {
pageView.onBeforeDraw = function pdfViewLoadOnBeforeDraw() {
// Add the page to the buffer at the start of drawing. That way it can
// be evicted from the buffer and destroyed even if we pause its
// rendering.
self._buffer.push(this);
};
// when page is painted, using the image as thumbnail base
pageView.onAfterDraw = function pdfViewLoadOnAfterDraw() {
if (!isOnePageRenderedResolved) {
isOnePageRenderedResolved = true;
resolveOnePageRendered();
}
};
};
var firstPagePromise = pdfDocument.getPage(1);
this.firstPagePromise = firstPagePromise;
// Fetch a single page so we can get a viewport that will be the default
// viewport for all pages
return firstPagePromise.then(function(pdfPage) {
var scale = this.currentScale;
var viewport = pdfPage.getViewport(scale * CSS_UNITS);
for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
var textLayerFactory = null;
if (!PDFJS.disableTextLayer) {
textLayerFactory = this;
}
var pageView = new PDFPageView({
container: this.viewer,
id: pageNum,
scale: scale,
defaultViewport: viewport.clone(),
renderingQueue: this.renderingQueue,
textLayerFactory: textLayerFactory,
annotationLayerFactory: this
});
bindOnAfterAndBeforeDraw(pageView);
this._pages.push(pageView);
}
var linkService = this.linkService;
// Fetch all the pages since the viewport is needed before printing
// starts to create the correct size canvas. Wait until one page is
// rendered so we don't tie up too many resources early on.
onePageRendered.then(function () {
if (!PDFJS.disableAutoFetch) {
var getPagesLeft = pagesCount;
for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
pdfDocument.getPage(pageNum).then(function (pageNum, pdfPage) {
var pageView = self._pages[pageNum - 1];
if (!pageView.pdfPage) {
pageView.setPdfPage(pdfPage);
}
linkService.cachePageRef(pageNum, pdfPage.ref);
getPagesLeft--;
if (!getPagesLeft) {
resolvePagesPromise();
}
}.bind(null, pageNum));
}
} else {
// XXX: Printing is semi-broken with auto fetch disabled.
resolvePagesPromise();
}
});
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagesinit', true, true, null);
self.container.dispatchEvent(event);
if (this.defaultRenderingQueue) {
this.update();
}
if (this.findController) {
this.findController.resolveFirstPage();
}
}.bind(this));
},
_resetView: function () {
this._pages = [];
this._currentPageNumber = 1;
this._currentScale = UNKNOWN_SCALE;
this._currentScaleValue = null;
this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
this._location = null;
this._pagesRotation = 0;
this._pagesRequests = [];
var container = this.viewer;
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
},
_scrollUpdate: function PDFViewer_scrollUpdate() {
if (this.pagesCount === 0) {
return;
}
this.update();
for (var i = 0, ii = this._pages.length; i < ii; i++) {
this._pages[i].updatePosition();
}
},
_setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent(
newScale, newValue, preset) {
var event = document.createEvent('UIEvents');
event.initUIEvent('scalechange', true, true, window, 0);
event.scale = newScale;
if (preset) {
event.presetValue = newValue;
}
this.container.dispatchEvent(event);
},
_setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(
newScale, newValue, noScroll, preset) {
this._currentScaleValue = newValue;
if (isSameScale(this._currentScale, newScale)) {
if (preset) {
this._setScaleDispatchEvent(newScale, newValue, true);
}
return;
}
for (var i = 0, ii = this._pages.length; i < ii; i++) {
this._pages[i].update(newScale);
}
this._currentScale = newScale;
if (!noScroll) {
var page = this._currentPageNumber, dest;
if (this._location && !IGNORE_CURRENT_POSITION_ON_ZOOM &&
!(this.isInPresentationMode || this.isChangingPresentationMode)) {
page = this._location.pageNumber;
dest = [null, { name: 'XYZ' }, this._location.left,
this._location.top, null];
}
this.scrollPageIntoView(page, dest);
}
this._setScaleDispatchEvent(newScale, newValue, preset);
if (this.defaultRenderingQueue) {
this.update();
}
},
_setScale: function pdfViewer_setScale(value, noScroll) {
var scale = parseFloat(value);
if (scale > 0) {
this._setScaleUpdatePages(scale, value, noScroll, false);
} else {
var currentPage = this._pages[this._currentPageNumber - 1];
if (!currentPage) {
return;
}
var hPadding = (this.isInPresentationMode || this.removePageBorders) ?
0 : SCROLLBAR_PADDING;
var vPadding = (this.isInPresentationMode || this.removePageBorders) ?
0 : VERTICAL_PADDING;
var pageWidthScale = (this.container.clientWidth - hPadding) /
currentPage.width * currentPage.scale;
var pageHeightScale = (this.container.clientHeight - vPadding) /
currentPage.height * currentPage.scale;
switch (value) {
case 'page-actual':
scale = 1;
break;
case 'page-width':
scale = pageWidthScale;
break;
case 'page-height':
scale = pageHeightScale;
break;
case 'page-fit':
scale = Math.min(pageWidthScale, pageHeightScale);
break;
case 'auto':
var isLandscape = (currentPage.width > currentPage.height);
// For pages in landscape mode, fit the page height to the viewer
// *unless* the page would thus become too wide to fit horizontally.
var horizontalScale = isLandscape ?
Math.min(pageHeightScale, pageWidthScale) : pageWidthScale;
scale = Math.min(MAX_AUTO_SCALE, horizontalScale);
break;
default:
console.error('pdfViewSetScale: \'' + value +
'\' is an unknown zoom value.');
return;
}
this._setScaleUpdatePages(scale, value, noScroll, true);
}
},
/**
* Scrolls page into view.
* @param {number} pageNumber
* @param {Array} dest - (optional) original PDF destination array:
* <page-ref> </XYZ|FitXXX> <args..>
*/
scrollPageIntoView: function PDFViewer_scrollPageIntoView(pageNumber,
dest) {
if (!this.pdfDocument) {
return;
}
var pageView = this._pages[pageNumber - 1];
if (this.isInPresentationMode) {
if (this._currentPageNumber !== pageView.id) {
// Avoid breaking getVisiblePages in presentation mode.
this.currentPageNumber = pageView.id;
return;
}
dest = null;
// Fixes the case when PDF has different page sizes.
this._setScale(this._currentScaleValue, true);
}
if (!dest) {
scrollIntoView(pageView.div);
return;
}
var x = 0, y = 0;
var width = 0, height = 0, widthScale, heightScale;
var changeOrientation = (pageView.rotation % 180 === 0 ? false : true);
var pageWidth = (changeOrientation ? pageView.height : pageView.width) /
pageView.scale / CSS_UNITS;
var pageHeight = (changeOrientation ? pageView.width : pageView.height) /
pageView.scale / CSS_UNITS;
var scale = 0;
switch (dest[1].name) {
case 'XYZ':
x = dest[2];
y = dest[3];
scale = dest[4];
// If x and/or y coordinates are not supplied, default to
// _top_ left of the page (not the obvious bottom left,
// since aligning the bottom of the intended page with the
// top of the window is rarely helpful).
x = x !== null ? x : 0;
y = y !== null ? y : pageHeight;
break;
case 'Fit':
case 'FitB':
scale = 'page-fit';
break;
case 'FitH':
case 'FitBH':
y = dest[2];
scale = 'page-width';
// According to the PDF spec, section 12.3.2.2, a `null` value in the
// parameter should maintain the position relative to the new page.
if (y === null && this._location) {
x = this._location.left;
y = this._location.top;
}
break;
case 'FitV':
case 'FitBV':
x = dest[2];
width = pageWidth;
height = pageHeight;
scale = 'page-height';
break;
case 'FitR':
x = dest[2];
y = dest[3];
width = dest[4] - x;
height = dest[5] - y;
var hPadding = this.removePageBorders ? 0 : SCROLLBAR_PADDING;
var vPadding = this.removePageBorders ? 0 : VERTICAL_PADDING;
widthScale = (this.container.clientWidth - hPadding) /
width / CSS_UNITS;
heightScale = (this.container.clientHeight - vPadding) /
height / CSS_UNITS;
scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
break;
default:
return;
}
if (scale && scale !== this._currentScale) {
this.currentScaleValue = scale;
} else if (this._currentScale === UNKNOWN_SCALE) {
this.currentScaleValue = DEFAULT_SCALE_VALUE;
}
if (scale === 'page-fit' && !dest[4]) {
scrollIntoView(pageView.div);
return;
}
var boundingRect = [
pageView.viewport.convertToViewportPoint(x, y),
pageView.viewport.convertToViewportPoint(x + width, y + height)
];
var left = Math.min(boundingRect[0][0], boundingRect[1][0]);
var top = Math.min(boundingRect[0][1], boundingRect[1][1]);
scrollIntoView(pageView.div, { left: left, top: top });
},
_updateLocation: function (firstPage) {
var currentScale = this._currentScale;
var currentScaleValue = this._currentScaleValue;
var normalizedScaleValue =
parseFloat(currentScaleValue) === currentScale ?
Math.round(currentScale * 10000) / 100 : currentScaleValue;
var pageNumber = firstPage.id;
var pdfOpenParams = '#page=' + pageNumber;
pdfOpenParams += '&zoom=' + normalizedScaleValue;
var currentPageView = this._pages[pageNumber - 1];
var container = this.container;
var topLeft = currentPageView.getPagePoint(
(container.scrollLeft - firstPage.x),
(container.scrollTop - firstPage.y));
var intLeft = Math.round(topLeft[0]);
var intTop = Math.round(topLeft[1]);
pdfOpenParams += ',' + intLeft + ',' + intTop;
this._location = {
pageNumber: pageNumber,
scale: normalizedScaleValue,
top: intTop,
left: intLeft,
pdfOpenParams: pdfOpenParams
};
},
update: function PDFViewer_update() {
var visible = this._getVisiblePages();
var visiblePages = visible.views;
if (visiblePages.length === 0) {
return;
}
this.updateInProgress = true;
var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE,
2 * visiblePages.length + 1);
this._buffer.resize(suggestedCacheSize);
this.renderingQueue.renderHighestPriority(visible);
var currentId = this._currentPageNumber;
var firstPage = visible.first;
for (var i = 0, ii = visiblePages.length, stillFullyVisible = false;
i < ii; ++i) {
var page = visiblePages[i];
if (page.percent < 100) {
break;
}
if (page.id === currentId) {
stillFullyVisible = true;
break;
}
}
if (!stillFullyVisible) {
currentId = visiblePages[0].id;
}
if (!this.isInPresentationMode) {
this.currentPageNumber = currentId;
}
this._updateLocation(firstPage);
this.updateInProgress = false;
var event = document.createEvent('UIEvents');
event.initUIEvent('updateviewarea', true, true, window, 0);
event.location = this._location;
this.container.dispatchEvent(event);
},
containsElement: function (element) {
return this.container.contains(element);
},
focus: function () {
this.container.focus();
},
get isInPresentationMode() {
return this.presentationModeState === PresentationModeState.FULLSCREEN;
},
get isChangingPresentationMode() {
return this.presentationModeState === PresentationModeState.CHANGING;
},
get isHorizontalScrollbarEnabled() {
return (this.isInPresentationMode ?
false : (this.container.scrollWidth > this.container.clientWidth));
},
_getVisiblePages: function () {
if (!this.isInPresentationMode) {
return getVisibleElements(this.container, this._pages, true);
} else {
// The algorithm in getVisibleElements doesn't work in all browsers and
// configurations when presentation mode is active.
var visible = [];
var currentPage = this._pages[this._currentPageNumber - 1];
visible.push({ id: currentPage.id, view: currentPage });
return { first: currentPage, last: currentPage, views: visible };
}
},
cleanup: function () {
for (var i = 0, ii = this._pages.length; i < ii; i++) {
if (this._pages[i] &&
this._pages[i].renderingState !== RenderingStates.FINISHED) {
this._pages[i].reset();
}
}
},
/**
* @param {PDFPageView} pageView
* @returns {PDFPage}
* @private
*/
_ensurePdfPageLoaded: function (pageView) {
if (pageView.pdfPage) {
return Promise.resolve(pageView.pdfPage);
}
var pageNumber = pageView.id;
if (this._pagesRequests[pageNumber]) {
return this._pagesRequests[pageNumber];
}
var promise = this.pdfDocument.getPage(pageNumber).then(
function (pdfPage) {
pageView.setPdfPage(pdfPage);
this._pagesRequests[pageNumber] = null;
return pdfPage;
}.bind(this));
this._pagesRequests[pageNumber] = promise;
return promise;
},
forceRendering: function (currentlyVisiblePages) {
var visiblePages = currentlyVisiblePages || this._getVisiblePages();
var pageView = this.renderingQueue.getHighestPriority(visiblePages,
this._pages,
this.scroll.down);
if (pageView) {
this._ensurePdfPageLoaded(pageView).then(function () {
this.renderingQueue.renderView(pageView);
}.bind(this));
return true;
}
return false;
},
getPageTextContent: function (pageIndex) {
return this.pdfDocument.getPage(pageIndex + 1).then(function (page) {
return page.getTextContent({ normalizeWhitespace: true });
});
},
/**
* @param {HTMLDivElement} textLayerDiv
* @param {number} pageIndex
* @param {PageViewport} viewport
* @returns {TextLayerBuilder}
*/
createTextLayerBuilder: function (textLayerDiv, pageIndex, viewport) {
return new TextLayerBuilder({
textLayerDiv: textLayerDiv,
pageIndex: pageIndex,
viewport: viewport,
findController: this.isInPresentationMode ? null : this.findController
});
},
/**
* @param {HTMLDivElement} pageDiv
* @param {PDFPage} pdfPage
* @returns {AnnotationLayerBuilder}
*/
createAnnotationLayerBuilder: function (pageDiv, pdfPage) {
return new AnnotationLayerBuilder({
pageDiv: pageDiv,
pdfPage: pdfPage,
linkService: this.linkService,
downloadManager: this.downloadManager
});
},
setFindController: function (findController) {
this.findController = findController;
},
};
return PDFViewer;
})();
var SimpleLinkService = (function SimpleLinkServiceClosure() {
function SimpleLinkService() {}
SimpleLinkService.prototype = {
/**
* @returns {number}
*/
get page() {
return 0;
},
/**
* @param {number} value
*/
set page(value) {},
/**
* @param dest - The PDF destination object.
*/
navigateTo: function (dest) {},
/**
* @param dest - The PDF destination object.
* @returns {string} The hyperlink to the PDF object.
*/
getDestinationHash: function (dest) {
return '#';
},
/**
* @param hash - The PDF parameters/hash.
* @returns {string} The hyperlink to the PDF object.
*/
getAnchorUrl: function (hash) {
return '#';
},
/**
* @param {string} hash
*/
setHash: function (hash) {},
/**
* @param {string} action
*/
executeNamedAction: function (action) {},
/**
* @param {number} pageNum - page number.
* @param {Object} pageRef - reference to the page.
*/
cachePageRef: function (pageNum, pageRef) {}
};
return SimpleLinkService;
})();
var PDFHistory = (function () {
function PDFHistory(options) {
this.linkService = options.linkService;
this.initialized = false;
this.initialDestination = null;
this.initialBookmark = null;
}
PDFHistory.prototype = {
/**
* @param {string} fingerprint
* @param {IPDFLinkService} linkService
*/
initialize: function pdfHistoryInitialize(fingerprint) {
this.initialized = true;
this.reInitialized = false;
this.allowHashChange = true;
this.historyUnlocked = true;
this.isViewerInPresentationMode = false;
this.previousHash = window.location.hash.substring(1);
this.currentBookmark = '';
this.currentPage = 0;
this.updatePreviousBookmark = false;
this.previousBookmark = '';
this.previousPage = 0;
this.nextHashParam = '';
this.fingerprint = fingerprint;
this.currentUid = this.uid = 0;
this.current = {};
var state = window.history.state;
if (this._isStateObjectDefined(state)) {
// This corresponds to navigating back to the document
// from another page in the browser history.
if (state.target.dest) {
this.initialDestination = state.target.dest;
} else {
this.initialBookmark = state.target.hash;
}
this.currentUid = state.uid;
this.uid = state.uid + 1;
this.current = state.target;
} else {
// This corresponds to the loading of a new document.
if (state && state.fingerprint &&
this.fingerprint !== state.fingerprint) {
// Reinitialize the browsing history when a new document
// is opened in the web viewer.
this.reInitialized = true;
}
this._pushOrReplaceState({fingerprint: this.fingerprint}, true);
}
var self = this;
window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
if (!self.historyUnlocked) {
return;
}
if (evt.state) {
// Move back/forward in the history.
self._goTo(evt.state);
return;
}
// If the state is not set, then the user tried to navigate to a
// different hash by manually editing the URL and pressing Enter, or by
// clicking on an in-page link (e.g. the "current view" link).
// Save the current view state to the browser history.
// Note: In Firefox, history.null could also be null after an in-page
// navigation to the same URL, and without dispatching the popstate
// event: https://bugzilla.mozilla.org/show_bug.cgi?id=1183881
if (self.uid === 0) {
// Replace the previous state if it was not explicitly set.
var previousParams = (self.previousHash && self.currentBookmark &&
self.previousHash !== self.currentBookmark) ?
{hash: self.currentBookmark, page: self.currentPage} :
{page: 1};
replacePreviousHistoryState(previousParams, function() {
updateHistoryWithCurrentHash();
});
} else {
updateHistoryWithCurrentHash();
}
}, false);
function updateHistoryWithCurrentHash() {
self.previousHash = window.location.hash.slice(1);
self._pushToHistory({hash: self.previousHash}, false, true);
self._updatePreviousBookmark();
}
function replacePreviousHistoryState(params, callback) {
// To modify the previous history entry, the following happens:
// 1. history.back()
// 2. _pushToHistory, which calls history.replaceState( ... )
// 3. history.forward()
// Because a navigation via the history API does not immediately update
// the history state, the popstate event is used for synchronization.
self.historyUnlocked = false;
// Suppress the hashchange event to avoid side effects caused by
// navigating back and forward.
self.allowHashChange = false;
window.addEventListener('popstate', rewriteHistoryAfterBack);
history.back();
function rewriteHistoryAfterBack() {
window.removeEventListener('popstate', rewriteHistoryAfterBack);
window.addEventListener('popstate', rewriteHistoryAfterForward);
self._pushToHistory(params, false, true);
history.forward();
}
function rewriteHistoryAfterForward() {
window.removeEventListener('popstate', rewriteHistoryAfterForward);
self.allowHashChange = true;
self.historyUnlocked = true;
callback();
}
}
function pdfHistoryBeforeUnload() {
var previousParams = self._getPreviousParams(null, true);
if (previousParams) {
var replacePrevious = (!self.current.dest &&
self.current.hash !== self.previousHash);
self._pushToHistory(previousParams, false, replacePrevious);
self._updatePreviousBookmark();
}
// Remove the event listener when navigating away from the document,
// since 'beforeunload' prevents Firefox from caching the document.
window.removeEventListener('beforeunload', pdfHistoryBeforeUnload,
false);
}
window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
// If the entire viewer (including the PDF file) is cached in
// the browser, we need to reattach the 'beforeunload' event listener
// since the 'DOMContentLoaded' event is not fired on 'pageshow'.
window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
}, false);
window.addEventListener('presentationmodechanged', function(e) {
self.isViewerInPresentationMode = !!e.detail.active;
});
},
clearHistoryState: function pdfHistory_clearHistoryState() {
this._pushOrReplaceState(null, true);
},
_isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
return (state && state.uid >= 0 &&
state.fingerprint && this.fingerprint === state.fingerprint &&
state.target && state.target.hash) ? true : false;
},
_pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj,
replace) {
if (replace) {
window.history.replaceState(stateObj, '');
} else {
window.history.pushState(stateObj, '');
}
},
get isHashChangeUnlocked() {
if (!this.initialized) {
return true;
}
return this.allowHashChange;
},
_updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
if (this.updatePreviousBookmark &&
this.currentBookmark && this.currentPage) {
this.previousBookmark = this.currentBookmark;
this.previousPage = this.currentPage;
this.updatePreviousBookmark = false;
}
},
updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark,
pageNum) {
if (this.initialized) {
this.currentBookmark = bookmark.substring(1);
this.currentPage = pageNum | 0;
this._updatePreviousBookmark();
}
},
updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
if (this.initialized) {
this.nextHashParam = param;
}
},
push: function pdfHistoryPush(params, isInitialBookmark) {
if (!(this.initialized && this.historyUnlocked)) {
return;
}
if (params.dest && !params.hash) {
params.hash = (this.current.hash && this.current.dest &&
this.current.dest === params.dest) ?
this.current.hash :
this.linkService.getDestinationHash(params.dest).split('#')[1];
}
if (params.page) {
params.page |= 0;
}
if (isInitialBookmark) {
var target = window.history.state.target;
if (!target) {
// Invoked when the user specifies an initial bookmark,
// thus setting initialBookmark, when the document is loaded.
this._pushToHistory(params, false);
this.previousHash = window.location.hash.substring(1);
}
this.updatePreviousBookmark = this.nextHashParam ? false : true;
if (target) {
// If the current document is reloaded,
// avoid creating duplicate entries in the history.
this._updatePreviousBookmark();
}
return;
}
if (this.nextHashParam) {
if (this.nextHashParam === params.hash) {
this.nextHashParam = null;
this.updatePreviousBookmark = true;
return;
} else {
this.nextHashParam = null;
}
}
if (params.hash) {
if (this.current.hash) {
if (this.current.hash !== params.hash) {
this._pushToHistory(params, true);
} else {
if (!this.current.page && params.page) {
this._pushToHistory(params, false, true);
}
this.updatePreviousBookmark = true;
}
} else {
this._pushToHistory(params, true);
}
} else if (this.current.page && params.page &&
this.current.page !== params.page) {
this._pushToHistory(params, true);
}
},
_getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage,
beforeUnload) {
if (!(this.currentBookmark && this.currentPage)) {
return null;
} else if (this.updatePreviousBookmark) {
this.updatePreviousBookmark = false;
}
if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {
// Prevent the history from getting stuck in the current state,
// effectively preventing the user from going back/forward in
// the history.
//
// This happens if the current position in the document didn't change
// when the history was previously updated. The reasons for this are
// either:
// 1. The current zoom value is such that the document does not need to,
// or cannot, be scrolled to display the destination.
// 2. The previous destination is broken, and doesn't actally point to a
// position within the document.
// (This is either due to a bad PDF generator, or the user making a
// mistake when entering a destination in the hash parameters.)
return null;
}
if ((!this.current.dest && !onlyCheckPage) || beforeUnload) {
if (this.previousBookmark === this.currentBookmark) {
return null;
}
} else if (this.current.page || onlyCheckPage) {
if (this.previousPage === this.currentPage) {
return null;
}
} else {
return null;
}
var params = {hash: this.currentBookmark, page: this.currentPage};
if (this.isViewerInPresentationMode) {
params.hash = null;
}
return params;
},
_stateObj: function pdfHistory_stateObj(params) {
return {fingerprint: this.fingerprint, uid: this.uid, target: params};
},
_pushToHistory: function pdfHistory_pushToHistory(params,
addPrevious, overwrite) {
if (!this.initialized) {
return;
}
if (!params.hash && params.page) {
params.hash = ('page=' + params.page);
}
if (addPrevious && !overwrite) {
var previousParams = this._getPreviousParams();
if (previousParams) {
var replacePrevious = (!this.current.dest &&
this.current.hash !== this.previousHash);
this._pushToHistory(previousParams, false, replacePrevious);
}
}
this._pushOrReplaceState(this._stateObj(params),
(overwrite || this.uid === 0));
this.currentUid = this.uid++;
this.current = params;
this.updatePreviousBookmark = true;
},
_goTo: function pdfHistory_goTo(state) {
if (!(this.initialized && this.historyUnlocked &&
this._isStateObjectDefined(state))) {
return;
}
if (!this.reInitialized && state.uid < this.currentUid) {
var previousParams = this._getPreviousParams(true);
if (previousParams) {
this._pushToHistory(this.current, false);
this._pushToHistory(previousParams, false);
this.currentUid = state.uid;
window.history.back();
return;
}
}
this.historyUnlocked = false;
if (state.target.dest) {
this.linkService.navigateTo(state.target.dest);
} else {
this.linkService.setHash(state.target.hash);
}
this.currentUid = state.uid;
if (state.uid > this.uid) {
this.uid = state.uid;
}
this.current = state.target;
this.updatePreviousBookmark = true;
var currentHash = window.location.hash.substring(1);
if (this.previousHash !== currentHash) {
this.allowHashChange = false;
}
this.previousHash = currentHash;
this.historyUnlocked = true;
},
back: function pdfHistoryBack() {
this.go(-1);
},
forward: function pdfHistoryForward() {
this.go(1);
},
go: function pdfHistoryGo(direction) {
if (this.initialized && this.historyUnlocked) {
var state = window.history.state;
if (direction === -1 && state && state.uid > 0) {
window.history.back();
} else if (direction === 1 && state && state.uid < (this.uid - 1)) {
window.history.forward();
}
}
}
};
return PDFHistory;
})();
var DownloadManager = (function DownloadManagerClosure() {
function download(blobUrl, filename) {
var a = document.createElement('a');
if (a.click) {
// Use a.click() if available. Otherwise, Chrome might show
// "Unsafe JavaScript attempt to initiate a navigation change
// for frame with URL" and not open the PDF at all.
// Supported by (not mentioned = untested):
// - Firefox 6 - 19 (4- does not support a.click, 5 ignores a.click)
// - Chrome 19 - 26 (18- does not support a.click)
// - Opera 9 - 12.15
// - Internet Explorer 6 - 10
// - Safari 6 (5.1- does not support a.click)
a.href = blobUrl;
a.target = '_parent';
// Use a.download if available. This increases the likelihood that
// the file is downloaded instead of opened by another PDF plugin.
if ('download' in a) {
a.download = filename;
}
// <a> must be in the document for IE and recent Firefox versions.
// (otherwise .click() is ignored)
(document.body || document.documentElement).appendChild(a);
a.click();
a.parentNode.removeChild(a);
} else {
if (window.top === window &&
blobUrl.split('#')[0] === window.location.href.split('#')[0]) {
// If _parent == self, then opening an identical URL with different
// location hash will only cause a navigation, not a download.
var padCharacter = blobUrl.indexOf('?') === -1 ? '?' : '&';
blobUrl = blobUrl.replace(/#|$/, padCharacter + '$&');
}
window.open(blobUrl, '_parent');
}
}
function DownloadManager() {}
DownloadManager.prototype = {
downloadUrl: function DownloadManager_downloadUrl(url, filename) {
if (!PDFJS.isValidUrl(url, true)) {
return; // restricted/invalid URL
}
download(url + '#pdfjs.action=download', filename);
},
downloadData: function DownloadManager_downloadData(data, filename,
contentType) {
if (navigator.msSaveBlob) { // IE10 and above
return navigator.msSaveBlob(new Blob([data], { type: contentType }),
filename);
}
var blobUrl = PDFJS.createObjectURL(data, contentType);
download(blobUrl, filename);
},
download: function DownloadManager_download(blob, url, filename) {
if (!URL) {
// URL.createObjectURL is not supported
this.downloadUrl(url, filename);
return;
}
if (navigator.msSaveBlob) {
// IE10 / IE11
if (!navigator.msSaveBlob(blob, filename)) {
this.downloadUrl(url, filename);
}
return;
}
var blobUrl = URL.createObjectURL(blob);
download(blobUrl, filename);
}
};
return DownloadManager;
})();
PDFJS.PDFViewer = PDFViewer;
PDFJS.PDFPageView = PDFPageView;
PDFJS.PDFLinkService = PDFLinkService;
PDFJS.TextLayerBuilder = TextLayerBuilder;
PDFJS.DefaultTextLayerFactory = DefaultTextLayerFactory;
PDFJS.AnnotationLayerBuilder = AnnotationLayerBuilder;
PDFJS.DefaultAnnotationLayerFactory = DefaultAnnotationLayerFactory;
PDFJS.PDFHistory = PDFHistory;
PDFJS.DownloadManager = DownloadManager;
PDFJS.ProgressBar = ProgressBar;
}).call((typeof window === 'undefined') ? this : window);
|
YUI.add('anim-base', function(Y) {
/**
* The Animation Utility provides an API for creating advanced transitions.
* @module anim
*/
/**
* Provides the base Anim class, for animating numeric properties.
*
* @module anim
* @submodule anim-base
*/
/**
* A class for constructing animation instances.
* @class Anim
* @for Anim
* @constructor
* @extends Base
*/
var RUNNING = 'running',
START_TIME = 'startTime',
ELAPSED_TIME = 'elapsedTime',
/**
* @for Anim
* @event start
* @description fires when an animation begins.
* @param {Event} ev The start event.
* @type Event.Custom
*/
START = 'start',
/**
* @event tween
* @description fires every frame of the animation.
* @param {Event} ev The tween event.
* @type Event.Custom
*/
TWEEN = 'tween',
/**
* @event end
* @description fires after the animation completes.
* @param {Event} ev The end event.
* @type Event.Custom
*/
END = 'end',
NODE = 'node',
PAUSED = 'paused',
REVERSE = 'reverse', // TODO: cleanup
ITERATION_COUNT = 'iterationCount',
NUM = Number;
var _running = {},
_instances = {},
_timer;
Y.Anim = function() {
Y.Anim.superclass.constructor.apply(this, arguments);
_instances[Y.stamp(this)] = this;
};
Y.Anim.NAME = 'anim';
/**
* Regex of properties that should use the default unit.
*
* @property RE_DEFAULT_UNIT
* @static
*/
Y.Anim.RE_DEFAULT_UNIT = /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i;
/**
* The default unit to use with properties that pass the RE_DEFAULT_UNIT test.
*
* @property DEFAULT_UNIT
* @static
*/
Y.Anim.DEFAULT_UNIT = 'px';
Y.Anim.DEFAULT_EASING = function (t, b, c, d) {
return c * t / d + b; // linear easing
};
/**
* Time in milliseconds passed to setInterval for frame processing
*
* @property intervalTime
* @default 20
* @static
*/
Y.Anim._intervalTime = 20;
/**
* Bucket for custom getters and setters
*
* @property behaviors
* @static
*/
Y.Anim.behaviors = {
left: {
get: function(anim, attr) {
return anim._getOffset(attr);
}
}
};
Y.Anim.behaviors.top = Y.Anim.behaviors.left;
/**
* The default setter to use when setting object properties.
*
* @property DEFAULT_SETTER
* @static
*/
Y.Anim.DEFAULT_SETTER = function(anim, att, from, to, elapsed, duration, fn, unit) {
unit = unit || '';
anim._node.setStyle(att, fn(elapsed, NUM(from), NUM(to) - NUM(from), duration) + unit);
};
/**
* The default getter to use when getting object properties.
*
* @property DEFAULT_GETTER
* @static
*/
Y.Anim.DEFAULT_GETTER = function(anim, prop) {
return anim._node.getComputedStyle(prop);
};
Y.Anim.ATTRS = {
/**
* The object to be animated.
* @attribute node
* @type Node
*/
node: {
setter: function(node) {
node = Y.one(node);
this._node = node;
if (!node) {
Y.log(node + ' is not a valid node', 'warn', 'Anim');
}
return node;
}
},
/**
* The length of the animation. Defaults to "1" (second).
* @attribute duration
* @type NUM
*/
duration: {
value: 1
},
/**
* The method that will provide values to the attribute(s) during the animation.
* Defaults to "Easing.easeNone".
* @attribute easing
* @type Function
*/
easing: {
value: Y.Anim.DEFAULT_EASING,
setter: function(val) {
if (typeof val === 'string' && Y.Easing) {
return Y.Easing[val];
}
}
},
/**
* The starting values for the animated properties.
* Fields may be strings, numbers, or functions.
* If a function is used, the return value becomes the from value.
* If no from value is specified, the DEFAULT_GETTER will be used.
* @attribute from
* @type Object
*/
from: {},
/**
* The ending values for the animated properties.
* Fields may be strings, numbers, or functions.
* @attribute to
* @type Object
*/
to: {},
/**
* Date stamp for the first frame of the animation.
* @attribute startTime
* @type Int
* @default 0
* @readOnly
*/
startTime: {
value: 0,
readOnly: true
},
/**
* Current time the animation has been running.
* @attribute elapsedTime
* @type Int
* @default 0
* @readOnly
*/
elapsedTime: {
value: 0,
readOnly: true
},
/**
* Whether or not the animation is currently running.
* @attribute running
* @type Boolean
* @default false
* @readOnly
*/
running: {
getter: function() {
return !!_running[Y.stamp(this)];
},
value: false,
readOnly: true
},
/**
* The number of times the animation should run
* @attribute iterations
* @type Int
* @default 1
*/
iterations: {
value: 1
},
/**
* The number of iterations that have occurred.
* Resets when an animation ends (reaches iteration count or stop() called).
* @attribute iterationCount
* @type Int
* @default 0
* @readOnly
*/
iterationCount: {
value: 0,
readOnly: true
},
/**
* How iterations of the animation should behave.
* Possible values are "normal" and "alternate".
* Normal will repeat the animation, alternate will reverse on every other pass.
*
* @attribute direction
* @type String
* @default "normal"
*/
direction: {
value: 'normal' // | alternate (fwd on odd, rev on even per spec)
},
/**
* Whether or not the animation is currently paused.
* @attribute paused
* @type Boolean
* @default false
* @readOnly
*/
paused: {
readOnly: true,
value: false
},
/**
* If true, animation begins from last frame
* @attribute reverse
* @type Boolean
* @default false
*/
reverse: {
value: false
}
};
/**
* Runs all animation instances.
* @method run
* @static
*/
Y.Anim.run = function() {
for (var i in _instances) {
if (_instances[i].run) {
_instances[i].run();
}
}
};
/**
* Pauses all animation instances.
* @method pause
* @static
*/
Y.Anim.pause = function() {
for (var i in _running) { // stop timer if nothing running
if (_running[i].pause) {
_running[i].pause();
}
}
Y.Anim._stopTimer();
};
/**
* Stops all animation instances.
* @method stop
* @static
*/
Y.Anim.stop = function() {
for (var i in _running) { // stop timer if nothing running
if (_running[i].stop) {
_running[i].stop();
}
}
Y.Anim._stopTimer();
};
Y.Anim._startTimer = function() {
if (!_timer) {
_timer = setInterval(Y.Anim._runFrame, Y.Anim._intervalTime);
}
};
Y.Anim._stopTimer = function() {
clearInterval(_timer);
_timer = 0;
};
/**
* Called per Interval to handle each animation frame.
* @method _runFrame
* @private
* @static
*/
Y.Anim._runFrame = function() {
var done = true;
for (var anim in _running) {
if (_running[anim]._runFrame) {
done = false;
_running[anim]._runFrame();
}
}
if (done) {
Y.Anim._stopTimer();
}
};
Y.Anim.RE_UNITS = /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/;
var proto = {
/**
* Starts or resumes an animation.
* @method run
* @chainable
*/
run: function() {
if (this.get(PAUSED)) {
this._resume();
} else if (!this.get(RUNNING)) {
this._start();
}
return this;
},
/**
* Pauses the animation and
* freezes it in its current state and time.
* Calling run() will continue where it left off.
* @method pause
* @chainable
*/
pause: function() {
if (this.get(RUNNING)) {
this._pause();
}
return this;
},
/**
* Stops the animation and resets its time.
* @method stop
* @chainable
*/
stop: function(finish) {
if (this.get(RUNNING) || this.get(PAUSED)) {
this._end(finish);
}
return this;
},
_added: false,
_start: function() {
this._set(START_TIME, new Date() - this.get(ELAPSED_TIME));
this._actualFrames = 0;
if (!this.get(PAUSED)) {
this._initAnimAttr();
}
_running[Y.stamp(this)] = this;
Y.Anim._startTimer();
this.fire(START);
},
_pause: function() {
this._set(START_TIME, null);
this._set(PAUSED, true);
delete _running[Y.stamp(this)];
/**
* @event pause
* @description fires when an animation is paused.
* @param {Event} ev The pause event.
* @type Event.Custom
*/
this.fire('pause');
},
_resume: function() {
this._set(PAUSED, false);
_running[Y.stamp(this)] = this;
/**
* @event resume
* @description fires when an animation is resumed (run from pause).
* @param {Event} ev The pause event.
* @type Event.Custom
*/
this.fire('resume');
},
_end: function(finish) {
var duration = this.get('duration') * 1000;
if (finish) { // jump to last frame
this._runAttrs(duration, duration, this.get(REVERSE));
}
this._set(START_TIME, null);
this._set(ELAPSED_TIME, 0);
this._set(PAUSED, false);
delete _running[Y.stamp(this)];
this.fire(END, {elapsed: this.get(ELAPSED_TIME)});
},
_runFrame: function() {
var d = this._runtimeAttr.duration,
t = new Date() - this.get(START_TIME),
reverse = this.get(REVERSE),
done = (t >= d),
attribute,
setter;
this._runAttrs(t, d, reverse);
this._actualFrames += 1;
this._set(ELAPSED_TIME, t);
this.fire(TWEEN);
if (done) {
this._lastFrame();
}
},
_runAttrs: function(t, d, reverse) {
var attr = this._runtimeAttr,
customAttr = Y.Anim.behaviors,
easing = attr.easing,
lastFrame = d,
attribute,
setter,
i;
if (reverse) {
t = d - t;
lastFrame = 0;
}
for (i in attr) {
if (attr[i].to) {
attribute = attr[i];
setter = (i in customAttr && 'set' in customAttr[i]) ?
customAttr[i].set : Y.Anim.DEFAULT_SETTER;
if (t < d) {
setter(this, i, attribute.from, attribute.to, t, d, easing, attribute.unit);
} else {
setter(this, i, attribute.from, attribute.to, lastFrame, d, easing, attribute.unit);
}
}
}
},
_lastFrame: function() {
var iter = this.get('iterations'),
iterCount = this.get(ITERATION_COUNT);
iterCount += 1;
if (iter === 'infinite' || iterCount < iter) {
if (this.get('direction') === 'alternate') {
this.set(REVERSE, !this.get(REVERSE)); // flip it
}
/**
* @event iteration
* @description fires when an animation begins an iteration.
* @param {Event} ev The iteration event.
* @type Event.Custom
*/
this.fire('iteration');
} else {
iterCount = 0;
this._end();
}
this._set(START_TIME, new Date());
this._set(ITERATION_COUNT, iterCount);
},
_initAnimAttr: function() {
var from = this.get('from') || {},
to = this.get('to') || {},
attr = {
duration: this.get('duration') * 1000,
easing: this.get('easing')
},
customAttr = Y.Anim.behaviors,
node = this.get(NODE), // implicit attr init
unit, begin, end;
Y.each(to, function(val, name) {
if (typeof val === 'function') {
val = val.call(this, node);
}
begin = from[name];
if (begin === undefined) {
begin = (name in customAttr && 'get' in customAttr[name]) ?
customAttr[name].get(this, name) : Y.Anim.DEFAULT_GETTER(this, name);
} else if (typeof begin === 'function') {
begin = begin.call(this, node);
}
var mFrom = Y.Anim.RE_UNITS.exec(begin);
var mTo = Y.Anim.RE_UNITS.exec(val);
begin = mFrom ? mFrom[1] : begin;
end = mTo ? mTo[1] : val;
unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units
if (!unit && Y.Anim.RE_DEFAULT_UNIT.test(name)) {
unit = Y.Anim.DEFAULT_UNIT;
}
if (!begin || !end) {
Y.error('invalid "from" or "to" for "' + name + '"', 'Anim');
return;
}
attr[name] = {
from: begin,
to: end,
unit: unit
};
}, this);
this._runtimeAttr = attr;
},
// TODO: move to computedStyle? (browsers dont agree on default computed offsets)
_getOffset: function(attr) {
var node = this._node,
val = node.getComputedStyle(attr),
get = (attr === 'left') ? 'getX': 'getY',
set = (attr === 'left') ? 'setX': 'setY';
if (val === 'auto') {
var position = node.getStyle('position');
if (position === 'absolute' || position === 'fixed') {
val = node[get]();
node[set](val);
} else {
val = 0;
}
}
return val;
}
};
Y.extend(Y.Anim, Y.Base, proto);
}, '@VERSION@' ,{requires:['base-base', 'node-style']});
YUI.add('anim-color', function(Y) {
/**
* Adds support for color properties in <code>to</code>
* and <code>from</code> attributes.
* @module anim
* @submodule anim-color
*/
var NUM = Number;
Y.Anim.behaviors.color = {
set: function(anim, att, from, to, elapsed, duration, fn) {
from = Y.Color.re_RGB.exec(Y.Color.toRGB(from));
to = Y.Color.re_RGB.exec(Y.Color.toRGB(to));
if (!from || from.length < 3 || !to || to.length < 3) {
Y.error('invalid from or to passed to color behavior');
}
anim._node.setStyle(att, 'rgb(' + [
Math.floor(fn(elapsed, NUM(from[1]), NUM(to[1]) - NUM(from[1]), duration)),
Math.floor(fn(elapsed, NUM(from[2]), NUM(to[2]) - NUM(from[2]), duration)),
Math.floor(fn(elapsed, NUM(from[3]), NUM(to[3]) - NUM(from[3]), duration))
].join(', ') + ')');
},
// TODO: default bgcolor const
get: function(anim, att) {
var val = anim._node.getComputedStyle(att);
val = (val === 'transparent') ? 'rgb(255, 255, 255)' : val;
return val;
}
};
Y.each(['backgroundColor',
'borderColor',
'borderTopColor',
'borderRightColor',
'borderBottomColor',
'borderLeftColor'],
function(v, i) {
Y.Anim.behaviors[v] = Y.Anim.behaviors.color;
}
);
}, '@VERSION@' ,{requires:['anim-base']});
YUI.add('anim-curve', function(Y) {
/**
* Adds support for the <code>curve</code> property for the <code>to</code>
* attribute. A curve is zero or more control points and an end point.
* @module anim
* @submodule anim-curve
*/
Y.Anim.behaviors.curve = {
set: function(anim, att, from, to, elapsed, duration, fn) {
from = from.slice.call(from);
to = to.slice.call(to);
var t = fn(elapsed, 0, 100, duration) / 100;
to.unshift(from);
anim._node.setXY(Y.Anim.getBezier(to, t));
},
get: function(anim, att) {
return anim._node.getXY();
}
};
/**
* Get the current position of the animated element based on t.
* Each point is an array of "x" and "y" values (0 = x, 1 = y)
* At least 2 points are required (start and end).
* First point is start. Last point is end.
* Additional control points are optional.
* @for Anim
* @method getBezier
* @static
* @param {Array} points An array containing Bezier points
* @param {Number} t A number between 0 and 1 which is the basis for determining current position
* @return {Array} An array containing int x and y member data
*/
Y.Anim.getBezier = function(points, t) {
var n = points.length;
var tmp = [];
for (var i = 0; i < n; ++i){
tmp[i] = [points[i][0], points[i][1]]; // save input
}
for (var j = 1; j < n; ++j) {
for (i = 0; i < n - j; ++i) {
tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0];
tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1];
}
}
return [ tmp[0][0], tmp[0][1] ];
};
}, '@VERSION@' ,{requires:['anim-xy']});
YUI.add('anim-easing', function(Y) {
/*
TERMS OF USE - EASING EQUATIONS
Open source under the BSD License.
Copyright 2001 Robert Penner All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* The easing module provides methods for customizing
* how an animation behaves during each run.
* @class Easing
* @module anim
* @submodule anim-easing
*/
Y.Easing = {
/**
* Uniform speed between points.
* @for Easing
* @method easeNone
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
easeNone: function (t, b, c, d) {
return c*t/d + b;
},
/**
* Begins slowly and accelerates towards end. (quadratic)
* @method easeIn
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
easeIn: function (t, b, c, d) {
return c*(t/=d)*t + b;
},
/**
* Begins quickly and decelerates towards end. (quadratic)
* @method easeOut
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
easeOut: function (t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
},
/**
* Begins slowly and decelerates towards end. (quadratic)
* @method easeBoth
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
easeBoth: function (t, b, c, d) {
if ((t/=d/2) < 1) {
return c/2*t*t + b;
}
return -c/2 * ((--t)*(t-2) - 1) + b;
},
/**
* Begins slowly and accelerates towards end. (quartic)
* @method easeInStrong
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
easeInStrong: function (t, b, c, d) {
return c*(t/=d)*t*t*t + b;
},
/**
* Begins quickly and decelerates towards end. (quartic)
* @method easeOutStrong
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
easeOutStrong: function (t, b, c, d) {
return -c * ((t=t/d-1)*t*t*t - 1) + b;
},
/**
* Begins slowly and decelerates towards end. (quartic)
* @method easeBothStrong
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
easeBothStrong: function (t, b, c, d) {
if ((t/=d/2) < 1) {
return c/2*t*t*t*t + b;
}
return -c/2 * ((t-=2)*t*t*t - 2) + b;
},
/**
* Snap in elastic effect.
* @method elasticIn
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @param {Number} a Amplitude (optional)
* @param {Number} p Period (optional)
* @return {Number} The computed value for the current animation frame
*/
elasticIn: function (t, b, c, d, a, p) {
var s;
if (t === 0) {
return b;
}
if ( (t /= d) === 1 ) {
return b+c;
}
if (!p) {
p = d* 0.3;
}
if (!a || a < Math.abs(c)) {
a = c;
s = p/4;
}
else {
s = p/(2*Math.PI) * Math.asin (c/a);
}
return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
},
/**
* Snap out elastic effect.
* @method elasticOut
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @param {Number} a Amplitude (optional)
* @param {Number} p Period (optional)
* @return {Number} The computed value for the current animation frame
*/
elasticOut: function (t, b, c, d, a, p) {
var s;
if (t === 0) {
return b;
}
if ( (t /= d) === 1 ) {
return b+c;
}
if (!p) {
p=d * 0.3;
}
if (!a || a < Math.abs(c)) {
a = c;
s = p / 4;
}
else {
s = p/(2*Math.PI) * Math.asin (c/a);
}
return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
},
/**
* Snap both elastic effect.
* @method elasticBoth
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @param {Number} a Amplitude (optional)
* @param {Number} p Period (optional)
* @return {Number} The computed value for the current animation frame
*/
elasticBoth: function (t, b, c, d, a, p) {
var s;
if (t === 0) {
return b;
}
if ( (t /= d/2) === 2 ) {
return b+c;
}
if (!p) {
p = d*(0.3*1.5);
}
if ( !a || a < Math.abs(c) ) {
a = c;
s = p/4;
}
else {
s = p/(2*Math.PI) * Math.asin (c/a);
}
if (t < 1) {
return -0.5*(a*Math.pow(2,10*(t-=1)) *
Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
}
return a*Math.pow(2,-10*(t-=1)) *
Math.sin( (t*d-s)*(2*Math.PI)/p )*0.5 + c + b;
},
/**
* Backtracks slightly, then reverses direction and moves to end.
* @method backIn
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @param {Number} s Overshoot (optional)
* @return {Number} The computed value for the current animation frame
*/
backIn: function (t, b, c, d, s) {
if (s === undefined) {
s = 1.70158;
}
if (t === d) {
t -= 0.001;
}
return c*(t/=d)*t*((s+1)*t - s) + b;
},
/**
* Overshoots end, then reverses and comes back to end.
* @method backOut
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @param {Number} s Overshoot (optional)
* @return {Number} The computed value for the current animation frame
*/
backOut: function (t, b, c, d, s) {
if (typeof s === 'undefined') {
s = 1.70158;
}
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
},
/**
* Backtracks slightly, then reverses direction, overshoots end,
* then reverses and comes back to end.
* @method backBoth
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @param {Number} s Overshoot (optional)
* @return {Number} The computed value for the current animation frame
*/
backBoth: function (t, b, c, d, s) {
if (typeof s === 'undefined') {
s = 1.70158;
}
if ((t /= d/2 ) < 1) {
return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
}
return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
},
/**
* Bounce off of start.
* @method bounceIn
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
bounceIn: function (t, b, c, d) {
return c - Y.Easing.bounceOut(d-t, 0, c, d) + b;
},
/**
* Bounces off end.
* @method bounceOut
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
bounceOut: function (t, b, c, d) {
if ((t/=d) < (1/2.75)) {
return c*(7.5625*t*t) + b;
} else if (t < (2/2.75)) {
return c*(7.5625*(t-=(1.5/2.75))*t + 0.75) + b;
} else if (t < (2.5/2.75)) {
return c*(7.5625*(t-=(2.25/2.75))*t + 0.9375) + b;
}
return c*(7.5625*(t-=(2.625/2.75))*t + 0.984375) + b;
},
/**
* Bounces off start and end.
* @method bounceBoth
* @param {Number} t Time value used to compute current value
* @param {Number} b Starting value
* @param {Number} c Delta between start and end values
* @param {Number} d Total length of animation
* @return {Number} The computed value for the current animation frame
*/
bounceBoth: function (t, b, c, d) {
if (t < d/2) {
return Y.Easing.bounceIn(t * 2, 0, c, d) * 0.5 + b;
}
return Y.Easing.bounceOut(t * 2 - d, 0, c, d) * 0.5 + c * 0.5 + b;
}
};
}, '@VERSION@' ,{requires:['anim-base']});
YUI.add('anim-node-plugin', function(Y) {
/**
* Binds an Anim instance to a Node instance
* @module anim
* @class Plugin.NodeFX
* @extends Base
* @submodule anim-node-plugin
*/
var NodeFX = function(config) {
config = (config) ? Y.merge(config) : {};
config.node = config.host;
NodeFX.superclass.constructor.apply(this, arguments);
};
NodeFX.NAME = "nodefx";
NodeFX.NS = "fx";
Y.extend(NodeFX, Y.Anim);
Y.namespace('Plugin');
Y.Plugin.NodeFX = NodeFX;
}, '@VERSION@' ,{requires:['node-pluginhost', 'anim-base']});
YUI.add('anim-scroll', function(Y) {
/**
* Adds support for the <code>scroll</code> property in <code>to</code>
* and <code>from</code> attributes.
* @module anim
* @submodule anim-scroll
*/
var NUM = Number;
//TODO: deprecate for scrollTop/Left properties?
Y.Anim.behaviors.scroll = {
set: function(anim, att, from, to, elapsed, duration, fn) {
var
node = anim._node,
val = ([
fn(elapsed, NUM(from[0]), NUM(to[0]) - NUM(from[0]), duration),
fn(elapsed, NUM(from[1]), NUM(to[1]) - NUM(from[1]), duration)
]);
if (val[0]) {
node.set('scrollLeft', val[0]);
}
if (val[1]) {
node.set('scrollTop', val[1]);
}
},
get: function(anim) {
var node = anim._node;
return [node.get('scrollLeft'), node.get('scrollTop')];
}
};
}, '@VERSION@' ,{requires:['anim-base']});
YUI.add('anim-xy', function(Y) {
/**
* Adds support for the <code>xy</code> property in <code>from</code> and
* <code>to</code> attributes.
* @module anim
* @submodule anim-xy
*/
var NUM = Number;
Y.Anim.behaviors.xy = {
set: function(anim, att, from, to, elapsed, duration, fn) {
anim._node.setXY([
fn(elapsed, NUM(from[0]), NUM(to[0]) - NUM(from[0]), duration),
fn(elapsed, NUM(from[1]), NUM(to[1]) - NUM(from[1]), duration)
]);
},
get: function(anim) {
return anim._node.getXY();
}
};
}, '@VERSION@' ,{requires:['anim-base', 'node-screen']});
YUI.add('anim', function(Y){}, '@VERSION@' ,{use:['anim-base', 'anim-color', 'anim-curve', 'anim-easing', 'anim-node-plugin', 'anim-scroll', 'anim-xy'], skinnable:false});
|
(function(h,t,z,q){function g(b,a){try{return t.hasOwnProperty?b.hasOwnProperty(a.toString()):Object.prototype.hasOwnProperty.call(b,a.toString())}catch(d){console.dir(d)}}function p(b,a){var d=[],c=/^[+-]?\d+(\.\d+)?$/,f={lat:"",lng:""};if("string"===typeof b||h.isArray(b))if(d="string"===typeof b?b.replace(/\s+/,"").split(","):b,2===d.length)c.test(d[0])&&c.test(d[1])&&(f.lat=d[0],f.lng=d[1]);else return b;else if("object"===typeof b){if("function"===typeof b.lat||"function"===typeof b.lng)return b;
g(b,"x")&&g(b,"y")?(f.lat=b.x,f.lng=b.y):g(b,"lat")&&g(b,"lng")&&(f.lat=b.lat,f.lng=b.lng)}return q!==a&&!0===a?new google.maps.LatLng(f.lat,f.lng):f}function r(b){var a=b.css||"";this.setValues(b);this.span=h("<span/>").css({position:"relative",left:"-50%",top:"0","white-space":"nowrap"}).addClass(a);this.div=h("<div/>").css({position:"absolute",display:"none"});this.span.appendTo(this.div)}function u(b,a){var d=h.extend({},y,a),c={},f="";if(g(t,"google")){this.map=null;this._markers=[];this._labels=
[];this.container=b;this.options=d;this.googleMapOptions={};this.interval=parseInt(this.options.interval,10)||200;for(f in this.options)g(this.options,f)&&(c=this.options[f],/ControlOptions/g.test(f)&&g(c,"position")&&"string"===typeof c.position&&(this.options[f].position=google.maps.ControlPosition[c.position.toUpperCase()]));this.googleMapOptions=this.options;g(d,"streetView")&&(this.googleMapOptions.streetViewObj=d.streetView,delete this.googleMapOptions.streetView);this.googleMapOptions.center=
p(d.center,!0);g(d,"styles")&&("string"===typeof d.styles?g(v,d.styles)&&(this.googleMapOptions.styles=v[d.styles]):h.isArray(d.styles)&&(this.googleMapOptions.styles=d.styles));h(this.container).html(d.loading);this.init()}}var y={autoLocation:!1,center:[24,121],event:null,infoWindowAutoClose:!0,interval:200,kml:[],loading:"\u8b80\u53d6\u4e2d…",marker:[],markerCluster:!1,markerFitBounds:!1,notfound:"\u627e\u4e0d\u5230\u67e5\u8a62\u7684\u5730\u9ede",polyline:[],zoom:8},w=0,x=0,v={},v={greyscale:[{featureType:"all",
stylers:[{saturation:-100},{gamma:.5}]}]};r.prototype=new google.maps.OverlayView;r.prototype.onAdd=function(){this.div.appendTo(h(this.getPanes().overlayLayer));this.listeners=[google.maps.event.addListener(this,"visible_changed",this.onRemove)]};r.prototype.draw=function(){var b=this.getProjection(),a={};try{a=b.fromLatLngToDivPixel(this.get("position")),this.div.css({left:a.x+"px",top:a.y+"px",display:"block"}),this.text&&this.span.html(this.text.toString())}catch(d){}};r.prototype.onRemove=function(){h(this.div).remove()};
u.prototype={VERSION:"2.9.8",_polylines:[],_polygons:[],_circles:[],_kmls:[],_directions:[],_directionsMarkers:[],bounds:new google.maps.LatLngBounds,kml:function(b,a){var d={},c={preserveViewport:!1,suppressInfoWindows:!1},f=0;if(g(a,"kml"))if("string"===typeof a.kml)d=new google.maps.KmlLayer(a.kml,c),d.setMap(b),this._kmls.push(d);else if(h.isArray(a.kml))for(f=0;f<a.kml.length;f+=1)"string"===typeof a.kml[f]&&(d=new google.maps.KmlLayer(a.kml[f],c),d.setMap(b),this._kmls.push(d))},direction:function(b,
a){if(g(a,"direction")&&h.isArray(a.direction))for(var d=0;d<a.direction.length;d+=1)this.directionService(a.direction[d])},markers:function(b,a,d){var c={},f=0,e=0,k=c=0,l=[],m=[];x=w=0;l=this._markers;if(!d||0===l.length&&h.isArray(a.marker))for(e=0,f=a.marker.length;e<f;e+=1)c=a.marker[e],g(c,"addr")&&(c.parseAddr=p(c.addr,!0),"string"===typeof c.parseAddr?this.markerByGeocoder(b,c,a):this.markerDirect(b,c,a));if("modify"===d)for(m=this._labels,e=0,f=a.marker.length;e<f;e+=1)if(g(a.marker[e],"id")){for(c=
0;c<l.length;c+=1)a.marker[e].id===l[c].id&&g(a.marker[e],"addr")&&(l[c].setPosition(new google.maps.LatLng(a.marker[e].addr[0],a.marker[e].addr[1])),g(a.marker[e],"text")&&(g(l[c],"infoWindow")?"function"===typeof l[c].infoWindow.setContent&&l[c].infoWindow.setContent(a.marker[e].text):(l[c].infoWindow=new google.maps.InfoWindow({content:a.marker[e].text}),this.bindEvents(l[c],a.marker[e].event))),g(a.marker[e],"icon")&&l[c].setIcon(a.marker[e].icon));c=0;for(k=m.length;c<k;c+=1)a.marker[e].id===
m[c].id&&(g(a.marker[e],"label")&&(m[c].text=a.marker[e].label),m[c].draw())}else g(a.marker[e],"addr")&&(a.marker[e].parseAddr=p(a.marker[e].addr,!0),"string"===typeof a.marker[e].parseAddr?this.markerByGeocoder(b,a.marker[e]):this.markerDirect(b,a.marker[e]));if(g(a,"markerCluster")&&!0===a.markerCluster&&"function"===typeof MarkerClusterer)return new MarkerClusterer(b,this._markers)},drawPolyline:function(b,a){var d={},c=0,f={},f={},e=0,k=new google.maps.MVCArray,f={},l=[],f={},m=[],s={};if(g(a,
"polyline")&&g(a.polyline,"coords")&&h.isArray(a.polyline.coords)){for(c=0;c<a.polyline.coords.length;c+=1)f=a.polyline.coords[c],f=p(f,!0),"function"===typeof f.lat&&k.push(f);f=h.extend({},{strokeColor:a.polyline.color||"#FF0000",strokeOpacity:1,strokeWeight:a.polyline.width||2},a.polyline);d=new google.maps.Polyline(f);this._polylines.push(d);if(2<k.getLength())for(c=0;c<k.length;c+=1)0<c&&k.length-1>c&&m.push({location:k.getAt(c),stopover:!1});g(a.polyline,"event")&&self.bindEvents(d,a.polyline.event);
g(a.polyline,"snap")&&!0===a.polyline.snap?(f=new google.maps.DirectionsService,f.route({origin:k.getAt(0),waypoints:m,destination:k.getAt(k.length-1),travelMode:google.maps.DirectionsTravelMode.DRIVING},function(b,f){if(f===google.maps.DirectionsStatus.OK){c=0;for(e=b.routes[0].overview_path;c<e.length;c+=1)l.push(e[c]);d.setPath(l);"function"===typeof a.polyline.getDistance&&(s=b.routes[0].legs[0].distance,a.polyline.getDistance.call(this,s))}})):(d.setPath(k),g(google.maps,"geometry")&&g(google.maps.geometry,
"spherical")&&"function"===typeof google.maps.geometry.spherical.computeDistanceBetween&&(s=google.maps.geometry.spherical.computeDistanceBetween(k.getAt(0),k.getAt(k.length-1)),"function"===typeof a.polyline.getDistance&&a.polyline.getDistance.call(this,s)));d.setMap(b)}},drawPolygon:function(b,a){var d={},d=0,c={},c={},d={},f=[];if(g(a,"polygon")&&g(a.polygon,"coords")&&h.isArray(a.polygon.coords)){for(d=0;d<a.polygon.coords.length;d+=1)c=a.polygon.coords[d],c=p(c,!0),"function"===typeof c.lat&&
f.push(c);d=h.extend({},{path:f,strokeColor:a.polygon.color||"#FF0000",strokeOpacity:1,strokeWeight:a.polygon.width||2,fillColor:a.polygon.fillcolor||"#CC0000",fillOpacity:.35},a.polygon);d=new google.maps.Polygon(d);g(a.polygon,"event")&&this.bindEvents(d,a.polygon.event);this._polygons.push(d);d.setMap(b)}},drawCircle:function(b,a){var d=0,c={},f={},e={},f={};if(g(a,"circle")&&h.isArray(a.circle))for(d=a.circle.length-1;0<=d;d-=1)e=a.circle[d],f=h.extend({},{map:b,strokeColor:e.color||"#FF0000",
strokeOpacity:e.opacity||.8,strokeWeight:e.width||2,fillColor:e.fillcolor||"#FF0000",fillOpacity:e.fillopacity||.35,radius:e.radius||10,zIndex:100,id:g(e,"id")?e.id:""},e),g(e,"center")&&(c=p(e.center,!0),f.center=c),"function"===typeof c.lat&&(f=new google.maps.Circle(f),this._circles.push(f),g(e,"event")&&this.bindEvents(f,e.event))},overlay:function(){var b=this.map,a=this.options;try{this.kml(b,a),this.direction(b,a),this.markers(b,a),this.drawPolyline(b,a),this.drawPolygon(b,a),this.drawCircle(b,
a),this.streetView(b,a),this.geoLocation(b,a)}catch(d){console.dir(d)}},markerIcon:function(b){var a=h.extend({},a,b.icon);if(g(b,"icon")){if("string"===typeof b.icon)return b.icon;g(b.icon,"url")&&(a.url=b.icon.url);g(b.icon,"size")&&h.isArray(b.icon.size)&&2===b.icon.size.length&&(a.size=new google.maps.Size(b.icon.size[0],b.icon.size[1]));g(b.icon,"scaledSize")&&h.isArray(b.icon.scaledSize)&&2===b.icon.scaledSize.length&&(a.scaledSize=new google.maps.Size(b.icon.scaledSize[0],b.icon.scaledSize[1]));
g(b.icon,"anchor")&&h.isArray(b.icon.anchor)&&2===b.icon.anchor.length&&(a.anchor=new google.maps.Point(b.icon.anchor[0],b.icon.anchor[1]))}return a},markerDirect:function(b,a){var d={},c={},c={},c=g(a,"id")?a.id:"",d=g(a,"title")?a.title.toString().replace(/<([^>]+)>/g,""):!1,f=g(a,"text")?a.text.toString():!1,e=h.extend({},{map:b,position:a.parseAddr,animation:null,id:c},a),k=this.markerIcon(a);d&&(e.title=d);f&&(e.text=f,e.infoWindow=new google.maps.InfoWindow({content:f}));h.isEmptyObject(k)||
(e.icon=k);g(a,"animation")&&"string"===typeof a.animation&&(e.animation=google.maps.Animation[a.animation.toUpperCase()]);d=new google.maps.Marker(e);this._markers.push(d);g(d,"position")&&("function"===typeof d.getPosition&&this.bounds.extend(d.position),!0===this.options.markerFitBounds&&this._markers.length===this.options.marker.length&&b.fitBounds(this.bounds));if(!0===this.options.markerCluster&&"function"===typeof MarkerClusterer&&w===this.options.marker.length)return new MarkerClusterer(b,
this._markers);c={map:b,css:g(a,"css")?a.css.toString():"",id:c};"string"===typeof a.label&&0!==a.label.length&&(c.text=a.label,c=new r(c),c.bindTo("position",d,"position"),c.bindTo("text",d,"position"),c.bindTo("visible",d),this._labels.push(c));this.bindEvents(d,a.event)},markerByGeocoder:function(b,a){var d=this;(new google.maps.Geocoder).geocode({address:a.parseAddr},function(c,f){if(f===google.maps.GeocoderStatus.OVER_QUERY_LIMIT)t.setTimeout(function(){d.markerByGeocoder(b,a)},d.interval);else if(f===
google.maps.GeocoderStatus.OK){var e={},k={},k={},l=g(a,"id")?a.id:"",e=g(a,"title")?a.title.toString().replace(/<([^>]+)>/g,""):!1,k=g(a,"text")?a.text.toString():!1,l={map:b,position:c[0].geometry.location,animation:null,id:l},m=d.markerIcon(a);e&&(l.title=e);k&&(l.text=k,l.infoWindow=new google.maps.InfoWindow({content:k}));h.isEmptyObject(m)||(l.icon=m);g(a,"animation")&&"string"===typeof a.animation&&(l.animation=google.maps.Animation[a.animation.toUpperCase()]);l=h.extend({},l,a);e=new google.maps.Marker(l);
d._markers.push(e);g(e,"position")&&("function"===typeof e.getPosition&&d.bounds.extend(e.position),!0===d.options.markerFitBounds&&d._markers.length===d.options.marker.length&&b.fitBounds(d.bounds));if(g(d.options,"markerCluster")&&"function"===typeof MarkerClusterer&&x===d.options.marker.length)return new MarkerClusterer(b,d._markers);k={map:d.map,css:g(a,"css")?a.css.toString():""};"string"===typeof a.label&&0!==a.label.length&&(k.text=a.label,k=new r(k),k.bindTo("position",e,"position"),k.bindTo("text",
e,"position"),k.bindTo("visible",e),d._labels.push(k));d.bindEvents(e,a.event)}})},directionService:function(b){if(g(b,"from")&&g(b,"to")){var a=this,d=new google.maps.DirectionsService,c=new google.maps.DirectionsRenderer,f={travelMode:google.maps.DirectionsTravelMode.DRIVING,optimizeWaypoints:g(b,"optimize")?b.optimize:!1},e={},k={},l=[],m={},s=[],q={},r="",n=0,t=0;f.origin=p(b.from,!0);f.destination=p(b.to,!0);g(b,"travel")&&google.maps.TravelMode[b.travel.toString().toUpperCase()]&&(f.travelMode=
google.maps.TravelMode[b.travel.toString().toUpperCase()]);g(b,"panel")&&(e=h(b.panel));if(g(b,"waypoint")&&h.isArray(b.waypoint)){n=0;for(t=b.waypoint.length;n<t;n+=1)m={},"string"===typeof b.waypoint[n]||h.isArray(b.waypoint[n])?m={location:p(b.waypoint[n],!0),stopover:!0}:(g(b.waypoint[n],"location")&&(m.location=p(b.waypoint[n].location,!0)),m.stopover=g(b.waypoint[n],"stopover")?b.waypoint[n].stopover:!0),s.push(b.waypoint[n].text||b.waypoint[n].toString()),l.push(m);f.waypoints=l}d.route(f,
function(d,f){var e=0,h=0;if(f===google.maps.DirectionsStatus.OK){e=d.routes[0].legs;g(b,"autoViewport")&&(k.preserveViewport=!1===b.autoViewport?!0:!1);try{for(g(b,"fromText")&&(e[0].start_address=b.fromText),g(b,"toText")&&(1===e.length?e[0].end_address=b.toText:e[e.length-1].end_address=b.toText),1===e.length?(q=e[0].end_location,r=e[0].end_address):(q=e[e.length-1].end_location,r=e[e.length-1].end_address),g(b,"icon")&&(k.suppressMarkers=!0,g(b.icon,"from")&&"string"===typeof b.icon.from&&a.directionServiceMarker(e[0].start_location,
{icon:b.icon.from,text:e[0].start_address}),g(b.icon,"to")&&"string"===typeof b.icon.to&&a.directionServiceMarker(q,{icon:b.icon.to,text:r})),h=0;h<e.length-1;h+=1)e[h].end_address=s[h],g(b,"icon")&&g(b.icon,"waypoint")&&a.directionServiceMarker(e[h].start_location,{icon:b.icon.waypoint,text:e[h].start_address})}catch(l){}a.bindEvents(c,b.event);c.setOptions(k);c.setDirections(d)}});c.setMap(a.map);e.length&&c.setPanel(e.get(0));a._directions.push(c)}},directionServiceMarker:function(b,a){var d=h.extend({},
{position:b,map:this.map},a),c={};g(d,"text")&&(d.infoWindow=new google.maps.InfoWindow({content:d.text}));c=new google.maps.Marker(d);this._directionsMarkers.push(c);this.bindEvents(c)},bindEvents:function(b,a){var d=this,c={};switch(typeof a){case "function":google.maps.event.addListener(b,"click",a);break;case "object":for(c in a)"function"===typeof a[c]?google.maps.event.addListener(b,c,a[c]):g(a[c],"func")&&"function"===typeof a[c].func?g(a[c],"once")&&!0===a[c].once?google.maps.event.addListenerOnce(b,
c,a[c].func):google.maps.event.addListener(b,c,a[c].func):"function"===typeof a[c]&&google.maps.event.addListener(b,c,a[c])}g(b,"infoWindow")&&google.maps.event.addListener(b,"click",function(){var a=0,c={};if(g(d.options,"infoWindowAutoClose")&&!0===d.options.infoWindowAutoClose)for(a=0;a<d._markers.length;a+=1)c=d._markers[a],g(c,"infoWindow")&&"function"===typeof c.infoWindow.close&&c.infoWindow.close();b.infoWindow.open(d.map,b)})},streetView:function(b,a){var d={},c=g(a,"streetViewObj")?a.streetViewObj:
{},f={heading:0,pitch:0,zoom:1},e={};"function"===typeof b.getStreetView&&g(a,"streetViewObj")&&(d=b.getStreetView(),g(c,"position")?(e=p(c.position,!0),c.position="object"!==typeof e?b.getCenter():e):c.position=b.getCenter(),g(c,"pov")&&(c.pov=h.extend({},f,c.pov)),g(c,"visible")&&d.setVisible(c.visible),d.setOptions(c),g(c,"event")&&this.bindEvents(d,c.event))},panto:function(b){var a={},d={},c=this.map;null!==c&&q!==c&&(a=p(b,!0),"string"===typeof a?(d=new google.maps.Geocoder,d.geocode({address:a},
function(a,b){b===google.maps.GeocoderStatus.OK?"function"===typeof c.panTo&&a.length&&c.panTo(a[0].geometry.location):console.error(b)})):"function"===typeof c.panTo&&c.panTo(a))},clear:function(b){for(var a="marker,circle,polygon,polyline,direction,kml",d="",c=0,f=0,a="string"===typeof b?b.split(","):h.isArray(b)?b:a.split(","),c=0;c<a.length;c+=1){d="_"+h.trim(a[c].toString().toLowerCase())+"s";if(q!==this[d]&&this[d].length){for(f=0;f<this[d].length;f+=1)this.map===this[d][f].getMap()&&(this[d][f].set("visible",
!1),this[d][f].set("directions",null),this[d][f].setMap(null));this[d].length=0}if("direction"===a[c])for(f=0;f<this._directionsMarkers.length;f+=1)this._directionsMarkers[f].setMap(null)}},modify:function(b){var a=[],d=[["kml","kml"],["marker","markers"],["direction","direction"],["polyline","drawPolyline"],["polygon","drawPolygon"],["circle","drawCircle"],["streetView","streetView"]],c=0,f=this.map;if(q!==b){for(c=0;c<d.length;c+=1)g(b,d[c][0])&&a.push(d[c][1]);if(null!==f){if(a.length)for(c=0;c<
a.length;c+=1)"function"===typeof this[a[c]]&&("streetView"===a[c]&&(b.streetViewObj=b.streetView,delete b.streetView),this[a[c]](f,b,"modify"));else f.setOptions(b);g(b,"event")&&this.bindEvents(f,b.event)}}},destroy:function(){var b=h(this.container);h.data(b.get(0),"tinyMap",null)},geoLocation:function(b,a){var d=navigator.geolocation;d&&!0===a.autoLocation&&d.getCurrentPosition(function(a){a&&g(a,"coords")&&b.panTo(new google.maps.LatLng(a.coords.latitude,a.coords.longitude))},function(a){console.error(a)},
{maximumAge:6E5,timeout:3E3,enableHighAccuracy:!1})},init:function(){var b=this,a={};"string"===typeof b.options.center?(a=new google.maps.Geocoder,a.geocode({address:b.options.center},function(a,c){try{c===google.maps.GeocoderStatus.OVER_QUERY_LIMIT?b.init():c===google.maps.GeocoderStatus.OK&&0!==a.length?q!==a[0]&&g(a[0],"geometry")&&(b.googleMapOptions.center=a[0].geometry.location,b.map=new google.maps.Map(b.container,b.googleMapOptions),google.maps.event.addListenerOnce(b.map,"idle",function(){b.overlay()}),
b.bindEvents(b.map,b.options.event)):console.error(c)}catch(f){console.error(f)}})):(b.map=new google.maps.Map(b.container,b.googleMapOptions),google.maps.event.addListenerOnce(b.map,"idle",function(){b.overlay()}),b.bindEvents(b.map,b.options.event))}};h.fn.tinyMap=function(b){var a=arguments,d=[],c={};return"string"===typeof b?(this.each(function(){c=h.data(this,"tinyMap");c instanceof u&&"function"===typeof c[b]&&(d=c[b].apply(c,Array.prototype.slice.call(a,1)))}),q!==d?d:this):this.each(function(){h.data(this,
"tinyMap")||h.data(this,"tinyMap",new u(this,b))})}})(jQuery,window,document);
|
/*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4,
maxerr: 50, browser: true */
/*global $, define, brackets, WebSocket, ArrayBuffer, Uint32Array */
define(function (require, exports, module) {
"use strict";
var EventDispatcher = require("utils/EventDispatcher");
/**
* Connection attempts to make before failing
* @type {number}
*/
var CONNECTION_ATTEMPTS = 10;
/**
* Milliseconds to wait before a particular connection attempt is considered failed.
* NOTE: It's okay for the connection timeout to be long because the
* expected behavior of WebSockets is to send a "close" event as soon
* as they realize they can't connect. So, we should rarely hit the
* connection timeout even if we try to connect to a port that isn't open.
* @type {number}
*/
var CONNECTION_TIMEOUT = 10000; // 10 seconds
/**
* Milliseconds to wait before retrying connecting
* @type {number}
*/
var RETRY_DELAY = 500; // 1/2 second
/**
* Maximum value of the command ID counter
* @type {number}
*/
var MAX_COUNTER_VALUE = 4294967295; // 2^32 - 1
/**
* @private
* Helper function to auto-reject a deferred after a given amount of time.
* If the deferred is resolved/rejected manually, then the timeout is
* automatically cleared.
*/
function setDeferredTimeout(deferred, delay) {
var timer = setTimeout(function () {
deferred.reject("timeout");
}, delay);
deferred.always(function () { clearTimeout(timer); });
}
/**
* @private
* Helper function to attempt a single connection to the node server
*/
function attemptSingleConnect() {
var deferred = $.Deferred();
var port = null;
var ws = null;
setDeferredTimeout(deferred, CONNECTION_TIMEOUT);
brackets.app.getNodeState(function (err, nodePort) {
if (!err && nodePort && deferred.state() !== "rejected") {
port = nodePort;
ws = new WebSocket("ws://localhost:" + port);
// Expect ArrayBuffer objects from Node when receiving binary
// data instead of DOM Blobs, which are the default.
ws.binaryType = "arraybuffer";
// If the server port isn't open, we get a close event
// at some point in the future (and will not get an onopen
// event)
ws.onclose = function () {
deferred.reject("WebSocket closed");
};
ws.onopen = function () {
// If we successfully opened, remove the old onclose
// handler (which was present to detect failure to
// connect at all).
ws.onclose = null;
deferred.resolveWith(null, [ws, port]);
};
} else {
deferred.reject("brackets.app.getNodeState error: " + err);
}
});
return deferred.promise();
}
/**
* Provides an interface for interacting with the node server.
* @constructor
*/
function NodeConnection() {
this.domains = {};
this._registeredModules = [];
this._pendingInterfaceRefreshDeferreds = [];
this._pendingCommandDeferreds = [];
}
EventDispatcher.makeEventDispatcher(NodeConnection.prototype);
/**
* @type {Object}
* Exposes the domains registered with the server. This object will
* have a property for each registered domain. Each of those properties
* will be an object containing properties for all the commands in that
* domain. So, myConnection.base.enableDebugger would point to the function
* to call to enable the debugger.
*
* This object is automatically replaced every time the API changes (based
* on the base:newDomains event from the server). Therefore, code that
* uses this object should not keep their own pointer to the domain property.
*/
NodeConnection.prototype.domains = null;
/**
* @private
* @type {Array.<string>}
* List of module pathnames that should be re-registered if there is
* a disconnection/connection (i.e. if the server died).
*/
NodeConnection.prototype._registeredModules = null;
/**
* @private
* @type {WebSocket}
* The connection to the server
*/
NodeConnection.prototype._ws = null;
/**
* @private
* @type {?number}
* The port the WebSocket is currently connected to
*/
NodeConnection.prototype._port = null;
/**
* @private
* @type {number}
* Unique ID for commands
*/
NodeConnection.prototype._commandCount = 1;
/**
* @private
* @type {boolean}
* Whether to attempt reconnection if connection fails
*/
NodeConnection.prototype._autoReconnect = false;
/**
* @private
* @type {Array.<jQuery.Deferred>}
* List of deferred objects that should be resolved pending
* a successful refresh of the API
*/
NodeConnection.prototype._pendingInterfaceRefreshDeferreds = null;
/**
* @private
* @type {Array.<jQuery.Deferred>}
* Array (indexed on command ID) of deferred objects that should be
* resolved/rejected with the response of commands.
*/
NodeConnection.prototype._pendingCommandDeferreds = null;
/**
* @private
* @return {number} The next command ID to use. Always representable as an
* unsigned 32-bit integer.
*/
NodeConnection.prototype._getNextCommandID = function () {
var nextID;
if (this._commandCount > MAX_COUNTER_VALUE) {
nextID = this._commandCount = 0;
} else {
nextID = this._commandCount++;
}
return nextID;
};
/**
* @private
* Helper function to do cleanup work when a connection fails
*/
NodeConnection.prototype._cleanup = function () {
// clear out the domains, since we may get different ones
// on the next connection
this.domains = {};
// shut down the old connection if there is one
if (this._ws && this._ws.readyState !== WebSocket.CLOSED) {
try {
this._ws.close();
} catch (e) { }
}
var failedDeferreds = this._pendingInterfaceRefreshDeferreds
.concat(this._pendingCommandDeferreds);
failedDeferreds.forEach(function (d) {
d.reject("cleanup");
});
this._pendingInterfaceRefreshDeferreds = [];
this._pendingCommandDeferreds = [];
this._ws = null;
this._port = null;
};
/**
* Connect to the node server. After connecting, the NodeConnection
* object will trigger a "close" event when the underlying socket
* is closed. If the connection is set to autoReconnect, then the
* event will also include a jQuery promise for the connection.
*
* @param {boolean} autoReconnect Whether to automatically try to
* reconnect to the server if the connection succeeds and then
* later disconnects. Note if this connection fails initially, the
* autoReconnect flag is set to false. Future calls to connect()
* can reset it to true
* @return {jQuery.Promise} Promise that resolves/rejects when the
* connection succeeds/fails
*/
NodeConnection.prototype.connect = function (autoReconnect) {
var self = this;
self._autoReconnect = autoReconnect;
var deferred = $.Deferred();
var attemptCount = 0;
var attemptTimestamp = null;
// Called after a successful connection to do final setup steps
function registerHandlersAndDomains(ws, port) {
// Called if we succeed at the final setup
function success() {
self._ws.onclose = function () {
if (self._autoReconnect) {
var $promise = self.connect(true);
self.trigger("close", $promise);
} else {
self._cleanup();
self.trigger("close");
}
};
deferred.resolve();
}
// Called if we fail at the final setup
function fail(err) {
self._cleanup();
deferred.reject(err);
}
self._ws = ws;
self._port = port;
self._ws.onmessage = self._receive.bind(self);
// refresh the current domains, then re-register any
// "autoregister" modules
self._refreshInterface().then(
function () {
if (self._registeredModules.length > 0) {
self.loadDomains(self._registeredModules, false).then(
success,
fail
);
} else {
success();
}
},
fail
);
}
// Repeatedly tries to connect until we succeed or until we've
// failed CONNECTION_ATTEMPT times. After each attempt, waits
// at least RETRY_DELAY before trying again.
function doConnect() {
attemptCount++;
attemptTimestamp = new Date();
attemptSingleConnect().then(
registerHandlersAndDomains, // succeded
function () { // failed this attempt, possibly try again
if (attemptCount < CONNECTION_ATTEMPTS) { //try again
// Calculate how long we should wait before trying again
var now = new Date();
var delay = Math.max(
RETRY_DELAY - (now - attemptTimestamp),
1
);
setTimeout(doConnect, delay);
} else { // too many attempts, give up
deferred.reject("Max connection attempts reached");
}
}
);
}
// Start the connection process
self._cleanup();
doConnect();
return deferred.promise();
};
/**
* Determines whether the NodeConnection is currently connected
* @return {boolean} Whether the NodeConnection is connected.
*/
NodeConnection.prototype.connected = function () {
return !!(this._ws && this._ws.readyState === WebSocket.OPEN);
};
/**
* Explicitly disconnects from the server. Note that even if
* autoReconnect was set to true at connection time, the connection
* will not reconnect after this call. Reconnection can be manually done
* by calling connect() again.
*/
NodeConnection.prototype.disconnect = function () {
this._autoReconnect = false;
this._cleanup();
};
/**
* Load domains into the server by path
* @param {Array.<string>} List of absolute paths to load
* @param {boolean} autoReload Whether to auto-reload the domains if the server
* fails and restarts. Note that the reload is initiated by the
* client, so it will only happen after the client reconnects.
* @return {jQuery.Promise} Promise that resolves after the load has
* succeeded and the new API is availale at NodeConnection.domains,
* or that rejects on failure.
*/
NodeConnection.prototype.loadDomains = function (paths, autoReload) {
var deferred = $.Deferred();
setDeferredTimeout(deferred, CONNECTION_TIMEOUT);
var pathArray = paths;
if (!Array.isArray(paths)) {
pathArray = [paths];
}
if (autoReload) {
Array.prototype.push.apply(this._registeredModules, pathArray);
}
if (this.domains.base && this.domains.base.loadDomainModulesFromPaths) {
this.domains.base.loadDomainModulesFromPaths(pathArray).then(
function (success) { // command call succeeded
if (!success) {
// response from commmand call was "false" so we know
// the actual load failed.
deferred.reject("loadDomainModulesFromPaths failed");
}
// if the load succeeded, we wait for the API refresh to
// resolve the deferred.
},
function (reason) { // command call failed
deferred.reject("Unable to load one of the modules: " + pathArray + (reason ? ", reason: " + reason : ""));
}
);
this._pendingInterfaceRefreshDeferreds.push(deferred);
} else {
deferred.reject("this.domains.base is undefined");
}
return deferred.promise();
};
/**
* @private
* Sends a message over the WebSocket. Automatically JSON.stringifys
* the message if necessary.
* @param {Object|string} m Object to send. Must be JSON.stringify-able.
*/
NodeConnection.prototype._send = function (m) {
if (this.connected()) {
// Convert the message to a string
var messageString = null;
if (typeof m === "string") {
messageString = m;
} else {
try {
messageString = JSON.stringify(m);
} catch (stringifyError) {
console.error("[NodeConnection] Unable to stringify message in order to send: " + stringifyError.message);
}
}
// If we succeded in making a string, try to send it
if (messageString) {
try {
this._ws.send(messageString);
} catch (sendError) {
console.error("[NodeConnection] Error sending message: " + sendError.message);
}
}
} else {
console.error("[NodeConnection] Not connected to node, unable to send.");
}
};
/**
* @private
* Handler for receiving events on the WebSocket. Parses the message
* and dispatches it appropriately.
* @param {WebSocket.Message} message Message object from WebSocket
*/
NodeConnection.prototype._receive = function (message) {
var responseDeferred = null;
var data = message.data;
var m;
if (message.data instanceof ArrayBuffer) {
// The first four bytes encode the command ID as an unsigned 32-bit integer
if (data.byteLength < 4) {
console.error("[NodeConnection] received malformed binary message");
return;
}
var header = data.slice(0, 4),
body = data.slice(4),
headerView = new Uint32Array(header),
id = headerView[0];
// Unpack the binary message into a commandResponse
m = {
type: "commandResponse",
message: {
id: id,
response: body
}
};
} else {
try {
m = JSON.parse(data);
} catch (e) {
console.error("[NodeConnection] received malformed message", message, e.message);
return;
}
}
switch (m.type) {
case "event":
if (m.message.domain === "base" && m.message.event === "newDomains") {
this._refreshInterface();
}
// Event type "domain:event"
EventDispatcher.triggerWithArray(this, m.message.domain + ":" + m.message.event,
m.message.parameters);
break;
case "commandResponse":
responseDeferred = this._pendingCommandDeferreds[m.message.id];
if (responseDeferred) {
responseDeferred.resolveWith(this, [m.message.response]);
delete this._pendingCommandDeferreds[m.message.id];
}
break;
case "commandError":
responseDeferred = this._pendingCommandDeferreds[m.message.id];
if (responseDeferred) {
responseDeferred.rejectWith(
this,
[m.message.message, m.message.stack]
);
delete this._pendingCommandDeferreds[m.message.id];
}
break;
case "error":
console.error("[NodeConnection] received error: " +
m.message.message);
break;
default:
console.error("[NodeConnection] unknown event type: " + m.type);
}
};
/**
* @private
* Helper function for refreshing the interface in the "domain" property.
* Automatically called when the connection receives a base:newDomains
* event from the server, and also called at connection time.
*/
NodeConnection.prototype._refreshInterface = function () {
var deferred = $.Deferred();
var self = this;
var pendingDeferreds = this._pendingInterfaceRefreshDeferreds;
this._pendingInterfaceRefreshDeferreds = [];
deferred.then(
function () {
pendingDeferreds.forEach(function (d) { d.resolve(); });
},
function (err) {
pendingDeferreds.forEach(function (d) { d.reject(err); });
}
);
function refreshInterfaceCallback(spec) {
function makeCommandFunction(domainName, commandSpec) {
return function () {
var deferred = $.Deferred();
var parameters = Array.prototype.slice.call(arguments, 0);
var id = self._getNextCommandID();
self._pendingCommandDeferreds[id] = deferred;
self._send({id: id,
domain: domainName,
command: commandSpec.name,
parameters: parameters
});
return deferred;
};
}
// TODO: Don't replace the domain object every time. Instead, merge.
self.domains = {};
self.domainEvents = {};
spec.forEach(function (domainSpec) {
self.domains[domainSpec.domain] = {};
domainSpec.commands.forEach(function (commandSpec) {
self.domains[domainSpec.domain][commandSpec.name] =
makeCommandFunction(domainSpec.domain, commandSpec);
});
self.domainEvents[domainSpec.domain] = {};
domainSpec.events.forEach(function (eventSpec) {
var parameters = eventSpec.parameters;
self.domainEvents[domainSpec.domain][eventSpec.name] = parameters;
});
});
deferred.resolve();
}
if (this.connected()) {
$.getJSON("http://localhost:" + this._port + "/api")
.done(refreshInterfaceCallback)
.fail(function (err) { deferred.reject(err); });
} else {
deferred.reject("Attempted to call _refreshInterface when not connected.");
}
return deferred.promise();
};
/**
* @private
* Get the default timeout value
* @return {number} Timeout value in milliseconds
*/
NodeConnection._getConnectionTimeout = function () {
return CONNECTION_TIMEOUT;
};
module.exports = NodeConnection;
});
|
module.exports = function(grunt) {
/**
* Initialize development environment for Testacular
*
* - register git hooks (commit-msg)
*/
grunt.registerTask('init-dev-env', 'Initialize dev environment.', function() {
var fs = require('fs');
var done = this.async();
fs.symlink('../../tasks/lib/validate-commit-msg.js', '.git/hooks/commit-msg', function(e) {
if (!e) {
grunt.log.ok('Hook "validate-commit-msg" installed.');
}
done();
});
});
};
|
// @flow
let tests = [
// setting a property
function(x: $Tainted<string>, y: string) {
let obj: Object = {};
obj.foo = x; // error, taint ~> any
obj[y] = x; // error, taint ~> any
},
// getting a property
function() {
let obj: Object = { foo: 'foo' };
(obj.foo: $Tainted<string>); // ok
},
// calling a method
function(x: $Tainted<string>) {
let obj: Object = {};
obj.foo(x); // error, taint ~> any
let foo = obj.foo;
foo(x); // error, taint ~> any
},
];
|
/**
* @author TristanVALCKE / https://github.com/Itee
* @author moraxy / https://github.com/moraxy
*/
/* global QUnit */
import { runStdLightTests } from '../../qunit-utils';
import { DirectionalLight } from '../../../../src/lights/DirectionalLight';
export default QUnit.module( 'Lights', () => {
QUnit.module( 'DirectionalLight', ( hooks ) => {
var lights = undefined;
hooks.beforeEach( function () {
const parameters = {
color: 0xaaaaaa,
intensity: 0.8
};
lights = [
new DirectionalLight(),
new DirectionalLight( parameters.color ),
new DirectionalLight( parameters.color, parameters.intensity )
];
} );
// INHERITANCE
QUnit.todo( "Extending", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
// INSTANCING
QUnit.todo( "Instancing", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
// PUBLIC STUFF
QUnit.todo( "isDirectionalLight", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
QUnit.todo( "copy", ( assert ) => {
assert.ok( false, "everything's gonna be alright" );
} );
// OTHERS
QUnit.test( 'Standard light tests', ( assert ) => {
runStdLightTests( assert, lights );
} );
} );
} );
|
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang("language","es",{button:"Fijar lenguaje",remove:"Quitar lenguaje"}); |
//=require rich/base |
var numLimitInput = element(by.model('numLimit'));
var letterLimitInput = element(by.model('letterLimit'));
var longNumberLimitInput = element(by.model('longNumberLimit'));
var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
it('should limit the number array to first three items', function() {
expect(numLimitInput.getAttribute('value')).toBe('3');
expect(letterLimitInput.getAttribute('value')).toBe('3');
expect(longNumberLimitInput.getAttribute('value')).toBe('3');
expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
expect(limitedLetters.getText()).toEqual('Output letters: abc');
expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
});
// There is a bug in safari and protractor that doesn't like the minus key
// it('should update the output when -3 is entered', function() {
// numLimitInput.clear();
// numLimitInput.sendKeys('-3');
// letterLimitInput.clear();
// letterLimitInput.sendKeys('-3');
// longNumberLimitInput.clear();
// longNumberLimitInput.sendKeys('-3');
// expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
// expect(limitedLetters.getText()).toEqual('Output letters: ghi');
// expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
// });
it('should not exceed the maximum size of input array', function() {
numLimitInput.clear();
numLimitInput.sendKeys('100');
letterLimitInput.clear();
letterLimitInput.sendKeys('100');
longNumberLimitInput.clear();
longNumberLimitInput.sendKeys('100');
expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
}); |
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Competency rule config.
*
* @package tool_lp
* @copyright 2015 Frédéric Massart - FMCorz.net
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define(['jquery',
'core/str'],
function($, Str) {
var OUTCOME_NONE = 0,
OUTCOME_EVIDENCE = 1,
OUTCOME_COMPLETE = 2,
OUTCOME_RECOMMEND = 3;
return /** @alias module:tool_lp/competency_outcomes */ {
NONE: OUTCOME_NONE,
EVIDENCE: OUTCOME_EVIDENCE,
COMPLETE: OUTCOME_COMPLETE,
RECOMMEND: OUTCOME_RECOMMEND,
/**
* Get all the outcomes.
*
* @return {Object} Indexed by outcome code, contains code and name.
* @method getAll
*/
getAll: function() {
var self = this;
return Str.get_strings([
{ key: 'competencyoutcome_none', component: 'tool_lp' },
{ key: 'competencyoutcome_evidence', component: 'tool_lp' },
{ key: 'competencyoutcome_recommend', component: 'tool_lp' },
{ key: 'competencyoutcome_complete', component: 'tool_lp' },
]).then(function(strings) {
var outcomes = {};
outcomes[self.NONE] = { code: self.NONE, name: strings[0] };
outcomes[self.EVIDENCE] = { code: self.EVIDENCE, name: strings[1] };
outcomes[self.RECOMMEND] = { code: self.RECOMMEND, name: strings[2] };
outcomes[self.COMPLETE] = { code: self.COMPLETE, name: strings[3] };
return outcomes;
});
},
/**
* Get the string for an outcome.
*
* @param {Number} id The outcome code.
* @return {Promise Resolved with the string.
* @method getString
*/
getString: function(id) {
var self = this,
all = self.getAll();
return all.then(function(outcomes) {
if (typeof outcomes[id] === 'undefined') {
return $.Deferred().reject().promise();
}
return outcomes[id].name;
});
}
};
});
|
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
/**
* <p>cc.Point extensions based on Chipmunk's cpVect file.<br />
* These extensions work both with cc.Point</p>
*
* <p>The "ccp" prefix means: "CoCos2d Point"</p>
*
* <p> //Examples:<br />
* - cc.pAdd( cc.p(1,1), cc.p(2,2) ); // preferred cocos2d way<br />
* - cc.pAdd( cc.p(1,1), cc.p(2,2) ); // also ok but more verbose<br />
* - cc.pAdd( cc.cpv(1,1), cc.cpv(2,2) ); // mixing chipmunk and cocos2d (avoid)</p>
*/
/**
* smallest such that 1.0+FLT_EPSILON != 1.0
* @constant
* @type Number
*/
cc.POINT_EPSILON = parseFloat('1.192092896e-07F');
/**
* Returns opposite of point.
* @param {cc.Point} point
* @return {cc.Point}
*/
cc.pNeg = function (point) {
return cc.p(-point.x, -point.y);
};
/**
* Calculates sum of two points.
* @param {cc.Point} v1
* @param {cc.Point} v2
* @return {cc.Point}
*/
cc.pAdd = function (v1, v2) {
return cc.p(v1.x + v2.x, v1.y + v2.y);
};
/**
* Calculates difference of two points.
* @param {cc.Point} v1
* @param {cc.Point} v2
* @return {cc.Point}
*/
cc.pSub = function (v1, v2) {
return cc.p(v1.x - v2.x, v1.y - v2.y);
};
/**
* Returns point multiplied by given factor.
* @param {cc.Point} point
* @param {Number} floatVar
* @return {cc.Point}
*/
cc.pMult = function (point, floatVar) {
return cc.p(point.x * floatVar, point.y * floatVar);
};
/**
* Calculates midpoint between two points.
* @param {cc.Point} v1
* @param {cc.Point} v2
* @return {cc.pMult}
*/
cc.pMidpoint = function (v1, v2) {
return cc.pMult(cc.pAdd(v1, v2), 0.5);
};
/**
* Calculates dot product of two points.
* @param {cc.Point} v1
* @param {cc.Point} v2
* @return {Number}
*/
cc.pDot = function (v1, v2) {
return v1.x * v2.x + v1.y * v2.y;
};
/**
* Calculates cross product of two points.
* @param {cc.Point} v1
* @param {cc.Point} v2
* @return {Number}
*/
cc.pCross = function (v1, v2) {
return v1.x * v2.y - v1.y * v2.x;
};
/**
* Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) >= 0
* @param {cc.Point} point
* @return {cc.Point}
*/
cc.pPerp = function (point) {
return cc.p(-point.y, point.x);
};
/**
* Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v)) <= 0
* @param {cc.Point} point
* @return {cc.Point}
*/
cc.pRPerp = function (point) {
return cc.p(point.y, -point.x);
};
/**
* Calculates the projection of v1 over v2.
* @param {cc.Point} v1
* @param {cc.Point} v2
* @return {cc.pMult}
*/
cc.pProject = function (v1, v2) {
return cc.pMult(v2, cc.pDot(v1, v2) / cc.pDot(v2, v2));
};
/**
* Rotates two points.
* @param {cc.Point} v1
* @param {cc.Point} v2
* @return {cc.Point}
*/
cc.pRotate = function (v1, v2) {
return cc.p(v1.x * v2.x - v1.y * v2.y, v1.x * v2.y + v1.y * v2.x);
};
/**
* Unrotates two points.
* @param {cc.Point} v1
* @param {cc.Point} v2
* @return {cc.Point}
*/
cc.pUnrotate = function (v1, v2) {
return cc.p(v1.x * v2.x + v1.y * v2.y, v1.y * v2.x - v1.x * v2.y);
};
/**
* Calculates the square length of a cc.Point (not calling sqrt() )
* @param {cc.Point} v
*@return {Number}
*/
cc.pLengthSQ = function (v) {
return cc.pDot(v, v);
};
/**
* Calculates the square distance between two points (not calling sqrt() )
* @param {cc.Point} point1
* @param {cc.Point} point2
* @return {Number}
*/
cc.pDistanceSQ = function(point1, point2){
return cc.pLengthSQ(cc.pSub(point1,point2));
};
/**
* Calculates distance between point an origin
* @param {cc.Point} v
* @return {Number}
*/
cc.pLength = function (v) {
return Math.sqrt(cc.pLengthSQ(v));
};
/**
* Calculates the distance between two points
* @param {cc.Point} v1
* @param {cc.Point} v2
* @return {Number}
*/
cc.pDistance = function (v1, v2) {
return cc.pLength(cc.pSub(v1, v2));
};
/**
* Returns point multiplied to a length of 1.
* @param {cc.Point} v
* @return {cc.Point}
*/
cc.pNormalize = function (v) {
var n = cc.pLength(v);
return n === 0 ? cc.p(v) : cc.pMult(v, 1.0 / n);
};
/**
* Converts radians to a normalized vector.
* @param {Number} a
* @return {cc.Point}
*/
cc.pForAngle = function (a) {
return cc.p(Math.cos(a), Math.sin(a));
};
/**
* Converts a vector to radians.
* @param {cc.Point} v
* @return {Number}
*/
cc.pToAngle = function (v) {
return Math.atan2(v.y, v.x);
};
/**
* Clamp a value between from and to.
* @param {Number} value
* @param {Number} min_inclusive
* @param {Number} max_inclusive
* @return {Number}
*/
cc.clampf = function (value, min_inclusive, max_inclusive) {
if (min_inclusive > max_inclusive) {
var temp = min_inclusive;
min_inclusive = max_inclusive;
max_inclusive = temp;
}
return value < min_inclusive ? min_inclusive : value < max_inclusive ? value : max_inclusive;
};
/**
* Clamp a point between from and to.
* @param {Point} p
* @param {Number} min_inclusive
* @param {Number} max_inclusive
* @return {cc.Point}
*/
cc.pClamp = function (p, min_inclusive, max_inclusive) {
return cc.p(cc.clampf(p.x, min_inclusive.x, max_inclusive.x), cc.clampf(p.y, min_inclusive.y, max_inclusive.y));
};
/**
* Quickly convert cc.Size to a cc.Point
* @param {cc.Size} s
* @return {cc.Point}
*/
cc.pFromSize = function (s) {
return cc.p(s.width, s.height);
};
/**
* Run a math operation function on each point component <br />
* Math.abs, Math.fllor, Math.ceil, Math.round.
* @param {cc.Point} p
* @param {Function} opFunc
* @return {cc.Point}
* @example
* //For example: let's try to take the floor of x,y
* var p = cc.pCompOp(cc.p(10,10),Math.abs);
*/
cc.pCompOp = function (p, opFunc) {
return cc.p(opFunc(p.x), opFunc(p.y));
};
/**
* Linear Interpolation between two points a and b
* alpha == 0 ? a
* alpha == 1 ? b
* otherwise a value between a..b
* @param {cc.Point} a
* @param {cc.Point} b
* @param {Number} alpha
* @return {cc.pAdd}
*/
cc.pLerp = function (a, b, alpha) {
return cc.pAdd(cc.pMult(a, 1 - alpha), cc.pMult(b, alpha));
};
/**
* @param {cc.Point} a
* @param {cc.Point} b
* @param {Number} variance
* @return {Boolean} if points have fuzzy equality which means equal with some degree of variance.
*/
cc.pFuzzyEqual = function (a, b, variance) {
if (a.x - variance <= b.x && b.x <= a.x + variance) {
if (a.y - variance <= b.y && b.y <= a.y + variance)
return true;
}
return false;
};
/**
* Multiplies a nd b components, a.x*b.x, a.y*b.y
* @param {cc.Point} a
* @param {cc.Point} b
* @return {cc.Point}
*/
cc.pCompMult = function (a, b) {
return cc.p(a.x * b.x, a.y * b.y);
};
/**
* @param {cc.Point} a
* @param {cc.Point} b
* @return {Number} the signed angle in radians between two vector directions
*/
cc.pAngleSigned = function (a, b) {
var a2 = cc.pNormalize(a);
var b2 = cc.pNormalize(b);
var angle = Math.atan2(a2.x * b2.y - a2.y * b2.x, cc.pDot(a2, b2));
if (Math.abs(angle) < cc.POINT_EPSILON)
return 0.0;
return angle;
};
/**
* @param {cc.Point} a
* @param {cc.Point} b
* @return {Number} the angle in radians between two vector directions
*/
cc.pAngle = function (a, b) {
var angle = Math.acos(cc.pDot(cc.pNormalize(a), cc.pNormalize(b)));
if (Math.abs(angle) < cc.POINT_EPSILON) return 0.0;
return angle;
};
/**
* Rotates a point counter clockwise by the angle around a pivot
* @param {cc.Point} v v is the point to rotate
* @param {cc.Point} pivot pivot is the pivot, naturally
* @param {Number} angle angle is the angle of rotation cw in radians
* @return {cc.Point} the rotated point
*/
cc.pRotateByAngle = function (v, pivot, angle) {
var r = cc.pSub(v, pivot);
var cosa = Math.cos(angle), sina = Math.sin(angle);
var t = r.x;
r.x = t * cosa - r.y * sina + pivot.x;
r.y = t * sina + r.y * cosa + pivot.y;
return r;
};
/**
* A general line-line intersection test
* indicating successful intersection of a line<br />
* note that to truly test intersection for segments we have to make<br />
* sure that s & t lie within [0..1] and for rays, make sure s & t > 0<br />
* the hit point is p3 + t * (p4 - p3);<br />
* the hit point also is p1 + s * (p2 - p1);
* @param {cc.Point} A A is the startpoint for the first line P1 = (p1 - p2).
* @param {cc.Point} B B is the endpoint for the first line P1 = (p1 - p2).
* @param {cc.Point} C C is the startpoint for the second line P2 = (p3 - p4).
* @param {cc.Point} D D is the endpoint for the second line P2 = (p3 - p4).
* @param {cc.Point} retP retP.x is the range for a hitpoint in P1 (pa = p1 + s*(p2 - p1)), <br />
* retP.y is the range for a hitpoint in P3 (pa = p2 + t*(p4 - p3)).
* @return {Boolean}
*/
cc.pLineIntersect = function (A, B, C, D, retP) {
if ((A.x === B.x && A.y === B.y) || (C.x === D.x && C.y === D.y)) {
return false;
}
var BAx = B.x - A.x;
var BAy = B.y - A.y;
var DCx = D.x - C.x;
var DCy = D.y - C.y;
var ACx = A.x - C.x;
var ACy = A.y - C.y;
var denom = DCy * BAx - DCx * BAy;
retP.x = DCx * ACy - DCy * ACx;
retP.y = BAx * ACy - BAy * ACx;
if (denom === 0) {
if (retP.x === 0 || retP.y === 0) {
// Lines incident
return true;
}
// Lines parallel and not incident
return false;
}
retP.x = retP.x / denom;
retP.y = retP.y / denom;
return true;
};
/**
* ccpSegmentIntersect return YES if Segment A-B intersects with segment C-D.
* @param {cc.Point} A
* @param {cc.Point} B
* @param {cc.Point} C
* @param {cc.Point} D
* @return {Boolean}
*/
cc.pSegmentIntersect = function (A, B, C, D) {
var retP = cc.p(0, 0);
if (cc.pLineIntersect(A, B, C, D, retP))
if (retP.x >= 0.0 && retP.x <= 1.0 && retP.y >= 0.0 && retP.y <= 1.0)
return true;
return false;
};
/**
* ccpIntersectPoint return the intersection point of line A-B, C-D
* @param {cc.Point} A
* @param {cc.Point} B
* @param {cc.Point} C
* @param {cc.Point} D
* @return {cc.Point}
*/
cc.pIntersectPoint = function (A, B, C, D) {
var retP = cc.p(0, 0);
if (cc.pLineIntersect(A, B, C, D, retP)) {
// Point of intersection
var P = cc.p(0, 0);
P.x = A.x + retP.x * (B.x - A.x);
P.y = A.y + retP.x * (B.y - A.y);
return P;
}
return cc.p(0,0);
};
/**
* check to see if both points are equal
* @param {cc.Point} A A ccp a
* @param {cc.Point} B B ccp b to be compared
* @return {Boolean} the true if both ccp are same
*/
cc.pSameAs = function (A, B) {
if ((A != null) && (B != null)) {
return (A.x === B.x && A.y === B.y);
}
return false;
};
// High Perfomance In Place Operationrs ---------------------------------------
/**
* sets the position of the point to 0
* @param {cc.Point} v
*/
cc.pZeroIn = function(v) {
v.x = 0;
v.y = 0;
};
/**
* copies the position of one point to another
* @param {cc.Point} v1
* @param {cc.Point} v2
*/
cc.pIn = function(v1, v2) {
v1.x = v2.x;
v1.y = v2.y;
};
/**
* multiplies the point with the given factor (inplace)
* @param {cc.Point} point
* @param {Number} floatVar
*/
cc.pMultIn = function(point, floatVar) {
point.x *= floatVar;
point.y *= floatVar;
};
/**
* subtracts one point from another (inplace)
* @param {cc.Point} v1
* @param {cc.Point} v2
*/
cc.pSubIn = function(v1, v2) {
v1.x -= v2.x;
v1.y -= v2.y;
};
/**
* adds one point to another (inplace)
* @param {cc.Point} v1
* @param {cc.point} v2
*/
cc.pAddIn = function(v1, v2) {
v1.x += v2.x;
v1.y += v2.y;
};
/**
* normalizes the point (inplace)
* @param {cc.Point} v
*/
cc.pNormalizeIn = function(v) {
cc.pMultIn(v, 1.0 / Math.sqrt(v.x * v.x + v.y * v.y));
};
|
/*! leaflet-routing-machine - v3.2.1 - 2016-10-11
* Copyright (c) 2013-2016 Per Liedman
* Distributed under the ISC license */
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}(g.L || (g.L = {})).Routing = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
function corslite(url, callback, cors) {
var sent = false;
if (typeof window.XMLHttpRequest === 'undefined') {
return callback(Error('Browser not supported'));
}
if (typeof cors === 'undefined') {
var m = url.match(/^\s*https?:\/\/[^\/]*/);
cors = m && (m[0] !== location.protocol + '//' + location.hostname +
(location.port ? ':' + location.port : ''));
}
var x = new window.XMLHttpRequest();
function isSuccessful(status) {
return status >= 200 && status < 300 || status === 304;
}
if (cors && !('withCredentials' in x)) {
// IE8-9
x = new window.XDomainRequest();
// Ensure callback is never called synchronously, i.e., before
// x.send() returns (this has been observed in the wild).
// See https://github.com/mapbox/mapbox.js/issues/472
var original = callback;
callback = function() {
if (sent) {
original.apply(this, arguments);
} else {
var that = this, args = arguments;
setTimeout(function() {
original.apply(that, args);
}, 0);
}
}
}
function loaded() {
if (
// XDomainRequest
x.status === undefined ||
// modern browsers
isSuccessful(x.status)) callback.call(x, null, x);
else callback.call(x, x, null);
}
// Both `onreadystatechange` and `onload` can fire. `onreadystatechange`
// has [been supported for longer](http://stackoverflow.com/a/9181508/229001).
if ('onload' in x) {
x.onload = loaded;
} else {
x.onreadystatechange = function readystate() {
if (x.readyState === 4) {
loaded();
}
};
}
// Call the callback with the XMLHttpRequest object as an error and prevent
// it from ever being called again by reassigning it to `noop`
x.onerror = function error(evt) {
// XDomainRequest provides no evt parameter
callback.call(this, evt || true, null);
callback = function() { };
};
// IE9 must have onprogress be set to a unique function.
x.onprogress = function() { };
x.ontimeout = function(evt) {
callback.call(this, evt, null);
callback = function() { };
};
x.onabort = function(evt) {
callback.call(this, evt, null);
callback = function() { };
};
// GET is the only supported HTTP Verb by XDomainRequest and is the
// only one supported here.
x.open('GET', url, true);
// Send the request. Sending data is not supported.
x.send(null);
sent = true;
return x;
}
if (typeof module !== 'undefined') module.exports = corslite;
},{}],2:[function(_dereq_,module,exports){
'use strict';
/**
* Based off of [the offical Google document](https://developers.google.com/maps/documentation/utilities/polylinealgorithm)
*
* Some parts from [this implementation](http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/PolylineEncoder.js)
* by [Mark McClure](http://facstaff.unca.edu/mcmcclur/)
*
* @module polyline
*/
var polyline = {};
function encode(coordinate, factor) {
coordinate = Math.round(coordinate * factor);
coordinate <<= 1;
if (coordinate < 0) {
coordinate = ~coordinate;
}
var output = '';
while (coordinate >= 0x20) {
output += String.fromCharCode((0x20 | (coordinate & 0x1f)) + 63);
coordinate >>= 5;
}
output += String.fromCharCode(coordinate + 63);
return output;
}
/**
* Decodes to a [latitude, longitude] coordinates array.
*
* This is adapted from the implementation in Project-OSRM.
*
* @param {String} str
* @param {Number} precision
* @returns {Array}
*
* @see https://github.com/Project-OSRM/osrm-frontend/blob/master/WebContent/routing/OSRM.RoutingGeometry.js
*/
polyline.decode = function(str, precision) {
var index = 0,
lat = 0,
lng = 0,
coordinates = [],
shift = 0,
result = 0,
byte = null,
latitude_change,
longitude_change,
factor = Math.pow(10, precision || 5);
// Coordinates have variable length when encoded, so just keep
// track of whether we've hit the end of the string. In each
// loop iteration, a single coordinate is decoded.
while (index < str.length) {
// Reset shift, result, and byte
byte = null;
shift = 0;
result = 0;
do {
byte = str.charCodeAt(index++) - 63;
result |= (byte & 0x1f) << shift;
shift += 5;
} while (byte >= 0x20);
latitude_change = ((result & 1) ? ~(result >> 1) : (result >> 1));
shift = result = 0;
do {
byte = str.charCodeAt(index++) - 63;
result |= (byte & 0x1f) << shift;
shift += 5;
} while (byte >= 0x20);
longitude_change = ((result & 1) ? ~(result >> 1) : (result >> 1));
lat += latitude_change;
lng += longitude_change;
coordinates.push([lat / factor, lng / factor]);
}
return coordinates;
};
/**
* Encodes the given [latitude, longitude] coordinates array.
*
* @param {Array.<Array.<Number>>} coordinates
* @param {Number} precision
* @returns {String}
*/
polyline.encode = function(coordinates, precision) {
if (!coordinates.length) { return ''; }
var factor = Math.pow(10, precision || 5),
output = encode(coordinates[0][0], factor) + encode(coordinates[0][1], factor);
for (var i = 1; i < coordinates.length; i++) {
var a = coordinates[i], b = coordinates[i - 1];
output += encode(a[0] - b[0], factor);
output += encode(a[1] - b[1], factor);
}
return output;
};
function flipped(coords) {
var flipped = [];
for (var i = 0; i < coords.length; i++) {
flipped.push(coords[i].slice().reverse());
}
return flipped;
}
/**
* Encodes a GeoJSON LineString feature/geometry.
*
* @param {Object} geojson
* @param {Number} precision
* @returns {String}
*/
polyline.fromGeoJSON = function(geojson, precision) {
if (geojson && geojson.type === 'Feature') {
geojson = geojson.geometry;
}
if (!geojson || geojson.type !== 'LineString') {
throw new Error('Input must be a GeoJSON LineString');
}
return polyline.encode(flipped(geojson.coordinates), precision);
};
/**
* Decodes to a GeoJSON LineString geometry.
*
* @param {String} str
* @param {Number} precision
* @returns {Object}
*/
polyline.toGeoJSON = function(str, precision) {
var coords = polyline.decode(str, precision);
return {
type: 'LineString',
coordinates: flipped(coords)
};
};
if (typeof module === 'object' && module.exports) {
module.exports = polyline;
}
},{}],3:[function(_dereq_,module,exports){
(function() {
'use strict';
L.Routing = L.Routing || {};
L.Routing.Autocomplete = L.Class.extend({
options: {
timeout: 500,
blurTimeout: 100,
noResultsMessage: 'No results found.'
},
initialize: function(elem, callback, context, options) {
L.setOptions(this, options);
this._elem = elem;
this._resultFn = options.resultFn ? L.Util.bind(options.resultFn, options.resultContext) : null;
this._autocomplete = options.autocompleteFn ? L.Util.bind(options.autocompleteFn, options.autocompleteContext) : null;
this._selectFn = L.Util.bind(callback, context);
this._container = L.DomUtil.create('div', 'leaflet-routing-geocoder-result');
this._resultTable = L.DomUtil.create('table', '', this._container);
// TODO: looks a bit like a kludge to register same for input and keypress -
// browsers supporting both will get duplicate events; just registering
// input will not catch enter, though.
L.DomEvent.addListener(this._elem, 'input', this._keyPressed, this);
L.DomEvent.addListener(this._elem, 'keypress', this._keyPressed, this);
L.DomEvent.addListener(this._elem, 'keydown', this._keyDown, this);
L.DomEvent.addListener(this._elem, 'blur', function() {
if (this._isOpen) {
this.close();
}
}, this);
},
close: function() {
L.DomUtil.removeClass(this._container, 'leaflet-routing-geocoder-result-open');
this._isOpen = false;
},
_open: function() {
var rect = this._elem.getBoundingClientRect();
if (!this._container.parentElement) {
// See notes section under https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollX
// This abomination is required to support all flavors of IE
var scrollX = (window.pageXOffset !== undefined) ? window.pageXOffset
: (document.documentElement || document.body.parentNode || document.body).scrollLeft;
var scrollY = (window.pageYOffset !== undefined) ? window.pageYOffset
: (document.documentElement || document.body.parentNode || document.body).scrollTop;
this._container.style.left = (rect.left + scrollX) + 'px';
this._container.style.top = (rect.bottom + scrollY) + 'px';
this._container.style.width = (rect.right - rect.left) + 'px';
document.body.appendChild(this._container);
}
L.DomUtil.addClass(this._container, 'leaflet-routing-geocoder-result-open');
this._isOpen = true;
},
_setResults: function(results) {
var i,
tr,
td,
text;
delete this._selection;
this._results = results;
while (this._resultTable.firstChild) {
this._resultTable.removeChild(this._resultTable.firstChild);
}
for (i = 0; i < results.length; i++) {
tr = L.DomUtil.create('tr', '', this._resultTable);
tr.setAttribute('data-result-index', i);
td = L.DomUtil.create('td', '', tr);
text = document.createTextNode(results[i].name);
td.appendChild(text);
// mousedown + click because:
// http://stackoverflow.com/questions/10652852/jquery-fire-click-before-blur-event
L.DomEvent.addListener(td, 'mousedown', L.DomEvent.preventDefault);
L.DomEvent.addListener(td, 'click', this._createClickListener(results[i]));
}
if (!i) {
tr = L.DomUtil.create('tr', '', this._resultTable);
td = L.DomUtil.create('td', 'leaflet-routing-geocoder-no-results', tr);
td.innerHTML = this.options.noResultsMessage;
}
this._open();
if (results.length > 0) {
// Select the first entry
this._select(1);
}
},
_createClickListener: function(r) {
var resultSelected = this._resultSelected(r);
return L.bind(function() {
this._elem.blur();
resultSelected();
}, this);
},
_resultSelected: function(r) {
return L.bind(function() {
this.close();
this._elem.value = r.name;
this._lastCompletedText = r.name;
this._selectFn(r);
}, this);
},
_keyPressed: function(e) {
var index;
if (this._isOpen && e.keyCode === 13 && this._selection) {
index = parseInt(this._selection.getAttribute('data-result-index'), 10);
this._resultSelected(this._results[index])();
L.DomEvent.preventDefault(e);
return;
}
if (e.keyCode === 13) {
this._complete(this._resultFn, true);
return;
}
if (this._autocomplete && document.activeElement === this._elem) {
if (this._timer) {
clearTimeout(this._timer);
}
this._timer = setTimeout(L.Util.bind(function() { this._complete(this._autocomplete); }, this),
this.options.timeout);
return;
}
this._unselect();
},
_select: function(dir) {
var sel = this._selection;
if (sel) {
L.DomUtil.removeClass(sel.firstChild, 'leaflet-routing-geocoder-selected');
sel = sel[dir > 0 ? 'nextSibling' : 'previousSibling'];
}
if (!sel) {
sel = this._resultTable[dir > 0 ? 'firstChild' : 'lastChild'];
}
if (sel) {
L.DomUtil.addClass(sel.firstChild, 'leaflet-routing-geocoder-selected');
this._selection = sel;
}
},
_unselect: function() {
if (this._selection) {
L.DomUtil.removeClass(this._selection.firstChild, 'leaflet-routing-geocoder-selected');
}
delete this._selection;
},
_keyDown: function(e) {
if (this._isOpen) {
switch (e.keyCode) {
// Escape
case 27:
this.close();
L.DomEvent.preventDefault(e);
return;
// Up
case 38:
this._select(-1);
L.DomEvent.preventDefault(e);
return;
// Down
case 40:
this._select(1);
L.DomEvent.preventDefault(e);
return;
}
}
},
_complete: function(completeFn, trySelect) {
var v = this._elem.value;
function completeResults(results) {
this._lastCompletedText = v;
if (trySelect && results.length === 1) {
this._resultSelected(results[0])();
} else {
this._setResults(results);
}
}
if (!v) {
return;
}
if (v !== this._lastCompletedText) {
completeFn(v, completeResults, this);
} else if (trySelect) {
completeResults.call(this, this._results);
}
}
});
})();
},{}],4:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null);
L.Routing = L.Routing || {};
L.extend(L.Routing, _dereq_('./L.Routing.Itinerary'));
L.extend(L.Routing, _dereq_('./L.Routing.Line'));
L.extend(L.Routing, _dereq_('./L.Routing.Plan'));
L.extend(L.Routing, _dereq_('./L.Routing.OSRMv1'));
L.extend(L.Routing, _dereq_('./L.Routing.Mapbox'));
L.extend(L.Routing, _dereq_('./L.Routing.ErrorControl'));
L.Routing.Control = L.Routing.Itinerary.extend({
options: {
fitSelectedRoutes: 'smart',
routeLine: function(route, options) { return L.Routing.line(route, options); },
autoRoute: true,
routeWhileDragging: false,
routeDragInterval: 500,
waypointMode: 'connect',
showAlternatives: false,
defaultErrorHandler: function(e) {
console.error('Routing error:', e.error);
}
},
initialize: function(options) {
L.Util.setOptions(this, options);
this._router = this.options.router || new L.Routing.OSRMv1(options);
this._plan = this.options.plan || L.Routing.plan(this.options.waypoints, options);
this._requestCount = 0;
L.Routing.Itinerary.prototype.initialize.call(this, options);
this.on('routeselected', this._routeSelected, this);
if (this.options.defaultErrorHandler) {
this.on('routingerror', this.options.defaultErrorHandler);
}
this._plan.on('waypointschanged', this._onWaypointsChanged, this);
if (options.routeWhileDragging) {
this._setupRouteDragging();
}
if (this.options.autoRoute) {
this.route();
}
},
onAdd: function(map) {
var container = L.Routing.Itinerary.prototype.onAdd.call(this, map);
this._map = map;
this._map.addLayer(this._plan);
this._map.on('zoomend', function() {
if (!this._selectedRoute ||
!this._router.requiresMoreDetail) {
return;
}
var map = this._map;
if (this._router.requiresMoreDetail(this._selectedRoute,
map.getZoom(), map.getBounds())) {
this.route({
callback: L.bind(function(err, routes) {
var i;
if (!err) {
for (i = 0; i < routes.length; i++) {
this._routes[i].properties = routes[i].properties;
}
this._updateLineCallback(err, routes);
}
}, this),
simplifyGeometry: false,
geometryOnly: true
});
}
}, this);
if (this._plan.options.geocoder) {
container.insertBefore(this._plan.createGeocoders(), container.firstChild);
}
return container;
},
onRemove: function(map) {
if (this._line) {
map.removeLayer(this._line);
}
map.removeLayer(this._plan);
if (this._alternatives && this._alternatives.length > 0) {
for (var i = 0, len = this._alternatives.length; i < len; i++) {
map.removeLayer(this._alternatives[i]);
}
}
return L.Routing.Itinerary.prototype.onRemove.call(this, map);
},
getWaypoints: function() {
return this._plan.getWaypoints();
},
setWaypoints: function(waypoints) {
this._plan.setWaypoints(waypoints);
return this;
},
spliceWaypoints: function() {
var removed = this._plan.spliceWaypoints.apply(this._plan, arguments);
return removed;
},
getPlan: function() {
return this._plan;
},
getRouter: function() {
return this._router;
},
_routeSelected: function(e) {
var route = this._selectedRoute = e.route,
alternatives = this.options.showAlternatives && e.alternatives,
fitMode = this.options.fitSelectedRoutes,
fitBounds =
(fitMode === 'smart' && !this._waypointsVisible()) ||
(fitMode !== 'smart' && fitMode);
this._updateLines({route: route, alternatives: alternatives});
if (fitBounds) {
this._map.fitBounds(this._line.getBounds());
}
if (this.options.waypointMode === 'snap') {
this._plan.off('waypointschanged', this._onWaypointsChanged, this);
this.setWaypoints(route.waypoints);
this._plan.on('waypointschanged', this._onWaypointsChanged, this);
}
},
_waypointsVisible: function() {
var wps = this.getWaypoints(),
mapSize,
bounds,
boundsSize,
i,
p;
try {
mapSize = this._map.getSize();
for (i = 0; i < wps.length; i++) {
p = this._map.latLngToLayerPoint(wps[i].latLng);
if (bounds) {
bounds.extend(p);
} else {
bounds = L.bounds([p]);
}
}
boundsSize = bounds.getSize();
return (boundsSize.x > mapSize.x / 5 ||
boundsSize.y > mapSize.y / 5) && this._waypointsInViewport();
} catch (e) {
return false;
}
},
_waypointsInViewport: function() {
var wps = this.getWaypoints(),
mapBounds,
i;
try {
mapBounds = this._map.getBounds();
} catch (e) {
return false;
}
for (i = 0; i < wps.length; i++) {
if (mapBounds.contains(wps[i].latLng)) {
return true;
}
}
return false;
},
_updateLines: function(routes) {
var addWaypoints = this.options.addWaypoints !== undefined ?
this.options.addWaypoints : true;
this._clearLines();
// add alternatives first so they lie below the main route
this._alternatives = [];
if (routes.alternatives) routes.alternatives.forEach(function(alt, i) {
this._alternatives[i] = this.options.routeLine(alt,
L.extend({
isAlternative: true
}, this.options.altLineOptions || this.options.lineOptions));
this._alternatives[i].addTo(this._map);
this._hookAltEvents(this._alternatives[i]);
}, this);
this._line = this.options.routeLine(routes.route,
L.extend({
addWaypoints: addWaypoints,
extendToWaypoints: this.options.waypointMode === 'connect'
}, this.options.lineOptions));
this._line.addTo(this._map);
this._hookEvents(this._line);
},
_hookEvents: function(l) {
l.on('linetouched', function(e) {
this._plan.dragNewWaypoint(e);
}, this);
},
_hookAltEvents: function(l) {
l.on('linetouched', function(e) {
var alts = this._routes.slice();
var selected = alts.splice(e.target._route.routesIndex, 1)[0];
this.fire('routeselected', {route: selected, alternatives: alts});
}, this);
},
_onWaypointsChanged: function(e) {
if (this.options.autoRoute) {
this.route({});
}
if (!this._plan.isReady()) {
this._clearLines();
this._clearAlts();
}
this.fire('waypointschanged', {waypoints: e.waypoints});
},
_setupRouteDragging: function() {
var timer = 0,
waypoints;
this._plan.on('waypointdrag', L.bind(function(e) {
waypoints = e.waypoints;
if (!timer) {
timer = setTimeout(L.bind(function() {
this.route({
waypoints: waypoints,
geometryOnly: true,
callback: L.bind(this._updateLineCallback, this)
});
timer = undefined;
}, this), this.options.routeDragInterval);
}
}, this));
this._plan.on('waypointdragend', function() {
if (timer) {
clearTimeout(timer);
timer = undefined;
}
this.route();
}, this);
},
_updateLineCallback: function(err, routes) {
if (!err) {
routes = routes.slice();
var selected = routes.splice(this._selectedRoute.routesIndex, 1)[0];
this._updateLines({route: selected, alternatives: routes });
} else if (err.type !== 'abort') {
this._clearLines();
}
},
route: function(options) {
var ts = ++this._requestCount,
wps;
if (this._pendingRequest && this._pendingRequest.abort) {
this._pendingRequest.abort();
this._pendingRequest = null;
}
options = options || {};
if (this._plan.isReady()) {
if (this.options.useZoomParameter) {
options.z = this._map && this._map.getZoom();
}
wps = options && options.waypoints || this._plan.getWaypoints();
this.fire('routingstart', {waypoints: wps});
this._pendingRequest = this._router.route(wps, function(err, routes) {
this._pendingRequest = null;
if (options.callback) {
return options.callback.call(this, err, routes);
}
// Prevent race among multiple requests,
// by checking the current request's count
// against the last request's; ignore result if
// this isn't the last request.
if (ts === this._requestCount) {
this._clearLines();
this._clearAlts();
if (err && err.type !== 'abort') {
this.fire('routingerror', {error: err});
return;
}
routes.forEach(function(route, i) { route.routesIndex = i; });
if (!options.geometryOnly) {
this.fire('routesfound', {waypoints: wps, routes: routes});
this.setAlternatives(routes);
} else {
var selectedRoute = routes.splice(0,1)[0];
this._routeSelected({route: selectedRoute, alternatives: routes});
}
}
}, this, options);
}
},
_clearLines: function() {
if (this._line) {
this._map.removeLayer(this._line);
delete this._line;
}
if (this._alternatives && this._alternatives.length) {
for (var i in this._alternatives) {
this._map.removeLayer(this._alternatives[i]);
}
this._alternatives = [];
}
}
});
L.Routing.control = function(options) {
return new L.Routing.Control(options);
};
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./L.Routing.ErrorControl":5,"./L.Routing.Itinerary":8,"./L.Routing.Line":10,"./L.Routing.Mapbox":12,"./L.Routing.OSRMv1":13,"./L.Routing.Plan":14}],5:[function(_dereq_,module,exports){
(function() {
'use strict';
L.Routing = L.Routing || {};
L.Routing.ErrorControl = L.Control.extend({
options: {
header: 'Routing error',
formatMessage: function(error) {
if (error.status < 0) {
return 'Calculating the route caused an error. Technical description follows: <code><pre>' +
error.message + '</pre></code';
} else {
return 'The route could not be calculated. ' +
error.message;
}
}
},
initialize: function(routingControl, options) {
L.Control.prototype.initialize.call(this, options);
routingControl
.on('routingerror', L.bind(function(e) {
if (this._element) {
this._element.children[1].innerHTML = this.options.formatMessage(e.error);
this._element.style.visibility = 'visible';
}
}, this))
.on('routingstart', L.bind(function() {
if (this._element) {
this._element.style.visibility = 'hidden';
}
}, this));
},
onAdd: function() {
var header,
message;
this._element = L.DomUtil.create('div', 'leaflet-bar leaflet-routing-error');
this._element.style.visibility = 'hidden';
header = L.DomUtil.create('h3', null, this._element);
message = L.DomUtil.create('span', null, this._element);
header.innerHTML = this.options.header;
return this._element;
},
onRemove: function() {
delete this._element;
}
});
L.Routing.errorControl = function(routingControl, options) {
return new L.Routing.ErrorControl(routingControl, options);
};
})();
},{}],6:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null);
L.Routing = L.Routing || {};
L.extend(L.Routing, _dereq_('./L.Routing.Localization'));
L.Routing.Formatter = L.Class.extend({
options: {
units: 'metric',
unitNames: null,
language: 'en',
roundingSensitivity: 1,
distanceTemplate: '{value} {unit}'
},
initialize: function(options) {
L.setOptions(this, options);
var langs = L.Util.isArray(this.options.language) ?
this.options.language :
[this.options.language, 'en'];
this._localization = new L.Routing.Localization(langs);
},
formatDistance: function(d /* Number (meters) */, sensitivity) {
var un = this.options.unitNames || this._localization.localize('units'),
simpleRounding = sensitivity <= 0,
round = simpleRounding ? function(v) { return v; } : L.bind(this._round, this),
v,
yards,
data,
pow10;
if (this.options.units === 'imperial') {
yards = d / 0.9144;
if (yards >= 1000) {
data = {
value: round(d / 1609.344, sensitivity),
unit: un.miles
};
} else {
data = {
value: round(yards, sensitivity),
unit: un.yards
};
}
} else {
v = round(d, sensitivity);
data = {
value: v >= 1000 ? (v / 1000) : v,
unit: v >= 1000 ? un.kilometers : un.meters
};
}
if (simpleRounding) {
data.value = data.value.toFixed(-sensitivity);
}
return L.Util.template(this.options.distanceTemplate, data);
},
_round: function(d, sensitivity) {
var s = sensitivity || this.options.roundingSensitivity,
pow10 = Math.pow(10, (Math.floor(d / s) + '').length - 1),
r = Math.floor(d / pow10),
p = (r > 5) ? pow10 : pow10 / 2;
return Math.round(d / p) * p;
},
formatTime: function(t /* Number (seconds) */) {
var un = this.options.unitNames || this._localization.localize('units');
// More than 30 seconds precision looks ridiculous
t = Math.round(t / 30) * 30;
if (t > 86400) {
return Math.round(t / 3600) + ' ' + un.hours;
} else if (t > 3600) {
return Math.floor(t / 3600) + ' ' + un.hours + ' ' +
Math.round((t % 3600) / 60) + ' ' + un.minutes;
} else if (t > 300) {
return Math.round(t / 60) + ' ' + un.minutes;
} else if (t > 60) {
return Math.floor(t / 60) + ' ' + un.minutes +
(t % 60 !== 0 ? ' ' + (t % 60) + ' ' + un.seconds : '');
} else {
return t + ' ' + un.seconds;
}
},
formatInstruction: function(instr, i) {
if (instr.text === undefined) {
return this.capitalize(L.Util.template(this._getInstructionTemplate(instr, i),
L.extend({}, instr, {
exitStr: instr.exit ? this._localization.localize('formatOrder')(instr.exit) : '',
dir: this._localization.localize(['directions', instr.direction]),
modifier: this._localization.localize(['directions', instr.modifier])
})));
} else {
return instr.text;
}
},
getIconName: function(instr, i) {
switch (instr.type) {
case 'Head':
if (i === 0) {
return 'depart';
}
break;
case 'WaypointReached':
return 'via';
case 'Roundabout':
return 'enter-roundabout';
case 'DestinationReached':
return 'arrive';
}
switch (instr.modifier) {
case 'Straight':
return 'continue';
case 'SlightRight':
return 'bear-right';
case 'Right':
return 'turn-right';
case 'SharpRight':
return 'sharp-right';
case 'TurnAround':
case 'Uturn':
return 'u-turn';
case 'SharpLeft':
return 'sharp-left';
case 'Left':
return 'turn-left';
case 'SlightLeft':
return 'bear-left';
}
},
capitalize: function(s) {
return s.charAt(0).toUpperCase() + s.substring(1);
},
_getInstructionTemplate: function(instr, i) {
var type = instr.type === 'Straight' ? (i === 0 ? 'Head' : 'Continue') : instr.type,
strings = this._localization.localize(['instructions', type]);
if (!strings) {
strings = [
this._localization.localize(['directions', type]),
' ' + this._localization.localize(['instructions', 'Onto'])
];
}
return strings[0] + (strings.length > 1 && instr.road ? strings[1] : '');
}
});
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./L.Routing.Localization":11}],7:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null);
L.Routing = L.Routing || {};
L.extend(L.Routing, _dereq_('./L.Routing.Autocomplete'));
function selectInputText(input) {
if (input.setSelectionRange) {
// On iOS, select() doesn't work
input.setSelectionRange(0, 9999);
} else {
// On at least IE8, setSeleectionRange doesn't exist
input.select();
}
}
L.Routing.GeocoderElement = L.Class.extend({
includes: L.Mixin.Events,
options: {
createGeocoder: function(i, nWps, options) {
var container = L.DomUtil.create('div', 'leaflet-routing-geocoder'),
input = L.DomUtil.create('input', '', container),
remove = options.addWaypoints ? L.DomUtil.create('span', 'leaflet-routing-remove-waypoint', container) : undefined;
input.disabled = !options.addWaypoints;
return {
container: container,
input: input,
closeButton: remove
};
},
geocoderPlaceholder: function(i, numberWaypoints, geocoderElement) {
var l = new L.Routing.Localization(geocoderElement.options.language).localize('ui');
return i === 0 ?
l.startPlaceholder :
(i < numberWaypoints - 1 ?
L.Util.template(l.viaPlaceholder, {viaNumber: i}) :
l.endPlaceholder);
},
geocoderClass: function() {
return '';
},
waypointNameFallback: function(latLng) {
var ns = latLng.lat < 0 ? 'S' : 'N',
ew = latLng.lng < 0 ? 'W' : 'E',
lat = (Math.round(Math.abs(latLng.lat) * 10000) / 10000).toString(),
lng = (Math.round(Math.abs(latLng.lng) * 10000) / 10000).toString();
return ns + lat + ', ' + ew + lng;
},
maxGeocoderTolerance: 200,
autocompleteOptions: {},
language: 'en',
},
initialize: function(wp, i, nWps, options) {
L.setOptions(this, options);
var g = this.options.createGeocoder(i, nWps, this.options),
closeButton = g.closeButton,
geocoderInput = g.input;
geocoderInput.setAttribute('placeholder', this.options.geocoderPlaceholder(i, nWps, this));
geocoderInput.className = this.options.geocoderClass(i, nWps);
this._element = g;
this._waypoint = wp;
this.update();
// This has to be here, or geocoder's value will not be properly
// initialized.
// TODO: look into why and make _updateWaypointName fix this.
geocoderInput.value = wp.name;
L.DomEvent.addListener(geocoderInput, 'click', function() {
selectInputText(this);
}, geocoderInput);
if (closeButton) {
L.DomEvent.addListener(closeButton, 'click', function() {
this.fire('delete', { waypoint: this._waypoint });
}, this);
}
new L.Routing.Autocomplete(geocoderInput, function(r) {
geocoderInput.value = r.name;
wp.name = r.name;
wp.latLng = r.center;
this.fire('geocoded', { waypoint: wp, value: r });
}, this, L.extend({
resultFn: this.options.geocoder.geocode,
resultContext: this.options.geocoder,
autocompleteFn: this.options.geocoder.suggest,
autocompleteContext: this.options.geocoder
}, this.options.autocompleteOptions));
},
getContainer: function() {
return this._element.container;
},
setValue: function(v) {
this._element.input.value = v;
},
update: function(force) {
var wp = this._waypoint,
wpCoords;
wp.name = wp.name || '';
if (wp.latLng && (force || !wp.name)) {
wpCoords = this.options.waypointNameFallback(wp.latLng);
if (this.options.geocoder && this.options.geocoder.reverse) {
this.options.geocoder.reverse(wp.latLng, 67108864 /* zoom 18 */, function(rs) {
if (rs.length > 0 && rs[0].center.distanceTo(wp.latLng) < this.options.maxGeocoderTolerance) {
wp.name = rs[0].name;
} else {
wp.name = wpCoords;
}
this._update();
}, this);
} else {
wp.name = wpCoords;
this._update();
}
}
},
focus: function() {
var input = this._element.input;
input.focus();
selectInputText(input);
},
_update: function() {
var wp = this._waypoint,
value = wp && wp.name ? wp.name : '';
this.setValue(value);
this.fire('reversegeocoded', {waypoint: wp, value: value});
}
});
L.Routing.geocoderElement = function(wp, i, nWps, plan) {
return new L.Routing.GeocoderElement(wp, i, nWps, plan);
};
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./L.Routing.Autocomplete":3}],8:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null);
L.Routing = L.Routing || {};
L.extend(L.Routing, _dereq_('./L.Routing.Formatter'));
L.extend(L.Routing, _dereq_('./L.Routing.ItineraryBuilder'));
L.Routing.Itinerary = L.Control.extend({
includes: L.Mixin.Events,
options: {
pointMarkerStyle: {
radius: 5,
color: '#03f',
fillColor: 'white',
opacity: 1,
fillOpacity: 0.7
},
summaryTemplate: '<h2>{name}</h2><h3>{distance}, {time}</h3>',
timeTemplate: '{time}',
containerClassName: '',
alternativeClassName: '',
minimizedClassName: '',
itineraryClassName: '',
totalDistanceRoundingSensitivity: -1,
show: true,
collapsible: undefined,
collapseBtn: function(itinerary) {
var collapseBtn = L.DomUtil.create('span', itinerary.options.collapseBtnClass);
L.DomEvent.on(collapseBtn, 'click', itinerary._toggle, itinerary);
itinerary._container.insertBefore(collapseBtn, itinerary._container.firstChild);
},
collapseBtnClass: 'leaflet-routing-collapse-btn'
},
initialize: function(options) {
L.setOptions(this, options);
this._formatter = this.options.formatter || new L.Routing.Formatter(this.options);
this._itineraryBuilder = this.options.itineraryBuilder || new L.Routing.ItineraryBuilder({
containerClassName: this.options.itineraryClassName
});
},
onAdd: function(map) {
var collapsible = this.options.collapsible;
collapsible = collapsible || (collapsible === undefined && map.getSize().x <= 640);
this._container = L.DomUtil.create('div', 'leaflet-routing-container leaflet-bar ' +
(!this.options.show ? 'leaflet-routing-container-hide ' : '') +
(collapsible ? 'leaflet-routing-collapsible ' : '') +
this.options.containerClassName);
this._altContainer = this.createAlternativesContainer();
this._container.appendChild(this._altContainer);
L.DomEvent.disableClickPropagation(this._container);
L.DomEvent.addListener(this._container, 'mousewheel', function(e) {
L.DomEvent.stopPropagation(e);
});
if (collapsible) {
this.options.collapseBtn(this);
}
return this._container;
},
onRemove: function() {
},
createAlternativesContainer: function() {
return L.DomUtil.create('div', 'leaflet-routing-alternatives-container');
},
setAlternatives: function(routes) {
var i,
alt,
altDiv;
this._clearAlts();
this._routes = routes;
for (i = 0; i < this._routes.length; i++) {
alt = this._routes[i];
altDiv = this._createAlternative(alt, i);
this._altContainer.appendChild(altDiv);
this._altElements.push(altDiv);
}
this._selectRoute({route: this._routes[0], alternatives: this._routes.slice(1)});
return this;
},
show: function() {
L.DomUtil.removeClass(this._container, 'leaflet-routing-container-hide');
},
hide: function() {
L.DomUtil.addClass(this._container, 'leaflet-routing-container-hide');
},
_toggle: function() {
var collapsed = L.DomUtil.hasClass(this._container, 'leaflet-routing-container-hide');
this[collapsed ? 'show' : 'hide']();
},
_createAlternative: function(alt, i) {
var altDiv = L.DomUtil.create('div', 'leaflet-routing-alt ' +
this.options.alternativeClassName +
(i > 0 ? ' leaflet-routing-alt-minimized ' + this.options.minimizedClassName : '')),
template = this.options.summaryTemplate,
data = L.extend({
name: alt.name,
distance: this._formatter.formatDistance(alt.summary.totalDistance, this.options.totalDistanceRoundingSensitivity),
time: this._formatter.formatTime(alt.summary.totalTime)
}, alt);
altDiv.innerHTML = typeof(template) === 'function' ? template(data) : L.Util.template(template, data);
L.DomEvent.addListener(altDiv, 'click', this._onAltClicked, this);
this.on('routeselected', this._selectAlt, this);
altDiv.appendChild(this._createItineraryContainer(alt));
return altDiv;
},
_clearAlts: function() {
var el = this._altContainer;
while (el && el.firstChild) {
el.removeChild(el.firstChild);
}
this._altElements = [];
},
_createItineraryContainer: function(r) {
var container = this._itineraryBuilder.createContainer(),
steps = this._itineraryBuilder.createStepsContainer(),
i,
instr,
step,
distance,
text,
icon;
container.appendChild(steps);
for (i = 0; i < r.instructions.length; i++) {
instr = r.instructions[i];
text = this._formatter.formatInstruction(instr, i);
distance = this._formatter.formatDistance(instr.distance);
icon = this._formatter.getIconName(instr, i);
step = this._itineraryBuilder.createStep(text, distance, icon, steps);
this._addRowListeners(step, r.coordinates[instr.index]);
}
return container;
},
_addRowListeners: function(row, coordinate) {
L.DomEvent.addListener(row, 'mouseover', function() {
this._marker = L.circleMarker(coordinate,
this.options.pointMarkerStyle).addTo(this._map);
}, this);
L.DomEvent.addListener(row, 'mouseout', function() {
if (this._marker) {
this._map.removeLayer(this._marker);
delete this._marker;
}
}, this);
L.DomEvent.addListener(row, 'click', function(e) {
this._map.panTo(coordinate);
L.DomEvent.stopPropagation(e);
}, this);
},
_onAltClicked: function(e) {
var altElem = e.target || window.event.srcElement;
while (!L.DomUtil.hasClass(altElem, 'leaflet-routing-alt')) {
altElem = altElem.parentElement;
}
var j = this._altElements.indexOf(altElem);
var alts = this._routes.slice();
var route = alts.splice(j, 1)[0];
this.fire('routeselected', {
route: route,
alternatives: alts
});
},
_selectAlt: function(e) {
var altElem,
j,
n,
classFn;
altElem = this._altElements[e.route.routesIndex];
if (L.DomUtil.hasClass(altElem, 'leaflet-routing-alt-minimized')) {
for (j = 0; j < this._altElements.length; j++) {
n = this._altElements[j];
classFn = j === e.route.routesIndex ? 'removeClass' : 'addClass';
L.DomUtil[classFn](n, 'leaflet-routing-alt-minimized');
if (this.options.minimizedClassName) {
L.DomUtil[classFn](n, this.options.minimizedClassName);
}
if (j !== e.route.routesIndex) n.scrollTop = 0;
}
}
L.DomEvent.stop(e);
},
_selectRoute: function(routes) {
if (this._marker) {
this._map.removeLayer(this._marker);
delete this._marker;
}
this.fire('routeselected', routes);
}
});
L.Routing.itinerary = function(options) {
return new L.Routing.Itinerary(options);
};
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./L.Routing.Formatter":6,"./L.Routing.ItineraryBuilder":9}],9:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null);
L.Routing = L.Routing || {};
L.Routing.ItineraryBuilder = L.Class.extend({
options: {
containerClassName: ''
},
initialize: function(options) {
L.setOptions(this, options);
},
createContainer: function(className) {
var table = L.DomUtil.create('table', className || ''),
colgroup = L.DomUtil.create('colgroup', '', table);
L.DomUtil.create('col', 'leaflet-routing-instruction-icon', colgroup);
L.DomUtil.create('col', 'leaflet-routing-instruction-text', colgroup);
L.DomUtil.create('col', 'leaflet-routing-instruction-distance', colgroup);
return table;
},
createStepsContainer: function() {
return L.DomUtil.create('tbody', '');
},
createStep: function(text, distance, icon, steps) {
var row = L.DomUtil.create('tr', '', steps),
span,
td;
td = L.DomUtil.create('td', '', row);
span = L.DomUtil.create('span', 'leaflet-routing-icon leaflet-routing-icon-'+icon, td);
td.appendChild(span);
td = L.DomUtil.create('td', '', row);
td.appendChild(document.createTextNode(text));
td = L.DomUtil.create('td', '', row);
td.appendChild(document.createTextNode(distance));
return row;
}
});
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],10:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null);
L.Routing = L.Routing || {};
L.Routing.Line = L.LayerGroup.extend({
includes: L.Mixin.Events,
options: {
styles: [
{color: 'black', opacity: 0.15, weight: 9},
{color: 'white', opacity: 0.8, weight: 6},
{color: 'red', opacity: 1, weight: 2}
],
missingRouteStyles: [
{color: 'black', opacity: 0.15, weight: 7},
{color: 'white', opacity: 0.6, weight: 4},
{color: 'gray', opacity: 0.8, weight: 2, dashArray: '7,12'}
],
addWaypoints: true,
extendToWaypoints: true,
missingRouteTolerance: 10
},
initialize: function(route, options) {
L.setOptions(this, options);
L.LayerGroup.prototype.initialize.call(this, options);
this._route = route;
if (this.options.extendToWaypoints) {
this._extendToWaypoints();
}
this._addSegment(
route.coordinates,
this.options.styles,
this.options.addWaypoints);
},
getBounds: function() {
return L.latLngBounds(this._route.coordinates);
},
_findWaypointIndices: function() {
var wps = this._route.inputWaypoints,
indices = [],
i;
for (i = 0; i < wps.length; i++) {
indices.push(this._findClosestRoutePoint(wps[i].latLng));
}
return indices;
},
_findClosestRoutePoint: function(latlng) {
var minDist = Number.MAX_VALUE,
minIndex,
i,
d;
for (i = this._route.coordinates.length - 1; i >= 0 ; i--) {
// TODO: maybe do this in pixel space instead?
d = latlng.distanceTo(this._route.coordinates[i]);
if (d < minDist) {
minIndex = i;
minDist = d;
}
}
return minIndex;
},
_extendToWaypoints: function() {
var wps = this._route.inputWaypoints,
wpIndices = this._getWaypointIndices(),
i,
wpLatLng,
routeCoord;
for (i = 0; i < wps.length; i++) {
wpLatLng = wps[i].latLng;
routeCoord = L.latLng(this._route.coordinates[wpIndices[i]]);
if (wpLatLng.distanceTo(routeCoord) >
this.options.missingRouteTolerance) {
this._addSegment([wpLatLng, routeCoord],
this.options.missingRouteStyles);
}
}
},
_addSegment: function(coords, styles, mouselistener) {
var i,
pl;
for (i = 0; i < styles.length; i++) {
pl = L.polyline(coords, styles[i]);
this.addLayer(pl);
if (mouselistener) {
pl.on('mousedown', this._onLineTouched, this);
}
}
},
_findNearestWpBefore: function(i) {
var wpIndices = this._getWaypointIndices(),
j = wpIndices.length - 1;
while (j >= 0 && wpIndices[j] > i) {
j--;
}
return j;
},
_onLineTouched: function(e) {
var afterIndex = this._findNearestWpBefore(this._findClosestRoutePoint(e.latlng));
this.fire('linetouched', {
afterIndex: afterIndex,
latlng: e.latlng
});
},
_getWaypointIndices: function() {
if (!this._wpIndices) {
this._wpIndices = this._route.waypointIndices || this._findWaypointIndices();
}
return this._wpIndices;
}
});
L.Routing.line = function(route, options) {
return new L.Routing.Line(route, options);
};
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],11:[function(_dereq_,module,exports){
(function() {
'use strict';
var spanish = {
directions: {
N: 'norte',
NE: 'noreste',
E: 'este',
SE: 'sureste',
S: 'sur',
SW: 'suroeste',
W: 'oeste',
NW: 'noroeste',
SlightRight: 'leve giro a la derecha',
Right: 'derecha',
SharpRight: 'giro pronunciado a la derecha',
SlightLeft: 'leve giro a la izquierda',
Left: 'izquierda',
SharpLeft: 'giro pronunciado a la izquierda',
Uturn: 'media vuelta'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Derecho {dir}', ' sobre {road}'],
'Continue':
['Continuar {dir}', ' en {road}'],
'TurnAround':
['Dar vuelta'],
'WaypointReached':
['Llegó a un punto del camino'],
'Roundabout':
['Tomar {exitStr} salida en la rotonda', ' en {road}'],
'DestinationReached':
['Llegada a destino'],
'Fork': ['En el cruce gira a {modifier}', ' hacia {road}'],
'Merge': ['Incorpórate {modifier}', ' hacia {road}'],
'OnRamp': ['Gira {modifier} en la salida', ' hacia {road}'],
'OffRamp': ['Toma la salida {modifier}', ' hacia {road}'],
'EndOfRoad': ['Gira {modifier} al final de la carretera', ' hacia {road}'],
'Onto': 'hacia {road}'
},
formatOrder: function(n) {
return n + 'º';
},
ui: {
startPlaceholder: 'Inicio',
viaPlaceholder: 'Via {viaNumber}',
endPlaceholder: 'Destino'
},
units: {
meters: 'm',
kilometers: 'km',
yards: 'yd',
miles: 'mi',
hours: 'h',
minutes: 'min',
seconds: 's'
}
};
L.Routing = L.Routing || {};
L.Routing.Localization = L.Class.extend({
initialize: function(langs) {
this._langs = L.Util.isArray(langs) ? langs : [langs, 'en'];
for (var i = 0, l = this._langs.length; i < l; i++) {
if (!L.Routing.Localization[this._langs[i]]) {
throw new Error('No localization for language "' + this._langs[i] + '".');
}
}
},
localize: function(keys) {
var dict,
key,
value;
keys = L.Util.isArray(keys) ? keys : [keys];
for (var i = 0, l = this._langs.length; i < l; i++) {
dict = L.Routing.Localization[this._langs[i]];
for (var j = 0, nKeys = keys.length; dict && j < nKeys; j++) {
key = keys[j];
value = dict[key];
dict = value;
}
if (value) {
return value;
}
}
}
});
L.Routing.Localization = L.extend(L.Routing.Localization, {
'en': {
directions: {
N: 'north',
NE: 'northeast',
E: 'east',
SE: 'southeast',
S: 'south',
SW: 'southwest',
W: 'west',
NW: 'northwest',
SlightRight: 'slight right',
Right: 'right',
SharpRight: 'sharp right',
SlightLeft: 'slight left',
Left: 'left',
SharpLeft: 'sharp left',
Uturn: 'Turn around'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Head {dir}', ' on {road}'],
'Continue':
['Continue {dir}'],
'TurnAround':
['Turn around'],
'WaypointReached':
['Waypoint reached'],
'Roundabout':
['Take the {exitStr} exit in the roundabout', ' onto {road}'],
'DestinationReached':
['Destination reached'],
'Fork': ['At the fork, turn {modifier}', ' onto {road}'],
'Merge': ['Merge {modifier}', ' onto {road}'],
'OnRamp': ['Turn {modifier} on the ramp', ' onto {road}'],
'OffRamp': ['Take the ramp on the {modifier}', ' onto {road}'],
'EndOfRoad': ['Turn {modifier} at the end of the road', ' onto {road}'],
'Onto': 'onto {road}'
},
formatOrder: function(n) {
var i = n % 10 - 1,
suffix = ['st', 'nd', 'rd'];
return suffix[i] ? n + suffix[i] : n + 'th';
},
ui: {
startPlaceholder: 'Start',
viaPlaceholder: 'Via {viaNumber}',
endPlaceholder: 'End'
},
units: {
meters: 'm',
kilometers: 'km',
yards: 'yd',
miles: 'mi',
hours: 'h',
minutes: 'min',
seconds: 's'
}
},
'de': {
directions: {
N: 'Norden',
NE: 'Nordosten',
E: 'Osten',
SE: 'Südosten',
S: 'Süden',
SW: 'Südwesten',
W: 'Westen',
NW: 'Nordwesten'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Richtung {dir}', ' auf {road}'],
'Continue':
['Geradeaus Richtung {dir}', ' auf {road}'],
'SlightRight':
['Leicht rechts abbiegen', ' auf {road}'],
'Right':
['Rechts abbiegen', ' auf {road}'],
'SharpRight':
['Scharf rechts abbiegen', ' auf {road}'],
'TurnAround':
['Wenden'],
'SharpLeft':
['Scharf links abbiegen', ' auf {road}'],
'Left':
['Links abbiegen', ' auf {road}'],
'SlightLeft':
['Leicht links abbiegen', ' auf {road}'],
'WaypointReached':
['Zwischenhalt erreicht'],
'Roundabout':
['Nehmen Sie die {exitStr} Ausfahrt im Kreisverkehr', ' auf {road}'],
'DestinationReached':
['Sie haben ihr Ziel erreicht'],
},
formatOrder: function(n) {
return n + '.';
},
ui: {
startPlaceholder: 'Start',
viaPlaceholder: 'Via {viaNumber}',
endPlaceholder: 'Ziel'
}
},
'sv': {
directions: {
N: 'norr',
NE: 'nordost',
E: 'öst',
SE: 'sydost',
S: 'syd',
SW: 'sydväst',
W: 'väst',
NW: 'nordväst',
SlightRight: 'svagt höger',
Right: 'höger',
SharpRight: 'skarpt höger',
SlightLeft: 'svagt vänster',
Left: 'vänster',
SharpLeft: 'skarpt vänster',
Uturn: 'Vänd'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Åk åt {dir}', ' till {road}'],
'Continue':
['Fortsätt {dir}'],
'SlightRight':
['Svagt höger', ' till {road}'],
'Right':
['Sväng höger', ' till {road}'],
'SharpRight':
['Skarpt höger', ' till {road}'],
'TurnAround':
['Vänd'],
'SharpLeft':
['Skarpt vänster', ' till {road}'],
'Left':
['Sväng vänster', ' till {road}'],
'SlightLeft':
['Svagt vänster', ' till {road}'],
'WaypointReached':
['Viapunkt nådd'],
'Roundabout':
['Tag {exitStr} avfarten i rondellen', ' till {road}'],
'DestinationReached':
['Framme vid resans mål'],
'Fork': ['Tag av {modifier}', ' till {road}'],
'Merge': ['Anslut {modifier} ', ' till {road}'],
'OnRamp': ['Tag påfarten {modifier}', ' till {road}'],
'OffRamp': ['Tag avfarten {modifier}', ' till {road}'],
'EndOfRoad': ['Sväng {modifier} vid vägens slut', ' till {road}'],
'Onto': 'till {road}'
},
formatOrder: function(n) {
return ['första', 'andra', 'tredje', 'fjärde', 'femte',
'sjätte', 'sjunde', 'åttonde', 'nionde', 'tionde'
/* Can't possibly be more than ten exits, can there? */][n - 1];
},
ui: {
startPlaceholder: 'Från',
viaPlaceholder: 'Via {viaNumber}',
endPlaceholder: 'Till'
}
},
'es': spanish,
'sp': spanish,
'nl': {
directions: {
N: 'noordelijke',
NE: 'noordoostelijke',
E: 'oostelijke',
SE: 'zuidoostelijke',
S: 'zuidelijke',
SW: 'zuidewestelijke',
W: 'westelijke',
NW: 'noordwestelijke'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Vertrek in {dir} richting', ' de {road} op'],
'Continue':
['Ga in {dir} richting', ' de {road} op'],
'SlightRight':
['Volg de weg naar rechts', ' de {road} op'],
'Right':
['Ga rechtsaf', ' de {road} op'],
'SharpRight':
['Ga scherpe bocht naar rechts', ' de {road} op'],
'TurnAround':
['Keer om'],
'SharpLeft':
['Ga scherpe bocht naar links', ' de {road} op'],
'Left':
['Ga linksaf', ' de {road} op'],
'SlightLeft':
['Volg de weg naar links', ' de {road} op'],
'WaypointReached':
['Aangekomen bij tussenpunt'],
'Roundabout':
['Neem de {exitStr} afslag op de rotonde', ' de {road} op'],
'DestinationReached':
['Aangekomen op eindpunt'],
},
formatOrder: function(n) {
if (n === 1 || n >= 20) {
return n + 'ste';
} else {
return n + 'de';
}
},
ui: {
startPlaceholder: 'Vertrekpunt',
viaPlaceholder: 'Via {viaNumber}',
endPlaceholder: 'Bestemming'
}
},
'fr': {
directions: {
N: 'nord',
NE: 'nord-est',
E: 'est',
SE: 'sud-est',
S: 'sud',
SW: 'sud-ouest',
W: 'ouest',
NW: 'nord-ouest'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Tout droit au {dir}', ' sur {road}'],
'Continue':
['Continuer au {dir}', ' sur {road}'],
'SlightRight':
['Légèrement à droite', ' sur {road}'],
'Right':
['A droite', ' sur {road}'],
'SharpRight':
['Complètement à droite', ' sur {road}'],
'TurnAround':
['Faire demi-tour'],
'SharpLeft':
['Complètement à gauche', ' sur {road}'],
'Left':
['A gauche', ' sur {road}'],
'SlightLeft':
['Légèrement à gauche', ' sur {road}'],
'WaypointReached':
['Point d\'étape atteint'],
'Roundabout':
['Au rond-point, prenez la {exitStr} sortie', ' sur {road}'],
'DestinationReached':
['Destination atteinte'],
},
formatOrder: function(n) {
return n + 'º';
},
ui: {
startPlaceholder: 'Départ',
viaPlaceholder: 'Intermédiaire {viaNumber}',
endPlaceholder: 'Arrivée'
}
},
'it': {
directions: {
N: 'nord',
NE: 'nord-est',
E: 'est',
SE: 'sud-est',
S: 'sud',
SW: 'sud-ovest',
W: 'ovest',
NW: 'nord-ovest'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Dritto verso {dir}', ' su {road}'],
'Continue':
['Continuare verso {dir}', ' su {road}'],
'SlightRight':
['Mantenere la destra', ' su {road}'],
'Right':
['A destra', ' su {road}'],
'SharpRight':
['Strettamente a destra', ' su {road}'],
'TurnAround':
['Fare inversione di marcia'],
'SharpLeft':
['Strettamente a sinistra', ' su {road}'],
'Left':
['A sinistra', ' sur {road}'],
'SlightLeft':
['Mantenere la sinistra', ' su {road}'],
'WaypointReached':
['Punto di passaggio raggiunto'],
'Roundabout':
['Alla rotonda, prendere la {exitStr} uscita'],
'DestinationReached':
['Destinazione raggiunta'],
},
formatOrder: function(n) {
return n + 'º';
},
ui: {
startPlaceholder: 'Partenza',
viaPlaceholder: 'Intermedia {viaNumber}',
endPlaceholder: 'Destinazione'
}
},
'pt': {
directions: {
N: 'norte',
NE: 'nordeste',
E: 'leste',
SE: 'sudeste',
S: 'sul',
SW: 'sudoeste',
W: 'oeste',
NW: 'noroeste',
SlightRight: 'curva ligeira a direita',
Right: 'direita',
SharpRight: 'curva fechada a direita',
SlightLeft: 'ligeira a esquerda',
Left: 'esquerda',
SharpLeft: 'curva fechada a esquerda',
Uturn: 'Meia volta'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Siga {dir}', ' na {road}'],
'Continue':
['Continue {dir}', ' na {road}'],
'SlightRight':
['Curva ligeira a direita', ' na {road}'],
'Right':
['Curva a direita', ' na {road}'],
'SharpRight':
['Curva fechada a direita', ' na {road}'],
'TurnAround':
['Retorne'],
'SharpLeft':
['Curva fechada a esquerda', ' na {road}'],
'Left':
['Curva a esquerda', ' na {road}'],
'SlightLeft':
['Curva ligueira a esquerda', ' na {road}'],
'WaypointReached':
['Ponto de interesse atingido'],
'Roundabout':
['Pegue a {exitStr} saída na rotatória', ' na {road}'],
'DestinationReached':
['Destino atingido'],
'Fork': ['Na encruzilhada, vire a {modifier}', ' na {road}'],
'Merge': ['Entre à {modifier}', ' na {road}'],
'OnRamp': ['Vire {modifier} na rampa', ' na {road}'],
'OffRamp': ['Entre na rampa na {modifier}', ' na {road}'],
'EndOfRoad': ['Vire {modifier} no fim da rua', ' na {road}'],
'Onto': 'na {road}'
},
formatOrder: function(n) {
return n + 'º';
},
ui: {
startPlaceholder: 'Origem',
viaPlaceholder: 'Intermédio {viaNumber}',
endPlaceholder: 'Destino'
}
},
'sk': {
directions: {
N: 'sever',
NE: 'serverovýchod',
E: 'východ',
SE: 'juhovýchod',
S: 'juh',
SW: 'juhozápad',
W: 'západ',
NW: 'serverozápad'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Mierte na {dir}', ' na {road}'],
'Continue':
['Pokračujte na {dir}', ' na {road}'],
'SlightRight':
['Mierne doprava', ' na {road}'],
'Right':
['Doprava', ' na {road}'],
'SharpRight':
['Prudko doprava', ' na {road}'],
'TurnAround':
['Otočte sa'],
'SharpLeft':
['Prudko doľava', ' na {road}'],
'Left':
['Doľava', ' na {road}'],
'SlightLeft':
['Mierne doľava', ' na {road}'],
'WaypointReached':
['Ste v prejazdovom bode.'],
'Roundabout':
['Odbočte na {exitStr} výjazde', ' na {road}'],
'DestinationReached':
['Prišli ste do cieľa.'],
},
formatOrder: function(n) {
var i = n % 10 - 1,
suffix = ['.', '.', '.'];
return suffix[i] ? n + suffix[i] : n + '.';
},
ui: {
startPlaceholder: 'Začiatok',
viaPlaceholder: 'Cez {viaNumber}',
endPlaceholder: 'Koniec'
}
},
'el': {
directions: {
N: 'βόρεια',
NE: 'βορειοανατολικά',
E: 'ανατολικά',
SE: 'νοτιοανατολικά',
S: 'νότια',
SW: 'νοτιοδυτικά',
W: 'δυτικά',
NW: 'βορειοδυτικά'
},
instructions: {
// instruction, postfix if the road is named
'Head':
['Κατευθυνθείτε {dir}', ' στην {road}'],
'Continue':
['Συνεχίστε {dir}', ' στην {road}'],
'SlightRight':
['Ελαφρώς δεξιά', ' στην {road}'],
'Right':
['Δεξιά', ' στην {road}'],
'SharpRight':
['Απότομη δεξιά στροφή', ' στην {road}'],
'TurnAround':
['Κάντε αναστροφή'],
'SharpLeft':
['Απότομη αριστερή στροφή', ' στην {road}'],
'Left':
['Αριστερά', ' στην {road}'],
'SlightLeft':
['Ελαφρώς αριστερά', ' στην {road}'],
'WaypointReached':
['Φτάσατε στο σημείο αναφοράς'],
'Roundabout':
['Ακολουθήστε την {exitStr} έξοδο στο κυκλικό κόμβο', ' στην {road}'],
'DestinationReached':
['Φτάσατε στον προορισμό σας'],
},
formatOrder: function(n) {
return n + 'º';
},
ui: {
startPlaceholder: 'Αφετηρία',
viaPlaceholder: 'μέσω {viaNumber}',
endPlaceholder: 'Προορισμός'
}
},
'ca': {
directions: {
N: 'nord',
NE: 'nord-est',
E: 'est',
SE: 'sud-est',
S: 'sud',
SW: 'sud-oest',
W: 'oest',
NW: 'nord-oest',
SlightRight: 'lleu gir a la dreta',
Right: 'dreta',
SharpRight: 'gir pronunciat a la dreta',
SlightLeft: 'gir pronunciat a l\'esquerra',
Left: 'esquerra',
SharpLeft: 'lleu gir a l\'esquerra',
Uturn: 'mitja volta'
},
instructions: {
'Head':
['Recte {dir}', ' sobre {road}'],
'Continue':
['Continuar {dir}'],
'TurnAround':
['Donar la volta'],
'WaypointReached':
['Ha arribat a un punt del camí'],
'Roundabout':
['Agafar {exitStr} sortida a la rotonda', ' a {road}'],
'DestinationReached':
['Arribada al destí'],
'Fork': ['A la cruïlla gira a la {modifier}', ' cap a {road}'],
'Merge': ['Incorpora\'t {modifier}', ' a {road}'],
'OnRamp': ['Gira {modifier} a la sortida', ' cap a {road}'],
'OffRamp': ['Pren la sortida {modifier}', ' cap a {road}'],
'EndOfRoad': ['Gira {modifier} al final de la carretera', ' cap a {road}'],
'Onto': 'cap a {road}'
},
formatOrder: function(n) {
return n + 'º';
},
ui: {
startPlaceholder: 'Origen',
viaPlaceholder: 'Via {viaNumber}',
endPlaceholder: 'Destí'
},
units: {
meters: 'm',
kilometers: 'km',
yards: 'yd',
miles: 'mi',
hours: 'h',
minutes: 'min',
seconds: 's'
}
}
});
module.exports = L.Routing;
})();
},{}],12:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null);
L.Routing = L.Routing || {};
L.extend(L.Routing, _dereq_('./L.Routing.OSRMv1'));
/**
* Works against OSRM's new API in version 5.0; this has
* the API version v1.
*/
L.Routing.Mapbox = L.Routing.OSRMv1.extend({
options: {
serviceUrl: 'https://api.mapbox.com/directions/v5',
profile: 'mapbox/driving',
useHints: false
},
initialize: function(accessToken, options) {
L.Routing.OSRMv1.prototype.initialize.call(this, options);
this.options.requestParameters = this.options.requestParameters || {};
/* jshint camelcase: false */
this.options.requestParameters.access_token = accessToken;
/* jshint camelcase: true */
}
});
L.Routing.mapbox = function(accessToken, options) {
return new L.Routing.Mapbox(accessToken, options);
};
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./L.Routing.OSRMv1":13}],13:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null),
corslite = _dereq_('corslite'),
polyline = _dereq_('polyline');
// Ignore camelcase naming for this file, since OSRM's API uses
// underscores.
/* jshint camelcase: false */
L.Routing = L.Routing || {};
L.extend(L.Routing, _dereq_('./L.Routing.Waypoint'));
/**
* Works against OSRM's new API in version 5.0; this has
* the API version v1.
*/
L.Routing.OSRMv1 = L.Class.extend({
options: {
serviceUrl: 'https://router.project-osrm.org/route/v1',
profile: 'driving',
timeout: 30 * 1000,
routingOptions: {
alternatives: true,
steps: true
},
polylinePrecision: 5,
useHints: true
},
initialize: function(options) {
L.Util.setOptions(this, options);
this._hints = {
locations: {}
};
},
route: function(waypoints, callback, context, options) {
var timedOut = false,
wps = [],
url,
timer,
wp,
i,
xhr;
options = L.extend({}, this.options.routingOptions, options);
url = this.buildRouteUrl(waypoints, options);
if (this.options.requestParameters) {
url += L.Util.getParamString(this.options.requestParameters, url);
}
timer = setTimeout(function() {
timedOut = true;
callback.call(context || callback, {
status: -1,
message: 'OSRM request timed out.'
});
}, this.options.timeout);
// Create a copy of the waypoints, since they
// might otherwise be asynchronously modified while
// the request is being processed.
for (i = 0; i < waypoints.length; i++) {
wp = waypoints[i];
wps.push(new L.Routing.Waypoint(wp.latLng, wp.name, wp.options));
}
return xhr = corslite(url, L.bind(function(err, resp) {
var data,
error = {};
clearTimeout(timer);
if (!timedOut) {
if (!err) {
try {
data = JSON.parse(resp.responseText);
try {
return this._routeDone(data, wps, options, callback, context);
} catch (ex) {
error.status = -3;
error.error = ex.toString();
}
} catch (ex) {
error.status = -2;
error.error = 'Error parsing OSRM response: ' + ex.toString();
}
} else {
error = L.extend({}, err, {
error: 'HTTP request failed: ' + err.type,
status: -1
})
}
callback.call(context || callback, error);
} else {
xhr.abort();
}
}, this));
},
requiresMoreDetail: function(route, zoom, bounds) {
if (!route.properties.isSimplified) {
return false;
}
var waypoints = route.inputWaypoints,
i;
for (i = 0; i < waypoints.length; ++i) {
if (!bounds.contains(waypoints[i].latLng)) {
return true;
}
}
return false;
},
_routeDone: function(response, inputWaypoints, options, callback, context) {
var alts = [],
actualWaypoints,
i,
route;
context = context || callback;
if (response.code !== 'Ok') {
callback.call(context, {
status: response.code
});
return;
}
actualWaypoints = this._toWaypoints(inputWaypoints, response.waypoints);
for (i = 0; i < response.routes.length; i++) {
route = this._convertRoute(response.routes[i]);
route.inputWaypoints = inputWaypoints;
route.waypoints = actualWaypoints;
route.properties = {isSimplified: !options || !options.geometryOnly || options.simplifyGeometry};
alts.push(route);
}
this._saveHintData(response.waypoints, inputWaypoints);
callback.call(context, null, alts);
},
_convertRoute: function(responseRoute) {
var result = {
name: '',
coordinates: [],
instructions: [],
summary: {
totalDistance: responseRoute.distance,
totalTime: responseRoute.duration
}
},
legNames = [],
index = 0,
legCount = responseRoute.legs.length,
hasSteps = responseRoute.legs[0].steps.length > 0,
i,
j,
leg,
step,
geometry,
type,
modifier;
for (i = 0; i < legCount; i++) {
leg = responseRoute.legs[i];
legNames.push(leg.summary && leg.summary.charAt(0).toUpperCase() + leg.summary.substring(1));
for (j = 0; j < leg.steps.length; j++) {
step = leg.steps[j];
geometry = this._decodePolyline(step.geometry);
result.coordinates.push.apply(result.coordinates, geometry);
type = this._maneuverToInstructionType(step.maneuver, i === legCount - 1);
modifier = this._maneuverToModifier(step.maneuver);
if (type) {
result.instructions.push({
type: type,
distance: step.distance,
time: step.duration,
road: step.name,
direction: this._bearingToDirection(step.maneuver.bearing_after),
exit: step.maneuver.exit,
index: index,
mode: step.mode,
modifier: modifier
});
}
index += geometry.length;
}
}
result.name = legNames.join(', ');
if (!hasSteps) {
result.coordinates = this._decodePolyline(responseRoute.geometry);
}
return result;
},
_bearingToDirection: function(bearing) {
var oct = Math.round(bearing / 45) % 8;
return ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'][oct];
},
_maneuverToInstructionType: function(maneuver, lastLeg) {
switch (maneuver.type) {
case 'new name':
return 'Continue';
case 'depart':
return 'Head';
case 'arrive':
return lastLeg ? 'DestinationReached' : 'WaypointReached';
case 'roundabout':
case 'rotary':
return 'Roundabout';
case 'merge':
case 'fork':
case 'on ramp':
case 'off ramp':
case 'end of road':
return this._camelCase(maneuver.type);
// These are all reduced to the same instruction in the current model
//case 'turn':
//case 'ramp': // deprecated in v5.1
default:
return this._camelCase(maneuver.modifier);
}
},
_maneuverToModifier: function(maneuver) {
var modifier = maneuver.modifier;
switch (maneuver.type) {
case 'merge':
case 'fork':
case 'on ramp':
case 'off ramp':
case 'end of road':
modifier = this._leftOrRight(modifier);
}
return modifier && this._camelCase(modifier);
},
_camelCase: function(s) {
var words = s.split(' '),
result = '';
for (var i = 0, l = words.length; i < l; i++) {
result += words[i].charAt(0).toUpperCase() + words[i].substring(1);
}
return result;
},
_leftOrRight: function(d) {
return d.indexOf('left') >= 0 ? 'Left' : 'Right';
},
_decodePolyline: function(routeGeometry) {
var cs = polyline.decode(routeGeometry, this.options.polylinePrecision),
result = new Array(cs.length),
i;
for (i = cs.length - 1; i >= 0; i--) {
result[i] = L.latLng(cs[i]);
}
return result;
},
_toWaypoints: function(inputWaypoints, vias) {
var wps = [],
i,
viaLoc;
for (i = 0; i < vias.length; i++) {
viaLoc = vias[i].location;
wps.push(L.Routing.waypoint(L.latLng(viaLoc[1], viaLoc[0]),
inputWaypoints[i].name,
inputWaypoints[i].options));
}
return wps;
},
buildRouteUrl: function(waypoints, options) {
var locs = [],
hints = [],
wp,
latLng,
computeInstructions,
computeAlternative = true;
for (var i = 0; i < waypoints.length; i++) {
wp = waypoints[i];
latLng = wp.latLng;
locs.push(latLng.lng + ',' + latLng.lat);
hints.push(this._hints.locations[this._locationKey(latLng)] || '');
}
computeInstructions =
!(options && options.geometryOnly);
return this.options.serviceUrl + '/' + this.options.profile + '/' +
locs.join(';') + '?' +
(options.geometryOnly ? (options.simplifyGeometry ? '' : 'overview=full') : 'overview=false') +
'&alternatives=' + computeAlternative.toString() +
'&steps=' + computeInstructions.toString() +
(this.options.useHints ? '&hints=' + hints.join(';') : '') +
(options.allowUTurns ? '&continue_straight=' + !options.allowUTurns : '');
},
_locationKey: function(location) {
return location.lat + ',' + location.lng;
},
_saveHintData: function(actualWaypoints, waypoints) {
var loc;
this._hints = {
locations: {}
};
for (var i = actualWaypoints.length - 1; i >= 0; i--) {
loc = waypoints[i].latLng;
this._hints.locations[this._locationKey(loc)] = actualWaypoints[i].hint;
}
},
});
L.Routing.osrmv1 = function(options) {
return new L.Routing.OSRMv1(options);
};
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./L.Routing.Waypoint":15,"corslite":1,"polyline":2}],14:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null);
L.Routing = L.Routing || {};
L.extend(L.Routing, _dereq_('./L.Routing.GeocoderElement'));
L.extend(L.Routing, _dereq_('./L.Routing.Waypoint'));
L.Routing.Plan = (L.Layer || L.Class).extend({
includes: L.Mixin.Events,
options: {
dragStyles: [
{color: 'black', opacity: 0.15, weight: 9},
{color: 'white', opacity: 0.8, weight: 6},
{color: 'red', opacity: 1, weight: 2, dashArray: '7,12'}
],
draggableWaypoints: true,
routeWhileDragging: false,
addWaypoints: true,
reverseWaypoints: false,
addButtonClassName: '',
language: 'en',
createGeocoderElement: L.Routing.geocoderElement,
createMarker: function(i, wp) {
var options = {
draggable: this.draggableWaypoints
},
marker = L.marker(wp.latLng, options);
return marker;
},
geocodersClassName: ''
},
initialize: function(waypoints, options) {
L.Util.setOptions(this, options);
this._waypoints = [];
this.setWaypoints(waypoints);
},
isReady: function() {
var i;
for (i = 0; i < this._waypoints.length; i++) {
if (!this._waypoints[i].latLng) {
return false;
}
}
return true;
},
getWaypoints: function() {
var i,
wps = [];
for (i = 0; i < this._waypoints.length; i++) {
wps.push(this._waypoints[i]);
}
return wps;
},
setWaypoints: function(waypoints) {
var args = [0, this._waypoints.length].concat(waypoints);
this.spliceWaypoints.apply(this, args);
return this;
},
spliceWaypoints: function() {
var args = [arguments[0], arguments[1]],
i;
for (i = 2; i < arguments.length; i++) {
args.push(arguments[i] && arguments[i].hasOwnProperty('latLng') ? arguments[i] : L.Routing.waypoint(arguments[i]));
}
[].splice.apply(this._waypoints, args);
// Make sure there's always at least two waypoints
while (this._waypoints.length < 2) {
this.spliceWaypoints(this._waypoints.length, 0, null);
}
this._updateMarkers();
this._fireChanged.apply(this, args);
},
onAdd: function(map) {
this._map = map;
this._updateMarkers();
},
onRemove: function() {
var i;
this._removeMarkers();
if (this._newWp) {
for (i = 0; i < this._newWp.lines.length; i++) {
this._map.removeLayer(this._newWp.lines[i]);
}
}
delete this._map;
},
createGeocoders: function() {
var container = L.DomUtil.create('div', 'leaflet-routing-geocoders ' + this.options.geocodersClassName),
waypoints = this._waypoints,
addWpBtn,
reverseBtn;
this._geocoderContainer = container;
this._geocoderElems = [];
if (this.options.addWaypoints) {
addWpBtn = L.DomUtil.create('button', 'leaflet-routing-add-waypoint ' + this.options.addButtonClassName, container);
addWpBtn.setAttribute('type', 'button');
L.DomEvent.addListener(addWpBtn, 'click', function() {
this.spliceWaypoints(waypoints.length, 0, null);
}, this);
}
if (this.options.reverseWaypoints) {
reverseBtn = L.DomUtil.create('button', 'leaflet-routing-reverse-waypoints', container);
reverseBtn.setAttribute('type', 'button');
L.DomEvent.addListener(reverseBtn, 'click', function() {
this._waypoints.reverse();
this.setWaypoints(this._waypoints);
}, this);
}
this._updateGeocoders();
this.on('waypointsspliced', this._updateGeocoders);
return container;
},
_createGeocoder: function(i) {
var geocoder = this.options.createGeocoderElement(this._waypoints[i], i, this._waypoints.length, this.options);
geocoder
.on('delete', function() {
if (i > 0 || this._waypoints.length > 2) {
this.spliceWaypoints(i, 1);
} else {
this.spliceWaypoints(i, 1, new L.Routing.Waypoint());
}
}, this)
.on('geocoded', function(e) {
this._updateMarkers();
this._fireChanged();
this._focusGeocoder(i + 1);
this.fire('waypointgeocoded', {
waypointIndex: i,
waypoint: e.waypoint
});
}, this)
.on('reversegeocoded', function(e) {
this.fire('waypointgeocoded', {
waypointIndex: i,
waypoint: e.waypoint
});
}, this);
return geocoder;
},
_updateGeocoders: function() {
var elems = [],
i,
geocoderElem;
for (i = 0; i < this._geocoderElems.length; i++) {
this._geocoderContainer.removeChild(this._geocoderElems[i].getContainer());
}
for (i = this._waypoints.length - 1; i >= 0; i--) {
geocoderElem = this._createGeocoder(i);
this._geocoderContainer.insertBefore(geocoderElem.getContainer(), this._geocoderContainer.firstChild);
elems.push(geocoderElem);
}
this._geocoderElems = elems.reverse();
},
_removeMarkers: function() {
var i;
if (this._markers) {
for (i = 0; i < this._markers.length; i++) {
if (this._markers[i]) {
this._map.removeLayer(this._markers[i]);
}
}
}
this._markers = [];
},
_updateMarkers: function() {
var i,
m;
if (!this._map) {
return;
}
this._removeMarkers();
for (i = 0; i < this._waypoints.length; i++) {
if (this._waypoints[i].latLng) {
m = this.options.createMarker(i, this._waypoints[i], this._waypoints.length);
if (m) {
m.addTo(this._map);
if (this.options.draggableWaypoints) {
this._hookWaypointEvents(m, i);
}
}
} else {
m = null;
}
this._markers.push(m);
}
},
_fireChanged: function() {
this.fire('waypointschanged', {waypoints: this.getWaypoints()});
if (arguments.length >= 2) {
this.fire('waypointsspliced', {
index: Array.prototype.shift.call(arguments),
nRemoved: Array.prototype.shift.call(arguments),
added: arguments
});
}
},
_hookWaypointEvents: function(m, i, trackMouseMove) {
var eventLatLng = function(e) {
return trackMouseMove ? e.latlng : e.target.getLatLng();
},
dragStart = L.bind(function(e) {
this.fire('waypointdragstart', {index: i, latlng: eventLatLng(e)});
}, this),
drag = L.bind(function(e) {
this._waypoints[i].latLng = eventLatLng(e);
this.fire('waypointdrag', {index: i, latlng: eventLatLng(e)});
}, this),
dragEnd = L.bind(function(e) {
this._waypoints[i].latLng = eventLatLng(e);
this._waypoints[i].name = '';
if (this._geocoderElems) {
this._geocoderElems[i].update(true);
}
this.fire('waypointdragend', {index: i, latlng: eventLatLng(e)});
this._fireChanged();
}, this),
mouseMove,
mouseUp;
if (trackMouseMove) {
mouseMove = L.bind(function(e) {
this._markers[i].setLatLng(e.latlng);
drag(e);
}, this);
mouseUp = L.bind(function(e) {
this._map.dragging.enable();
this._map.off('mouseup', mouseUp);
this._map.off('mousemove', mouseMove);
dragEnd(e);
}, this);
this._map.dragging.disable();
this._map.on('mousemove', mouseMove);
this._map.on('mouseup', mouseUp);
dragStart({latlng: this._waypoints[i].latLng});
} else {
m.on('dragstart', dragStart);
m.on('drag', drag);
m.on('dragend', dragEnd);
}
},
dragNewWaypoint: function(e) {
var newWpIndex = e.afterIndex + 1;
if (this.options.routeWhileDragging) {
this.spliceWaypoints(newWpIndex, 0, e.latlng);
this._hookWaypointEvents(this._markers[newWpIndex], newWpIndex, true);
} else {
this._dragNewWaypoint(newWpIndex, e.latlng);
}
},
_dragNewWaypoint: function(newWpIndex, initialLatLng) {
var wp = new L.Routing.Waypoint(initialLatLng),
prevWp = this._waypoints[newWpIndex - 1],
nextWp = this._waypoints[newWpIndex],
marker = this.options.createMarker(newWpIndex, wp, this._waypoints.length + 1),
lines = [],
mouseMove = L.bind(function(e) {
var i;
if (marker) {
marker.setLatLng(e.latlng);
}
for (i = 0; i < lines.length; i++) {
lines[i].spliceLatLngs(1, 1, e.latlng);
}
}, this),
mouseUp = L.bind(function(e) {
var i;
if (marker) {
this._map.removeLayer(marker);
}
for (i = 0; i < lines.length; i++) {
this._map.removeLayer(lines[i]);
}
this._map.off('mousemove', mouseMove);
this._map.off('mouseup', mouseUp);
this.spliceWaypoints(newWpIndex, 0, e.latlng);
}, this),
i;
if (marker) {
marker.addTo(this._map);
}
for (i = 0; i < this.options.dragStyles.length; i++) {
lines.push(L.polyline([prevWp.latLng, initialLatLng, nextWp.latLng],
this.options.dragStyles[i]).addTo(this._map));
}
this._map.on('mousemove', mouseMove);
this._map.on('mouseup', mouseUp);
},
_focusGeocoder: function(i) {
if (this._geocoderElems[i]) {
this._geocoderElems[i].focus();
} else {
document.activeElement.blur();
}
}
});
L.Routing.plan = function(waypoints, options) {
return new L.Routing.Plan(waypoints, options);
};
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./L.Routing.GeocoderElement":7,"./L.Routing.Waypoint":15}],15:[function(_dereq_,module,exports){
(function (global){
(function() {
'use strict';
var L = (typeof window !== "undefined" ? window['L'] : typeof global !== "undefined" ? global['L'] : null);
L.Routing = L.Routing || {};
L.Routing.Waypoint = L.Class.extend({
options: {
allowUTurn: false,
},
initialize: function(latLng, name, options) {
L.Util.setOptions(this, options);
this.latLng = L.latLng(latLng);
this.name = name;
}
});
L.Routing.waypoint = function(latLng, name, options) {
return new L.Routing.Waypoint(latLng, name, options);
};
module.exports = L.Routing;
})();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[4])(4)
}); |
/*! angular-deckgrid (v0.1.1) - Copyright: 2013, André König ([email protected]) - MIT */
/*
* angular-deckgrid
*
* Copyright(c) 2013 Andre Koenig <[email protected]>
* MIT Licensed
*
*/
/**
* @author André König ([email protected])
*
*/
angular.module('akoenig.deckgrid', []);
angular.module('akoenig.deckgrid').directive('deckgrid', [
'DeckgridDescriptor',
function initialize (DeckgridDescriptor) {
'use strict';
return DeckgridDescriptor.create();
}
]);
/*
* angular-deckgrid
*
* Copyright(c) 2013 Andre Koenig <[email protected]>
* MIT Licensed
*
*/
/**
* @author André König ([email protected])
*
*/
angular.module('akoenig.deckgrid').factory('DeckgridDescriptor', [
'Deckgrid',
function initialize (Deckgrid) {
'use strict';
/**
* This is a wrapper around the AngularJS
* directive description object.
*
*/
function Descriptor () {
this.restrict = 'AE';
this.template = '<div data-ng-repeat="column in columns" class="{{layout.classList}}">' +
'<div data-ng-repeat="card in column" data-ng-include="cardTemplate"></div>' +
'</div>';
this.scope = {
'model': '=source'
};
//
// Will be created in the linking function.
//
this.$$deckgrid = null;
this.link = this.$$link.bind(this);
}
/**
* @private
*
* Cleanup method. Will be called when the
* deckgrid directive should be destroyed.
*
*/
Descriptor.prototype.$$destroy = function $$destroy () {
this.$$deckgrid.destroy();
};
/**
* @private
*
* The deckgrid link method. Will instantiate the deckgrid.
*
*/
Descriptor.prototype.$$link = function $$link (scope, elem, attrs) {
scope.$on('$destroy', this.$$destroy.bind(this));
scope.cardTemplate = attrs.cardtemplate;
this.$$deckgrid = Deckgrid.create(scope, elem[0]);
};
return {
create : function create () {
return new Descriptor();
}
};
}
]);
/*
* angular-deckgrid
*
* Copyright(c) 2013 Andre Koenig <[email protected]>
* MIT Licensed
*
*/
/**
* @author André König ([email protected])
*
*/
angular.module('akoenig.deckgrid').factory('Deckgrid', [
'$window',
'$log',
function initialize ($window, $log) {
'use strict';
/**
* The deckgrid directive.
*
*/
function Deckgrid (scope, element) {
var self = this,
watcher;
this.$$elem = element;
this.$$watchers = [];
this.$$scope = scope;
this.$$scope.columns = [];
//
// The layout configuration will be parsed from
// the pseudo "before element." There you have to save all
// the column configurations.
//
this.$$scope.layout = this.$$getLayout();
this.$$createColumns();
//
// Register model change.
//
watcher = this.$$scope.$watch('model', this.$$onModelChange.bind(this), true);
this.$$watchers.push(watcher);
//
// Register window resize change event.
//
watcher = angular.element($window).on('resize', self.$$onWindowResize.bind(self));
this.$$watchers.push(watcher);
}
/**
* @private
*
* Creates the column segmentation. With other words:
* This method creates the internal data structure from the
* passed "source" attribute. Every card within this "source"
* model will be passed into this internal column structure by
* reference. So if you modify the data within your controller
* this directive will reflect these changes immediately.
*
* NOTE that calling this method will trigger a complete template "redraw".
*
*/
Deckgrid.prototype.$$createColumns = function $$createColumns () {
var self = this;
if (!this.$$scope.layout) {
return $log.error('angular-deckgrid: No CSS configuration found (see ' +
'https://github.com/akoenig/angular-deckgrid#the-grid-configuration)');
}
this.$$scope.columns = [];
angular.forEach(this.$$scope.model, function onIteration (card, index) {
var column = (index % self.$$scope.layout.columns) | 0;
if (!self.$$scope.columns[column]) {
self.$$scope.columns[column] = [];
}
self.$$scope.columns[column].push(card);
});
};
/**
* @private
*
* Parses the configuration out of the configured CSS styles.
*
* Example:
*
* .deckgrid::before {
* content: '3 .column.size-1-3';
* }
*
* Will result in a three column grid where each column will have the
* classes: "column size-1-3".
*
* You are responsible for defining the respective styles within your CSS.
*
*/
Deckgrid.prototype.$$getLayout = function $$getLayout () {
var content = $window.getComputedStyle(this.$$elem, ':before').content,
layout;
if (content) {
content = content.replace(/'/g, ''); // before e.g. '3 .column.size-1of3'
content = content.replace(/"/g, ''); // before e.g. "3 .column.size-1of3"
content = content.split(' ');
if (2 === content.length) {
layout = {};
layout.columns = (content[0] | 0);
layout.classList = content[1].replace(/\./g, ' ').trim();
}
}
return layout;
};
/**
* @private
*
* Event that will be triggered on "window resize".
*
*/
Deckgrid.prototype.$$onWindowResize = function $$onWindowResize () {
var self = this,
layout = this.$$getLayout();
//
// Okay, the layout has changed.
// Creating a new column structure is not avoidable.
//
if (layout.columns !== this.$$scope.layout.columns) {
self.$$scope.layout = layout;
self.$$scope.$apply(function onApply () {
self.$$createColumns();
});
}
};
/**
* @private
*
* Event that will be triggered when the source model has changed.
*
*/
Deckgrid.prototype.$$onModelChange = function $$onModelChange (oldModel, newModel) {
var self = this;
if (oldModel.length !== newModel.length) {
self.$$createColumns();
}
};
/**
* Destroys the directive. Takes care of cleaning all
* watchers and event handlers.
*
*/
Deckgrid.prototype.destroy = function destroy () {
var i = this.$$watchers.length - 1;
for (i; i >= 0; i = i - 1) {
this.$$watchers[i]();
}
};
return {
create : function create (scope, element) {
return new Deckgrid(scope, element);
}
};
}
]);
|
/*! /support/test/element/video/mp4 1.0.5 | http://nucleus.qoopido.com | (c) 2016 Dirk Lueth */
!function(e){"use strict";function c(c,n){var t=c.defer();return n.then(function(){var c=e.createElement("video");c.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"')?t.resolve():t.reject()},t.reject),t.pledge}provide(["/demand/pledge","../video"],c)}(document);
//# sourceMappingURL=mp4.js.map
|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"am",
"pm"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y HH:mm:ss",
"mediumDate": "d MMM y",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/y HH:mm",
"shortDate": "dd/MM/y",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u00a3",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-fk",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
// add new post notification callback on post submit
postAfterSubmitMethodCallbacks.push(function (post) {
var adminIds = _.pluck(Meteor.users.find({'isAdmin': true}, {fields: {_id:1}}).fetch(), '_id');
var notifiedUserIds = _.pluck(Meteor.users.find({'profile.notifications.posts': 1}, {fields: {_id:1}}).fetch(), '_id');
// remove post author ID from arrays
var adminIds = _.without(adminIds, post.userId);
var notifiedUserIds = _.without(notifiedUserIds, post.userId);
if (post.status === STATUS_PENDING && !!adminIds.length) {
// if post is pending, only notify admins
Herald.createNotification(adminIds, {courier: 'newPendingPost', data: post});
} else if (!!notifiedUserIds.length) {
// if post is approved, notify everybody
Herald.createNotification(notifiedUserIds, {courier: 'newPost', data: post});
}
return post;
});
// notify users that their pending post has been approved
postApproveCallbacks.push(function (post) {
Herald.createNotification(post.userId, {courier: 'postApproved', data: post});
return post;
});
// add new comment notification callback on comment submit
commentAfterSubmitMethodCallbacks.push(function (comment) {
if(Meteor.isServer && !comment.disableNotifications){
var post = Posts.findOne(comment.postId),
notificationData = {
comment: _.pick(comment, '_id', 'userId', 'author', 'body'),
post: _.pick(post, '_id', 'userId', 'title', 'url')
},
userIdsNotified = [];
// 1. Notify author of post
// do not notify author of post if they're the ones posting the comment
if (comment.userId !== post.userId) {
Herald.createNotification(post.userId, {courier: 'newComment', data: notificationData});
userIdsNotified.push(post.userId);
}
// 2. Notify author of comment being replied to
if (!!comment.parentCommentId) {
var parentComment = Comments.findOne(comment.parentCommentId);
// do not notify author of parent comment if they're also post author or comment author
// (someone could be replying to their own comment)
if (parentComment.userId !== post.userId && parentComment.userId !== comment.userId) {
// add parent comment to notification data
notificationData.parentComment = _.pick(parentComment, '_id', 'userId', 'author');
Herald.createNotification(parentComment.userId, {courier: 'newReply', data: notificationData});
userIdsNotified.push(parentComment.userId);
}
}
// 3. Notify users subscribed to the thread
// TODO: ideally this would be injected from the telescope-subscribe-to-posts package
if (!!post.subscribers) {
// remove userIds of users that have already been notified
// and of comment author (they could be replying in a thread they're subscribed to)
var subscriberIdsToNotify = _.difference(post.subscribers, userIdsNotified, [comment.userId]);
Herald.createNotification(subscriberIdsToNotify, {courier: 'newCommentSubscribed', data: notificationData});
userIdsNotified = userIdsNotified.concat(subscriberIdsToNotify);
}
}
return comment;
});
var emailNotifications = {
propertyName: 'emailNotifications',
propertySchema: {
type: Boolean,
optional: true,
defaultValue: true,
autoform: {
group: 'notifications_fieldset',
instructions: 'Enable email notifications for new posts and new comments (requires restart).'
}
}
};
addToSettingsSchema.push(emailNotifications);
// make it possible to disable notifications on a per-comment basis
addToCommentsSchema.push(
{
propertyName: 'disableNotifications',
propertySchema: {
type: Boolean,
optional: true,
autoform: {
omit: true
}
}
}
);
function setNotificationDefaults (user) {
// set notifications default preferences
user.profile.notifications = {
users: false,
posts: false,
comments: true,
replies: true
};
return user;
}
userCreatedCallbacks.push(setNotificationDefaults);
|
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
define( ["jquery", "../jquery.validate"], factory );
} else if (typeof module === "object" && module.exports) {
module.exports = factory( require( "jquery" ) );
} else {
factory( jQuery );
}
}(function( $ ) {
/*
* Translated default messages for the jQuery validation plugin.
* Locale: ZH (Chinese, 中文 (Zhōngwén), 汉语, 漢語)
*/
$.extend( $.validator.messages, {
required: "这是必填字段",
remote: "请修正此字段",
email: "请输入有效的电子邮件地址",
url: "请输入有效的网址",
date: "请输入有效的日期",
dateISO: "请输入有效的日期 (YYYY-MM-DD)",
number: "请输入有效的数字",
digits: "只能输入数字",
creditcard: "请输入有效的信用卡号码",
equalTo: "你的输入不相同",
extension: "请输入有效的后缀",
maxlength: $.validator.format( "最多可以输入 {0} 个字符" ),
minlength: $.validator.format( "最少要输入 {0} 个字符" ),
rangelength: $.validator.format( "请输入长度在 {0} 到 {1} 之间的字符串" ),
range: $.validator.format( "请输入范围在 {0} 到 {1} 之间的数值" ),
step: $.validator.format( "请输入 {0} 的整数倍值" ),
max: $.validator.format( "请输入不大于 {0} 的数值" ),
min: $.validator.format( "请输入不小于 {0} 的数值" )
} );
return $;
})); |
/* babelfish 1.0.2 nodeca/babelfish */!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Babelfish=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
module.exports = _dereq_('./lib/babelfish');
},{"./lib/babelfish":2}],2:[function(_dereq_,module,exports){
/**
* class BabelFish
*
* Internalization and localization library that makes i18n and l10n fun again.
*
* ##### Example
*
* ```javascript
* var BabelFish = require('babelfish'),
* i18n = new BabelFish();
* ```
*
* or
*
* ```javascript
* var babelfish = require('babelfish'),
* i18n = babelfish();
* ```
**/
'use strict';
var parser = _dereq_('./babelfish/parser');
var pluralizer = _dereq_('./babelfish/pluralizer');
function _class(obj) { return Object.prototype.toString.call(obj); }
function isString(obj) { return _class(obj) === '[object String]'; }
function isNumber(obj) { return !isNaN(obj) && isFinite(obj); }
function isBoolean(obj) { return obj === true || obj === false; }
function isFunction(obj) { return _class(obj) === '[object Function]'; }
function isObject(obj) { return _class(obj) === '[object Object]'; }
var isArray = Array.isArray || function _isArray(obj) {
return _class(obj) === '[object Array]';
};
////////////////////////////////////////////////////////////////////////////////
// The following two utilities (forEach and extend) are modified from Underscore
//
// http://underscorejs.org
//
// (c) 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
//
// Underscore may be freely distributed under the MIT license
////////////////////////////////////////////////////////////////////////////////
var nativeForEach = Array.prototype.forEach;
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
function forEach(obj, iterator, context) {
if (obj === null) {
return;
}
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i += 1) {
iterator.call(context, obj[i], i, obj);
}
} else {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
iterator.call(context, obj[key], key, obj);
}
}
}
}
var formatRegExp = /%[sdj%]/g;
function format(f) {
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') { return '%'; }
if (i >= len) { return x; }
switch (x) {
case '%s':
return String(args[i++]);
case '%d':
return Number(args[i++]);
case '%j':
return JSON.stringify(args[i++]);
default:
return x;
}
});
return str;
}
// helpers
////////////////////////////////////////////////////////////////////////////////
// Last resort locale, that exists for sure
var GENERIC_LOCALE = 'en';
// flatten(obj) -> Object
//
// Flattens object into one-level dictionary.
//
// ##### Example
//
// var obj = {
// abc: { def: 'foo' },
// hij: 'bar'
// };
//
// flatten(obj);
// // -> { 'abc.def': 'foo', 'hij': 'bar' };
//
function flatten(obj) {
var params = {};
forEach(obj || {}, function (val, key) {
if (val && 'object' === typeof val) {
forEach(flatten(val), function (sub_val, sub_key) {
params[key + '.' + sub_key] = sub_val;
});
return;
}
params[key] = val;
});
return params;
}
var keySeparator = '#@$';
function makePhraseKey(locale, phrase) {
return locale + keySeparator + phrase;
}
function searchPhraseKey(self, locale, phrase) {
var key = makePhraseKey(locale, phrase);
var storage = self._storage;
// direct search first
if (storage.hasOwnProperty(key)) { return key; }
// don't try follbacks for default locale
if (locale === self._defaultLocale) { return null; }
// search via fallback map cache
var fb_cache = self._fallbacks_cache;
if (fb_cache.hasOwnProperty(key)) { return fb_cache[key]; }
// scan fallbacks & cache result
var fb = self._fallbacks[locale] || [self._defaultLocale];
var fb_key;
for (var i=0, l=fb.length; i<l; i++) {
fb_key = makePhraseKey(fb[i], phrase);
if (storage.hasOwnProperty(fb_key)) {
// found - update cache and return result
fb_cache[key] = fb_key;
return fb_cache[key];
}
}
// mark fb_cache entry empty for fast lookup on next request
fb_cache[key] = null;
return null;
}
// public api (module)
////////////////////////////////////////////////////////////////////////////////
/**
* new BabelFish([defaultLocale = 'en'])
*
* Initiates new instance of BabelFish.
*
* __Note!__ you can omit `new` for convenience, direct call will return
* new instance too.
**/
function BabelFish(defaultLocale) {
if (!(this instanceof BabelFish)) { return new BabelFish(defaultLocale); }
this._defaultLocale = defaultLocale ? String(defaultLocale) : GENERIC_LOCALE;
// hash of locale => [ fallback1, fallback2, ... ] pairs
this._fallbacks = {};
// fallback cache for each phrase
//
// {
// locale_key: fallback_key
// }
//
// fallback_key can be null if search failed
//
this._fallbacks_cache = {};
// storage of compiled translations
//
// {
// locale + @#$ + phrase_key: {
// locale: locale name - can be different for fallbacks
// translation: original translation phrase or data variable/object
// raw: true/false - does translation contain plain data or
// string to compile
// compiled: copiled translation fn or plain string
// }
// ...
// }
//
this._storage = {};
// cache for complex plural parts (with params)
//
// {
// language: new BabelFish(language)
// }
//
this._plurals_cache = {};
}
// public api (instance)
////////////////////////////////////////////////////////////////////////////////
/**
* BabelFish#addPhrase(locale, phrase, translation [, flattenLevel]) -> BabelFish
* - locale (String): Locale of translation
* - phrase (String|Null): Phrase ID, e.g. `apps.forum`
* - translation (String|Object|Array|Number|Boolean): Translation or an object
* with nested phrases, or a pure object.
* - flattenLevel (Number|Boolean): Optional, 0..infinity. `Infinity` by default.
* Define "flatten" deepness for loaded object. You can also use
* `true` as `0` or `false` as `Infinity`.
*
*
* ##### Flatten & using JS objects
*
* By default all nested properties are normalized to strings like "foo.bar.baz",
* and if value is string, it will be compiled with babelfish notation.
* If deepness is above `flattenLevel` OR value is not object and not string,
* it will be used "as is". Note, only JSON stringifiable data should be used.
*
* In short: you can safely pass `Array`, `Number` or `Boolean`. For objects you
* should define flatten level or disable it compleetely, to work with pure data.
*
* Pure objects can be useful to prepare bulk data for external libraries, like
* calendars, time/date generators and so on.
*
* ##### Example
*
* ```javascript
* i18n.addPhrase('ru-RU',
* 'apps.forums.replies_count',
* '#{count} %{ответ|ответа|ответов}:count в теме');
*
* // equals to:
* i18n.addPhrase('ru-RU',
* 'apps.forums',
* { replies_count: '#{count} %{ответ|ответа|ответов}:count в теме' });
* ```
**/
BabelFish.prototype.addPhrase = function _addPhrase(locale, phrase, translation, flattenLevel) {
var self = this, fl;
// Calculate flatten level. Infinity by default
if (isBoolean(flattenLevel)) {
fl = flattenLevel ? Infinity : 0;
} else if (isNumber(flattenLevel)) {
fl = Math.floor(flattenLevel);
fl = (fl < 0) ? 0 : fl;
} else {
fl = Infinity;
}
if (isObject(translation) && (fl > 0)) {
// recursive object walk, until flattenLevel allows
forEach(translation, function (val, key) {
self.addPhrase(locale, phrase + '.' + key, val, fl-1);
});
return;
}
if (isString(translation)) {
this._storage[makePhraseKey(locale, phrase)] = {
translation: translation,
locale: locale,
raw: false
};
} else if (isArray(translation) ||
isNumber(translation) ||
isBoolean(translation) ||
(fl === 0 && isObject(translation))) {
// Pure objects are stored without compilation
// Limit allowed types.
this._storage[makePhraseKey(locale, phrase)] = {
translation: translation,
locale: locale,
raw: true
};
} else {
// `Regex`, `Date`, `Uint8Array` and others types will
// fuckup `stringify()`. Don't allow here.
// `undefined` also means wrong param in real life.
// `null` can be allowed when examples from real life available.
throw new TypeError('Invalid translation - [String|Object|Array|Number|Boolean] expected.');
}
self._fallbacks_cache = {};
};
/**
* BabelFish#setFallback(locale, fallbacks) -> BabelFish
* - locale (String): Target locale
* - fallbacks (Array): List of fallback locales
*
* Set fallbacks for given locale.
*
* When `locale` has no translation for the phrase, `fallbacks[0]` will be
* tried, if translation still not found, then `fallbacks[1]` will be tried
* and so on. If none of fallbacks have translation,
* default locale will be tried as last resort.
*
* ##### Errors
*
* - throws `Error`, when `locale` equals default locale
*
* ##### Example
*
* ```javascript
* i18n.setFallback('ua-UK', ['ua', 'ru']);
* ```
**/
BabelFish.prototype.setFallback = function _setFallback(locale, fallbacks) {
var def = this._defaultLocale;
if (def === locale) {
throw new Error('Default locale can\'t have fallbacks');
}
var fb = isArray(fallbacks) ? fallbacks.slice() : [fallbacks];
if (fb[fb.length-1] !== def) { fb.push(def); }
this._fallbacks[locale] = fb;
this._fallbacks_cache = {};
};
// Compiles given string into function. Used to compile phrases,
// which contains `plurals`, `variables`, etc.
function compile(self, str, locale) {
var nodes, buf, key, strict_exec, forms_exec, plurals_cache;
// Quick check to avoid parse in most cases :)
if (str.indexOf('#{') === -1 &&
str.indexOf('((') === -1 &&
str.indexOf('\\') === -1) {
return str;
}
nodes = parser.parse(str);
if (1 === nodes.length && 'literal' === nodes[0].type) {
return nodes[0].text;
}
// init cache instance for plural parts, if not exists yet.
if (!self._plurals_cache[locale]) {
self._plurals_cache[locale] = new BabelFish(locale);
}
plurals_cache = self._plurals_cache[locale];
buf = [];
buf.push(['var str = "", strict, strict_exec, forms, forms_exec, plrl, cache, loc, loc_plzr, anchor;']);
buf.push('params = flatten(params);');
forEach(nodes, function (node) {
if ('literal' === node.type) {
buf.push(format('str += %j;', node.text));
return;
}
if ('variable' === node.type) {
key = node.anchor;
buf.push(format(
'str += ("undefined" === typeof (params[%j])) ? "[missed variable: %s]" : params[%j];',
key, key, key
));
return;
}
if ('plural' === node.type) {
key = node.anchor;
// check if plural parts are plain strings or executable,
// and add executable to "cache" instance of babelfish
// plural part text will be used as translation key
strict_exec = {};
forEach(node.strict, function (text, key) {
if (text === '') {
strict_exec[key] = false;
return;
}
var parsed = parser.parse(text);
if (1 === parsed.length && 'literal' === parsed[0].type) {
strict_exec[key] = false;
// patch with unescaped value for direct extract
node.strict[key] = parsed[0].text;
return;
}
strict_exec[key] = true;
if (!plurals_cache.hasPhrase(locale, text, true)) {
plurals_cache.addPhrase(locale, text, text);
}
});
forms_exec = {};
forEach(node.forms, function (text, idx) {
if (text === '') {
forms_exec[''] = false;
return;
}
var parsed = parser.parse(text), unescaped;
if (1 === parsed.length && 'literal' === parsed[0].type) {
// patch with unescaped value for direct extract
unescaped = parsed[0].text;
node.forms[idx] = unescaped;
forms_exec[unescaped] = false;
return;
}
forms_exec[text] = true;
if (!plurals_cache.hasPhrase(locale, text, true)) {
plurals_cache.addPhrase(locale, text, text);
}
});
buf.push(format('loc = %j;', locale));
buf.push(format('loc_plzr = %j;', locale.split(/[-_]/)[0]));
buf.push(format('anchor = params[%j];', key));
buf.push(format('cache = this._plurals_cache[loc];'));
buf.push(format('strict = %j;', node.strict));
buf.push(format('strict_exec = %j;', strict_exec));
buf.push(format('forms = %j;', node.forms));
buf.push(format('forms_exec = %j;', forms_exec));
buf.push( 'if (+(anchor) != anchor) {');
buf.push(format(' str += "[invalid plurals amount: %s(" + anchor + ")]";', key));
buf.push( '} else {');
buf.push( ' if (strict[anchor] !== undefined) {');
buf.push( ' plrl = strict[anchor];');
buf.push( ' str += strict_exec[anchor] ? cache.t(loc, plrl, params) : plrl;');
buf.push( ' } else {');
buf.push( ' plrl = pluralizer(loc_plzr, +anchor, forms);');
buf.push( ' str += forms_exec[plrl] ? cache.t(loc, plrl, params) : plrl;');
buf.push( ' }');
buf.push( '}');
return;
}
// should never happen
throw new Error('Unknown node type');
});
buf.push('return str;');
/*jslint evil:true*/
return new Function('params', 'flatten', 'pluralizer', buf.join('\n'));
}
/**
* BabelFish#translate(locale, phrase[, params]) -> String
* - locale (String): Locale of translation
* - phrase (String): Phrase ID, e.g. `app.forums.replies_count`
* - params (Object|Number|String): Params for translation. `Number` & `String`
* will be coerced to `{ count: X, value: X }`
*
* ##### Example
*
* ```javascript
* i18n.addPhrase('ru-RU',
* 'apps.forums.replies_count',
* '#{count} ((ответ|ответа|ответов)) в теме');
*
* // ...
*
* i18n.translate('ru-RU', 'app.forums.replies_count', { count: 1 });
* i18n.translate('ru-RU', 'app.forums.replies_count', 1});
* // -> '1 ответ'
*
* i18n.translate('ru-RU', 'app.forums.replies_count', { count: 2 });
* i18n.translate('ru-RU', 'app.forums.replies_count', 2);
* // -> '2 ответa'
* ```
**/
BabelFish.prototype.translate = function _translate(locale, phrase, params) {
var key = searchPhraseKey(this, locale, phrase);
var data;
if (!key) {
return locale + ': No translation for [' + phrase + ']';
}
data = this._storage[key];
// simple string or other pure object
if (data.raw) { return data.translation; }
// compile data if not done yet
if (!data.hasOwnProperty('compiled')) {
// We should use locale from phrase, because of possible fallback,
// to keep plural locales in sync.
data.compiled = compile(this, data.translation, data.locale);
}
// return simple string immediately
if (!isFunction(data.compiled)) {
return data.compiled;
}
//
// Generate "complex" phrase
//
// Sugar: coerce numbers & strings to { count: X, value: X }
if (isNumber(params) || isString (params)) {
params = { count: params, value: params };
}
return data.compiled.call(this, params, flatten, pluralizer);
};
/**
* BabelFish#hasPhrase(locale, phrase) -> Boolean
* - locale (String): Locale of translation
* - phrase (String): Phrase ID, e.g. `app.forums.replies_count`
* - noFallback (Boolean): Disable search in fallbacks
*
* Returns whenever or not there's a translation of a `phrase`.
**/
BabelFish.prototype.hasPhrase = function _hasPhrase(locale, phrase, noFallback) {
return noFallback ?
this._storage.hasOwnProperty(makePhraseKey(locale, phrase))
:
searchPhraseKey(this, locale, phrase) ? true : false;
};
/** alias of: BabelFish#translate
* BabelFish#t(locale, phrase[, params]) -> String
**/
BabelFish.prototype.t = BabelFish.prototype.translate;
/**
* BabelFish#stringify(locale) -> String
* - locale (String): Locale of translation
*
* Returns serialized locale data, uncluding fallbacks.
* It can be loaded back via `load()` method.
**/
BabelFish.prototype.stringify = function _stringify(locale) {
var self = this;
// Collect unique keys
var unique = {};
forEach(this._storage, function (val, key) {
unique[key.split(keySeparator)[1]] = true;
});
// Collect phrases (with fallbacks)
var result = {};
forEach(unique, function(val, key) {
var k = searchPhraseKey(self, locale, key);
// if key was just a garbage from another
// and doesn't fit into fallback chain for current locale - skip it
if (!k) { return; }
// create namespace if not exists
var l = self._storage[k].locale;
if (!result[l]) { result[l] = {}; }
result[l][key] = self._storage[k].translation;
});
// Get fallback rule. Cut auto-added fallback to default locale
var fallback = (self._fallbacks[locale] || []).pop();
return JSON.stringify({
fallback: { locale: fallback },
locales: result
});
};
/**
* BabelFish#load(data)
* - data (Object|String) - data from `stringify()` method, as object or string.
*
* Batch load phrases data, prepared with `stringify()` method.
* Useful at browser side.
**/
BabelFish.prototype.load = function _load(data) {
var self = this;
if (isString(data)) { data = JSON.parse(data); }
forEach(data.locales, function (phrases, locale) {
forEach(phrases, function(translation, key) {
self.addPhrase(locale, key, translation, 0);
});
});
forEach(data.fallback, function (rule, locale) {
if (rule.length) { self.setFallback(locale, rule); }
});
};
// export module
module.exports = BabelFish;
},{"./babelfish/parser":3,"./babelfish/pluralizer":4}],3:[function(_dereq_,module,exports){
module.exports = (function() {
/*
* Generated by PEG.js 0.8.0.
*
* http://pegjs.majda.cz/
*/
function peg$subclass(child, parent) {
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor();
}
function SyntaxError(message, expected, found, offset, line, column) {
this.message = message;
this.expected = expected;
this.found = found;
this.offset = offset;
this.line = line;
this.column = column;
this.name = "SyntaxError";
}
peg$subclass(SyntaxError, Error);
function parse(input) {
var options = arguments.length > 1 ? arguments[1] : {},
peg$FAILED = {},
peg$startRuleIndices = { start: 0 },
peg$startRuleIndex = 0,
peg$consts = [
[],
peg$FAILED,
"((",
{ type: "literal", value: "((", description: "\"((\"" },
"))",
{ type: "literal", value: "))", description: "\"))\"" },
null,
function(forms, anchor) {
return {
type: 'plural',
forms: regularForms(forms),
strict: strictForms(forms),
anchor: anchor || 'count'
};
},
"|",
{ type: "literal", value: "|", description: "\"|\"" },
function(part, more) {
return [part].concat(more);
},
function(part) {
return [part];
},
"=",
{ type: "literal", value: "=", description: "\"=\"" },
/^[0-9]/,
{ type: "class", value: "[0-9]", description: "[0-9]" },
" ",
{ type: "literal", value: " ", description: "\" \"" },
function(strict, form) {
return {
strict: strict.join(''),
text: form.join('')
}
},
function() {
return {
text: text()
};
},
"\\",
{ type: "literal", value: "\\", description: "\"\\\\\"" },
/^[\\|)(]/,
{ type: "class", value: "[\\\\|)(]", description: "[\\\\|)(]" },
function(char) {
return char;
},
void 0,
{ type: "any", description: "any character" },
function() {
return text();
},
":",
{ type: "literal", value: ":", description: "\":\"" },
function(name) {
return name;
},
"#{",
{ type: "literal", value: "#{", description: "\"#{\"" },
"}",
{ type: "literal", value: "}", description: "\"}\"" },
function(anchor) {
return {
type: 'variable',
anchor: anchor
};
},
".",
{ type: "literal", value: ".", description: "\".\"" },
function() {
return text()
},
/^[a-zA-Z_$]/,
{ type: "class", value: "[a-zA-Z_$]", description: "[a-zA-Z_$]" },
/^[a-zA-Z0-9_$]/,
{ type: "class", value: "[a-zA-Z0-9_$]", description: "[a-zA-Z0-9_$]" },
function(lc) { return lc; },
function(literal_chars) {
return {
type: 'literal',
text: literal_chars.join('')
};
},
/^[\\#()]/,
{ type: "class", value: "[\\\\#()]", description: "[\\\\#()]" }
],
peg$bytecode = [
peg$decode(" 7)*) \"7!*# \"7&,/&7)*) \"7!*# \"7&\""),
peg$decode("!.\"\"\"2\"3#+S$7\"+I%.$\"\"2$3%+9%7%*# \" &+)%4$6'$\"\" %$$# !$## !$\"# !\"# !"),
peg$decode("!7#+C$.(\"\"2(3)+3%7\"+)%4#6*#\"\" %$## !$\"# !\"# !*/ \"!7#+' 4!6+!! %"),
peg$decode("!.,\"\"2,3-+}$ 0.\"\"1!3/+,$,)&0.\"\"1!3/\"\"\" !+X%.0\"\"2031*# \" &+B% 7$+&$,#&7$\"\"\" !+)%4$62$\"\" %$$# !$## !$\"# !\"# !*= \"! 7$+&$,#&7$\"\"\" !+& 4!63! %"),
peg$decode("!.4\"\"2435+8$06\"\"1!37+(%4\"68\"! %$\"# !\"# !*a \"!!8.(\"\"2(3)*) \".$\"\"2$3%9*$$\"\" 9\"# !+6$-\"\"1!3:+'%4\"6;\" %$\"# !\"# !"),
peg$decode("!.<\"\"2<3=+2$7'+(%4\"6>\"! %$\"# !\"# !"),
peg$decode("!.?\"\"2?3@+B$7'+8%.A\"\"2A3B+(%4#6C#!!%$## !$\"# !\"# !"),
peg$decode("!7(+P$.D\"\"2D3E+@% 7'+&$,#&7'\"\"\" !+'%4#6F# %$## !$\"# !\"# !*# \"7("),
peg$decode("!0G\"\"1!3H+E$ 0I\"\"1!3J,)&0I\"\"1!3J\"+'%4\"6;\" %$\"# !\"# !"),
peg$decode("! !!87!*# \"7&9*$$\"\" 9\"# !+2$7*+(%4\"6K\"! %$\"# !\"# !+T$,Q&!!87!*# \"7&9*$$\"\" 9\"# !+2$7*+(%4\"6K\"! %$\"# !\"# !\"\"\" !+' 4!6L!! %"),
peg$decode("!.4\"\"2435+8$0M\"\"1!3N+(%4\"68\"! %$\"# !\"# !*( \"-\"\"1!3:")
],
peg$currPos = 0,
peg$reportedPos = 0,
peg$cachedPos = 0,
peg$cachedPosDetails = { line: 1, column: 1, seenCR: false },
peg$maxFailPos = 0,
peg$maxFailExpected = [],
peg$silentFails = 0,
peg$result;
if ("startRule" in options) {
if (!(options.startRule in peg$startRuleIndices)) {
throw new Error("Can't start parsing from rule \"" + options.startRule + "\".");
}
peg$startRuleIndex = peg$startRuleIndices[options.startRule];
}
function text() {
return input.substring(peg$reportedPos, peg$currPos);
}
function offset() {
return peg$reportedPos;
}
function line() {
return peg$computePosDetails(peg$reportedPos).line;
}
function column() {
return peg$computePosDetails(peg$reportedPos).column;
}
function expected(description) {
throw peg$buildException(
null,
[{ type: "other", description: description }],
peg$reportedPos
);
}
function error(message) {
throw peg$buildException(message, null, peg$reportedPos);
}
function peg$computePosDetails(pos) {
function advance(details, startPos, endPos) {
var p, ch;
for (p = startPos; p < endPos; p++) {
ch = input.charAt(p);
if (ch === "\n") {
if (!details.seenCR) { details.line++; }
details.column = 1;
details.seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
details.line++;
details.column = 1;
details.seenCR = true;
} else {
details.column++;
details.seenCR = false;
}
}
}
if (peg$cachedPos !== pos) {
if (peg$cachedPos > pos) {
peg$cachedPos = 0;
peg$cachedPosDetails = { line: 1, column: 1, seenCR: false };
}
advance(peg$cachedPosDetails, peg$cachedPos, pos);
peg$cachedPos = pos;
}
return peg$cachedPosDetails;
}
function peg$fail(expected) {
if (peg$currPos < peg$maxFailPos) { return; }
if (peg$currPos > peg$maxFailPos) {
peg$maxFailPos = peg$currPos;
peg$maxFailExpected = [];
}
peg$maxFailExpected.push(expected);
}
function peg$buildException(message, expected, pos) {
function cleanupExpected(expected) {
var i = 1;
expected.sort(function(a, b) {
if (a.description < b.description) {
return -1;
} else if (a.description > b.description) {
return 1;
} else {
return 0;
}
});
while (i < expected.length) {
if (expected[i - 1] === expected[i]) {
expected.splice(i, 1);
} else {
i++;
}
}
}
function buildMessage(expected, found) {
function stringEscape(s) {
function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); }
return s
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\x08/g, '\\b')
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n')
.replace(/\f/g, '\\f')
.replace(/\r/g, '\\r')
.replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); })
.replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); })
.replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); })
.replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); });
}
var expectedDescs = new Array(expected.length),
expectedDesc, foundDesc, i;
for (i = 0; i < expected.length; i++) {
expectedDescs[i] = expected[i].description;
}
expectedDesc = expected.length > 1
? expectedDescs.slice(0, -1).join(", ")
+ " or "
+ expectedDescs[expected.length - 1]
: expectedDescs[0];
foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input";
return "Expected " + expectedDesc + " but " + foundDesc + " found.";
}
var posDetails = peg$computePosDetails(pos),
found = pos < input.length ? input.charAt(pos) : null;
if (expected !== null) {
cleanupExpected(expected);
}
return new SyntaxError(
message !== null ? message : buildMessage(expected, found),
expected,
found,
pos,
posDetails.line,
posDetails.column
);
}
function peg$decode(s) {
var bc = new Array(s.length), i;
for (i = 0; i < s.length; i++) {
bc[i] = s.charCodeAt(i) - 32;
}
return bc;
}
function peg$parseRule(index) {
var bc = peg$bytecode[index],
ip = 0,
ips = [],
end = bc.length,
ends = [],
stack = [],
params, i;
function protect(object) {
return Object.prototype.toString.apply(object) === "[object Array]" ? [] : object;
}
while (true) {
while (ip < end) {
switch (bc[ip]) {
case 0:
stack.push(protect(peg$consts[bc[ip + 1]]));
ip += 2;
break;
case 1:
stack.push(peg$currPos);
ip++;
break;
case 2:
stack.pop();
ip++;
break;
case 3:
peg$currPos = stack.pop();
ip++;
break;
case 4:
stack.length -= bc[ip + 1];
ip += 2;
break;
case 5:
stack.splice(-2, 1);
ip++;
break;
case 6:
stack[stack.length - 2].push(stack.pop());
ip++;
break;
case 7:
stack.push(stack.splice(stack.length - bc[ip + 1], bc[ip + 1]));
ip += 2;
break;
case 8:
stack.pop();
stack.push(input.substring(stack[stack.length - 1], peg$currPos));
ip++;
break;
case 9:
ends.push(end);
ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]);
if (stack[stack.length - 1]) {
end = ip + 3 + bc[ip + 1];
ip += 3;
} else {
end = ip + 3 + bc[ip + 1] + bc[ip + 2];
ip += 3 + bc[ip + 1];
}
break;
case 10:
ends.push(end);
ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]);
if (stack[stack.length - 1] === peg$FAILED) {
end = ip + 3 + bc[ip + 1];
ip += 3;
} else {
end = ip + 3 + bc[ip + 1] + bc[ip + 2];
ip += 3 + bc[ip + 1];
}
break;
case 11:
ends.push(end);
ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]);
if (stack[stack.length - 1] !== peg$FAILED) {
end = ip + 3 + bc[ip + 1];
ip += 3;
} else {
end = ip + 3 + bc[ip + 1] + bc[ip + 2];
ip += 3 + bc[ip + 1];
}
break;
case 12:
if (stack[stack.length - 1] !== peg$FAILED) {
ends.push(end);
ips.push(ip);
end = ip + 2 + bc[ip + 1];
ip += 2;
} else {
ip += 2 + bc[ip + 1];
}
break;
case 13:
ends.push(end);
ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]);
if (input.length > peg$currPos) {
end = ip + 3 + bc[ip + 1];
ip += 3;
} else {
end = ip + 3 + bc[ip + 1] + bc[ip + 2];
ip += 3 + bc[ip + 1];
}
break;
case 14:
ends.push(end);
ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]);
if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length) === peg$consts[bc[ip + 1]]) {
end = ip + 4 + bc[ip + 2];
ip += 4;
} else {
end = ip + 4 + bc[ip + 2] + bc[ip + 3];
ip += 4 + bc[ip + 2];
}
break;
case 15:
ends.push(end);
ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]);
if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length).toLowerCase() === peg$consts[bc[ip + 1]]) {
end = ip + 4 + bc[ip + 2];
ip += 4;
} else {
end = ip + 4 + bc[ip + 2] + bc[ip + 3];
ip += 4 + bc[ip + 2];
}
break;
case 16:
ends.push(end);
ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]);
if (peg$consts[bc[ip + 1]].test(input.charAt(peg$currPos))) {
end = ip + 4 + bc[ip + 2];
ip += 4;
} else {
end = ip + 4 + bc[ip + 2] + bc[ip + 3];
ip += 4 + bc[ip + 2];
}
break;
case 17:
stack.push(input.substr(peg$currPos, bc[ip + 1]));
peg$currPos += bc[ip + 1];
ip += 2;
break;
case 18:
stack.push(peg$consts[bc[ip + 1]]);
peg$currPos += peg$consts[bc[ip + 1]].length;
ip += 2;
break;
case 19:
stack.push(peg$FAILED);
if (peg$silentFails === 0) {
peg$fail(peg$consts[bc[ip + 1]]);
}
ip += 2;
break;
case 20:
peg$reportedPos = stack[stack.length - 1 - bc[ip + 1]];
ip += 2;
break;
case 21:
peg$reportedPos = peg$currPos;
ip++;
break;
case 22:
params = bc.slice(ip + 4, ip + 4 + bc[ip + 3]);
for (i = 0; i < bc[ip + 3]; i++) {
params[i] = stack[stack.length - 1 - params[i]];
}
stack.splice(
stack.length - bc[ip + 2],
bc[ip + 2],
peg$consts[bc[ip + 1]].apply(null, params)
);
ip += 4 + bc[ip + 3];
break;
case 23:
stack.push(peg$parseRule(bc[ip + 1]));
ip += 2;
break;
case 24:
peg$silentFails++;
ip++;
break;
case 25:
peg$silentFails--;
ip++;
break;
default:
throw new Error("Invalid opcode: " + bc[ip] + ".");
}
}
if (ends.length > 0) {
end = ends.pop();
ip = ips.pop();
} else {
break;
}
}
return stack[0];
}
function regularForms(forms) {
var result = [];
for (var i=0; i<forms.length; i++) {
if (forms[i].strict === undefined) { result.push(forms[i].text); }
}
return result;
}
function strictForms(forms) {
var result = {};
for (var i=0; i<forms.length; i++) {
if (forms[i].strict !== undefined) { result[forms[i].strict] = forms[i].text; }
}
return result;
}
peg$result = peg$parseRule(peg$startRuleIndex);
if (peg$result !== peg$FAILED && peg$currPos === input.length) {
return peg$result;
} else {
if (peg$result !== peg$FAILED && peg$currPos < input.length) {
peg$fail({ type: "end", description: "end of input" });
}
throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos);
}
}
return {
SyntaxError: SyntaxError,
parse: parse
};
})();
},{}],4:[function(_dereq_,module,exports){
//
// CLDR Version 21
// http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
//
// Charts: http://cldr.unicode.org/index/charts
// Latest: http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html
//
// TODO: update to latest
//
'use strict';
// pluralizers cache
var PLURALIZERS = {};
module.exports = function pluralize(lang, count, forms) {
var idx;
if (!PLURALIZERS[lang]) {
return '[pluralizer for (' + lang + ') not exists]';
}
idx = PLURALIZERS[lang](count);
if (undefined === forms[idx]) {
return '[plural form N' + idx + ' not found in translation]';
}
return forms[idx];
};
// HELPERS
////////////////////////////////////////////////////////////////////////////////
// adds given `rule` pluralizer for given `locales` into `storage`
function add(locales, rule) {
var i;
for (i = 0; i < locales.length; i += 1) {
PLURALIZERS[locales[i]] = rule;
}
}
// check if number is int or float
function is_int(input) {
return (0 === input % 1);
}
// PLURALIZATION RULES
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Azerbaijani, Bambara, Burmese, Chinese, Dzongkha, Georgian, Hungarian, Igbo,
// Indonesian, Japanese, Javanese, Kabuverdianu, Kannada, Khmer, Korean,
// Koyraboro Senni, Lao, Makonde, Malay, Persian, Root, Sakha, Sango,
// Sichuan Yi, Thai, Tibetan, Tonga, Turkish, Vietnamese, Wolof, Yoruba
add(['az', 'bm', 'my', 'zh', 'dz', 'ka', 'hu', 'ig',
'id', 'ja', 'jv', 'kea', 'kn', 'km', 'ko',
'ses', 'lo', 'kde', 'ms', 'fa', 'root', 'sah', 'sg',
'ii', 'th', 'bo', 'to', 'tr', 'vi', 'wo', 'yo'], function () {
return 0;
});
// Manx
add(['gv'], function (n) {
var m10 = n % 10, m20 = n % 20;
if ((m10 === 1 || m10 === 2 || m20 === 0) && is_int(n)) {
return 0;
}
return 1;
});
// Central Morocco Tamazight
add(['tzm'], function (n) {
if (n === 0 || n === 1 || (11 <= n && n <= 99 && is_int(n))) {
return 0;
}
return 1;
});
// Macedonian
add(['mk'], function (n) {
if ((n % 10 === 1) && (n !== 11) && is_int(n)) {
return 0;
}
return 1;
});
// Akan, Amharic, Bihari, Filipino, Gun, Hindi,
// Lingala, Malagasy, Northern Sotho, Tagalog, Tigrinya, Walloon
add(['ak', 'am', 'bh', 'fil', 'guw', 'hi',
'ln', 'mg', 'nso', 'tl', 'ti', 'wa'], function (n) {
return (n === 0 || n === 1) ? 0 : 1;
});
// Afrikaans, Albanian, Basque, Bemba, Bengali, Bodo, Bulgarian, Catalan,
// Cherokee, Chiga, Danish, Divehi, Dutch, English, Esperanto, Estonian, Ewe,
// Faroese, Finnish, Friulian, Galician, Ganda, German, Greek, Gujarati, Hausa,
// Hawaiian, Hebrew, Icelandic, Italian, Kalaallisut, Kazakh, Kurdish,
// Luxembourgish, Malayalam, Marathi, Masai, Mongolian, Nahuatl, Nepali,
// Norwegian, Norwegian Bokmål, Norwegian Nynorsk, Nyankole, Oriya, Oromo,
// Papiamento, Pashto, Portuguese, Punjabi, Romansh, Saho, Samburu, Soga,
// Somali, Spanish, Swahili, Swedish, Swiss German, Syriac, Tamil, Telugu,
// Turkmen, Urdu, Walser, Western Frisian, Zulu
add(['af', 'sq', 'eu', 'bem', 'bn', 'brx', 'bg', 'ca',
'chr', 'cgg', 'da', 'dv', 'nl', 'en', 'eo', 'et', 'ee',
'fo', 'fi', 'fur', 'gl', 'lg', 'de', 'el', 'gu', 'ha',
'haw', 'he', 'is', 'it', 'kl', 'kk', 'ku',
'lb', 'ml', 'mr', 'mas', 'mn', 'nah', 'ne',
'no', 'nb', 'nn', 'nyn', 'or', 'om',
'pap', 'ps', 'pt', 'pa', 'rm', 'ssy', 'saq', 'xog',
'so', 'es', 'sw', 'sv', 'gsw', 'syr', 'ta', 'te',
'tk', 'ur', 'wae', 'fy', 'zu'], function (n) {
return (1 === n) ? 0 : 1;
});
// Latvian
add(['lv'], function (n) {
if (n === 0) {
return 0;
}
if ((n % 10 === 1) && (n % 100 !== 11) && is_int(n)) {
return 1;
}
return 2;
});
// Colognian
add(['ksh'], function (n) {
return (n === 0) ? 0 : ((n === 1) ? 1 : 2);
});
// Cornish, Inari Sami, Inuktitut, Irish, Lule Sami, Northern Sami,
// Sami Language, Skolt Sami, Southern Sami
add(['kw', 'smn', 'iu', 'ga', 'smj', 'se',
'smi', 'sms', 'sma'], function (n) {
return (n === 1) ? 0 : ((n === 2) ? 1 : 2);
});
// Belarusian, Bosnian, Croatian, Russian, Serbian, Serbo-Croatian, Ukrainian
add(['be', 'bs', 'hr', 'ru', 'sr', 'sh', 'uk'], function (n) {
var m10 = n % 10, m100 = n % 100;
if (!is_int(n)) {
return 3;
}
// one → n mod 10 is 1 and n mod 100 is not 11;
if (1 === m10 && 11 !== m100) {
return 0;
}
// few → n mod 10 in 2..4 and n mod 100 not in 12..14;
if (2 <= m10 && m10 <= 4 && !(12 <= m100 && m100 <= 14)) {
return 1;
}
// many → n mod 10 is 0 or n mod 10 in 5..9 or n mod 100 in 11..14;
/* if (0 === m10 || (5 <= m10 && m10 <= 9) || (11 <= m100 && m100 <= 14)) {
return 2;
}
// other
return 3;*/
return 2;
});
// Polish
add(['pl'], function (n) {
var m10 = n % 10, m100 = n % 100;
if (!is_int(n)) {
return 3;
}
// one → n is 1;
if (n === 1) {
return 0;
}
// few → n mod 10 in 2..4 and n mod 100 not in 12..14;
if (2 <= m10 && m10 <= 4 && !(12 <= m100 && m100 <= 14)) {
return 1;
}
// many → n is not 1 and n mod 10 in 0..1 or
// n mod 10 in 5..9 or n mod 100 in 12..14
// (all other except partials)
return 2;
});
// Lithuanian
add(['lt'], function (n) {
var m10 = n % 10, m100 = n % 100;
if (!is_int(n)) {
return 2;
}
// one → n mod 10 is 1 and n mod 100 not in 11..19
if (m10 === 1 && !(11 <= m100 && m100 <= 19)) {
return 0;
}
// few → n mod 10 in 2..9 and n mod 100 not in 11..19
if (2 <= m10 && m10 <= 9 && !(11 <= m100 && m100 <= 19)) {
return 1;
}
// other
return 2;
});
// Tachelhit
add(['shi'], function (n) {
return (0 <= n && n <= 1) ? 0 : ((is_int(n) && 2 <= n && n <= 10) ? 1 : 2);
});
// Moldavian, Romanian
add(['mo', 'ro'], function (n) {
var m100 = n % 100;
if (!is_int(n)) {
return 2;
}
// one → n is 1
if (n === 1) {
return 0;
}
// few → n is 0 OR n is not 1 AND n mod 100 in 1..19
if (n === 0 || (1 <= m100 && m100 <= 19)) {
return 1;
}
// other
return 2;
});
// Czech, Slovak
add(['cs', 'sk'], function (n) {
// one → n is 1
if (n === 1) {
return 0;
}
// few → n in 2..4
if (n === 2 || n === 3 || n === 4) {
return 1;
}
// other
return 2;
});
// Slovenian
add(['sl'], function (n) {
var m100 = n % 100;
if (!is_int(n)) {
return 3;
}
// one → n mod 100 is 1
if (m100 === 1) {
return 0;
}
// one → n mod 100 is 2
if (m100 === 2) {
return 1;
}
// one → n mod 100 in 3..4
if (m100 === 3 || m100 === 4) {
return 2;
}
// other
return 3;
});
// Maltese
add(['mt'], function (n) {
var m100 = n % 100;
if (!is_int(n)) {
return 3;
}
// one → n is 1
if (n === 1) {
return 0;
}
// few → n is 0 or n mod 100 in 2..10
if (n === 0 || (2 <= m100 && m100 <= 10)) {
return 1;
}
// many → n mod 100 in 11..19
if (11 <= m100 && m100 <= 19) {
return 2;
}
// other
return 3;
});
// Arabic
add(['ar'], function (n) {
var m100 = n % 100;
if (!is_int(n)) {
return 5;
}
if (n === 0) {
return 0;
}
if (n === 1) {
return 1;
}
if (n === 2) {
return 2;
}
// few → n mod 100 in 3..10
if (3 <= m100 && m100 <= 10) {
return 3;
}
// many → n mod 100 in 11..99
if (11 <= m100 && m100 <= 99) {
return 4;
}
// other
return 5;
});
// Breton, Welsh
add(['br', 'cy'], function (n) {
if (n === 0) {
return 0;
}
if (n === 1) {
return 1;
}
if (n === 2) {
return 2;
}
if (n === 3) {
return 3;
}
if (n === 6) {
return 4;
}
return 5;
});
// FRACTIONAL PARTS - SPECIAL CASES
////////////////////////////////////////////////////////////////////////////////
// French, Fulah, Kabyle
add(['fr', 'ff', 'kab'], function (n) {
return (0 <= n && n < 2) ? 0 : 1;
});
// Langi
add(['lag'], function (n) {
return (n === 0) ? 0 : ((0 < n && n < 2) ? 1 : 2);
});
},{}]},{},[1])
(1)
}); |
/*[email protected]#typeable*/
var syn = require('./synthetic.js');
var typeables = [];
var __indexOf = [].indexOf || function (item) {
for (var i = 0, l = this.length; i < l; i++) {
if (i in this && this[i] === item) {
return i;
}
}
return -1;
};
syn.typeable = function (fn) {
if (__indexOf.call(typeables, fn) === -1) {
typeables.push(fn);
}
};
syn.typeable.test = function (el) {
for (var i = 0, len = typeables.length; i < len; i++) {
if (typeables[i](el)) {
return true;
}
}
return false;
};
var type = syn.typeable;
var typeableExp = /input|textarea/i;
type(function (el) {
return typeableExp.test(el.nodeName);
});
type(function (el) {
return __indexOf.call([
'',
'true'
], el.getAttribute('contenteditable')) !== -1;
}); |
/*
* Globalize Culture zh-HK
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* This file was generated by the Globalize Culture Generator
* Translation: bugs found in this file need to be fixed in the generator
*/
(function( window, undefined ) {
var Globalize;
if ( typeof require !== "undefined"
&& typeof exports !== "undefined"
&& typeof module !== "undefined" ) {
// Assume CommonJS
Globalize = require( "globalize" );
} else {
// Global variable
Globalize = window.Globalize;
}
Globalize.addCultureInfo( "zh-HK", "default", {
name: "zh-HK",
englishName: "Chinese (Traditional, Hong Kong S.A.R.)",
nativeName: "中文(香港特別行政區)",
language: "zh-CHT",
numberFormat: {
NaN: "非數字",
negativeInfinity: "負無窮大",
positiveInfinity: "正無窮大",
percent: {
pattern: ["-n%","n%"]
},
currency: {
symbol: "HK$"
}
},
calendars: {
standard: {
days: {
names: ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],
namesAbbr: ["週日","週一","週二","週三","週四","週五","週六"],
namesShort: ["日","一","二","三","四","五","六"]
},
months: {
names: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月",""],
namesAbbr: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月",""]
},
AM: ["上午","上午","上午"],
PM: ["下午","下午","下午"],
eras: [{"name":"公元","start":null,"offset":0}],
patterns: {
d: "d/M/yyyy",
D: "yyyy'年'M'月'd'日'",
t: "H:mm",
T: "H:mm:ss",
f: "yyyy'年'M'月'd'日' H:mm",
F: "yyyy'年'M'月'd'日' H:mm:ss",
M: "M'月'd'日'",
Y: "yyyy'年'M'月'"
}
}
}
});
}( this ));
|
Meteor.methods({
'livechat:removeCustomField'(_id) {
if (!Meteor.userId() || !RocketChat.authz.hasPermission(Meteor.userId(), 'view-livechat-manager')) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'livechat:removeCustomField' });
}
check(_id, String);
var customField = RocketChat.models.LivechatCustomField.findOneById(_id, { fields: { _id: 1 } });
if (!customField) {
throw new Meteor.Error('error-invalid-custom-field', 'Custom field not found', { method: 'livechat:removeCustomField' });
}
return RocketChat.models.LivechatCustomField.removeById(_id);
}
});
|
/*--------------------------------------------------------------------------
* linq-vsdoc.js - LINQ for JavaScript
* ver 2.2.0.2 (Jan. 21th, 2011)
*
* created and maintained by neuecc <[email protected]>
* licensed under Microsoft Public License(Ms-PL)
* http://neue.cc/
* http://linqjs.codeplex.com/
*--------------------------------------------------------------------------*/
Enumerable = (function ()
{
var Enumerable = function (getEnumerator)
{
this.GetEnumerator = getEnumerator;
}
Enumerable.Choice = function (Params_Contents)
{
/// <summary>Random choice from arguments.
/// Ex: Choice(1,2,3) - 1,3,2,3,3,2,1...</summary>
/// <param type="T" name="Params_Contents" parameterArray="true">Array or Params Contents</param>
/// <returns type="Enumerable"></returns>
}
Enumerable.Cycle = function (Params_Contents)
{
/// <summary>Cycle Repeat from arguments.
/// Ex: Cycle(1,2,3) - 1,2,3,1,2,3,1,2,3...</summary>
/// <param type="T" name="Params_Contents" parameterArray="true">Array or Params Contents</param>
/// <returns type="Enumerable"></returns>
}
Enumerable.Empty = function ()
{
/// <summary>Returns an empty Enumerable.</summary>
/// <returns type="Enumerable"></returns>
}
Enumerable.From = function (obj)
{
/// <summary>
/// Make Enumerable from obj.
/// 1. null = Enumerable.Empty().
/// 2. Enumerable = Enumerable.
/// 3. Number/Boolean = Enumerable.Repeat(obj, 1).
/// 4. String = to CharArray.(Ex:"abc" => "a","b","c").
/// 5. Object/Function = to KeyValuePair(except function) Ex:"{a:0}" => (.Key=a, .Value=0).
/// 6. Array or ArrayLikeObject(has length) = to Enumerable.
/// 7. JScript's IEnumerable = to Enumerable(using Enumerator).
/// </summary>
/// <param name="obj">object</param>
/// <returns type="Enumerable"></returns>
}
Enumerable.Return = function (element)
{
/// <summary>Make one sequence. This equals Repeat(element, 1)</summary>
/// <param name="element">element</param>
/// <returns type="Enumerable"></returns>
}
Enumerable.Matches = function (input, pattern, flags)
{
/// <summary>Global regex match and send regexp object.
/// Ex: Matches((.)z,"0z1z2z") - $[1] => 0,1,2</summary>
/// <param type="String" name="input">input string</param>
/// <param type="RegExp/String" name="pattern">RegExp or Pattern string</param>
/// <param type="Optional:String" name="flags" optional="true">If pattern is String then can use regexp flags "i" or "m" or "im"</param>
/// <returns type="Enumerable"></returns>
}
Enumerable.Range = function (start, count, step)
{
/// <summary>Generates a sequence of integral numbers within a specified range.
/// Ex: Range(1,5) - 1,2,3,4,5</summary>
/// <param type="Number" integer="true" name="start">The value of the first integer in the sequence.</param>
/// <param type="Number" integer="true" name="count">The number of sequential integers to generate.</param>
/// <param type="Optional:Number" integer="true" name="step" optional="true">Step of generate number.(Ex:Range(0,3,5) - 0,5,10)</param>
/// <returns type="Enumerable"></returns>
}
Enumerable.RangeDown = function (start, count, step)
{
/// <summary>Generates a sequence of integral numbers within a specified range.
/// Ex: RangeDown(5,5) - 5,4,3,2,1</summary>
/// <param type="Number" integer="true" name="start">The value of the first integer in the sequence.</param>
/// <param type="Number" integer="true" name="count">The number of sequential integers to generate.</param>
/// <param type="Optional:Number" integer="true" name="step" optional="true">Step of generate number.(Ex:RangeDown(0,3,5) - 0,-5,-10)</param>
/// <returns type="Enumerable"></returns>
}
Enumerable.RangeTo = function (start, to, step)
{
/// <summary>Generates a sequence of integral numbers.
/// Ex: RangeTo(10,12) - 10,11,12 RangeTo(0,-2) - 0, -1, -2</summary>
/// <param type="Number" integer="true" name="start">start integer</param>
/// <param type="Number" integer="true" name="to">to integer</param>
/// <param type="Optional:Number" integer="true" name="step" optional="true">Step of generate number.(Ex:RangeTo(0,7,3) - 0,3,6)</param>
/// <returns type="Enumerable"></returns>
}
Enumerable.Repeat = function (obj, count)
{
/// <summary>Generates a sequence that contains one repeated value.
/// If omit count then generate to infinity.
/// Ex: Repeat("foo",3) - "foo","foo","foo"</summary>
/// <param type="TResult" name="obj">The value to be repeated.</param>
/// <param type="Optional:Number" integer="true" name="count" optional="true">The number of times to repeat the value in the generated sequence.</param>
/// <returns type="Enumerable"></returns>
}
Enumerable.RepeatWithFinalize = function (initializer, finalizer)
{
/// <summary>Lazy Generates one value by initializer's result and do finalize when enumerate end</summary>
/// <param type="Func<T>" name="initializer">value factory.</param>
/// <param type="Action<T>" name="finalizer">execute when finalize.</param>
/// <returns type="Enumerable"></returns>
}
Enumerable.Generate = function (func, count)
{
/// <summary>Generates a sequence that execute func value.
/// If omit count then generate to infinity.
/// Ex: Generate("Math.random()", 5) - 0.131341,0.95425252,...</summary>
/// <param type="Func<T>" name="func">The value of execute func to be repeated.</param>
/// <param type="Optional:Number" integer="true" name="count" optional="true">The number of times to repeat the value in the generated sequence.</param>
/// <returns type="Enumerable"></returns>
}
Enumerable.ToInfinity = function (start, step)
{
/// <summary>Generates a sequence of integral numbers to infinity.
/// Ex: ToInfinity() - 0,1,2,3...</summary>
/// <param type="Optional:Number" integer="true" name="start" optional="true">start integer</param>
/// <param type="Optional:Number" integer="true" name="step" optional="true">Step of generate number.(Ex:ToInfinity(10,3) - 10,13,16,19,...)</param>
/// <returns type="Enumerable"></returns>
}
Enumerable.ToNegativeInfinity = function (start, step)
{
/// <summary>Generates a sequence of integral numbers to negative infinity.
/// Ex: ToNegativeInfinity() - 0,-1,-2,-3...</summary>
/// <param type="Optional:Number" integer="true" name="start" optional="true">start integer</param>
/// <param type="Optional:Number" integer="true" name="step" optional="true">Step of generate number.(Ex:ToNegativeInfinity(10,3) - 10,7,4,1,...)</param>
/// <returns type="Enumerable"></returns>
}
Enumerable.Unfold = function (seed, func)
{
/// <summary>Applies function and generates a infinity sequence.
/// Ex: Unfold(3,"$+10") - 3,13,23,...</summary>
/// <param type="T" name="seed">The initial accumulator value.</param>
/// <param type="Func<T,T>" name="func">An accumulator function to be invoked on each element.</param>
/// <returns type="Enumerable"></returns>
}
Enumerable.prototype =
{
/* Projection and Filtering Methods */
CascadeBreadthFirst: function (func, resultSelector)
{
/// <summary>Projects each element of sequence and flattens the resulting sequences into one sequence use breadth first search.</summary>
/// <param name="func" type="Func<T,T[]>">Select child sequence.</param>
/// <param name="resultSelector" type="Optional:Func<T>_or_Func<T,int>" optional="true">Optional:the second parameter of the function represents the nestlevel of the source sequence.</param>
/// <returns type="Enumerable"></returns>
},
CascadeDepthFirst: function (func, resultSelector)
{
/// <summary>Projects each element of sequence and flattens the resulting sequences into one sequence use depth first search.</summary>
/// <param name="func" type="Func<T,T[]>">Select child sequence.</param>
/// <param name="resultSelector" type="Optional:Func<T>_or_Func<T,int>" optional="true">Optional:the second parameter of the function represents the nestlevel of the source sequence.</param>
/// <returns type="Enumerable"></returns>
},
Flatten: function ()
{
/// <summary>Flatten sequences into one sequence.</summary>
/// <returns type="Enumerable"></returns>
},
Pairwise: function (selector)
{
/// <summary>Projects current and next element of a sequence into a new form.</summary>
/// <param type="Func<TSource,TSource,TResult>" name="selector">A transform function to apply to current and next element.</param>
/// <returns type="Enumerable"></returns>
},
Scan: function (func_or_seed, func, resultSelector)
{
/// <summary>Applies an accumulator function over a sequence.</summary>
/// <param name="func_or_seed" type="Func<T,T,T>_or_TAccumulate">Func is an accumulator function to be invoked on each element. Seed is the initial accumulator value.</param>
/// <param name="func" type="Optional:Func<TAccumulate,T,TAccumulate>" optional="true">An accumulator function to be invoked on each element.</param>
/// <param name="resultSelector" type="Optional:Func<TAccumulate,TResult>" optional="true">A function to transform the final accumulator value into the result value.</param>
/// <returns type="Enumerable"></returns>
},
Select: function (selector)
{
/// <summary>Projects each element of a sequence into a new form.</summary>
/// <param name="selector" type="Func<T,T>_or_Func<T,int,T>">A transform function to apply to each source element; Optional:the second parameter of the function represents the index of the source element.</param>
/// <returns type="Enumerable"></returns>
},
SelectMany: function (collectionSelector, resultSelector)
{
/// <summary>Projects each element of a sequence and flattens the resulting sequences into one sequence.</summary>
/// <param name="collectionSelector" type="Func<T,TCollection[]>_or_Func<T,int,TCollection[]>">A transform function to apply to each source element; Optional:the second parameter of the function represents the index of the source element.</param>
/// <param name="resultSelector" type="Optional:Func<T,TCollection,TResult>" optional="true">Optional:A transform function to apply to each element of the intermediate sequence.</param>
/// <returns type="Enumerable"></returns>
},
Where: function (predicate)
{
/// <summary>Filters a sequence of values based on a predicate.</summary>
/// <param name="predicate" type="Func<T,bool>_or_Func<T,int,bool>">A function to test each source element for a condition; Optional:the second parameter of the function represents the index of the source element.</param>
/// <returns type="Enumerable"></returns>
},
OfType: function (type)
{
/// <summary>Filters the elements based on a specified type.</summary>
/// <param name="type" type="T">The type to filter the elements of the sequence on.</param>
/// <returns type="Enumerable"></returns>
},
Zip: function (second, selector)
{
/// <summary>Merges two sequences by using the specified predicate function.</summary>
/// <param name="second" type="T[]">The second sequence to merge.</param>
/// <param name="selector" type="Func<TFirst,TSecond,TResult>_or_Func<TFirst,TSecond,int,TResult>">A function that specifies how to merge the elements from the two sequences. Optional:the third parameter of the function represents the index of the source element.</param>
/// <returns type="Enumerable"></returns>
},
/* Join Methods */
Join: function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector)
{
/// <summary>Correlates the elements of two sequences based on matching keys.</summary>
/// <param name="inner" type="T[]">The sequence to join to the first sequence.</param>
/// <param name="outerKeySelector" type="Func<TOuter,TKey>">A function to extract the join key from each element of the first sequence.</param>
/// <param name="innerKeySelector" type="Func<TInner,TKey>">A function to extract the join key from each element of the second sequence.</param>
/// <param name="resultSelector" type="Func<TOuter,TInner,TResult>">A function to create a result element from two matching elements.</param>
/// <param name="compareSelector" type="Optional:Func<TKey,TCompare>" optional="true">An equality comparer to compare values.</param>
/// <returns type="Enumerable"></returns>
},
GroupJoin: function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector)
{
/// <summary>Correlates the elements of two sequences based on equality of keys and groups the results.</summary>
/// <param name="inner" type="T[]">The sequence to join to the first sequence.</param>
/// <param name="outerKeySelector" type="Func<TOuter>">A function to extract the join key from each element of the first sequence.</param>
/// <param name="innerKeySelector" type="Func<TInner>">A function to extract the join key from each element of the second sequence.</param>
/// <param name="resultSelector" type="Func<TOuter,Enumerable<TInner>,TResult">A function to create a result element from an element from the first sequence and a collection of matching elements from the second sequence.</param>
/// <param name="compareSelector" type="Optional:Func<TKey,TCompare>" optional="true">An equality comparer to compare values.</param>
/// <returns type="Enumerable"></returns>
},
/* Set Methods */
All: function (predicate)
{
/// <summary>Determines whether all elements of a sequence satisfy a condition.</summary>
/// <param type="Func<T,bool>" name="predicate">A function to test each element for a condition.</param>
/// <returns type="Boolean"></returns>
},
Any: function (predicate)
{
/// <summary>Determines whether a sequence contains any elements or any element of a sequence satisfies a condition.</summary>
/// <param name="predicate" type="Optional:Func<T,bool>" optional="true">A function to test each element for a condition.</param>
/// <returns type="Boolean"></returns>
},
Concat: function (second)
{
/// <summary>Concatenates two sequences.</summary>
/// <param name="second" type="T[]">The sequence to concatenate to the first sequence.</param>
/// <returns type="Enumerable"></returns>
},
Insert: function (index, second)
{
/// <summary>Merge two sequences.</summary>
/// <param name="index" type="Number" integer="true">The index of insert start position.</param>
/// <param name="second" type="T[]">The sequence to concatenate to the first sequence.</param>
/// <returns type="Enumerable"></returns>
},
Alternate: function (value)
{
/// <summary>Insert value to between sequence.</summary>
/// <param name="value" type="T">The value of insert.</param>
/// <returns type="Enumerable"></returns>
},
// Overload:function(value)
// Overload:function(value, compareSelector)
Contains: function (value, compareSelector)
{
/// <summary>Determines whether a sequence contains a specified element.</summary>
/// <param name="value" type="T">The value to locate in the sequence.</param>
/// <param name="compareSelector" type="Optional:Func<T,TKey>" optional="true">An equality comparer to compare values.</param>
/// <returns type="Boolean"></returns>
},
DefaultIfEmpty: function (defaultValue)
{
/// <summary>Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.</summary>
/// <param name="defaultValue" type="T">The value to return if the sequence is empty.</param>
/// <returns type="Enumerable"></returns>
},
Distinct: function (compareSelector)
{
/// <summary>Returns distinct elements from a sequence.</summary>
/// <param name="compareSelector" type="Optional:Func<T,TKey>" optional="true">An equality comparer to compare values.</param>
/// <returns type="Enumerable"></returns>
},
Except: function (second, compareSelector)
{
/// <summary>Produces the set difference of two sequences.</summary>
/// <param name="second" type="T[]">An T[] whose Elements that also occur in the first sequence will cause those elements to be removed from the returned sequence.</param>
/// <param name="compareSelector" type="Optional:Func<T,TKey>" optional="true">An equality comparer to compare values.</param>
/// <returns type="Enumerable"></returns>
},
Intersect: function (second, compareSelector)
{
/// <summary>Produces the set difference of two sequences.</summary>
/// <param name="second" type="T[]">An T[] whose distinct elements that also appear in the first sequence will be returned.</param>
/// <param name="compareSelector" type="Optional:Func<T,TKey>" optional="true">An equality comparer to compare values.</param>
/// <returns type="Enumerable"></returns>
},
SequenceEqual: function (second, compareSelector)
{
/// <summary>Determines whether two sequences are equal by comparing the elements.</summary>
/// <param name="second" type="T[]">An T[] to compare to the first sequence.</param>
/// <param name="compareSelector" type="Optional:Func<T,TKey>" optional="true">An equality comparer to compare values.</param>
/// <returns type="Enumerable"></returns>
},
Union: function (second, compareSelector)
{
/// <summary>Produces the union of two sequences.</summary>
/// <param name="second" type="T[]">An T[] whose distinct elements form the second set for the union.</param>
/// <param name="compareSelector" type="Optional:Func<T,TKey>" optional="true">An equality comparer to compare values.</param>
/// <returns type="Enumerable"></returns>
},
/* Ordering Methods */
OrderBy: function (keySelector)
{
/// <summary>Sorts the elements of a sequence in ascending order according to a key.</summary>
/// <param name="keySelector" type="Optional:Func<T,TKey>">A function to extract a key from an element.</param>
return new OrderedEnumerable();
},
OrderByDescending: function (keySelector)
{
/// <summary>Sorts the elements of a sequence in descending order according to a key.</summary>
/// <param name="keySelector" type="Optional:Func<T,TKey>">A function to extract a key from an element.</param>
return new OrderedEnumerable();
},
Reverse: function ()
{
/// <summary>Inverts the order of the elements in a sequence.</summary>
/// <returns type="Enumerable"></returns>
},
Shuffle: function ()
{
/// <summary>Shuffle sequence.</summary>
/// <returns type="Enumerable"></returns>
},
/* Grouping Methods */
GroupBy: function (keySelector, elementSelector, resultSelector, compareSelector)
{
/// <summary>Groups the elements of a sequence according to a specified key selector function.</summary>
/// <param name="keySelector" type="Func<T,TKey>">A function to extract the key for each element.</param>
/// <param name="elementSelector" type="Optional:Func<T,TElement>">A function to map each source element to an element in an Grouping<TKey, TElement>.</param>
/// <param name="resultSelector" type="Optional:Func<TKey,Enumerable<TElement>,TResult>">A function to create a result value from each group.</param>
/// <param name="compareSelector" type="Optional:Func<TKey,TCompare>" optional="true">An equality comparer to compare values.</param>
/// <returns type="Enumerable"></returns>
},
PartitionBy: function (keySelector, elementSelector, resultSelector, compareSelector)
{
/// <summary>Create Group by continuation key.</summary>
/// <param name="keySelector" type="Func<T,TKey>">A function to extract the key for each element.</param>
/// <param name="elementSelector" type="Optional:Func<T,TElement>">A function to map each source element to an element in an Grouping<TKey, TElement>.</param>
/// <param name="resultSelector" type="Optional:Func<TKey,Enumerable<TElement>,TResult>">A function to create a result value from each group.</param>
/// <param name="compareSelector" type="Optional:Func<TKey,TCompare>" optional="true">An equality comparer to compare values.</param>
/// <returns type="Enumerable"></returns>
},
BufferWithCount: function (count)
{
/// <summary>Divide by count</summary>
/// <param name="count" type="Number" integer="true">integer</param>
/// <returns type="Enumerable"></returns>
},
/* Aggregate Methods */
Aggregate: function (func_or_seed, func, resultSelector)
{
/// <summary>Applies an accumulator function over a sequence.</summary>
/// <param name="func_or_seed" type="Func<T,T,T>_or_TAccumulate">Func is an accumulator function to be invoked on each element. Seed is the initial accumulator value.</param>
/// <param name="func" type="Optional:Func<TAccumulate,T,TAccumulate>" optional="true">An accumulator function to be invoked on each element.</param>
/// <param name="resultSelector" type="Optional:Func<TAccumulate,TResult>" optional="true">A function to transform the final accumulator value into the result value.</param>
/// <returns type="TResult"></returns>
},
Average: function (selector)
{
/// <summary>Computes the average of a sequence.</summary>
/// <param name="selector" type="Optional:Func<T,Number>" optional="true">A transform function to apply to each element.</param>
/// <returns type="Number"></returns>
},
Count: function (predicate)
{
/// <summary>Returns the number of elements in a sequence.</summary>
/// <param name="predicate" type="Optional:Func<T,Boolean>" optional="true">A function to test each element for a condition.</param>
/// <returns type="Number"></returns>
},
Max: function (selector)
{
/// <summary>Returns the maximum value in a sequence</summary>
/// <param name="selector" type="Optional:Func<T,TKey>" optional="true">A transform function to apply to each element.</param>
/// <returns type="Number"></returns>
},
Min: function (selector)
{
/// <summary>Returns the minimum value in a sequence</summary>
/// <param name="selector" type="Optional:Func<T,TKey>" optional="true">A transform function to apply to each element.</param>
/// <returns type="Number"></returns>
},
MaxBy: function (keySelector)
{
/// <summary>Returns the maximum value in a sequence by keySelector</summary>
/// <param name="keySelector" type="Func<T,TKey>">A compare selector of element.</param>
/// <returns type="T"></returns>
},
MinBy: function (keySelector)
{
/// <summary>Returns the minimum value in a sequence by keySelector</summary>
/// <param name="keySelector" type="Func<T,TKey>">A compare selector of element.</param>
/// <returns type="T"></returns>
},
Sum: function (selector)
{
/// <summary>Computes the sum of a sequence of values.</summary>
/// <param name="selector" type="Optional:Func<T,TKey>" optional="true">A transform function to apply to each element.</param>
/// <returns type="Number"></returns>
},
/* Paging Methods */
ElementAt: function (index)
{
/// <summary>Returns the element at a specified index in a sequence.</summary>
/// <param name="index" type="Number" integer="true">The zero-based index of the element to retrieve.</param>
/// <returns type="T"></returns>
},
ElementAtOrDefault: function (index, defaultValue)
{
/// <summary>Returns the element at a specified index in a sequence or a default value if the index is out of range.</summary>
/// <param name="index" type="Number" integer="true">The zero-based index of the element to retrieve.</param>
/// <param name="defaultValue" type="T">The value if the index is outside the bounds then send.</param>
/// <returns type="T"></returns>
},
First: function (predicate)
{
/// <summary>Returns the first element of a sequence.</summary>
/// <param name="predicate" type="Optional:Func<T,Boolean>">A function to test each element for a condition.</param>
/// <returns type="T"></returns>
},
FirstOrDefault: function (defaultValue, predicate)
{
/// <summary>Returns the first element of a sequence, or a default value.</summary>
/// <param name="defaultValue" type="T">The value if not found then send.</param>
/// <param name="predicate" type="Optional:Func<T,Boolean>">A function to test each element for a condition.</param>
/// <returns type="T"></returns>
},
Last: function (predicate)
{
/// <summary>Returns the last element of a sequence.</summary>
/// <param name="predicate" type="Optional:Func<T,Boolean>">A function to test each element for a condition.</param>
/// <returns type="T"></returns>
},
LastOrDefault: function (defaultValue, predicate)
{
/// <summary>Returns the last element of a sequence, or a default value.</summary>
/// <param name="defaultValue" type="T">The value if not found then send.</param>
/// <param name="predicate" type="Optional:Func<T,Boolean>">A function to test each element for a condition.</param>
/// <returns type="T"></returns>
},
Single: function (predicate)
{
/// <summary>Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.</summary>
/// <param name="predicate" type="Optional:Func<T,Boolean>">A function to test each element for a condition.</param>
/// <returns type="T"></returns>
},
SingleOrDefault: function (defaultValue, predicate)
{
/// <summary>Returns a single, specific element of a sequence of values, or a default value if no such element is found.</summary>
/// <param name="defaultValue" type="T">The value if not found then send.</param>
/// <param name="predicate" type="Optional:Func<T,Boolean>">A function to test each element for a condition.</param>
/// <returns type="T"></returns>
},
Skip: function (count)
{
/// <summary>Bypasses a specified number of elements in a sequence and then returns the remaining elements.</summary>
/// <param name="count" type="Number" integer="true">The number of elements to skip before returning the remaining elements.</param>
/// <returns type="Enumerable"></returns>
},
SkipWhile: function (predicate)
{
/// <summary>Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.</summary>
/// <param name="predicate" type="Func<T,Boolean>_or_Func<T,int,Boolean>">A function to test each source element for a condition; Optional:the second parameter of the function represents the index of the source element.</param>
/// <returns type="Enumerable"></returns>
},
Take: function (count)
{
/// <summary>Returns a specified number of contiguous elements from the start of a sequence.</summary>
/// <param name="count" type="Number" integer="true">The number of elements to return.</param>
/// <returns type="Enumerable"></returns>
},
TakeWhile: function (predicate)
{
/// <summary>Returns elements from a sequence as long as a specified condition is true, and then skips the remaining elements.</summary>
/// <param name="predicate" type="Func<T,Boolean>_or_Func<T,int,Boolean>">A function to test each source element for a condition; Optional:the second parameter of the function represents the index of the source element.</param>
/// <returns type="Enumerable"></returns>
},
TakeExceptLast: function (count)
{
/// <summary>Take a sequence except last count.</summary>
/// <param name="count" type="Optional:Number" integer="true">The number of skip count.</param>
/// <returns type="Enumerable"></returns>
},
TakeFromLast: function (count)
{
/// <summary>Take a sequence from last count.</summary>
/// <param name="count" type="Number" integer="true">The number of take count.</param>
/// <returns type="Enumerable"></returns>
},
IndexOf: function (item)
{
/// <summary>Returns the zero-based index of the flrst occurrence of a value.</summary>
/// <param name="item" type="T">The zero-based starting index of the search.</param>
/// <returns type="Number" integer="true"></returns>
},
LastIndexOf: function (item)
{
/// <summary>Returns the zero-based index of the last occurrence of a value.</summary>
/// <param name="item" type="T">The zero-based starting index of the search.</param>
/// <returns type="Number" integer="true"></returns>
},
/* Convert Methods */
ToArray: function ()
{
/// <summary>Creates an array from this sequence.</summary>
/// <returns type="Array"></returns>
},
ToLookup: function (keySelector, elementSelector, compareSelector)
{
/// <summary>Creates a Lookup from this sequence.</summary>
/// <param name="keySelector" type="Func<T,TKey>">A function to extract a key from each element.</param>
/// <param name="elementSelector" type="Optional:Func<T,TElement>">A transform function to produce a result element value from each element.</param>
/// <param name="compareSelector" type="Optional:Func<TKey,TCompare>" optional="true">An equality comparer to compare values.</param>
return new Lookup();
},
ToObject: function (keySelector, elementSelector)
{
/// <summary>Creates a Object from this sequence.</summary>
/// <param name="keySelector" type="Func<T,String>">A function to extract a key from each element.</param>
/// <param name="elementSelector" type="Func<T,TElement>">A transform function to produce a result element value from each element.</param>
/// <returns type="Object"></returns>
},
ToDictionary: function (keySelector, elementSelector, compareSelector)
{
/// <summary>Creates a Dictionary from this sequence.</summary>
/// <param name="keySelector" type="Func<T,TKey>">A function to extract a key from each element.</param>
/// <param name="elementSelector" type="Func<T,TElement>">A transform function to produce a result element value from each element.</param>
/// <param name="compareSelector" type="Optional:Func<TKey,TCompare>" optional="true">An equality comparer to compare values.</param>
return new Dictionary();
},
// Overload:function()
// Overload:function(replacer)
// Overload:function(replacer, space)
ToJSON: function (replacer, space)
{
/// <summary>Creates a JSON String from sequence, performed only native JSON support browser or included json2.js.</summary>
/// <param name="replacer" type="Optional:Func">a replacer.</param>
/// <param name="space" type="Optional:Number">indent spaces.</param>
/// <returns type="String"></returns>
},
// Overload:function()
// Overload:function(separator)
// Overload:function(separator,selector)
ToString: function (separator, selector)
{
/// <summary>Creates Joined string from this sequence.</summary>
/// <param name="separator" type="Optional:String">A String.</param>
/// <param name="selector" type="Optional:Func<T,String>">A transform function to apply to each source element.</param>
/// <returns type="String"></returns>
},
/* Action Methods */
Do: function (action)
{
/// <summary>Performs the specified action on each element of the sequence.</summary>
/// <param name="action" type="Action<T>_or_Action<T,int>">Optional:the second parameter of the function represents the index of the source element.</param>
/// <returns type="Enumerable"></returns>
},
ForEach: function (action)
{
/// <summary>Performs the specified action on each element of the sequence.</summary>
/// <param name="action" type="Action<T>_or_Action<T,int>">[return true;]continue iteration.[return false;]break iteration. Optional:the second parameter of the function represents the index of the source element.</param>
/// <returns type="void"></returns>
},
Write: function (separator, selector)
{
/// <summary>Do document.write.</summary>
/// <param name="separator" type="Optional:String">A String.</param>
/// <param name="selector" type="Optional:Func<T,String>">A transform function to apply to each source element.</param>
/// <returns type="void"></returns>
},
WriteLine: function (selector)
{
/// <summary>Do document.write + <br />.</summary>
/// <param name="selector" type="Optional:Func<T,String>">A transform function to apply to each source element.</param>
/// <returns type="void"></returns>
},
Force: function ()
{
/// <summary>Execute enumerate.</summary>
/// <returns type="void"></returns>
},
/* Functional Methods */
Let: function (func)
{
/// <summary>Bind the source to the parameter so that it can be used multiple times.</summary>
/// <param name="func" type="Func<Enumerable<T>,Enumerable<TR>>">apply function.</param>
/// <returns type="Enumerable"></returns>
},
Share: function ()
{
/// <summary>Shares cursor of all enumerators to the sequence.</summary>
/// <returns type="Enumerable"></returns>
},
MemoizeAll: function ()
{
/// <summary>Creates an enumerable that enumerates the original enumerable only once and caches its results.</summary>
/// <returns type="Enumerable"></returns>
},
/* Error Handling Methods */
Catch: function (handler)
{
/// <summary>catch error and do handler.</summary>
/// <param name="handler" type="Action<Error>">execute if error occured.</param>
/// <returns type="Enumerable"></returns>
},
Finally: function (finallyAction)
{
/// <summary>do action if enumerate end or disposed or error occured.</summary>
/// <param name="handler" type="Action">finally execute.</param>
/// <returns type="Enumerable"></returns>
},
/* For Debug Methods */
Trace: function (message, selector)
{
/// <summary>Trace object use console.log.</summary>
/// <param name="message" type="Optional:String">Default is 'Trace:'.</param>
/// <param name="selector" type="Optional:Func<T,String>">A transform function to apply to each source element.</param>
/// <returns type="Enumerable"></returns>
}
}
// vsdoc-dummy
Enumerable.prototype.GetEnumerator = function ()
{
/// <summary>Returns an enumerator that iterates through the collection.</summary>
return new IEnumerator();
}
var IEnumerator = function () { }
IEnumerator.prototype.Current = function ()
{
/// <summary>Gets the element in the collection at the current position of the enumerator.</summary>
/// <returns type="T"></returns>
}
IEnumerator.prototype.MoveNext = function ()
{
/// <summary>Advances the enumerator to the next element of the collection.</summary>
/// <returns type="Boolean"></returns>
}
IEnumerator.prototype.Dispose = function ()
{
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
/// <returns type="Void"></returns>
}
var Dictionary = function () { }
Dictionary.prototype =
{
Add: function (key, value)
{
/// <summary>add new pair. if duplicate key then overwrite new value.</summary>
/// <returns type="Void"></returns>
},
Get: function (key)
{
/// <summary>get value. if not find key then return undefined.</summary>
/// <returns type="T"></returns>
},
Set: function (key, value)
{
/// <summary>set value. if complete set value then return true, not find key then return false.</summary>
/// <returns type="Boolean"></returns>
},
Contains: function (key)
{
/// <summary>check contains key.</summary>
/// <returns type="Boolean"></returns>
},
Clear: function ()
{
/// <summary>clear dictionary.</summary>
/// <returns type="Void"></returns>
},
Remove: function (key)
{
/// <summary>remove key and value.</summary>
/// <returns type="Void"></returns>
},
Count: function ()
{
/// <summary>contains value's count.</summary>
/// <returns type="Number"></returns>
},
ToEnumerable: function ()
{
/// <summary>Convert to Enumerable<{Key:, Value:}>.</summary>
/// <returns type="Enumerable"></returns>
}
}
var Lookup = function () { }
Lookup.prototype =
{
Count: function ()
{
/// <summary>contains value's count.</summary>
/// <returns type="Number"></returns>
},
Get: function (key)
{
/// <summary>get grouped enumerable.</summary>
/// <returns type="Enumerable"></returns>
},
Contains: function (key)
{
/// <summary>check contains key.</summary>
/// <returns type="Boolean"></returns>
},
ToEnumerable: function ()
{
/// <summary>Convert to Enumerable<Grouping>.</summary>
/// <returns type="Enumerable"></returns>
}
}
var Grouping = function () { }
Grouping.prototype = new Enumerable();
Grouping.prototype.Key = function ()
{
/// <summary>get grouping key.</summary>
/// <returns type="T"></returns>
}
var OrderedEnumerable = function () { }
OrderedEnumerable.prototype = new Enumerable();
OrderedEnumerable.prototype.ThenBy = function (keySelector)
{
/// <summary>Performs a subsequent ordering of the elements in a sequence in ascending order according to a key.</summary>
/// <param name="keySelector" type="Func<T,TKey>">A function to extract a key from each element.</param>
return Enumerable.Empty().OrderBy();
}
OrderedEnumerable.prototype.ThenByDescending = function (keySelector)
{
/// <summary>Performs a subsequent ordering of the elements in a sequence in descending order, according to a key.</summary>
/// <param name="keySelector" type="Func<T,TKey>">A function to extract a key from each element.</param>
return Enumerable.Empty().OrderBy();
}
return Enumerable;
})() |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
CollectionGroup = _dereq_('../lib/CollectionGroup'),
View = _dereq_('../lib/View'),
Highchart = _dereq_('../lib/Highchart'),
Persist = _dereq_('../lib/Persist'),
Document = _dereq_('../lib/Document'),
Overview = _dereq_('../lib/Overview'),
OldView = _dereq_('../lib/OldView'),
OldViewBind = _dereq_('../lib/OldView.Bind');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/CollectionGroup":4,"../lib/Core":5,"../lib/Document":7,"../lib/Highchart":8,"../lib/OldView":22,"../lib/OldView.Bind":21,"../lib/Overview":25,"../lib/Persist":27,"../lib/View":30}],2:[function(_dereq_,module,exports){
"use strict";
/**
* Creates an always-sorted multi-key bucket that allows ForerunnerDB to
* know the index that a document will occupy in an array with minimal
* processing, speeding up things like sorted views.
*/
var Shared = _dereq_('./Shared');
/**
* The active bucket class.
* @param {object} orderBy An order object.
* @constructor
*/
var ActiveBucket = function (orderBy) {
var sortKey;
this._primaryKey = '_id';
this._keyArr = [];
this._data = [];
this._objLookup = {};
this._count = 0;
for (sortKey in orderBy) {
if (orderBy.hasOwnProperty(sortKey)) {
this._keyArr.push({
key: sortKey,
dir: orderBy[sortKey]
});
}
}
};
Shared.addModule('ActiveBucket', ActiveBucket);
Shared.synthesize(ActiveBucket.prototype, 'primaryKey');
Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting');
/**
* Quicksorts a single document into the passed array and
* returns the index that the document should occupy.
* @param {object} obj The document to calculate index for.
* @param {array} arr The array the document index will be
* calculated for.
* @param {string} item The string key representation of the
* document whose index is being calculated.
* @param {function} fn The comparison function that is used
* to determine if a document is sorted below or above the
* document we are calculating the index for.
* @returns {number} The index the document should occupy.
*/
ActiveBucket.prototype.qs = function (obj, arr, item, fn) {
// If the array is empty then return index zero
if (!arr.length) {
return 0;
}
var lastMidwayIndex = -1,
midwayIndex,
lookupItem,
result,
start = 0,
end = arr.length - 1;
// Loop the data until our range overlaps
while (end >= start) {
// Calculate the midway point (divide and conquer)
midwayIndex = Math.floor((start + end) / 2);
if (lastMidwayIndex === midwayIndex) {
// No more items to scan
break;
}
// Get the item to compare against
lookupItem = arr[midwayIndex];
if (lookupItem !== undefined) {
// Compare items
result = fn(this, obj, item, lookupItem);
if (result > 0) {
start = midwayIndex + 1;
}
if (result < 0) {
end = midwayIndex - 1;
}
}
lastMidwayIndex = midwayIndex;
}
if (result > 0) {
return midwayIndex + 1;
} else {
return midwayIndex;
}
};
/**
* Calculates the sort position of an item against another item.
* @param {object} sorter An object or instance that contains
* sortAsc and sortDesc methods.
* @param {object} obj The document to compare.
* @param {string} a The first key to compare.
* @param {string} b The second key to compare.
* @returns {number} Either 1 for sort a after b or -1 to sort
* a before b.
* @private
*/
ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) {
var aVals = a.split('.:.'),
bVals = b.split('.:.'),
arr = sorter._keyArr,
count = arr.length,
index,
sortType,
castType;
for (index = 0; index < count; index++) {
sortType = arr[index];
castType = typeof obj[sortType.key];
if (castType === 'number') {
aVals[index] = Number(aVals[index]);
bVals[index] = Number(bVals[index]);
}
// Check for non-equal items
if (aVals[index] !== bVals[index]) {
// Return the sorted items
if (sortType.dir === 1) {
return sorter.sortAsc(aVals[index], bVals[index]);
}
if (sortType.dir === -1) {
return sorter.sortDesc(aVals[index], bVals[index]);
}
}
}
};
/**
* Inserts a document into the active bucket.
* @param {object} obj The document to insert.
* @returns {number} The index the document now occupies.
*/
ActiveBucket.prototype.insert = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Insert key
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
this._data.splice(keyIndex, 0, key);
} else {
this._data.splice(keyIndex, 0, key);
}
this._objLookup[obj[this._primaryKey]] = key;
this._count++;
return keyIndex;
};
/**
* Removes a document from the active bucket.
* @param {object} obj The document to remove.
* @returns {boolean} True if the document was removed
* successfully or false if it wasn't found in the active
* bucket.
*/
ActiveBucket.prototype.remove = function (obj) {
var key,
keyIndex;
key = this._objLookup[obj[this._primaryKey]];
if (key) {
keyIndex = this._data.indexOf(key);
if (keyIndex > -1) {
this._data.splice(keyIndex, 1);
delete this._objLookup[obj[this._primaryKey]];
this._count--;
return true;
} else {
return false;
}
}
return false;
};
/**
* Get the index that the passed document currently occupies
* or the index it will occupy if added to the active bucket.
* @param {object} obj The document to get the index for.
* @returns {number} The index.
*/
ActiveBucket.prototype.index = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Get key index
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
}
return keyIndex;
};
/**
* The key that represents the passed document.
* @param {object} obj The document to get the key for.
* @returns {string} The document key.
*/
ActiveBucket.prototype.documentKey = function (obj) {
var key = '',
arr = this._keyArr,
count = arr.length,
index,
sortType;
for (index = 0; index < count; index++) {
sortType = arr[index];
if (key) {
key += '.:.';
}
key += obj[sortType.key];
}
// Add the unique identifier on the end of the key
key += '.:.' + obj[this._primaryKey];
return key;
};
/**
* Get the number of documents currently indexed in the active
* bucket instance.
* @returns {number} The number of documents.
*/
ActiveBucket.prototype.count = function () {
return this._count;
};
Shared.finishModule('ActiveBucket');
module.exports = ActiveBucket;
},{"./Shared":29}],3:[function(_dereq_,module,exports){
"use strict";
/**
* The main collection class. Collections store multiple documents and
* can operate on them using the query language to insert, read, update
* and delete.
*/
var Shared,
Core,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Crc,
Overload,
ReactorIO;
Shared = _dereq_('./Shared');
/**
* Collection object used to store data.
* @constructor
*/
var Collection = function (name) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name) {
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
// Set the subset to itself since it is the root collection
this._subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Crc = _dereq_('./Crc');
Core = Shared.modules.Core;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Get the internal data
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function () {
var key;
if (this._state !== 'dropped') {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log('Dropping collection ' + this._name);
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
return true;
}
} else {
return true;
}
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Core=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
}
}
return this.$super.apply(this, arguments);
});
/**
* Sets the collection's data to the array of documents passed.
* @param data
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
// Rebuild all other indexes
op.time('Rebuild All Other Indexes');
this._rebuildIndexes();
op.time('Rebuild All Other Indexes');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw('ForerunnerDB.Collection "' + this.name() + '": Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = JSON.stringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert;
var returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj);
break;
case 'update':
returnData.result = this.update(query, obj);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
// Decouple the update data
update = this.decouple(update);
// Handle transform
update = this.transformIn(update);
if (this.debug()) {
console.log('Updating some collection data for collection "' + this.name() + '"');
}
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (originalDoc) {
var newDoc = self.decouple(originalDoc),
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, originalDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(originalDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, originalDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(originalDoc, update, query, options, '');
}
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: dataSet
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw('ForerunnerDB.Collection "' + this.name() + '": Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return true;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Array} The items that were updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update);
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
// Ignore some operators
operation = true;
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
this._updateIncrement(doc, i, update[i]);
updated = true;
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = JSON.stringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (JSON.stringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot splicePush without a $index integer value!');
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot pop from a key that is not an array! (' + i + ')');
}
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Updates a property on an object depending on if the collection is
* currently running data-binding or not.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
Collection.prototype._updateProperty = function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log('ForerunnerDB.Collection: Setting non-data-bound document property "' + prop + '" for collection "' + this.name() + '"');
}
};
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
Collection.prototype._updateIncrement = function (doc, prop, val) {
doc[prop] += val;
};
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
Collection.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log('ForerunnerDB.Collection: Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for collection "' + this.name() + '"');
}
};
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._updateSplicePush = function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
};
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._updatePush = function (arr, doc) {
arr.push(doc);
};
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
Collection.prototype._updatePull = function (arr, index) {
arr.splice(index, 1);
};
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
Collection.prototype._updateMultiply = function (doc, prop, val) {
doc[prop] *= val;
};
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
Collection.prototype._updateRename = function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
};
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
Collection.prototype._updateUnset = function (doc, prop) {
delete doc[prop];
};
/**
* Pops an item from the array stack.
* @param {Object} doc The document to modify.
* @param {Number=} val Optional, if set to 1 will pop, if set to -1 will shift.
* @return {Boolean}
* @private
*/
Collection.prototype._updatePop = function (doc, val) {
var updated = false;
if (doc.length > 0) {
if (val === 1) {
doc.pop();
updated = true;
} else if (val === -1) {
doc.shift();
updated = true;
}
}
return updated;
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
//op.time('Resolve chains');
this.chainSend('remove', {
query: query,
dataSet: dataSet
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(dataSet);
}
this.deferEmit('change', {type: 'remove', data: dataSet});
}
if (callback) { callback(false, dataSet); }
return dataSet;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Array} An array of documents that were removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj);
};
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc.
* @private
*/
Collection.prototype.deferEmit = function () {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
if (this._changeTimeout) {
clearTimeout(this._changeTimeout);
}
// Set a timeout
this._changeTimeout = setTimeout(function () {
if (self.debug()) { console.log('ForerunnerDB.Collection: Emitting ' + args[0]); }
self.emit.apply(self, args);
}, 100);
} else {
this.emit.apply(this, arguments);
}
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
*/
Collection.prototype.processQueue = function (type, callback) {
var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];
if (queue.length) {
var self = this,
dataArr;
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
this[type](dataArr);
}
// Queue another process
setTimeout(function () {
self.processQueue(type, callback);
}, deferTime);
} else {
if (callback) { callback(); }
}
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object||Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object||Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
//op.time('Resolve chains');
this.chainSend('insert', data, {index: index});
//op.time('Resolve chains');
this._onInsert(inserted, failed);
if (callback) { callback(); }
this.deferEmit('change', {type: 'insert', data: inserted});
return {
inserted: inserted,
failed: failed
};
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc;
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return false;
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = JSON.stringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = JSON.stringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {Object} item The item whose primary key should be used to lookup.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (item) {
return this._data.indexOf(
this._primaryIndex.get(
item[this._primaryKey]
)
);
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
._subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Gets the collection that this collection is a subset of.
* @returns {Collection}
*/
Collection.prototype.subsetOf = function () {
return this.__subsetOf;
};
/**
* Sets the collection that this collection is a subset of.
* @param {Collection} collection The collection to set as the parent of this subset.
* @returns {*} This object for chaining.
* @private
*/
Collection.prototype._subsetOf = function (collection) {
this.__subsetOf = collection;
return this;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = JSON.stringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
options = this.options(options);
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
//finalQuery,
scanLength,
requiresTableScan = true,
resultArr,
joinCollectionIndex,
joinIndex,
joinCollection = {},
joinQuery,
joinPath,
joinCollectionName,
joinCollectionInstance,
joinMatch,
joinMatchIndex,
joinSearch,
joinMulti,
joinRequire,
joinFindResults,
resultCollectionName,
resultIndex,
resultRemove = [],
index,
i, j, k,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
matcher = function (doc) {
return self._match(doc, query, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(query, options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get an instance reference to the join collections
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinCollectionName = analysis.joinsOn[joinIndex];
joinPath = new Path(analysis.joinQueries[joinCollectionName]);
joinQuery = joinPath.value(query)[0];
joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery);
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup;
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
op.time('tableScan: ' + scanLength);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
// Set the key to store the join result in to the collection name by default
resultCollectionName = joinCollectionName;
// Get the join collection instance from the DB
joinCollectionInstance = this._db.collection(joinCollectionName);
// Get the match data for the join
joinMatch = options.$join[joinCollectionIndex][joinCollectionName];
// Loop our result data array
for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearch = {};
joinMulti = false;
joinRequire = false;
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$as':
// Rename the collection when stored in the result document
resultCollectionName = joinMatch[joinMatchIndex];
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatch[joinMatchIndex];
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatch[joinMatchIndex];
break;
/*default:
// Check for a double-dollar which is a back-reference to the root collection item
if (joinMatchIndex.substr(0, 3) === '$$.') {
// Back reference
// TODO: Support complex joins
}
break;*/
}
} else {
// TODO: Could optimise this by caching path objects
// Get the data to match against and store in the search object
joinSearch[joinMatchIndex] = new Path(joinMatch[joinMatchIndex]).value(resultArr[resultIndex])[0];
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinCollectionInstance.find(joinSearch);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultArr[resultIndex]);
}
}
}
}
}
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
for (i = 0; i < resultRemove.length; i++) {
index = resultArr.indexOf(resultRemove[i]);
if (index > -1) {
resultArr.splice(index, 1);
}
}
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
op.stop();
resultArr.__fdbOp = op;
return resultArr;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query) {
var item = this.find(query, {$decouple: false})[0];
if (item) {
return this._data.indexOf(item);
}
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformIn(data[i]);
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformOut(data[i]);
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = sortKey;
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
buckets = this.bucket(keyObj.___fdbKey, arr);
// Loop buckets and sort contents
for (i in buckets) {
if (buckets.hasOwnProperty(i)) {
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[i]));
}
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
Collection.prototype.bucket = function (key, arr) {
var i,
buckets = {};
for (i = 0; i < arr.length; i++) {
buckets[arr[i][key]] = buckets[arr[i][key]] || [];
buckets[arr[i][key]].push(arr[i]);
}
return buckets;
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [this._name],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinCollectionIndex,
joinCollectionName,
joinCollections = [],
joinCollectionReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.countKeys(query);
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
analysis.indexMatch.push({
lookup: this._primaryIndex.lookup(query, options),
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
// Loop the join collections and keep a reference to them
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
joinCollections.push(joinCollectionName);
// Check if the join uses an $as operator
if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) {
joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as);
} else {
joinCollectionReferences.push(joinCollectionName);
}
}
}
}
// Loop the join collection references and determine if the query references
// any of the collections that are used in the join. If there no queries against
// joined collections the find method can use a code path optimised for this.
// Queries against joined collections requires the joined collections to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinCollectionReferences.length; index++) {
// Check if the query references any collection data that the join will create
queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinCollections[index]] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinCollections;
analysis.queriesOn = analysis.queriesOn.concat(joinCollections);
}
return analysis;
};
/**
* Checks if the passed query references this collection.
* @param query
* @param collection
* @param path
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesCollection = function (query, collection, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === collection) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesCollection(query[i], collection, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param match
* @param path
* @param subDocQuery
* @param subDocOptions
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docArr = this.find(match),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
resultObj.subDocs.push(subDocResults);
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.noStats) {
return resultObj.subDocs;
}
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
return resultObj;
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this._state === 'dropped') {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pm = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pm !== collection.primaryKey()) {
throw('ForerunnerDB.Collection "' + this.name() + '": Collection diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pm])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pm])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
};
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Core.prototype.collection = new Overload({
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @param {Object} options An options object.
* @returns {Collection}
*/
'object': function (options) {
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This get's called by all the other variants and
* handles the actual logic of the overloaded method.
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var name = options.name;
if (name) {
if (!this._collection[name]) {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw('ForerunnerDB.Core "' + this.name() + '": Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
}
if (this.debug()) {
console.log('Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name).db(this);
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw('ForerunnerDB.Core "' + this.name() + '": Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Core.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Core.prototype.collections = function (search) {
var arr = [],
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: this._collection[i].count()
});
}
} else {
arr.push({
name: i,
count: this._collection[i].count()
});
}
}
}
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":6,"./IndexBinaryTree":9,"./IndexHashMap":10,"./KeyValueStore":11,"./Metrics":12,"./Overload":24,"./Path":26,"./ReactorIO":28,"./Shared":29}],4:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Core,
CoreInit,
Collection;
Shared = _dereq_('./Shared');
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Collection = _dereq_('./Collection');
Core = Shared.modules.Core;
CoreInit = Shared.modules.Core.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Core=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw('ForerunnerDB.CollectionGroup "' + this.name() + '": All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Remove old data
this._data.remove(chainPacket.options.oldData);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
._subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function () {
if (this._state !== 'dropped') {
var i,
collArr,
viewArr;
if (this._debug) {
console.log('Dropping collection group ' + this._name);
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
}
return true;
};
// Extend DB to include collection groups
Core.prototype.init = function () {
this._collectionGroup = {};
CoreInit.apply(this, arguments);
};
Core.prototype.collectionGroup = function (collectionGroupName) {
if (collectionGroupName) {
this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this);
return this._collectionGroup[collectionGroupName];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Core.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":3,"./Shared":29}],5:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Collection,
Metrics,
Crc,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* The main ForerunnerDB core object.
* @constructor
*/
var Core = function (name) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
callback();
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.ChainReactor');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Crc = _dereq_('./Crc.js');
Core.prototype._isServer = false;
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Core.prototype.crc = Crc;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Core.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Core.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Core.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Core.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Core.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Core.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
/**
* Drops all collections in the database.
* @param {Function=} callback Optional callback method.
*/
Core.prototype.drop = function (callback) {
if (this._state !== 'dropped') {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) {
callback();
}
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
}
return true;
};
module.exports = Core;
},{"./Collection.js":3,"./Crc.js":6,"./Metrics.js":12,"./Overload":24,"./Shared":29}],6:[function(_dereq_,module,exports){
"use strict";
var crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
module.exports = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
},{}],7:[function(_dereq_,module,exports){
"use strict";
var Shared,
Collection,
Core,
CoreInit;
Shared = _dereq_('./Shared');
(function init () {
var Document = function () {
this.init.apply(this, arguments);
};
Document.prototype.init = function (name) {
this._name = name;
this._data = {};
};
Shared.addModule('Document', Document);
Shared.mixin(Document.prototype, 'Mixin.Common');
Shared.mixin(Document.prototype, 'Mixin.Events');
Shared.mixin(Document.prototype, 'Mixin.ChainReactor');
Shared.mixin(Document.prototype, 'Mixin.Constants');
Shared.mixin(Document.prototype, 'Mixin.Triggers');
Collection = _dereq_('./Collection');
Core = Shared.modules.Core;
CoreInit = Shared.modules.Core.prototype.init;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Document.prototype, 'state');
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Core=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Document.prototype, 'db');
/**
* Gets / sets the document name.
* @param {String=} val The name to assign
* @returns {*}
*/
Shared.synthesize(Document.prototype, 'name');
Document.prototype.setData = function (data) {
var i,
$unset;
if (data) {
data = this.decouple(data);
if (this._linked) {
$unset = {};
// Remove keys that don't exist in the new data from the current object
for (i in this._data) {
if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) {
// Check if existing data has key
if (data[i] === undefined) {
// Add property name to those to unset
$unset[i] = 1;
}
}
}
data.$unset = $unset;
// Now update the object with new data
this.updateObject(this._data, data, {});
} else {
// Straight data assignment
this._data = data;
}
}
return this;
};
/**
* Modifies the document. This will update the document with the data held in 'update'.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
Document.prototype.update = function (query, update, options) {
this.updateObject(this._data, update, query, options);
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Document.prototype.updateObject = Collection.prototype.updateObject;
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Document.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Updates a property on an object depending on if the collection is
* currently running data-binding or not.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
Document.prototype._updateProperty = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, val);
if (this.debug()) {
console.log('ForerunnerDB.Document: Setting data-bound document property "' + prop + '" for collection "' + this.name() + '"');
}
} else {
doc[prop] = val;
if (this.debug()) {
console.log('ForerunnerDB.Document: Setting non-data-bound document property "' + prop + '" for collection "' + this.name() + '"');
}
}
};
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
Document.prototype._updateIncrement = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] + val);
} else {
doc[prop] += val;
}
};
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
Document.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) {
if (this._linked) {
window.jQuery.observable(arr).move(indexFrom, indexTo);
if (this.debug()) {
console.log('ForerunnerDB.Document: Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for collection "' + this.name() + '"');
}
} else {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log('ForerunnerDB.Document: Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '" for collection "' + this.name() + '"');
}
}
};
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
Document.prototype._updateSplicePush = function (arr, index, doc) {
if (arr.length > index) {
if (this._linked) {
window.jQuery.observable(arr).insert(index, doc);
} else {
arr.splice(index, 0, doc);
}
} else {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
}
};
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
Document.prototype._updatePush = function (arr, doc) {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
};
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
Document.prototype._updatePull = function (arr, index) {
if (this._linked) {
window.jQuery.observable(arr).remove(index);
} else {
arr.splice(index, 1);
}
};
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
Document.prototype._updateMultiply = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] * val);
} else {
doc[prop] *= val;
}
};
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
Document.prototype._updateRename = function (doc, prop, val) {
var existingVal = doc[prop];
if (this._linked) {
window.jQuery.observable(doc).setProperty(val, existingVal);
window.jQuery.observable(doc).removeProperty(prop);
} else {
doc[val] = existingVal;
delete doc[prop];
}
};
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
Document.prototype._updateUnset = function (doc, prop) {
if (this._linked) {
window.jQuery.observable(doc).removeProperty(prop);
} else {
delete doc[prop];
}
};
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {*} val The property to delete.
* @return {Boolean}
* @private
*/
Document.prototype._updatePop = function (doc, val) {
var index,
updated = false;
if (doc.length > 0) {
if (this._linked) {
if (val === 1) {
index = doc.length - 1;
} else if (val === -1) {
index = 0;
}
if (index > -1) {
window.jQuery.observable(doc).remove(index);
updated = true;
}
} else {
if (val === 1) {
doc.pop();
updated = true;
} else if (val === -1) {
doc.shift();
updated = true;
}
}
}
return updated;
};
Document.prototype.drop = function () {
if (this._state !== 'dropped') {
if (this._db && this._name) {
if (this._db && this._db._document && this._db._document[this._name]) {
this._state = 'dropped';
delete this._db._document[this._name];
delete this._data;
this.emit('drop', this);
return true;
}
}
} else {
return true;
}
return false;
};
// Extend DB to include documents
Core.prototype.init = function () {
CoreInit.apply(this, arguments);
};
Core.prototype.document = function (documentName) {
if (documentName) {
this._document = this._document || {};
this._document[documentName] = this._document[documentName] || new Document(documentName).db(this);
return this._document[documentName];
} else {
// Return an object of document data
return this._document;
}
};
/**
* Returns an array of documents the DB currently has.
* @returns {Array} An array of objects containing details of each document
* the database is currently managing.
*/
Core.prototype.documents = function () {
var arr = [],
i;
for (i in this._document) {
if (this._document.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
Shared.finishModule('Document');
module.exports = Document;
}());
},{"./Collection":3,"./Shared":29}],8:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Collection,
CollectionInit,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* The constructor.
*
* @constructor
*/
var Highchart = function (collection, options) {
this.init.apply(this, arguments);
};
Highchart.prototype.init = function (collection, options) {
this._options = options;
this._selector = window.jQuery(this._options.selector);
if (!this._selector[0]) {
throw('ForerunnerDB.Highchart "' + collection.name() + '": Chart target element does not exist via selector: ' + this._options.selector);
}
this._listeners = {};
this._collection = collection;
// Setup the chart
this._options.series = [];
// Disable attribution on highcharts
options.chartOptions = options.chartOptions || {};
options.chartOptions.credits = false;
// Set the data for the chart
var data,
seriesObj,
chartData;
switch (this._options.type) {
case 'pie':
// Create chart from data
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
// Generate graph data from collection data
data = this._collection.find();
seriesObj = {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)',
style: {
color: (window.Highcharts.theme && window.Highcharts.theme.contrastTextColor) || 'black'
}
}
};
chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField);
window.jQuery.extend(seriesObj, this._options.seriesOptions);
window.jQuery.extend(seriesObj, {
name: this._options.seriesName,
data: chartData
});
this._chart.addSeries(seriesObj, true, true);
break;
case 'line':
case 'area':
case 'column':
case 'bar':
// Generate graph data from collection data
chartData = this.seriesDataFromCollectionData(
this._options.seriesField,
this._options.keyField,
this._options.valField,
this._options.orderBy
);
this._options.chartOptions.xAxis = chartData.xAxis;
this._options.chartOptions.series = chartData.series;
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
break;
default:
throw('ForerunnerDB.Highchart "' + collection.name() + '": Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type);
}
// Hook the collection events to auto-update the chart
this._hookEvents();
};
Shared.addModule('Highchart', Highchart);
Collection = Shared.modules.Collection;
CollectionInit = Collection.prototype.init;
Shared.mixin(Highchart.prototype, 'Mixin.Events');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Highchart.prototype, 'state');
/**
* Generate pie-chart series data from the given collection data array.
* @param data
* @param keyField
* @param valField
* @returns {Array}
*/
Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) {
var graphData = [],
i;
for (i = 0; i < data.length; i++) {
graphData.push([data[i][keyField], data[i][valField]]);
}
return graphData;
};
/**
* Generate line-chart series data from the given collection data array.
* @param seriesField
* @param keyField
* @param valField
* @param orderBy
*/
Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy) {
var data = this._collection.distinct(seriesField),
seriesData = [],
xAxis = {
categories: []
},
seriesName,
query,
dataSearch,
seriesValues,
i, k;
// What we WANT to output:
/*series: [{
name: 'Responses',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}]*/
// Loop keys
for (i = 0; i < data.length; i++) {
seriesName = data[i];
query = {};
query[seriesField] = seriesName;
seriesValues = [];
dataSearch = this._collection.find(query, {
orderBy: orderBy
});
// Loop the keySearch data and grab the value for each item
for (k = 0; k < dataSearch.length; k++) {
xAxis.categories.push(dataSearch[k][keyField]);
seriesValues.push(dataSearch[k][valField]);
}
seriesData.push({
name: seriesName,
data: seriesValues
});
}
return {
xAxis: xAxis,
series: seriesData
};
};
/**
* Hook the events the chart needs to know about from the internal collection.
* @private
*/
Highchart.prototype._hookEvents = function () {
var self = this;
self._collection.on('change', function () { self._changeListener.apply(self, arguments); });
// If the collection is dropped, clean up after ourselves
self._collection.on('drop', function () { self.drop.apply(self, arguments); });
};
/**
* Handles changes to the collection data that the chart is reading from and then
* updates the data in the chart display.
* @private
*/
Highchart.prototype._changeListener = function () {
var self = this;
// Update the series data on the chart
if(typeof self._collection !== 'undefined' && self._chart) {
var data = self._collection.find(),
i;
switch (self._options.type) {
case 'pie':
self._chart.series[0].setData(
self.pieDataFromCollectionData(
data,
self._options.keyField,
self._options.valField
),
true,
true
);
break;
case 'bar':
case 'line':
case 'area':
case 'column':
var seriesData = self.seriesDataFromCollectionData(
self._options.seriesField,
self._options.keyField,
self._options.valField,
self._options.orderBy
);
self._chart.xAxis[0].setCategories(
seriesData.xAxis.categories
);
for (i = 0; i < seriesData.series.length; i++) {
if (self._chart.series[i]) {
// Series exists, set it's data
self._chart.series[i].setData(
seriesData.series[i].data,
true,
true
);
} else {
// Series data does not yet exist, add a new series
self._chart.addSeries(
seriesData.series[i],
true,
true
);
}
}
break;
default:
break;
}
}
};
/**
* Destroys the chart and all internal references.
* @returns {Boolean}
*/
Highchart.prototype.drop = function () {
if (this._state !== 'dropped') {
this._state = 'dropped';
if (this._chart) {
this._chart.destroy();
}
if (this._collection) {
this._collection.off('change', this._changeListener);
this._collection.off('drop', this.drop);
if (this._collection._highcharts) {
delete this._collection._highcharts[this._options.selector];
}
}
delete this._chart;
delete this._options;
delete this._collection;
this.emit('drop', this);
return true;
} else {
return true;
}
};
// Extend collection with highchart init
Collection.prototype.init = function () {
this._highcharts = {};
CollectionInit.apply(this, arguments);
};
/**
* Creates a pie chart from the collection.
* @type {Overload}
*/
Collection.prototype.pieChart = new Overload({
/**
* Chart via options object.
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'pie';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'pie';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {String} seriesName The name of the series to display on the chart.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) {
options = options || {};
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
options.seriesName = seriesName;
// Call the main chart method
this.pieChart(options);
}
});
/**
* Creates a line chart from the collection.
* @type {Overload}
*/
Collection.prototype.lineChart = new Overload({
/**
* Chart via options object.
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'line';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'line';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.lineChart(options);
}
});
/**
* Creates an area chart from the collection.
* @type {Overload}
*/
Collection.prototype.areaChart = new Overload({
/**
* Chart via options object.
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'area';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'area';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.areaChart(options);
}
});
/**
* Creates a column chart from the collection.
* @type {Overload}
*/
Collection.prototype.columnChart = new Overload({
/**
* Chart via options object.
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'column';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'column';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.columnChart(options);
}
});
/**
* Creates a bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.barChart = new Overload({
/**
* Chart via options object.
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.barChart(options);
}
});
/**
* Creates a stacked bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.stackedBarChart = new Overload({
/**
* Chart via options object.
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
options.plotOptions = options.plotOptions || {};
options.plotOptions.series = options.plotOptions.series || {};
options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.stackedBarChart(options);
}
});
/**
* Removes a chart from the page by it's selector.
* @param {String} selector The chart selector.
*/
Collection.prototype.dropChart = function (selector) {
if (this._highcharts && this._highcharts[selector]) {
this._highcharts[selector].drop();
}
};
Shared.finishModule('Highchart');
module.exports = Highchart;
},{"./Overload":24,"./Shared":29}],9:[function(_dereq_,module,exports){
"use strict";
/*
name
id
rebuild
state
match
lookup
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
btree = function () {};
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new (btree.create(2, this.sortAsc))();
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree = new (btree.create(2, this.sortAsc))();
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// We store multiple items that match a key inside an array
// that is then stored against that key in the tree...
// Check if item exists for this key already
keyArr = this._btree.get(dataItemHash);
// Check if the array exists
if (keyArr === undefined) {
// Generate an array for this key first
keyArr = [];
// Put the new array into the tree under the key
this._btree.put(dataItemHash, keyArr);
}
// Push the item into the array
keyArr.push(dataItem);
this._size++;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr,
itemIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Try and get the array for the item hash key
keyArr = this._btree.get(dataItemHash);
if (keyArr !== undefined) {
// The key array exits, remove the item from the key array
itemIndex = keyArr.indexOf(dataItem);
if (itemIndex > -1) {
// Check the length of the array
if (keyArr.length === 1) {
// This item is the last in the array, just kill the tree entry
this._btree.del(dataItemHash);
} else {
// Remove the item
keyArr.splice(itemIndex, 1);
}
this._size--;
}
}
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexBinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./Path":26,"./Shared":29}],10:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":26,"./Shared":29}],11:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} obj A lookup query, can be a string key, an array of string keys,
* an object with further query clauses or a regular expression that should be
* run against all keys.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (obj) {
var pKeyVal = obj[this._primaryKey],
arrIndex,
arrCount,
lookupItem,
result;
if (pKeyVal instanceof Array) {
// An array of primary keys, find all matches
arrCount = pKeyVal.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this._data[pKeyVal[arrIndex]];
if (lookupItem) {
result.push(lookupItem);
}
}
return result;
} else if (pKeyVal instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.test(arrIndex)) {
result.push(this._data[arrIndex]);
}
}
}
return result;
} else if (typeof pKeyVal === 'object') {
// The primary key clause is an object, now we have to do some
// more extensive searching
if (pKeyVal.$ne) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (arrIndex !== pKeyVal.$ne) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$in.indexOf(arrIndex) > -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$nin.indexOf(arrIndex) === -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) {
result = result.concat(this.lookup(pKeyVal.$or[arrIndex]));
}
return result;
}
} else {
// Key is a basic lookup from string
lookupItem = this._data[pKeyVal];
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
}
};
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":29}],12:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":23,"./Shared":29}],13:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],14:[function(_dereq_,module,exports){
"use strict";
// TODO: Document the methods in this mixin
var ChainReactor = {
chain: function (obj) {
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arr[index].chainReceive(this, type, data, options);
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],15:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Common;
Common = {
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined) {
if (!copies) {
return JSON.parse(JSON.stringify(data));
} else {
var i,
json = JSON.stringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(JSON.parse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
])
};
module.exports = Common;
},{"./Overload":24}],16:[function(_dereq_,module,exports){
"use strict";
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],17:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount;
// Handle global emit
if (this._listeners[event]['*']) {
var arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
var listenerIdArr = this._listeners[event],
listenerIdCount,
listenerIdIndex;
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
return this;
}
};
module.exports = Events;
},{"./Overload":24}],18:[function(_dereq_,module,exports){
"use strict";
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (typeof(source) === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (inArr[inArrIndex] === source) {
return true;
}
}
return false;
} else {
throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use an $in operator on a non-array key: ' + key);
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (notInArr[notInArrIndex] === source) {
return false;
}
}
return true;
} else {
throw('ForerunnerDB.Mixin.Matching "' + this.name() + '": Cannot use a $nin operator on a non-array key: ' + key);
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootQuery['//distinctLookup'] = options.$rootQuery['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootQuery['//distinctLookup'][distinctProp] = options.$rootQuery['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootQuery['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootQuery['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
}
return -1;
}
};
module.exports = Matching;
},{}],19:[function(_dereq_,module,exports){
"use strict";
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var Triggers = {
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Number} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {Function} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger does not exist, create it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
return this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{}],21:[function(_dereq_,module,exports){
"use strict";
// Grab the view class
var Shared,
Core,
OldView,
OldViewInit;
Shared = _dereq_('./Shared');
Core = Shared.modules.Core;
OldView = Shared.modules.OldView;
OldViewInit = OldView.prototype.init;
OldView.prototype.init = function () {
var self = this;
this._binds = [];
this._renderStart = 0;
this._renderEnd = 0;
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: [],
_bindInsert: [],
_bindUpdate: [],
_bindRemove: [],
_bindUpsert: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100,
_bindInsert: 100,
_bindUpdate: 100,
_bindRemove: 100,
_bindUpsert: 100
};
this._deferTime = {
insert: 100,
update: 1,
remove: 1,
upsert: 1,
_bindInsert: 100,
_bindUpdate: 1,
_bindRemove: 1,
_bindUpsert: 1
};
OldViewInit.apply(this, arguments);
// Hook view events to update binds
this.on('insert', function (successArr, failArr) {
self._bindEvent('insert', successArr, failArr);
});
this.on('update', function (successArr, failArr) {
self._bindEvent('update', successArr, failArr);
});
this.on('remove', function (successArr, failArr) {
self._bindEvent('remove', successArr, failArr);
});
this.on('change', self._bindChange);
};
/**
* Binds a selector to the insert, update and delete events of a particular
* view and keeps the selector in sync so that updates are reflected on the
* web page in real-time.
*
* @param {String} selector The jQuery selector string to get target elements.
* @param {Object} options The options object.
*/
OldView.prototype.bind = function (selector, options) {
if (options && options.template) {
this._binds[selector] = options;
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Cannot bind data to element, missing options information!');
}
return this;
};
/**
* Un-binds a selector from the view changes.
* @param {String} selector The jQuery selector string to identify the bind to remove.
* @returns {Collection}
*/
OldView.prototype.unBind = function (selector) {
delete this._binds[selector];
return this;
};
/**
* Returns true if the selector is bound to the view.
* @param {String} selector The jQuery selector string to identify the bind to check for.
* @returns {boolean}
*/
OldView.prototype.isBound = function (selector) {
return Boolean(this._binds[selector]);
};
/**
* Sorts items in the DOM based on the bind settings and the passed item array.
* @param {String} selector The jQuery selector of the bind container.
* @param {Array} itemArr The array of items used to determine the order the DOM
* elements should be in based on the order they are in, in the array.
*/
OldView.prototype.bindSortDom = function (selector, itemArr) {
var container = window.jQuery(selector),
arrIndex,
arrItem,
domItem;
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sorting data in DOM...', itemArr);
}
for (arrIndex = 0; arrIndex < itemArr.length; arrIndex++) {
arrItem = itemArr[arrIndex];
// Now we've done our inserts into the DOM, let's ensure
// they are still ordered correctly
domItem = container.find('#' + arrItem[this._primaryKey]);
if (domItem.length) {
if (arrIndex === 0) {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sort, moving to index 0...', domItem);
}
container.prepend(domItem);
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sort, moving to index ' + arrIndex + '...', domItem);
}
domItem.insertAfter(container.children(':eq(' + (arrIndex - 1) + ')'));
}
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Warning, element for array item not found!', arrItem);
}
}
}
};
OldView.prototype.bindRefresh = function (obj) {
var binds = this._binds,
bindKey,
bind;
if (!obj) {
// Grab current data
obj = {
data: this.find()
};
}
for (bindKey in binds) {
if (binds.hasOwnProperty(bindKey)) {
bind = binds[bindKey];
if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting DOM...'); }
this.bindSortDom(bindKey, obj.data);
if (bind.afterOperation) {
bind.afterOperation();
}
if (bind.refresh) {
bind.refresh();
}
}
}
};
/**
* Renders a bind view data to the DOM.
* @param {String} bindSelector The jQuery selector string to use to identify
* the bind target. Must match the selector used when defining the original bind.
* @param {Function=} domHandler If specified, this handler method will be called
* with the final HTML for the view instead of the DB handling the DOM insertion.
*/
OldView.prototype.bindRender = function (bindSelector, domHandler) {
// Check the bind exists
var bind = this._binds[bindSelector],
domTarget = window.jQuery(bindSelector),
allData,
dataItem,
itemHtml,
finalHtml = window.jQuery('<ul></ul>'),
bindCallback,
i;
if (bind) {
allData = this._data.find();
bindCallback = function (itemHtml) {
finalHtml.append(itemHtml);
};
// Loop all items and add them to the screen
for (i = 0; i < allData.length; i++) {
dataItem = allData[i];
itemHtml = bind.template(dataItem, bindCallback);
}
if (!domHandler) {
domTarget.append(finalHtml.html());
} else {
domHandler(bindSelector, finalHtml.html());
}
}
};
OldView.prototype.processQueue = function (type, callback) {
var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];
if (queue.length) {
var self = this,
dataArr;
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
this._bindEvent(type, dataArr, []);
}
// Queue another process
setTimeout(function () {
self.processQueue(type, callback);
}, deferTime);
} else {
if (callback) { callback(); }
this.emit('bindQueueComplete');
}
};
OldView.prototype._bindEvent = function (type, successArr, failArr) {
/*var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];*/
var binds = this._binds,
unfilteredDataSet = this.find({}),
filteredDataSet,
bindKey;
// Check if the number of inserts is greater than the defer threshold
/*if (successArr && successArr.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue[type] = queue.concat(successArr);
// Fire off the insert queue handler
this.processQueue(type);
return;
} else {*/
for (bindKey in binds) {
if (binds.hasOwnProperty(bindKey)) {
if (binds[bindKey].reduce) {
filteredDataSet = this.find(binds[bindKey].reduce.query, binds[bindKey].reduce.options);
} else {
filteredDataSet = unfilteredDataSet;
}
switch (type) {
case 'insert':
this._bindInsert(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
case 'update':
this._bindUpdate(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
case 'remove':
this._bindRemove(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
}
}
}
//}
};
OldView.prototype._bindChange = function (newDataArr) {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...', newDataArr);
}
this.bindRefresh(newDataArr);
};
OldView.prototype._bindInsert = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
itemHtml,
makeCallback,
i;
makeCallback = function (itemElem, insertedItem, failArr, all) {
return function (itemHtml) {
// Check if there is custom DOM insert method
if (options.insert) {
options.insert(itemHtml, insertedItem, failArr, all);
} else {
// Handle the insert automatically
// Add the item to the container
if (options.prependInsert) {
container.prepend(itemHtml);
} else {
container.append(itemHtml);
}
}
if (options.afterInsert) {
options.afterInsert(itemHtml, insertedItem, failArr, all);
}
};
};
// Loop the inserted items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
if (!itemElem.length) {
itemHtml = options.template(successArr[i], makeCallback(itemElem, successArr[i], failArr, all));
}
}
};
OldView.prototype._bindUpdate = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
makeCallback,
i;
makeCallback = function (itemElem, itemData) {
return function (itemHtml) {
// Check if there is custom DOM insert method
if (options.update) {
options.update(itemHtml, itemData, all, itemElem.length ? 'update' : 'append');
} else {
if (itemElem.length) {
// An existing item is in the container, replace it with the
// new rendered item from the updated data
itemElem.replaceWith(itemHtml);
} else {
// The item element does not already exist, append it
if (options.prependUpdate) {
container.prepend(itemHtml);
} else {
container.append(itemHtml);
}
}
}
if (options.afterUpdate) {
options.afterUpdate(itemHtml, itemData, all);
}
};
};
// Loop the updated items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
options.template(successArr[i], makeCallback(itemElem, successArr[i]));
}
};
OldView.prototype._bindRemove = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
makeCallback,
i;
makeCallback = function (itemElem, data, all) {
return function () {
if (options.remove) {
options.remove(itemElem, data, all);
} else {
itemElem.remove();
if (options.afterRemove) {
options.afterRemove(itemElem, data, all);
}
}
};
};
// Loop the removed items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
if (itemElem.length) {
if (options.beforeRemove) {
options.beforeRemove(itemElem, successArr[i], all, makeCallback(itemElem, successArr[i], all));
} else {
if (options.remove) {
options.remove(itemElem, successArr[i], all);
} else {
itemElem.remove();
if (options.afterRemove) {
options.afterRemove(itemElem, successArr[i], all);
}
}
}
}
}
};
},{"./Shared":29}],22:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Core,
CollectionGroup,
Collection,
CollectionInit,
CollectionGroupInit,
CoreInit;
Shared = _dereq_('./Shared');
/**
* The view constructor.
* @param viewName
* @constructor
*/
var OldView = function (viewName) {
this.init.apply(this, arguments);
};
OldView.prototype.init = function (viewName) {
var self = this;
this._name = viewName;
this._listeners = {};
this._query = {
query: {},
options: {}
};
// Register listeners for the CRUD events
this._onFromSetData = function () {
self._onSetData.apply(self, arguments);
};
this._onFromInsert = function () {
self._onInsert.apply(self, arguments);
};
this._onFromUpdate = function () {
self._onUpdate.apply(self, arguments);
};
this._onFromRemove = function () {
self._onRemove.apply(self, arguments);
};
this._onFromChange = function () {
if (self.debug()) { console.log('ForerunnerDB.OldView: Received change'); }
self._onChange.apply(self, arguments);
};
};
Shared.addModule('OldView', OldView);
CollectionGroup = _dereq_('./CollectionGroup');
Collection = _dereq_('./Collection');
CollectionInit = Collection.prototype.init;
CollectionGroupInit = CollectionGroup.prototype.init;
Core = Shared.modules.Core;
CoreInit = Core.prototype.init;
Shared.mixin(OldView.prototype, 'Mixin.Events');
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
OldView.prototype.drop = function () {
if ((this._db || this._from) && this._name) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Dropping view ' + this._name);
}
this._state = 'dropped';
this.emit('drop', this);
if (this._db && this._db._oldViews) {
delete this._db._oldViews[this._name];
}
if (this._from && this._from._oldViews) {
delete this._from._oldViews[this._name];
}
return true;
}
return false;
};
OldView.prototype.debug = function () {
// TODO: Make this function work
return false;
};
/**
* Gets / sets the DB the view is bound against. Automatically set
* when the db.oldView(viewName) method is called.
* @param db
* @returns {*}
*/
OldView.prototype.db = function (db) {
if (db !== undefined) {
this._db = db;
return this;
}
return this._db;
};
/**
* Gets / sets the collection that the view derives it's data from.
* @param {*} collection A collection instance or the name of a collection
* to use as the data set to derive view data from.
* @returns {*}
*/
OldView.prototype.from = function (collection) {
if (collection !== undefined) {
// Check if this is a collection name or a collection instance
if (typeof(collection) === 'string') {
if (this._db.collectionExists(collection)) {
collection = this._db.collection(collection);
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Invalid collection in view.from() call.');
}
}
// Check if the existing from matches the passed one
if (this._from !== collection) {
// Check if we already have a collection assigned
if (this._from) {
// Remove ourselves from the collection view lookup
this.removeFrom();
}
this.addFrom(collection);
}
return this;
}
return this._from;
};
OldView.prototype.addFrom = function (collection) {
//var self = this;
this._from = collection;
if (this._from) {
this._from.on('setData', this._onFromSetData);
//this._from.on('insert', this._onFromInsert);
//this._from.on('update', this._onFromUpdate);
//this._from.on('remove', this._onFromRemove);
this._from.on('change', this._onFromChange);
// Add this view to the collection's view lookup
this._from._addOldView(this);
this._primaryKey = this._from._primaryKey;
this.refresh();
return this;
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Cannot determine collection type in view.from()');
}
};
OldView.prototype.removeFrom = function () {
// Unsubscribe from events on this "from"
this._from.off('setData', this._onFromSetData);
//this._from.off('insert', this._onFromInsert);
//this._from.off('update', this._onFromUpdate);
//this._from.off('remove', this._onFromRemove);
this._from.off('change', this._onFromChange);
this._from._removeOldView(this);
};
/**
* Gets the primary key for this view from the assigned collection.
* @returns {String}
*/
OldView.prototype.primaryKey = function () {
if (this._from) {
return this._from.primaryKey();
}
return undefined;
};
/**
* Gets / sets the query that the view uses to build it's data set.
* @param {Object=} query
* @param {Boolean=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._query.query = query;
}
if (options !== undefined) {
this._query.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
OldView.prototype.queryAdd = function (obj, overwrite, refresh) {
var query = this._query.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
OldView.prototype.queryRemove = function (obj, refresh) {
var query = this._query.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Gets / sets the query being used to generate the view data.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.query = function (query, refresh) {
if (query !== undefined) {
this._query.query = query;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query.query;
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._query.options = options;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query.options;
};
/**
* Refreshes the view data and diffs between previous and new data to
* determine if any events need to be triggered or DOM binds updated.
*/
OldView.prototype.refresh = function (force) {
if (this._from) {
// Take a copy of the data before updating it, we will use this to
// "diff" between the old and new data and handle DOM bind updates
var oldData = this._data,
oldDataArr,
oldDataItem,
newData,
newDataArr,
query,
primaryKey,
dataItem,
inserted = [],
updated = [],
removed = [],
operated = false,
i;
if (this.debug()) {
console.log('ForerunnerDB.OldView: Refreshing view ' + this._name);
console.log('ForerunnerDB.OldView: Existing data: ' + (typeof(this._data) !== "undefined"));
if (typeof(this._data) !== "undefined") {
console.log('ForerunnerDB.OldView: Current data rows: ' + this._data.find().length);
}
//console.log(OldView.prototype.refresh.caller);
}
// Query the collection and update the data
if (this._query) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has query and options, getting subset...');
}
// Run query against collection
//console.log('refresh with query and options', this._query.options);
this._data = this._from.subset(this._query.query, this._query.options);
//console.log(this._data);
} else {
// No query, return whole collection
if (this._query.options) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has options, getting subset...');
}
this._data = this._from.subset({}, this._query.options);
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has no query or options, getting subset...');
}
this._data = this._from.subset({});
}
}
// Check if there was old data
if (!force && oldData) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Refresh not forced, old data detected...');
}
// Now determine the difference
newData = this._data;
if (oldData.subsetOf() === newData.subsetOf()) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Old and new data are from same collection...');
}
newDataArr = newData.find();
oldDataArr = oldData.find();
primaryKey = newData._primaryKey;
// The old data and new data were derived from the same parent collection
// so scan the data to determine changes
for (i = 0; i < newDataArr.length; i++) {
dataItem = newDataArr[i];
query = {};
query[primaryKey] = dataItem[primaryKey];
// Check if this item exists in the old data
oldDataItem = oldData.find(query)[0];
if (!oldDataItem) {
// New item detected
inserted.push(dataItem);
} else {
// Check if an update has occurred
if (JSON.stringify(oldDataItem) !== JSON.stringify(dataItem)) {
// Updated / already included item detected
updated.push(dataItem);
}
}
}
// Now loop the old data and check if any records were removed
for (i = 0; i < oldDataArr.length; i++) {
dataItem = oldDataArr[i];
query = {};
query[primaryKey] = dataItem[primaryKey];
// Check if this item exists in the old data
if (!newData.find(query)[0]) {
// Removed item detected
removed.push(dataItem);
}
}
if (this.debug()) {
console.log('ForerunnerDB.OldView: Removed ' + removed.length + ' rows');
console.log('ForerunnerDB.OldView: Inserted ' + inserted.length + ' rows');
console.log('ForerunnerDB.OldView: Updated ' + updated.length + ' rows');
}
// Now we have a diff of the two data sets, we need to get the DOM updated
if (inserted.length) {
this._onInsert(inserted, []);
operated = true;
}
if (updated.length) {
this._onUpdate(updated, []);
operated = true;
}
if (removed.length) {
this._onRemove(removed, []);
operated = true;
}
} else {
// The previous data and the new data are derived from different collections
// and can therefore not be compared, all data is therefore effectively "new"
// so first perform a remove of all existing data then do an insert on all new data
if (this.debug()) {
console.log('ForerunnerDB.OldView: Old and new data are from different collections...');
}
removed = oldData.find();
if (removed.length) {
this._onRemove(removed);
operated = true;
}
inserted = newData.find();
if (inserted.length) {
this._onInsert(inserted);
operated = true;
}
}
} else {
// Force an update as if the view never got created by padding all elements
// to the insert
if (this.debug()) {
console.log('ForerunnerDB.OldView: Forcing data update', newDataArr);
}
this._data = this._from.subset(this._query.query, this._query.options);
newDataArr = this._data.find();
if (this.debug()) {
console.log('ForerunnerDB.OldView: Emitting change event with data', newDataArr);
}
this._onInsert(newDataArr, []);
}
if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change'); }
this.emit('change');
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
OldView.prototype.count = function () {
return this._data && this._data._data ? this._data._data.length : 0;
};
/**
* Queries the view data. See Collection.find() for more information.
* @returns {*}
*/
OldView.prototype.find = function () {
if (this._data) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Finding data in view collection...', this._data);
}
return this._data.find.apply(this._data, arguments);
} else {
return [];
}
};
/**
* Inserts into view data via the view collection. See Collection.insert() for more information.
* @returns {*}
*/
OldView.prototype.insert = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.insert.apply(this._from, arguments);
} else {
return [];
}
};
/**
* Updates into view data via the view collection. See Collection.update() for more information.
* @returns {*}
*/
OldView.prototype.update = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.update.apply(this._from, arguments);
} else {
return [];
}
};
/**
* Removed from view data via the view collection. See Collection.remove() for more information.
* @returns {*}
*/
OldView.prototype.remove = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.remove.apply(this._from, arguments);
} else {
return [];
}
};
OldView.prototype._onSetData = function (newDataArr, oldDataArr) {
this.emit('remove', oldDataArr, []);
this.emit('insert', newDataArr, []);
//this.refresh();
};
OldView.prototype._onInsert = function (successArr, failArr) {
this.emit('insert', successArr, failArr);
//this.refresh();
};
OldView.prototype._onUpdate = function (successArr, failArr) {
this.emit('update', successArr, failArr);
//this.refresh();
};
OldView.prototype._onRemove = function (successArr, failArr) {
this.emit('remove', successArr, failArr);
//this.refresh();
};
OldView.prototype._onChange = function () {
if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing data'); }
this.refresh();
};
// Extend collection with view init
Collection.prototype.init = function () {
this._oldViews = [];
CollectionInit.apply(this, arguments);
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addOldView = function (view) {
if (view !== undefined) {
this._oldViews[view._name] = view;
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeOldView = function (view) {
if (view !== undefined) {
delete this._oldViews[view._name];
}
return this;
};
// Extend collection with view init
CollectionGroup.prototype.init = function () {
this._oldViews = [];
CollectionGroupInit.apply(this, arguments);
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
CollectionGroup.prototype._addOldView = function (view) {
if (view !== undefined) {
this._oldViews[view._name] = view;
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
CollectionGroup.prototype._removeOldView = function (view) {
if (view !== undefined) {
delete this._oldViews[view._name];
}
return this;
};
// Extend DB with views init
Core.prototype.init = function () {
this._oldViews = {};
CoreInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Core.prototype.oldView = function (viewName) {
if (!this._oldViews[viewName]) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Creating view ' + viewName);
}
}
this._oldViews[viewName] = this._oldViews[viewName] || new OldView(viewName).db(this);
return this._oldViews[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Core.prototype.oldViewExists = function (viewName) {
return Boolean(this._oldViews[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Core.prototype.oldViews = function () {
var arr = [],
i;
for (i in this._oldViews) {
if (this._oldViews.hasOwnProperty(i)) {
arr.push({
name: i,
count: this._oldViews[i].count()
});
}
}
return arr;
};
Shared.finishModule('OldView');
module.exports = OldView;
},{"./Collection":3,"./CollectionGroup":4,"./Shared":29}],23:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":26,"./Shared":29}],24:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {Object} def
* @returns {Function}
* @constructor
*/
var Overload = function (def) {
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
throw('ForerunnerDB.Overload "' + this.name() + '": Overloaded method does not have a matching signature for the passed arguments: ' + JSON.stringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],25:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Core,
CoreInit,
Collection,
DbDocument;
Shared = _dereq_('./Shared');
var Overview = function () {
this.init.apply(this, arguments);
};
Overview.prototype.init = function (name) {
var self = this;
this._name = name;
this._data = new DbDocument('__FDB__dc_data_' + this._name);
this._collData = new Collection();
this._collections = [];
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
};
Shared.addModule('Overview', Overview);
Shared.mixin(Overview.prototype, 'Mixin.Common');
Shared.mixin(Overview.prototype, 'Mixin.ChainReactor');
Shared.mixin(Overview.prototype, 'Mixin.Constants');
Shared.mixin(Overview.prototype, 'Mixin.Triggers');
Shared.mixin(Overview.prototype, 'Mixin.Events');
Collection = _dereq_('./Collection');
DbDocument = _dereq_('./Document');
Core = Shared.modules.Core;
CoreInit = Core.prototype.init;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Overview.prototype, 'state');
Shared.synthesize(Overview.prototype, 'db');
Shared.synthesize(Overview.prototype, 'name');
Shared.synthesize(Overview.prototype, 'query', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'queryOptions', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'reduce', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Overview.prototype.from = function (collection) {
if (collection !== undefined) {
if (typeof(collection) === 'string') {
collection = this._db.collection(collection);
}
this._addCollection(collection);
return this;
}
return this._collections;
};
Overview.prototype.find = function () {
return this._collData.find.apply(this._collData, arguments);
};
Overview.prototype.count = function () {
return this._collData.count.apply(this._collData, arguments);
};
Overview.prototype._addCollection = function (collection) {
if (this._collections.indexOf(collection) === -1) {
this._collections.push(collection);
collection.chain(this);
collection.on('drop', this._collectionDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._removeCollection = function (collection) {
var collectionIndex = this._collections.indexOf(collection);
if (collectionIndex > -1) {
this._collections.splice(collection, 1);
collection.unChain(this);
collection.off('drop', this._collectionDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from overview
this._removeCollection(collection);
}
};
Overview.prototype._refresh = function () {
if (this._state !== 'dropped') {
if (this._collections && this._collections[0]) {
this._collData.primaryKey(this._collections[0].primaryKey());
var tempArr = [],
i;
for (i = 0; i < this._collections.length; i++) {
tempArr = tempArr.concat(this._collections[i].find(this._query, this._queryOptions));
}
this._collData.setData(tempArr);
}
// Now execute the reduce method
if (this._reduce) {
var reducedData = this._reduce();
// Update the document with the newly returned data
this._data.setData(reducedData);
}
}
};
Overview.prototype._chainHandler = function (chainPacket) {
switch (chainPacket.type) {
case 'setData':
case 'insert':
case 'update':
case 'remove':
this._refresh();
break;
default:
break;
}
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
Overview.prototype.data = function () {
return this._data;
};
Overview.prototype.drop = function () {
if (this._state !== 'dropped') {
this._state = 'dropped';
delete this._data;
delete this._collData;
// Remove all collection references
while (this._collections.length) {
this._removeCollection(this._collections[0]);
}
delete this._collections;
if (this._db && this._name) {
delete this._db._overview[this._name];
}
delete this._name;
this.emit('drop', this);
}
return true;
};
// Extend DB to include collection groups
Core.prototype.init = function () {
this._overview = {};
CoreInit.apply(this, arguments);
};
Core.prototype.overview = function (overviewName) {
if (overviewName) {
this._overview[overviewName] = this._overview[overviewName] || new Overview(overviewName).db(this);
return this._overview[overviewName];
} else {
// Return an object of collection data
return this._overview;
}
};
Shared.finishModule('Overview');
module.exports = Overview;
},{"./Collection":3,"./Document":7,"./Shared":29}],26:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path) {
if (obj !== undefined && typeof obj === 'object') {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr = [],
i, k;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i]));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":29}],27:[function(_dereq_,module,exports){
"use strict";
// TODO: Add doc comments to this class
// Import external names locally
var Shared = _dereq_('./Shared'),
localforage = _dereq_('localforage'),
Core,
Collection,
CollectionDrop,
CollectionGroup,
CollectionInit,
CoreInit,
Persist,
Overload;
Persist = function () {
this.init.apply(this, arguments);
};
Persist.prototype.init = function (db) {
// Check environment
if (db.isClient()) {
if (window.Storage !== undefined) {
this.mode('localforage');
localforage.config({
driver: [
localforage.INDEXEDDB,
localforage.WEBSQL,
localforage.LOCALSTORAGE
],
name: 'ForerunnerDB',
storeName: 'FDB'
});
}
}
};
Shared.addModule('Persist', Persist);
Shared.mixin(Persist.prototype, 'Mixin.ChainReactor');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection');
CollectionDrop = Collection.prototype.drop;
CollectionGroup = _dereq_('./CollectionGroup');
CollectionInit = Collection.prototype.init;
CoreInit = Core.prototype.init;
Overload = Shared.overload;
Persist.prototype.mode = function (type) {
if (type !== undefined) {
this._mode = type;
return this;
}
return this._mode;
};
Persist.prototype.driver = function (val) {
if (val !== undefined) {
switch (val.toUpperCase()) {
case 'LOCALSTORAGE':
localforage.setDriver(localforage.LOCALSTORAGE);
break;
case 'WEBSQL':
localforage.setDriver(localforage.WEBSQL);
break;
case 'INDEXEDDB':
localforage.setDriver(localforage.INDEXEDDB);
break;
default:
throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!');
}
return this;
}
return localforage.driver();
};
Persist.prototype.save = function (key, data, callback) {
var encode;
encode = function (val, finished) {
if (typeof val === 'object') {
val = 'json::fdb::' + JSON.stringify(val);
} else {
val = 'raw::fdb::' + val;
}
if (finished) {
finished(false, val);
}
};
switch (this.mode()) {
case 'localforage':
encode(data, function (err, data) {
localforage.setItem(key, data).then(function (data) {
callback(false, data);
}, function (err) {
callback(err);
});
});
break;
default:
if (callback) {
callback('No data handler.');
}
break;
}
};
Persist.prototype.load = function (key, callback) {
var parts,
data,
decode;
decode = function (val, finished) {
if (val) {
parts = val.split('::fdb::');
switch (parts[0]) {
case 'json':
data = JSON.parse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
if (finished) {
finished(false, data);
}
} else {
finished(false, val);
}
};
switch (this.mode()) {
case 'localforage':
localforage.getItem(key).then(function (val) {
decode(val, callback);
}, function (err) {
callback(err);
});
break;
default:
if (callback) {
callback('No data handler or unrecognised data type.');
}
break;
}
};
Persist.prototype.drop = function (key, callback) {
switch (this.mode()) {
case 'localforage':
localforage.removeItem(key).then(function () {
callback(false);
}, function (err) {
callback(err);
});
break;
default:
if (callback) {
callback('No data handler or unrecognised data type.');
}
break;
}
};
// Extend the Collection prototype with persist methods
Collection.prototype.drop = new Overload({
/**
* Drop collection and persistent storage.
*/
'': function () {
if (this._state !== 'dropped') {
this.drop(true);
}
},
/**
* Drop collection and persistent storage with callback.
* @param {Function} callback Callback method.
*/
'function': function (callback) {
if (this._state !== 'dropped') {
this.drop(true, callback);
}
},
/**
* Drop collection and optionally drop persistent storage.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
*/
'boolean': function (removePersistent) {
if (this._state !== 'dropped') {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Save the collection data
this._db.persist.drop(this._name);
} else {
throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when the collection is not attached to a database!');
}
} else {
throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!');
}
}
// Call the original method
CollectionDrop.apply(this, arguments);
}
},
/**
* Drop collections and optionally drop persistent storage with callback.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
* @param {Function} callback Callback method.
*/
'boolean, function': function (removePersistent, callback) {
if (this._state !== 'dropped') {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Save the collection data
this._db.persist.drop(this._name, callback);
} else {
if (callback) {
callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!');
}
}
} else {
if (callback) {
callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!');
}
}
}
// Call the original method
CollectionDrop.apply(this, arguments);
}
}
});
Collection.prototype.save = function (callback) {
if (this._name) {
if (this._db) {
// Save the collection data
this._db.persist.save(this._name, this._data, callback);
} else {
if (callback) {
callback('Cannot save a collection that is not attached to a database!');
}
}
} else {
if (callback) {
callback('Cannot save a collection with no assigned name!');
}
}
};
Collection.prototype.load = function (callback) {
var self = this;
if (this._name) {
if (this._db) {
// Load the collection data
this._db.persist.load(this._name, function (err, data) {
if (!err) {
if (data) {
self.setData(data);
}
if (callback) {
callback(false);
}
} else {
if (callback) {
callback(err);
}
}
});
} else {
if (callback) {
callback('Cannot load a collection that is not attached to a database!');
}
}
} else {
if (callback) {
callback('Cannot load a collection with no assigned name!');
}
}
};
// Override the DB init to instantiate the plugin
Core.prototype.init = function () {
this.persist = new Persist(this);
CoreInit.apply(this, arguments);
};
Core.prototype.load = function (callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
loadCallback,
index;
loadCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
callback(false);
}
} else {
callback(err);
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection load method
obj[index].load(loadCallback);
}
}
};
Core.prototype.save = function (callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
saveCallback,
index;
saveCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
callback(false);
}
} else {
callback(err);
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection save method
obj[index].save(saveCallback);
}
}
};
Shared.finishModule('Persist');
module.exports = Persist;
},{"./Collection":3,"./CollectionGroup":4,"./Shared":29,"localforage":38}],28:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain || !reactorOut.chainReceive) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
ReactorIO.prototype.drop = function () {
if (this._state !== 'dropped') {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":29}],29:[function(_dereq_,module,exports){
"use strict";
var Shared = {
version: '1.3.29',
modules: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
this.modules[name] = module;
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
this.modules[name]._fdbFinished = true;
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
callback(name, this.modules[name]);
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
/**
* Adds the properties and methods defined in the mixin to the passed object.
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
mixin: function (obj, mixinName) {
var system = this.mixins[mixinName];
if (system) {
for (var i in system) {
if (system.hasOwnProperty(i)) {
obj[i] = system[i];
}
}
} else {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
},
/**
* Generates a generic getter/setter method for the passed method name.
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @param arr
* @returns {Function}
* @constructor
*/
overload: _dereq_('./Overload'),
/**
* Define the mixins that other modules can use as required.
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":13,"./Mixin.ChainReactor":14,"./Mixin.Common":15,"./Mixin.Constants":16,"./Mixin.Events":17,"./Mixin.Matching":18,"./Mixin.Sorting":19,"./Mixin.Triggers":20,"./Overload":24}],30:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Core,
Collection,
CollectionGroup,
CollectionInit,
CoreInit,
ReactorIO,
ActiveBucket;
Shared = _dereq_('./Shared');
/**
* The view constructor.
* @param name
* @param query
* @param options
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
View.prototype.init = function (name, query, options) {
var self = this;
this._name = name;
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, false);
this.queryOptions(options, false);
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
this._privateData = new Collection('__FDB__view_privateData_' + this._name);
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.ChainReactor');
Shared.mixin(View.prototype, 'Mixin.Constants');
Shared.mixin(View.prototype, 'Mixin.Triggers');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
ActiveBucket = _dereq_('./ActiveBucket');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Core = Shared.modules.Core;
CoreInit = Core.prototype.init;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'state');
Shared.synthesize(View.prototype, 'name');
/**
* Executes an insert against the view's underlying data-source.
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data. See Collection.find() for more information.
* @returns {*}
*/
View.prototype.find = function (query, options) {
return this.publicData().find(query, options);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._privateData;
};
/**
* Sets the collection from which the view will assemble its data.
* @param {Collection} collection The collection to use to assemble view data.
* @returns {View}
*/
View.prototype.from = function (collection) {
var self = this;
if (collection !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
delete this._from;
}
if (typeof(collection) === 'string') {
collection = this._db.collection(collection);
}
this._from = collection;
this._from.on('drop', this._collectionDroppedWrap);
// Create a new reactor IO graph node that intercepts chain packets from the
// view's "from" collection and determines how they should be interpreted by
// this view. If the view does not have a query then this reactor IO will
// simply pass along the chain packet without modifying it.
this._io = new ReactorIO(collection, this, function (chainPacket) {
var data,
diff,
query,
filteredData,
doSend,
pk,
i;
// Check if we have a constraining query
if (self._querySettings.query) {
if (chainPacket.type === 'insert') {
data = chainPacket.data;
// Check if the data matches our query
if (data instanceof Array) {
filteredData = [];
for (i = 0; i < data.length; i++) {
if (self._privateData._match(data[i], self._querySettings.query, 'and', {})) {
filteredData.push(data[i]);
doSend = true;
}
}
} else {
if (self._privateData._match(data, self._querySettings.query, 'and', {})) {
filteredData = data;
doSend = true;
}
}
if (doSend) {
this.chainSend('insert', filteredData);
}
return true;
}
if (chainPacket.type === 'update') {
// Do a DB diff between this view's data and the underlying collection it reads from
// to see if something has changed
diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options));
if (diff.insert.length || diff.remove.length) {
// Now send out new chain packets for each operation
if (diff.insert.length) {
this.chainSend('insert', diff.insert);
}
if (diff.update.length) {
pk = self._privateData.primaryKey();
for (i = 0; i < diff.update.length; i++) {
query = {};
query[pk] = diff.update[i][pk];
this.chainSend('update', {
query: query,
update: diff.update[i]
});
}
}
if (diff.remove.length) {
pk = self._privateData.primaryKey();
var $or = [],
removeQuery = {
query: {
$or: $or
}
};
for (i = 0; i < diff.remove.length; i++) {
$or.push({_id: diff.remove[i][pk]});
}
this.chainSend('remove', removeQuery);
}
// Return true to stop further propagation of the chain packet
return true;
} else {
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
}
}
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
});
var collData = collection.find(this._querySettings.query, this._querySettings.options);
this._transformPrimaryKey(collection.primaryKey());
this._transformSetData(collData);
this._privateData.primaryKey(collection.primaryKey());
this._privateData.setData(collData);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
}
return this;
};
View.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from view
delete this._from;
}
};
View.prototype.ensureIndex = function () {
return this._privateData.ensureIndex.apply(this._privateData, arguments);
};
View.prototype._chainHandler = function (chainPacket) {
var //self = this,
arr,
count,
index,
insertIndex,
//tempData,
//dataIsArray,
updates,
//finalUpdates,
primaryKey,
tQuery,
item,
currentIndex,
i;
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log('ForerunnerDB.View: Setting data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
// Modify transform data
this._transformSetData(collData);
this._privateData.setData(collData);
break;
case 'insert':
if (this.debug()) {
console.log('ForerunnerDB.View: Inserting some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Make sure we are working with an array
if (!(chainPacket.data instanceof Array)) {
chainPacket.data = [chainPacket.data];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
// Modify transform data
this._transformInsert(chainPacket.data, insertIndex);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._privateData._data.length;
// Modify transform data
this._transformInsert(chainPacket.data, insertIndex);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log('ForerunnerDB.View: Updating some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"');
}
primaryKey = this._privateData.primaryKey();
// Do the update
updates = this._privateData.update(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._privateData._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex);
}
}
}
if (this._transformEnabled && this._transformIn) {
primaryKey = this._publicData.primaryKey();
for (i = 0; i < updates.length; i++) {
tQuery = {};
item = updates[i];
tQuery[primaryKey] = item[primaryKey];
this._transformUpdate(tQuery, item);
}
}
break;
case 'remove':
if (this.debug()) {
console.log('ForerunnerDB.View: Removing some data on view "' + this.name() + '" in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Modify transform data
this._transformRemove(chainPacket.data.query, chainPacket.options);
this._privateData.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
View.prototype.on = function () {
this._privateData.on.apply(this._privateData, arguments);
};
View.prototype.off = function () {
this._privateData.off.apply(this._privateData, arguments);
};
View.prototype.emit = function () {
this._privateData.emit.apply(this._privateData, arguments);
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
View.prototype.distinct = function (key, query, options) {
return this._privateData.distinct.apply(this._privateData, arguments);
};
/**
* Gets the primary key for this view from the assigned collection.
* @returns {String}
*/
View.prototype.primaryKey = function () {
return this._privateData.primaryKey();
};
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
View.prototype.drop = function () {
if (this._state !== 'dropped') {
if (this._from) {
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeView(this);
if (this.debug() || (this._db && this._db.debug())) {
console.log('ForerunnerDB.View: Dropping view ' + this._name);
}
this._state = 'dropped';
// Clear io and chains
if (this._io) {
this._io.drop();
}
// Drop the view's internal collection
if (this._privateData) {
this._privateData.drop();
}
if (this._db && this._name) {
delete this._db._view[this._name];
}
this.emit('drop', this);
delete this._chain;
delete this._from;
delete this._privateData;
delete this._io;
delete this._listeners;
delete this._querySettings;
delete this._db;
return true;
}
} else {
return true;
}
return false;
};
/**
* Gets / sets the DB the view is bound against. Automatically set
* when the db.oldView(viewName) method is called.
* @param db
* @returns {*}
*/
View.prototype.db = function (db) {
if (db !== undefined) {
this._db = db;
this.privateData().db(db);
this.publicData().db(db);
return this;
}
return this._db;
};
/**
* Gets / sets the query that the view uses to build it's data set.
* @param {Object=} query
* @param {Boolean=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
this._querySettings.query = this._querySettings.query || {};
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Gets / sets the query being used to generate the view data.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = function (query, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings.query;
};
/**
* Gets / sets the orderBy clause in the query options for the view.
* @param {Object=} val The order object.
* @returns {*}
*/
View.prototype.orderBy = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
queryOptions.$orderBy = val;
this.queryOptions(queryOptions);
return this;
}
return (this.queryOptions() || {}).$orderBy;
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._querySettings.options = options;
if (options.$decouple === undefined) { options.$decouple = true; }
if (refresh === undefined || refresh === true) {
this.refresh();
} else {
this.rebuildActiveBucket(options.$orderBy);
}
return this;
}
return this._querySettings.options;
};
View.prototype.rebuildActiveBucket = function (orderBy) {
if (orderBy) {
var arr = this._privateData._data,
arrCount = arr.length;
// Build a new active bucket
this._activeBucket = new ActiveBucket(orderBy);
this._activeBucket.primaryKey(this._privateData.primaryKey());
// Loop the current view data and add each item
for (var i = 0; i < arrCount; i++) {
this._activeBucket.insert(arr[i]);
}
} else {
// Remove any existing active bucket
delete this._activeBucket;
}
};
/**
* Refreshes the view data such as ordering etc.
*/
View.prototype.refresh = function () {
if (this._from) {
var pubData = this.publicData();
// Re-grab all the data for the view from the collection
this._privateData.remove();
pubData.remove();
this._privateData.insert(this._from.find(this._querySettings.query, this._querySettings.options));
/*if (pubData._linked) {
// Update data and observers
//var transformedData = this._privateData.find();
// TODO: Shouldn't this data get passed into a transformIn first?
// TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data
// TODO: Is this even required anymore? After commenting it all seems to work
// TODO: Might be worth setting up a test to check trasforms and linking then remove this if working?
//jQuery.observable(pubData._data).refresh(transformedData);
}*/
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
View.prototype.count = function () {
return this._privateData && this._privateData._data ? this._privateData._data.length : 0;
};
// Call underlying
View.prototype.subset = function () {
return this.publicData().subset.apply(this._privateData, arguments);
};
/**
* Takes the passed data and uses it to set transform methods and globally
* enable or disable the transform system for the view.
* @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut":
* {
* "enabled": true,
* "dataIn": function (data) { return data; },
* "dataOut": function (data) { return data; }
* }
* @returns {*}
*/
View.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
// Update the transformed data object
this._transformPrimaryKey(this.privateData().primaryKey());
this._transformSetData(this.privateData().find());
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Returns the non-transformed data the view holds as a collection
* reference.
* @return {Collection} The non-transformed collection reference.
*/
View.prototype.privateData = function () {
return this._privateData;
};
/**
* Returns a data object representing the public data this view
* contains. This can change depending on if transforms are being
* applied to the view or not.
*
* If no transforms are applied then the public data will be the
* same as the private data the view holds. If transforms are
* applied then the public data will contain the transformed version
* of the private data.
*
* The public data collection is also used by data binding to only
* changes to the publicData will show in a data-bound element.
*/
View.prototype.publicData = function () {
if (this._transformEnabled) {
return this._publicData;
} else {
return this._privateData;
}
};
/**
* Updates the public data object to match data from the private data object
* by running private data through the dataIn method provided in
* the transform() call.
* @private
*/
View.prototype._transformSetData = function (data) {
if (this._transformEnabled) {
// Clear existing data
this._publicData = new Collection('__FDB__view_publicData_' + this._name);
this._publicData.db(this._privateData._db);
this._publicData.transform({
enabled: true,
dataIn: this._transformIn,
dataOut: this._transformOut
});
this._publicData.setData(data);
}
};
View.prototype._transformInsert = function (data, index) {
if (this._transformEnabled && this._publicData) {
this._publicData.insert(data, index);
}
};
View.prototype._transformUpdate = function (query, update, options) {
if (this._transformEnabled && this._publicData) {
this._publicData.update(query, update, options);
}
};
View.prototype._transformRemove = function (query, options) {
if (this._transformEnabled && this._publicData) {
this._publicData.remove(query, options);
}
};
View.prototype._transformPrimaryKey = function (key) {
if (this._transformEnabled && this._publicData) {
this._publicData.primaryKey(key);
}
};
// Extend collection with view init
Collection.prototype.init = function () {
this._view = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._view ) {
if (!this._db._view[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._view = this._view || [];
this._view.push(view);
return view;
} else {
throw('ForerunnerDB.Collection "' + this.name() + '": Cannot create a view using this collection because a view with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._view.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._view.indexOf(view);
if (index > -1) {
this._view.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Core.prototype.init = function () {
this._view = {};
CoreInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Core.prototype.view = function (viewName) {
if (!this._view[viewName]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log('Core.View: Creating view ' + viewName);
}
}
this._view[viewName] = this._view[viewName] || new View(viewName).db(this);
return this._view[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Core.prototype.viewExists = function (viewName) {
return Boolean(this._view[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Core.prototype.views = function () {
var arr = [],
i;
for (i in this._view) {
if (this._view.hasOwnProperty(i)) {
arr.push({
name: i,
count: this._view[i].count()
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":2,"./Collection":3,"./CollectionGroup":4,"./ReactorIO":28,"./Shared":29}],31:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
function drainQueue() {
if (draining) {
return;
}
draining = true;
var currentQueue;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
var i = -1;
while (++i < len) {
currentQueue[i]();
}
len = queue.length;
}
draining = false;
}
process.nextTick = function (fun) {
queue.push(fun);
if (!draining) {
setTimeout(drainQueue, 0);
}
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],32:[function(_dereq_,module,exports){
'use strict';
var asap = _dereq_('asap')
module.exports = Promise
function Promise(fn) {
if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new')
if (typeof fn !== 'function') throw new TypeError('not a function')
var state = null
var value = null
var deferreds = []
var self = this
this.then = function(onFulfilled, onRejected) {
return new Promise(function(resolve, reject) {
handle(new Handler(onFulfilled, onRejected, resolve, reject))
})
}
function handle(deferred) {
if (state === null) {
deferreds.push(deferred)
return
}
asap(function() {
var cb = state ? deferred.onFulfilled : deferred.onRejected
if (cb === null) {
(state ? deferred.resolve : deferred.reject)(value)
return
}
var ret
try {
ret = cb(value)
}
catch (e) {
deferred.reject(e)
return
}
deferred.resolve(ret)
})
}
function resolve(newValue) {
try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.')
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
var then = newValue.then
if (typeof then === 'function') {
doResolve(then.bind(newValue), resolve, reject)
return
}
}
state = true
value = newValue
finale()
} catch (e) { reject(e) }
}
function reject(newValue) {
state = false
value = newValue
finale()
}
function finale() {
for (var i = 0, len = deferreds.length; i < len; i++)
handle(deferreds[i])
deferreds = null
}
doResolve(fn, resolve, reject)
}
function Handler(onFulfilled, onRejected, resolve, reject){
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null
this.onRejected = typeof onRejected === 'function' ? onRejected : null
this.resolve = resolve
this.reject = reject
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(fn, onFulfilled, onRejected) {
var done = false;
try {
fn(function (value) {
if (done) return
done = true
onFulfilled(value)
}, function (reason) {
if (done) return
done = true
onRejected(reason)
})
} catch (ex) {
if (done) return
done = true
onRejected(ex)
}
}
},{"asap":34}],33:[function(_dereq_,module,exports){
'use strict';
//This file contains then/promise specific extensions to the core promise API
var Promise = _dereq_('./core.js')
var asap = _dereq_('asap')
module.exports = Promise
/* Static Functions */
function ValuePromise(value) {
this.then = function (onFulfilled) {
if (typeof onFulfilled !== 'function') return this
return new Promise(function (resolve, reject) {
asap(function () {
try {
resolve(onFulfilled(value))
} catch (ex) {
reject(ex);
}
})
})
}
}
ValuePromise.prototype = Object.create(Promise.prototype)
var TRUE = new ValuePromise(true)
var FALSE = new ValuePromise(false)
var NULL = new ValuePromise(null)
var UNDEFINED = new ValuePromise(undefined)
var ZERO = new ValuePromise(0)
var EMPTYSTRING = new ValuePromise('')
Promise.resolve = function (value) {
if (value instanceof Promise) return value
if (value === null) return NULL
if (value === undefined) return UNDEFINED
if (value === true) return TRUE
if (value === false) return FALSE
if (value === 0) return ZERO
if (value === '') return EMPTYSTRING
if (typeof value === 'object' || typeof value === 'function') {
try {
var then = value.then
if (typeof then === 'function') {
return new Promise(then.bind(value))
}
} catch (ex) {
return new Promise(function (resolve, reject) {
reject(ex)
})
}
}
return new ValuePromise(value)
}
Promise.from = Promise.cast = function (value) {
var err = new Error('Promise.from and Promise.cast are deprecated, use Promise.resolve instead')
err.name = 'Warning'
console.warn(err.stack)
return Promise.resolve(value)
}
Promise.denodeify = function (fn, argumentCount) {
argumentCount = argumentCount || Infinity
return function () {
var self = this
var args = Array.prototype.slice.call(arguments)
return new Promise(function (resolve, reject) {
while (args.length && args.length > argumentCount) {
args.pop()
}
args.push(function (err, res) {
if (err) reject(err)
else resolve(res)
})
fn.apply(self, args)
})
}
}
Promise.nodeify = function (fn) {
return function () {
var args = Array.prototype.slice.call(arguments)
var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null
try {
return fn.apply(this, arguments).nodeify(callback)
} catch (ex) {
if (callback === null || typeof callback == 'undefined') {
return new Promise(function (resolve, reject) { reject(ex) })
} else {
asap(function () {
callback(ex)
})
}
}
}
}
Promise.all = function () {
var calledWithArray = arguments.length === 1 && Array.isArray(arguments[0])
var args = Array.prototype.slice.call(calledWithArray ? arguments[0] : arguments)
if (!calledWithArray) {
var err = new Error('Promise.all should be called with a single array, calling it with multiple arguments is deprecated')
err.name = 'Warning'
console.warn(err.stack)
}
return new Promise(function (resolve, reject) {
if (args.length === 0) return resolve([])
var remaining = args.length
function res(i, val) {
try {
if (val && (typeof val === 'object' || typeof val === 'function')) {
var then = val.then
if (typeof then === 'function') {
then.call(val, function (val) { res(i, val) }, reject)
return
}
}
args[i] = val
if (--remaining === 0) {
resolve(args);
}
} catch (ex) {
reject(ex)
}
}
for (var i = 0; i < args.length; i++) {
res(i, args[i])
}
})
}
Promise.reject = function (value) {
return new Promise(function (resolve, reject) {
reject(value);
});
}
Promise.race = function (values) {
return new Promise(function (resolve, reject) {
values.forEach(function(value){
Promise.resolve(value).then(resolve, reject);
})
});
}
/* Prototype Methods */
Promise.prototype.done = function (onFulfilled, onRejected) {
var self = arguments.length ? this.then.apply(this, arguments) : this
self.then(null, function (err) {
asap(function () {
throw err
})
})
}
Promise.prototype.nodeify = function (callback) {
if (typeof callback != 'function') return this
this.then(function (value) {
asap(function () {
callback(null, value)
})
}, function (err) {
asap(function () {
callback(err)
})
})
}
Promise.prototype['catch'] = function (onRejected) {
return this.then(null, onRejected);
}
},{"./core.js":32,"asap":34}],34:[function(_dereq_,module,exports){
(function (process){
// Use the fastest possible means to execute a task in a future turn
// of the event loop.
// linked list of tasks (single, with head node)
var head = {task: void 0, next: null};
var tail = head;
var flushing = false;
var requestFlush = void 0;
var isNodeJS = false;
function flush() {
/* jshint loopfunc: true */
while (head.next) {
head = head.next;
var task = head.task;
head.task = void 0;
var domain = head.domain;
if (domain) {
head.domain = void 0;
domain.enter();
}
try {
task();
} catch (e) {
if (isNodeJS) {
// In node, uncaught exceptions are considered fatal errors.
// Re-throw them synchronously to interrupt flushing!
// Ensure continuation if the uncaught exception is suppressed
// listening "uncaughtException" events (as domains does).
// Continue in next event to avoid tick recursion.
if (domain) {
domain.exit();
}
setTimeout(flush, 0);
if (domain) {
domain.enter();
}
throw e;
} else {
// In browsers, uncaught exceptions are not fatal.
// Re-throw them asynchronously to avoid slow-downs.
setTimeout(function() {
throw e;
}, 0);
}
}
if (domain) {
domain.exit();
}
}
flushing = false;
}
if (typeof process !== "undefined" && process.nextTick) {
// Node.js before 0.9. Note that some fake-Node environments, like the
// Mocha test runner, introduce a `process` global without a `nextTick`.
isNodeJS = true;
requestFlush = function () {
process.nextTick(flush);
};
} else if (typeof setImmediate === "function") {
// In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate
if (typeof window !== "undefined") {
requestFlush = setImmediate.bind(window, flush);
} else {
requestFlush = function () {
setImmediate(flush);
};
}
} else if (typeof MessageChannel !== "undefined") {
// modern browsers
// http://www.nonblocking.io/2011/06/windownexttick.html
var channel = new MessageChannel();
channel.port1.onmessage = flush;
requestFlush = function () {
channel.port2.postMessage(0);
};
} else {
// old browsers
requestFlush = function () {
setTimeout(flush, 0);
};
}
function asap(task) {
tail = tail.next = {
task: task,
domain: isNodeJS && process.domain,
next: null
};
if (!flushing) {
flushing = true;
requestFlush();
}
};
module.exports = asap;
}).call(this,_dereq_('_process'))
},{"_process":31}],35:[function(_dereq_,module,exports){
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
(function() {
'use strict';
// Originally found in https://github.com/mozilla-b2g/gaia/blob/e8f624e4cc9ea945727278039b3bc9bcb9f8667a/shared/js/async_storage.js
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports) ?
_dereq_('promise') : this.Promise;
// Initialize IndexedDB; fall back to vendor-prefixed versions if needed.
var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB ||
this.mozIndexedDB || this.OIndexedDB ||
this.msIndexedDB;
// If IndexedDB isn't available, we get outta here!
if (!indexedDB) {
return;
}
// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
return new Promise(function(resolve, reject) {
var openreq = indexedDB.open(dbInfo.name, dbInfo.version);
openreq.onerror = function() {
reject(openreq.error);
};
openreq.onupgradeneeded = function() {
// First time setup: create an empty object store
openreq.result.createObjectStore(dbInfo.storeName);
};
openreq.onsuccess = function() {
dbInfo.db = openreq.result;
self._dbInfo = dbInfo;
resolve();
};
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function() {
var value = req.result;
if (value === undefined) {
value = null;
}
resolve(value);
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeDeferedCallback(promise, callback);
return promise;
}
// Iterate over all items stored in database.
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.openCursor();
var iterationNumber = 1;
req.onsuccess = function() {
var cursor = req.result;
if (cursor) {
var result = iterator(cursor.value, cursor.key, iterationNumber++);
if (result !== void(0)) {
resolve(result);
} else {
cursor['continue']();
}
} else {
resolve();
}
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeDeferedCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
var req = store.put(value, key);
transaction.oncomplete = function() {
// Cast to undefined so the value passed to
// callback/promise is the same as what one would get out
// of `getItem()` later. This leads to some weirdness
// (setItem('foo', undefined) will return `null`), but
// it's not my fault localStorage is our baseline and that
// it's weird.
if (value === undefined) {
value = null;
}
resolve(value);
};
transaction.onabort = transaction.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeDeferedCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// We use a Grunt task to make this safe for IE and some
// versions of Android (including those used by Cordova).
// Normally IE won't like `['delete']()` and will insist on
// using `['delete']()`, but we have a build step that
// fixes this for us now.
var req = store['delete'](key);
transaction.oncomplete = function() {
resolve();
};
transaction.onerror = function() {
reject(req.error);
};
// The request will be aborted if we've exceeded our storage
// space. In this case, we will reject with a specific
// "QuotaExceededError".
transaction.onabort = function(event) {
var error = event.target.error;
if (error === 'QuotaExceededError') {
reject(error);
}
};
})['catch'](reject);
});
executeDeferedCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
var req = store.clear();
transaction.oncomplete = function() {
resolve();
};
transaction.onabort = transaction.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeDeferedCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.count();
req.onsuccess = function() {
resolve(req.result);
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var advanced = false;
var req = store.openCursor();
req.onsuccess = function() {
var cursor = req.result;
if (!cursor) {
// this means there weren't enough keys
resolve(null);
return;
}
if (n === 0) {
// We have the first key, return it if that's what they
// wanted.
resolve(cursor.key);
} else {
if (!advanced) {
// Otherwise, ask the cursor to skip ahead n
// records.
advanced = true;
cursor.advance(n);
} else {
// When we get here, we've got the nth key.
resolve(cursor.key);
}
}
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.openCursor();
var keys = [];
req.onsuccess = function() {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor['continue']();
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
function executeDeferedCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
deferCallback(callback, result);
}, function(error) {
callback(error);
});
}
}
// Under Chrome the callback is called before the changes (save, clear)
// are actually made. So we use a defer function which wait that the
// call stack to be empty.
// For more info : https://github.com/mozilla/localForage/issues/175
// Pull request : https://github.com/mozilla/localForage/pull/178
function deferCallback(callback, result) {
if (callback) {
return setTimeout(function() {
return callback(null, result);
}, 0);
}
}
var asyncStorage = {
_driver: 'asyncStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (typeof module !== 'undefined' && module.exports) {
module.exports = asyncStorage;
} else if (typeof define === 'function' && define.amd) {
define('asyncStorage', function() {
return asyncStorage;
});
} else {
this.asyncStorage = asyncStorage;
}
}).call(window);
},{"promise":33}],36:[function(_dereq_,module,exports){
// If IndexedDB isn't available, we'll fall back to localStorage.
// Note that this will have considerable performance and storage
// side-effects (all data will be serialized on save and only data that
// can be converted to a string via `JSON.stringify()` will be saved).
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports) ?
_dereq_('promise') : this.Promise;
var globalObject = this;
var serializer = null;
var localStorage = null;
// If the app is running inside a Google Chrome packaged webapp, or some
// other context where localStorage isn't available, we don't use
// localStorage. This feature detection is preferred over the old
// `if (window.chrome && window.chrome.runtime)` code.
// See: https://github.com/mozilla/localForage/issues/68
try {
// If localStorage isn't available, we get outta here!
// This should be inside a try catch
if (!this.localStorage || !('setItem' in this.localStorage)) {
return;
}
// Initialize localStorage and create a variable to use throughout
// the code.
localStorage = this.localStorage;
} catch (e) {
return;
}
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports) {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// Config the localStorage backend, using options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = dbInfo.name + '/';
self._dbInfo = dbInfo;
var serializerPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_(['localforageSerializer'], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
resolve(_dereq_('./../utils/serializer'));
} else {
resolve(globalObject.localforageSerializer);
}
});
return serializerPromise.then(function(lib) {
serializer = lib;
return Promise.resolve();
});
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear(callback) {
var self = this;
var promise = self.ready().then(function() {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = serializer.deserialize(result);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items in the store.
function iterate(iterator, callback) {
var self = this;
var promise = self.ready().then(function() {
var keyPrefix = self._dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
var value = localStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), i + 1);
if (value !== void(0)) {
return value;
}
}
});
executeCallback(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function key(n, callback) {
var self = this;
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) {
keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function length(callback) {
var self = this;
var promise = self.keys().then(function(keys) {
return keys.length;
});
executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
executeCallback(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function() {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new Promise(function(resolve, reject) {
serializer.serialize(value, function(value, error) {
if (error) {
reject(error);
} else {
try {
var dbInfo = self._dbInfo;
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' ||
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
reject(e);
}
}
});
});
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: _initStorage,
// Default API, from Gaia/localStorage.
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (moduleType === ModuleType.EXPORT) {
module.exports = localStorageWrapper;
} else if (moduleType === ModuleType.DEFINE) {
define('localStorageWrapper', function() {
return localStorageWrapper;
});
} else {
this.localStorageWrapper = localStorageWrapper;
}
}).call(window);
},{"./../utils/serializer":39,"promise":33}],37:[function(_dereq_,module,exports){
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports) ?
_dereq_('promise') : this.Promise;
var globalObject = this;
var serializer = null;
var openDatabase = this.openDatabase;
// If WebSQL methods aren't available, we can stop now.
if (!openDatabase) {
return;
}
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports) {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = typeof(options[i]) !== 'string' ?
options[i].toString() : options[i];
}
}
var serializerPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_(['localforageSerializer'], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
resolve(_dereq_('./../utils/serializer'));
} else {
resolve(globalObject.localforageSerializer);
}
});
var dbInfoPromise = new Promise(function(resolve, reject) {
// Open the database; the openDatabase API will automatically
// create it for us if it doesn't exist.
try {
dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version),
dbInfo.description, dbInfo.size);
} catch (e) {
return self.setDriver(self.LOCALSTORAGE).then(function() {
return self._initStorage(options);
}).then(resolve)['catch'](reject);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function(t) {
t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName +
' (id INTEGER PRIMARY KEY, key unique, value)', [],
function() {
self._dbInfo = dbInfo;
resolve();
}, function(t, error) {
reject(error);
});
});
});
return serializerPromise.then(function(lib) {
serializer = lib;
return dbInfoPromise;
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName +
' WHERE key = ? LIMIT 1', [key],
function(t, results) {
var result = results.rows.length ?
results.rows.item(0).value : null;
// Check to see if this is serialized content we need to
// unpack.
if (result) {
result = serializer.deserialize(result);
}
resolve(result);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName, [],
function(t, results) {
var rows = results.rows;
var length = rows.length;
for (var i = 0; i < length; i++) {
var item = rows.item(i);
var result = item.value;
// Check to see if this is serialized content
// we need to unpack.
if (result) {
result = serializer.deserialize(result);
}
result = iterator(result, item.key, i + 1);
// void(0) prevents problems with redefinition
// of `undefined`.
if (result !== void(0)) {
resolve(result);
return;
}
}
resolve();
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
// The localStorage API doesn't return undefined values in an
// "expected" way, so undefined is always cast to null in all
// drivers. See: https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
serializer.serialize(value, function(value, error) {
if (error) {
reject(error);
} else {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('INSERT OR REPLACE INTO ' +
dbInfo.storeName +
' (key, value) VALUES (?, ?)',
[key, value], function() {
resolve(originalValue);
}, function(t, error) {
reject(error);
});
}, function(sqlError) { // The transaction failed; check
// to see if it's a quota error.
if (sqlError.code === sqlError.QUOTA_ERR) {
// We reject the callback outright for now, but
// it's worth trying to re-run the transaction.
// Even if the user accepts the prompt to use
// more storage on Safari, this error will
// be called.
//
// TODO: Try to re-run the transaction.
reject(sqlError);
}
});
}
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName +
' WHERE key = ?', [key], function() {
resolve();
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function clear(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName, [],
function() {
resolve();
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function length(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
// Ahhh, SQL makes this one soooooo easy.
t.executeSql('SELECT COUNT(key) as c FROM ' +
dbInfo.storeName, [], function(t, results) {
var result = results.rows.item(0).c;
resolve(result);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function key(n, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName +
' WHERE id = ? LIMIT 1', [n + 1],
function(t, results) {
var result = results.rows.length ?
results.rows.item(0).key : null;
resolve(result);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName, [],
function(t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) {
keys.push(results.rows.item(i).key);
}
resolve(keys);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var webSQLStorage = {
_driver: 'webSQLStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (moduleType === ModuleType.DEFINE) {
define('webSQLStorage', function() {
return webSQLStorage;
});
} else if (moduleType === ModuleType.EXPORT) {
module.exports = webSQLStorage;
} else {
this.webSQLStorage = webSQLStorage;
}
}).call(window);
},{"./../utils/serializer":39,"promise":33}],38:[function(_dereq_,module,exports){
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports) ?
_dereq_('promise') : this.Promise;
// Custom drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var CustomDrivers = {};
var DriverType = {
INDEXEDDB: 'asyncStorage',
LOCALSTORAGE: 'localStorageWrapper',
WEBSQL: 'webSQLStorage'
};
var DefaultDriverOrder = [
DriverType.INDEXEDDB,
DriverType.WEBSQL,
DriverType.LOCALSTORAGE
];
var LibraryMethods = [
'clear',
'getItem',
'iterate',
'key',
'keys',
'length',
'removeItem',
'setItem'
];
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
var DefaultConfig = {
description: '',
driver: DefaultDriverOrder.slice(),
name: 'localforage',
// Default DB size is _JUST UNDER_ 5MB, as it's the highest size
// we can use without a prompt.
size: 4980736,
storeName: 'keyvaluepairs',
version: 1.0
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports) {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// Check to see if IndexedDB is available and if it is the latest
// implementation; it's our preferred backend library. We use "_spec_test"
// as the name of the database because it's not the one we'll operate on,
// but it's useful to make sure its using the right spec.
// See: https://github.com/mozilla/localForage/issues/128
var driverSupport = (function(self) {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB ||
self.mozIndexedDB || self.OIndexedDB ||
self.msIndexedDB;
var result = {};
result[DriverType.WEBSQL] = !!self.openDatabase;
result[DriverType.INDEXEDDB] = !!(function() {
// We mimic PouchDB here; just UA test for Safari (which, as of
// iOS 8/Yosemite, doesn't properly support IndexedDB).
// IndexedDB support is broken and different from Blink's.
// This is faster than the test case (and it's sync), so we just
// do this. *SIGH*
// http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
if (typeof self.openDatabase !== 'undefined' && self.navigator &&
self.navigator.userAgent &&
/Safari/.test(self.navigator.userAgent) &&
!/Chrome/.test(self.navigator.userAgent)) {
return false;
}
try {
return indexedDB &&
typeof indexedDB.open === 'function' &&
// Some Samsung/HTC Android 4.0-4.3 devices
// have older IndexedDB specs; if this isn't available
// their IndexedDB is too old for us to use.
// (Replaces the onupgradeneeded test.)
typeof self.IDBKeyRange !== 'undefined';
} catch (e) {
return false;
}
})();
result[DriverType.LOCALSTORAGE] = !!(function() {
try {
return (self.localStorage &&
('setItem' in self.localStorage) &&
(self.localStorage.setItem));
} catch (e) {
return false;
}
})();
return result;
})(this);
var isArray = Array.isArray || function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function() {
var _args = arguments;
return localForageInstance.ready().then(function() {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
for (var key in arg) {
if (arg.hasOwnProperty(key)) {
if (isArray(arg[key])) {
arguments[0][key] = arg[key].slice();
} else {
arguments[0][key] = arg[key];
}
}
}
}
}
return arguments[0];
}
function isLibraryDriver(driverName) {
for (var driver in DriverType) {
if (DriverType.hasOwnProperty(driver) &&
DriverType[driver] === driverName) {
return true;
}
}
return false;
}
var globalObject = this;
function LocalForage(options) {
this._config = extend({}, DefaultConfig, options);
this._driverSet = null;
this._ready = false;
this._dbInfo = null;
// Add a stub for each driver API method that delays the call to the
// corresponding driver method until localForage is ready. These stubs
// will be replaced by the driver methods as soon as the driver is
// loaded, so there is no performance impact.
for (var i = 0; i < LibraryMethods.length; i++) {
callWhenReady(this, LibraryMethods[i]);
}
this.setDriver(this._config.driver);
}
LocalForage.prototype.INDEXEDDB = DriverType.INDEXEDDB;
LocalForage.prototype.LOCALSTORAGE = DriverType.LOCALSTORAGE;
LocalForage.prototype.WEBSQL = DriverType.WEBSQL;
// Set any config values for localForage; can be called anytime before
// the first API call (e.g. `getItem`, `setItem`).
// We loop through options so we don't overwrite existing config
// values.
LocalForage.prototype.config = function(options) {
// If the options argument is an object, we use it to set values.
// Otherwise, we return either a specified config value or all
// config values.
if (typeof(options) === 'object') {
// If localforage is ready and fully initialized, we can't set
// any new configuration values. Instead, we return an error.
if (this._ready) {
return new Error("Can't call config() after localforage " +
'has been used.');
}
for (var i in options) {
if (i === 'storeName') {
options[i] = options[i].replace(/\W/g, '_');
}
this._config[i] = options[i];
}
// after all config options are set and
// the driver option is used, try setting it
if ('driver' in options && options.driver) {
this.setDriver(this._config.driver);
}
return true;
} else if (typeof(options) === 'string') {
return this._config[options];
} else {
return this._config;
}
};
// Used to define a custom driver, shared across all instances of
// localForage.
LocalForage.prototype.defineDriver = function(driverObject, callback,
errorCallback) {
var defineDriver = new Promise(function(resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error(
'Custom driver not compliant; see ' +
'https://mozilla.github.io/localForage/#definedriver'
);
var namingError = new Error(
'Custom driver name already in use: ' + driverObject._driver
);
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
if (isLibraryDriver(driverObject._driver)) {
reject(namingError);
return;
}
var customDriverMethods = LibraryMethods.concat('_initStorage');
for (var i = 0; i < customDriverMethods.length; i++) {
var customDriverMethod = customDriverMethods[i];
if (!customDriverMethod ||
!driverObject[customDriverMethod] ||
typeof driverObject[customDriverMethod] !== 'function') {
reject(complianceError);
return;
}
}
var supportPromise = Promise.resolve(true);
if ('_support' in driverObject) {
if (driverObject._support && typeof driverObject._support === 'function') {
supportPromise = driverObject._support();
} else {
supportPromise = Promise.resolve(!!driverObject._support);
}
}
supportPromise.then(function(supportResult) {
driverSupport[driverName] = supportResult;
CustomDrivers[driverName] = driverObject;
resolve();
}, reject);
} catch (e) {
reject(e);
}
});
defineDriver.then(callback, errorCallback);
return defineDriver;
};
LocalForage.prototype.driver = function() {
return this._driver || null;
};
LocalForage.prototype.ready = function(callback) {
var self = this;
var ready = new Promise(function(resolve, reject) {
self._driverSet.then(function() {
if (self._ready === null) {
self._ready = self._initStorage(self._config);
}
self._ready.then(resolve, reject);
})['catch'](reject);
});
ready.then(callback, callback);
return ready;
};
LocalForage.prototype.setDriver = function(drivers, callback,
errorCallback) {
var self = this;
if (typeof drivers === 'string') {
drivers = [drivers];
}
this._driverSet = new Promise(function(resolve, reject) {
var driverName = self._getFirstSupportedDriver(drivers);
var error = new Error('No available storage method found.');
if (!driverName) {
self._driverSet = Promise.reject(error);
reject(error);
return;
}
self._dbInfo = null;
self._ready = null;
if (isLibraryDriver(driverName)) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_([driverName], function(lib) {
self._extend(lib);
resolve();
});
return;
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
var driver;
switch (driverName) {
case self.INDEXEDDB:
driver = _dereq_('./drivers/indexeddb');
break;
case self.LOCALSTORAGE:
driver = _dereq_('./drivers/localstorage');
break;
case self.WEBSQL:
driver = _dereq_('./drivers/websql');
}
self._extend(driver);
} else {
self._extend(globalObject[driverName]);
}
} else if (CustomDrivers[driverName]) {
self._extend(CustomDrivers[driverName]);
} else {
self._driverSet = Promise.reject(error);
reject(error);
return;
}
resolve();
});
function setDriverToConfig() {
self._config.driver = self.driver();
}
this._driverSet.then(setDriverToConfig, setDriverToConfig);
this._driverSet.then(callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function(driverName) {
return !!driverSupport[driverName];
};
LocalForage.prototype._extend = function(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
// Used to determine which driver we should use as the backend for this
// instance of localForage.
LocalForage.prototype._getFirstSupportedDriver = function(drivers) {
if (drivers && isArray(drivers)) {
for (var i = 0; i < drivers.length; i++) {
var driver = drivers[i];
if (this.supports(driver)) {
return driver;
}
}
}
return null;
};
LocalForage.prototype.createInstance = function(options) {
return new LocalForage(options);
};
// The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
var localForage = new LocalForage();
// We allow localForage to be declared as a module or as a library
// available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
define('localforage', function() {
return localForage;
});
} else if (moduleType === ModuleType.EXPORT) {
module.exports = localForage;
} else {
this.localforage = localForage;
}
}).call(window);
},{"./drivers/indexeddb":35,"./drivers/localstorage":36,"./drivers/websql":37,"promise":33}],39:[function(_dereq_,module,exports){
(function() {
'use strict';
// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH +
TYPE_ARRAYBUFFER.length;
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function serialize(value, callback) {
var valueString = '';
if (value) {
valueString = value.toString();
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (value.toString() === '[object ArrayBuffer]' ||
value.buffer &&
value.buffer.toString() === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueString === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueString === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueString === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueString === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueString === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueString === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueString === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueString === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueString === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
} else if (valueString === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function() {
var str = bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
window.console.error("Couldn't convert value into a JSON " +
'string: ', value);
callback(null, e);
}
}
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0,
SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH,
TYPE_SERIALIZED_MARKER_LENGTH);
var buffer = stringToBuffer(serializedString);
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return new Blob([buffer]);
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
function stringToBuffer(serializedString) {
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === '=') {
bufferLength--;
if (serializedString[serializedString.length - 2] === '=') {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i+=4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i+1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i+2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i+3]);
/*jslint bitwise: true */
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return buffer;
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var base64String = '';
var i;
for (i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64String += BASE_CHARS[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if ((bytes.length % 3) === 2) {
base64String = base64String.substring(0, base64String.length - 1) + '=';
} else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + '==';
}
return base64String;
}
var localforageSerializer = {
serialize: serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString
};
if (typeof module !== 'undefined' && module.exports) {
module.exports = localforageSerializer;
} else if (typeof define === 'function' && define.amd) {
define('localforageSerializer', function() {
return localforageSerializer;
});
} else {
this.localforageSerializer = localforageSerializer;
}
}).call(window);
},{}]},{},[1]);
|
/*
Plugin Name: amCharts Data Loader
Description: This plugin adds external data loading capabilities to all amCharts libraries.
Author: Martynas Majeris, amCharts
Version: 1.0.2
Author URI: http://www.amcharts.com/
Copyright 2015 amCharts
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.
Please note that the above license covers only this plugin. It by all means does
not apply to any other amCharts products that are covered by different licenses.
*/
/**
* TODO:
* incremental load
* XML support (?)
*/
/**
* Initialize language prompt container
*/
AmCharts.translations.dataLoader = {}
/**
* Set init handler
*/
AmCharts.addInitHandler( function ( chart ) {
/**
* Check if dataLoader is set (initialize it)
*/
if ( undefined === chart.dataLoader || ! isObject( chart.dataLoader ) )
chart.dataLoader = {};
/**
* Check charts version for compatibility:
* the first compatible version is 3.13
*/
var version = chart.version.split( '.' );
if ( ( Number( version[0] ) < 3 ) || ( 3 == Number( version[0] ) && ( Number( version[1] ) < 13 ) ) )
return;
/**
* Define object reference for easy access
*/
var l = chart.dataLoader;
l.remaining = 0;
/**
* Set defaults
*/
var defaults = {
'async': true,
'format': 'json',
'showErrors': true,
'showCurtain': true,
'noStyles': false,
'reload': 0,
'timestamp': false,
'delimiter': ',',
'skip': 0,
'useColumnNames': false,
'reverse': false,
'reloading': false,
'complete': false,
'error': false
};
/**
* Load all files in a row
*/
if ( 'stock' === chart.type ) {
// delay this a little bit so the chart has the chance to build itself
setTimeout( function () {
// preserve animation
if ( 0 > chart.panelsSettings.startDuration ) {
l.startDuration = chart.panelsSettings.startDuration;
chart.panelsSettings.startDuration = 0;
}
// cycle through all of the data sets
for ( var x = 0; x < chart.dataSets.length; x++ ) {
var ds = chart.dataSets[ x ];
// load data
if ( undefined !== ds.dataLoader && undefined !== ds.dataLoader.url ) {
ds.dataProvider = [];
applyDefaults( ds.dataLoader );
loadFile( ds.dataLoader.url, ds, ds.dataLoader, 'dataProvider' );
}
// load events data
if ( undefined !== ds.eventDataLoader && undefined !== ds.eventDataLoader.url ) {
ds.events = [];
applyDefaults( ds.eventDataLoader );
loadFile( ds.eventDataLoader.url, ds, ds.eventDataLoader, 'stockEvents' );
}
}
}, 100 );
}
else {
applyDefaults( l );
if ( undefined === l.url )
return;
// preserve animation
if ( undefined !== chart.startDuration && ( 0 < chart.startDuration ) ) {
l.startDuration = chart.startDuration;
chart.startDuration = 0;
}
chart.dataProvider = [];
loadFile( l.url, chart, l, 'dataProvider' );
}
/**
* Loads a file and determines correct parsing mechanism for it
*/
function loadFile( url, holder, options, providerKey ) {
// set default providerKey
if ( undefined === providerKey )
providerKey = 'dataProvider';
// show curtain
if ( options.showCurtain )
showCurtain( undefined, options.noStyles );
// increment loader count
l.remaining++;
// load the file
AmCharts.loadFile( url, options, function ( response ) {
// error?
if ( false === response ) {
callFunction( options.error, url, options );
raiseError( AmCharts.__( 'Error loading the file', chart.language ) + ': ' + url, false, options );
}
else {
// determine the format
if ( undefined === options.format ) {
// TODO
options.format = 'json';
}
// lowercase
options.format = options.format.toLowerCase();
// invoke parsing function
switch( options.format ) {
case 'json':
holder[providerKey] = AmCharts.parseJSON( response, options );
if ( false === holder[providerKey] ) {
callFunction( options.error, options );
raiseError( AmCharts.__( 'Error parsing JSON file', chart.language ) + ': ' + l.url, false, options );
holder[providerKey] = [];
return;
}
else {
holder[providerKey] = postprocess( holder[providerKey], options );
callFunction( options.load, options );
}
break;
case 'csv':
holder[providerKey] = AmCharts.parseCSV( response, options );
if ( false === holder[providerKey] ) {
callFunction( options.error, options );
raiseError( AmCharts.__( 'Error parsing CSV file', chart.language ) + ': ' + l.url, false, options );
holder[providerKey] = [];
return;
}
else {
holder[providerKey] = postprocess( holder[providerKey], options );
callFunction( options.load, options );
}
break;
default:
callFunction( options.error, options );
raiseError( AmCharts.__( 'Unsupported data format', chart.language ) + ': ' + options.format, false, options.noStyles );
return;
break;
}
// decrement remaining counter
l.remaining--;
// we done?
if ( 0 === l.remaining ) {
// callback
callFunction( options.complete );
// take in the new data
if ( options.async ) {
if ( 'map' === chart.type )
chart.validateNow( true );
else {
// take in new data
chart.validateData();
// make the chart animate again
if ( l.startDuration ) {
if ( 'stock' === chart.type ) {
chart.panelsSettings.startDuration = l.startDuration;
for ( var x = 0; x < chart.panels.length; x++ ) {
chart.panels[x].startDuration = l.startDuration;
chart.panels[x].animateAgain();
}
}
else {
chart.startDuration = l.startDuration;
chart.animateAgain();
}
}
}
}
// restore default period
if ( 'stock' === chart.type && ! options.reloading )
chart.periodSelector.setDefaultPeriod();
// remove curtain
removeCurtain();
}
// schedule another load of necessary
if ( options.reload ) {
if ( options.timeout )
clearTimeout( options.timeout );
options.timeout = setTimeout( loadFile, 1000 * options.reload, url, holder, options );
options.reloading = true;
}
}
} );
}
/**
* Checks if postProcess is set and invokes the handler
*/
function postprocess ( data, options ) {
if ( undefined !== options.postProcess && isFunction( options.postProcess ) )
try {
return options.postProcess.call( this, data, options );
}
catch ( e ) {
raiseError( AmCharts.__( 'Error loading file', chart.language ) + ': ' + options.url, false, options );
return data;
}
else
return data;
}
/**
* Returns true if argument is object
*/
function isArray ( obj ) {
return obj instanceof Array;
}
/**
* Returns true if argument is array
*/
function isObject ( obj ) {
return 'object' === typeof( obj );
}
/**
* Returns true is argument is a function
*/
function isFunction ( obj ) {
return 'function' === typeof( obj );
}
/**
* Applies defaults to config object
*/
function applyDefaults ( obj ) {
for ( var x = 0; x < defaults.length; x++ ) {
setDefault( obj, x, defaults[ x ] );
}
}
/**
* Checks if object property is set, sets with a default if it isn't
*/
function setDefault ( obj, key, value ) {
if ( undefined === obj[ key ] )
obj[ key ] = value;
}
/**
* Raises an internal error (writes it out to console)
*/
function raiseError ( msg, error, options ) {
if ( options.showErrors )
showCurtain( msg, options.noStyles );
else {
removeCurtain();
console.log( msg );
}
}
/**
* Shows curtain over chart area
*/
function showCurtain ( msg, noStyles ) {
// remove previous curtain if there is one
removeCurtain();
// did we pass in the message?
if ( undefined === msg )
msg = AmCharts.__( 'Loading data...', chart.language );
// create and populate curtain element
var curtain =document.createElement( 'div' );
curtain.setAttribute( 'id', chart.div.id + '-curtain' );
curtain.className = 'amcharts-dataloader-curtain';
if ( true !== noStyles ) {
curtain.style.position = 'absolute';
curtain.style.top = 0;
curtain.style.left = 0;
curtain.style.width = ( undefined !== chart.realWidth ? chart.realWidth : chart.divRealWidth ) + 'px';
curtain.style.height = ( undefined !== chart.realHeight ? chart.realHeight : chart.divRealHeight ) + 'px';
curtain.style.textAlign = 'center';
curtain.style.display = 'table';
curtain.style.fontSize = '20px';
curtain.style.background = 'rgba(255, 255, 255, 0.3)';
curtain.innerHTML = '<div style="display: table-cell; vertical-align: middle;">' + msg + '</div>';
}
else {
curtain.innerHTML = msg;
}
chart.containerDiv.appendChild( curtain );
l.curtain = curtain;
}
/**
* Removes the curtain
*/
function removeCurtain () {
try {
if ( undefined !== l.curtain )
chart.containerDiv.removeChild( l.curtain );
}
catch ( e ) {
// do nothing
}
l.curtain = undefined;
}
/**
* Execute callback function
*/
function callFunction ( func, param1, param2 ) {
if ( 'function' === typeof func )
func.call( l, param1, param2 );
}
}, [ 'pie', 'serial', 'xy', 'funnel', 'radar', 'gauge', 'gantt', 'stock', 'map' ] );
/**
* Returns prompt in a chart language (set by chart.language) if it is
* available
*/
if ( undefined === AmCharts.__ ) {
AmCharts.__ = function ( msg, language ) {
if ( undefined !== language
&& undefined !== AmCharts.translations.dataLoader[ chart.language ]
&& undefined !== AmCharts.translations.dataLoader[ chart.language ][ msg ] )
return AmCharts.translations.dataLoader[ chart.language ][ msg ];
else
return msg;
}
}
/**
* Loads a file from url and calls function handler with the result
*/
AmCharts.loadFile = function ( url, options, handler ) {
// create the request
if ( window.XMLHttpRequest ) {
// IE7+, Firefox, Chrome, Opera, Safari
var request = new XMLHttpRequest();
} else {
// code for IE6, IE5
var request = new ActiveXObject( 'Microsoft.XMLHTTP' );
}
// set handler for data if async loading
request.onreadystatechange = function () {
if ( 4 == request.readyState && 404 == request.status )
handler.call( this, false );
else if ( 4 == request.readyState && 200 == request.status )
handler.call( this, request.responseText );
}
// load the file
try {
request.open( 'GET', options.timestamp ? AmCharts.timestampUrl( url ) : url, options.async );
request.send();
}
catch ( e ) {
handler.call( this, false );
}
};
/**
* Parses JSON string into an object
*/
AmCharts.parseJSON = function ( response, options ) {
try {
if ( undefined !== JSON )
return JSON.parse( response );
else
return eval( response );
}
catch ( e ) {
return false;
}
}
/**
* Prases CSV string into an object
*/
AmCharts.parseCSV = function ( response, options ) {
// parse CSV into array
var data = AmCharts.CSVToArray( response, options.delimiter );
// init resuling array
var res = [];
var cols = [];
// first row holds column names?
if ( options.useColumnNames ) {
cols = data.shift();
// normalize column names
for ( var x = 0; x < cols.length; x++ ) {
// trim
var col = cols[ x ].replace( /^\s+|\s+$/gm, '' );
// check for empty
if ( '' === col )
col = 'col' + x;
cols[ x ] = col;
}
if ( 0 < options.skip )
options.skip--;
}
// skip rows
for ( var i = 0; i < options.skip; i++ )
data.shift();
// iterate through the result set
var row;
while ( row = options.reverse ? data.pop() : data.shift() ) {
var dataPoint = {};
for ( var i = 0; i < row.length; i++ ) {
var col = undefined === cols[ i ] ? 'col' + i : cols[ i ];
dataPoint[ col ] = row[ i ];
}
res.push( dataPoint );
}
return res;
}
/**
* Parses CSV data into array
* Taken from here: (thanks!)
* http://www.bennadel.com/blog/1504-ask-ben-parsing-csv-strings-with-javascript-exec-regular-expression-command.htm
*/
AmCharts.CSVToArray = function ( strData, strDelimiter ){
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp(
(
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"
),
"gi"
);
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec( strData )){
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[ 1 ];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (
strMatchedDelimiter.length &&
(strMatchedDelimiter != strDelimiter)
){
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push( [] );
}
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[ 2 ]){
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[ 2 ].replace(
new RegExp( "\"\"", "g" ),
"\""
);
} else {
// We found a non-quoted value.
var strMatchedValue = arrMatches[ 3 ];
}
// Now that we have our value string, let's add
// it to the data array.
arrData[ arrData.length - 1 ].push( strMatchedValue );
}
// Return the parsed data.
return( arrData );
}
/**
* Appends timestamp to the url
*/
AmCharts.timestampUrl = function ( url ) {
var p = url.split( '?' );
if ( 1 === p.length )
p[1] = new Date().getTime();
else
p[1] += '&' + new Date().getTime();
return p.join( '?' );
} |
loadIonicon('<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><path d="M64 64v384h384V64H64zm80 304c-8.836 0-16-7.164-16-16s7.164-16 16-16 16 7.164 16 16-7.164 16-16 16zm0-96c-8.836 0-16-7.164-16-16s7.164-16 16-16 16 7.164 16 16-7.164 16-16 16zm0-96c-8.836 0-16-7.164-16-16s7.164-16 16-16 16 7.164 16 16-7.164 16-16 16zm240 184H192v-16h192v16zm0-96H192v-16h192v16zm0-96H192v-16h192v16z"/></svg>','ios-list-box'); |
/// <reference path="/umbraco_client/Application/NamespaceManager.js" />
/// <reference path="/umbraco_client/Application/HistoryManager.js" />
/// <reference path="/umbraco_client/ui/jquery.js" />
/// <reference path="/umbraco_client/Tree/UmbracoTree.js" />
/// <reference name="MicrosoftAjax.js"/>
Umbraco.Sys.registerNamespace("Umbraco.Application");
(function($) {
Umbraco.Application.ClientManager = function() {
/// <summary>
/// A class which ensures that all calls made to the objects that it owns are done in the context
/// of the main Umbraco application window.
/// </summary>
return {
_isDirty: false,
_isDebug: false,
_mainTree: null,
_appActions: null,
_historyMgr: null,
_rootPath: "/umbraco", //this is the default
_modal: new Array(), //track all modal window objects (they get stacked)
historyManager: function() {
if (!this._historyMgr) {
this._historyMgr = new Umbraco.Controls.HistoryManager();
}
return this._historyMgr;
},
setUmbracoPath: function(strPath) {
/// <summary>
/// sets the Umbraco root path folder
/// </summary>
this._debug("setUmbracoPath: " + strPath);
this._rootPath = strPath;
},
mainWindow: function() {
/// <summary>
/// Returns a reference to the main frame of the application
/// </summary>
return top;
},
mainTree: function() {
/// <summary>
/// Returns a reference to the main UmbracoTree API object.
/// Sometimes an Umbraco page will need to be opened without being contained in the iFrame from the main window
/// so this method is will construct a false tree to be returned if this is the case as to avoid errors.
/// </summary>
/// <returns type="Umbraco.Controls.UmbracoTree" />
if (this._mainTree == null) {
this._mainTree = top.UmbClientMgr.mainTree();
}
return this._mainTree;
},
appActions: function() {
/// <summary>
/// Returns a reference to the application actions object
/// </summary>
//if the main window has no actions, we'll create some
if (this._appActions == null) {
if (typeof this.mainWindow().appActions == 'undefined') {
this._appActions = new Umbraco.Application.Actions();
}
else this._appActions = this.mainWindow().appActions;
}
return this._appActions;
},
uiKeys: function() {
/// <summary>
/// Returns a reference to the main windows uiKeys object for globalization
/// </summary>
//TODO: If there is no main window, we need to go retrieve the appActions from the server!
return this.mainWindow().uiKeys;
},
// windowMgr: function()
// return null;
// },
contentFrameAndSection: function(app, rightFrameUrl) {
//this.appActions().shiftApp(app, this.uiKeys()['sections_' + app]);
var self = this;
self.mainWindow().UmbClientMgr.historyManager().addHistory(app, true);
window.setTimeout(function() {
self.mainWindow().UmbClientMgr.contentFrame(rightFrameUrl);
}, 200);
},
contentFrame: function (strLocation) {
/// <summary>
/// This will return the reference to the right content frame if strLocation is null or empty,
/// or set the right content frames location to the one specified by strLocation.
/// </summary>
this._debug("contentFrame: " + strLocation);
if (strLocation == null || strLocation == "") {
if (typeof this.mainWindow().right != "undefined") {
return this.mainWindow().right;
}
else {
return this.mainWindow(); //return the current window if the content frame doesn't exist in the current context
}
}
else {
//its a hash change so process that like angular
if (strLocation.substr(0, 1) !== "#") {
if (strLocation.substr(0, 1) != "/") {
//if the path doesn't start with "/" or with the root path then
//prepend the root path
strLocation = this._rootPath + "/" + strLocation;
}
else if (strLocation.length >= this._rootPath.length
&& strLocation.substr(0, this._rootPath.length) != this._rootPath) {
strLocation = this._rootPath + "/" + strLocation;
}
}
this._debug("contentFrame: parsed location: " + strLocation);
if (!this.mainWindow().UmbClientMgr) {
window.setTimeout(function() {
var self = this;
self.mainWindow().location.href = strLocation;
}, 200);
}
else {
this.mainWindow().UmbClientMgr.contentFrame(strLocation);
}
}
},
reloadContentFrameUrlIfPathLoaded: function (url) {
var contentFrame;
if (typeof this.mainWindow().right != "undefined") {
contentFrame = this.mainWindow().right;
}
else {
contentFrame = this.mainWindow();
}
var currentPath = contentFrame.location.pathname + (contentFrame.location.search ? contentFrame.location.search : "");
if (currentPath == url) {
contentFrame.location.reload();
}
},
/** This is used to launch an angular based modal window instead of the legacy window */
openAngularModalWindow: function (options) {
if (!this.mainWindow().UmbClientMgr) {
throw "An angular modal window can only be launched when the modal is running within the main Umbraco application";
}
else {
this.mainWindow().UmbClientMgr.openAngularModalWindow.apply(this.mainWindow().UmbClientMgr, [options]);
}
},
/** This is used to launch an angular based modal window instead of the legacy window */
rootScope: function () {
if (!this.mainWindow().UmbClientMgr) {
throw "An angular modal window can only be launched when the modal is running within the main Umbraco application";
}
else {
return this.mainWindow().UmbClientMgr.rootScope();
}
},
openModalWindow: function(url, name, showHeader, width, height, top, leftOffset, closeTriggers, onCloseCallback) {
//need to create the modal on the top window if the top window has a client manager, if not, create it on the current window
//if this is the top window, or if the top window doesn't have a client manager, create the modal in this manager
if (window == this.mainWindow() || !this.mainWindow().UmbClientMgr) {
var m = new Umbraco.Controls.ModalWindow();
this._modal.push(m);
m.open(url, name, showHeader, width, height, top, leftOffset, closeTriggers, onCloseCallback);
}
else {
//if the main window has a client manager, then call the main window's open modal method whilst keeping the context of it's manager.
if (this.mainWindow().UmbClientMgr) {
this.mainWindow().UmbClientMgr.openModalWindow.apply(this.mainWindow().UmbClientMgr,
[url, name, showHeader, width, height, top, leftOffset, closeTriggers, onCloseCallback]);
}
else {
return; //exit recurse.
}
}
},
openModalWindowForContent: function (jQueryElement, name, showHeader, width, height, top, leftOffset, closeTriggers, onCloseCallback) {
//need to create the modal on the top window if the top window has a client manager, if not, create it on the current window
//if this is the top window, or if the top window doesn't have a client manager, create the modal in this manager
if (window == this.mainWindow() || !this.mainWindow().UmbClientMgr) {
var m = new Umbraco.Controls.ModalWindow();
this._modal.push(m);
m.show(jQueryElement, name, showHeader, width, height, top, leftOffset, closeTriggers, onCloseCallback);
}
else {
//if the main window has a client manager, then call the main window's open modal method whilst keeping the context of it's manager.
if (this.mainWindow().UmbClientMgr) {
this.mainWindow().UmbClientMgr.openModalWindowForContent.apply(this.mainWindow().UmbClientMgr,
[jQueryElement, name, showHeader, width, height, top, leftOffset, closeTriggers, onCloseCallback]);
}
else {
return; //exit recurse.
}
}
},
closeModalWindow: function(rVal) {
/// <summary>
/// will close the latest open modal window.
/// if an rVal is passed in, then this will be sent to the onCloseCallback method if it was specified.
/// </summary>
if (this._modal != null && this._modal.length > 0) {
this._modal.pop().close(rVal);
}
else {
//this will recursively try to close a modal window until the parent window has a modal object or the window is the top and has the modal object
var mgr = null;
if (window.parent == null || window.parent == window) {
//we are at the root window, check if we can close the modal window from here
if (window.UmbClientMgr != null && window.UmbClientMgr._modal != null && window.UmbClientMgr._modal.length > 0) {
mgr = window.UmbClientMgr;
}
else {
return; //exit recursion.
}
}
else if (typeof window.parent.UmbClientMgr != "undefined") {
mgr = window.parent.UmbClientMgr;
}
mgr.closeModalWindow.call(mgr, rVal);
}
},
_debug: function(strMsg) {
if (this._isDebug) {
Sys.Debug.trace("UmbClientMgr: " + strMsg);
}
},
get_isDirty: function() {
return this._isDirty;
},
set_isDirty: function(value) {
this._isDirty = value;
}
};
};
})(jQuery);
//define alias for use throughout application
var UmbClientMgr = new Umbraco.Application.ClientManager();
|
(function() {
var ATTACHMENT, Evented, Shepherd, Step, addClass, createFromHTML, extend, matchesSelector, parseShorthand, removeClass, uniqueId, _ref,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
_ref = Tether.Utils, extend = _ref.extend, removeClass = _ref.removeClass, addClass = _ref.addClass, Evented = _ref.Evented;
ATTACHMENT = {
'top': 'top center',
'left': 'middle right',
'right': 'middle left',
'bottom': 'bottom center'
};
uniqueId = (function() {
var id;
id = 0;
return function() {
return id++;
};
})();
createFromHTML = function(html) {
var el;
el = document.createElement('div');
el.innerHTML = html;
return el.children[0];
};
matchesSelector = function(el, sel) {
var matches, _ref1, _ref2, _ref3, _ref4;
matches = (_ref1 = (_ref2 = (_ref3 = (_ref4 = el.matches) != null ? _ref4 : el.matchesSelector) != null ? _ref3 : el.webkitMatchesSelector) != null ? _ref2 : el.mozMatchesSelector) != null ? _ref1 : el.oMatchesSelector;
return matches.call(el, sel);
};
parseShorthand = function(obj, props) {
var i, out, prop, vals, _i, _len;
if (obj == null) {
return obj;
} else if (typeof obj === 'object') {
return obj;
} else {
vals = obj.split(' ');
if (vals.length > props.length) {
vals[0] = vals.slice(0, +(vals.length - props.length) + 1 || 9e9).join(' ');
vals.splice(1, vals.length - props.length);
}
out = {};
for (i = _i = 0, _len = props.length; _i < _len; i = ++_i) {
prop = props[i];
out[prop] = vals[i];
}
return out;
}
};
Step = (function(_super) {
__extends(Step, _super);
function Step(shepherd, options) {
this.shepherd = shepherd;
this.destroy = __bind(this.destroy, this);
this.scrollTo = __bind(this.scrollTo, this);
this.complete = __bind(this.complete, this);
this.cancel = __bind(this.cancel, this);
this.hide = __bind(this.hide, this);
this.show = __bind(this.show, this);
this.setOptions(options);
}
Step.prototype.setOptions = function(options) {
var event, handler, _base, _ref1;
this.options = options != null ? options : {};
this.destroy();
this.id = this.options.id || this.id || ("step-" + (uniqueId()));
if (this.options.when) {
_ref1 = this.options.when;
for (event in _ref1) {
handler = _ref1[event];
this.on(event, handler, this);
}
}
return (_base = this.options).buttons != null ? (_base = this.options).buttons : _base.buttons = [
{
text: 'Next',
action: this.shepherd.next
}
];
};
Step.prototype.bindAdvance = function() {
var event, handler, selector, _ref1,
_this = this;
_ref1 = parseShorthand(this.options.advanceOn, ['event', 'selector']), event = _ref1.event, selector = _ref1.selector;
handler = function(e) {
if (selector != null) {
if (matchesSelector(e.target, selector)) {
return _this.shepherd.advance();
}
} else {
if (_this.el && e.target === _this.el) {
return _this.shepherd.advance();
}
}
};
document.body.addEventListener(event, handler);
return this.on('destroy', function() {
return document.body.removeEventListener(event, handler);
});
};
Step.prototype.getAttachTo = function() {
var opts;
opts = parseShorthand(this.options.attachTo, ['element', 'on']);
if (opts == null) {
opts = {};
}
if (typeof opts.element === 'string') {
opts.element = document.querySelector(opts.element);
if (opts.element == null) {
throw new Error("Shepherd step's attachTo was not found in the page");
}
}
return opts;
};
Step.prototype.setupTether = function() {
var attachment, opts, tetherOpts;
if (typeof Tether === "undefined" || Tether === null) {
throw new Error("Using the attachment feature of Shepherd requires the Tether library");
}
opts = this.getAttachTo();
attachment = ATTACHMENT[opts.on || 'right'];
if (opts.element == null) {
opts.element = 'viewport';
attachment = 'middle center';
}
tetherOpts = {
classPrefix: 'shepherd',
element: this.el,
constraints: [
{
to: 'window',
pin: true,
attachment: 'together'
}
],
target: opts.element,
offset: opts.offset || '0 0',
attachment: attachment
};
return this.tether = new Tether(extend(tetherOpts, this.options.tetherOptions));
};
Step.prototype.show = function() {
var _ref1,
_this = this;
if (this.el == null) {
this.render();
}
addClass(this.el, 'shepherd-open');
if ((_ref1 = this.tether) != null) {
_ref1.enable();
}
if (this.options.scrollTo) {
setTimeout(function() {
return _this.scrollTo();
});
}
return this.trigger('show');
};
Step.prototype.hide = function() {
var _ref1;
removeClass(this.el, 'shepherd-open');
if ((_ref1 = this.tether) != null) {
_ref1.disable();
}
return this.trigger('hide');
};
Step.prototype.cancel = function() {
this.hide();
return this.trigger('cancel');
};
Step.prototype.complete = function() {
this.hide();
return this.trigger('complete');
};
Step.prototype.scrollTo = function() {
var $attachTo, elHeight, elLeft, elTop, element, height, left, offset, top, _ref1;
element = this.getAttachTo().element;
if (element == null) {
return;
}
$attachTo = jQuery(element);
_ref1 = $attachTo.offset(), top = _ref1.top, left = _ref1.left;
height = $attachTo.outerHeight();
offset = $(this.el).offset();
elTop = offset.top;
elLeft = offset.left;
elHeight = $(this.el).outerHeight();
if (top < pageYOffset || elTop < pageYOffset) {
return jQuery(document.body).scrollTop(Math.min(top, elTop) - 10);
} else if ((top + height) > (pageYOffset + innerHeight) || (elTop + elHeight) > (pageYOffset + innerHeight)) {
return jQuery(document.body).scrollTop(Math.max(top + height, elTop + elHeight) - innerHeight + 10);
}
};
Step.prototype.destroy = function() {
var _ref1;
if (this.el != null) {
document.body.removeChild(this.el);
delete this.el;
}
if ((_ref1 = this.tether) != null) {
_ref1.destroy();
}
return this.trigger('destroy');
};
Step.prototype.render = function() {
var button, buttons, cfg, content, footer, header, paragraph, paragraphs, text, _i, _j, _len, _len1, _ref1, _ref2, _ref3;
if (this.el != null) {
this.destroy();
}
this.el = createFromHTML("<div class='shepherd-step " + ((_ref1 = this.options.classes) != null ? _ref1 : '') + "' data-id='" + this.id + "'></div>");
content = document.createElement('div');
content.className = 'shepherd-content';
this.el.appendChild(content);
if (this.options.title != null) {
header = document.createElement('header');
header.innerHTML = "<h3 class='shepherd-title'>" + this.options.title + "</h3>";
this.el.className += ' shepherd-has-title';
content.appendChild(header);
}
if (this.options.text != null) {
text = createFromHTML("<div class='shepherd-text'></div>");
paragraphs = this.options.text;
if (typeof paragraphs === 'string') {
paragraphs = [paragraphs];
}
for (_i = 0, _len = paragraphs.length; _i < _len; _i++) {
paragraph = paragraphs[_i];
text.innerHTML += "<p>" + paragraph + "</p>";
}
content.appendChild(text);
}
footer = document.createElement('footer');
if (this.options.buttons) {
buttons = createFromHTML("<ul class='shepherd-buttons'></ul>");
_ref2 = this.options.buttons;
for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
cfg = _ref2[_j];
button = createFromHTML("<li><a class='shepherd-button " + ((_ref3 = cfg.classes) != null ? _ref3 : '') + "'>" + cfg.text + "</a>");
buttons.appendChild(button);
this.bindButtonEvents(cfg, button.querySelector('a'));
}
footer.appendChild(buttons);
}
content.appendChild(footer);
document.body.appendChild(this.el);
this.setupTether();
if (this.options.advanceOn) {
return this.bindAdvance();
}
};
Step.prototype.bindButtonEvents = function(cfg, el) {
var event, handler, page, _ref1,
_this = this;
if (cfg.events == null) {
cfg.events = {};
}
if (cfg.action != null) {
cfg.events.click = cfg.action;
}
_ref1 = cfg.events;
for (event in _ref1) {
handler = _ref1[event];
if (typeof handler === 'string') {
page = handler;
handler = function() {
return _this.shepherd.show(page);
};
}
el.addEventListener(event, handler);
}
return this.on('destroy', function() {
var _ref2, _results;
_ref2 = cfg.events;
_results = [];
for (event in _ref2) {
handler = _ref2[event];
_results.push(el.removeEventListener(event, handler));
}
return _results;
});
};
return Step;
})(Evented);
Shepherd = (function(_super) {
__extends(Shepherd, _super);
function Shepherd(options) {
var _ref1;
this.options = options != null ? options : {};
this.hide = __bind(this.hide, this);
this.cancel = __bind(this.cancel, this);
this.back = __bind(this.back, this);
this.next = __bind(this.next, this);
this.steps = (_ref1 = this.options.steps) != null ? _ref1 : [];
}
Shepherd.prototype.addStep = function(name, step) {
if (step == null) {
step = name;
} else {
step.id = name;
}
step = extend({}, this.options.defaults, step);
return this.steps.push(new Step(this, step));
};
Shepherd.prototype.getById = function(id) {
var step, _i, _len, _ref1;
_ref1 = this.steps;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
step = _ref1[_i];
if (step.id === id) {
return step;
}
}
};
Shepherd.prototype.next = function() {
var index;
index = this.steps.indexOf(this.currentStep);
if (index === this.steps.length - 1) {
this.hide(index);
return this.trigger('complete');
} else {
return this.show(index + 1);
}
};
Shepherd.prototype.back = function() {
var index;
index = this.steps.indexOf(this.currentStep);
return this.show(index - 1);
};
Shepherd.prototype.cancel = function() {
var _ref1;
if ((_ref1 = this.currentStep) != null) {
_ref1.cancel();
}
return this.trigger('cancel');
};
Shepherd.prototype.hide = function() {
var _ref1;
if ((_ref1 = this.currentStep) != null) {
_ref1.hide();
}
return this.trigger('hide');
};
Shepherd.prototype.show = function(key) {
var next;
if (key == null) {
key = 0;
}
if (this.currentStep) {
this.currentStep.hide();
}
if (typeof key === 'string') {
next = this.getById(key);
} else {
next = this.steps[key];
}
if (next) {
this.trigger('shown', {
step: next,
previous: this.currentStep
});
this.currentStep = next;
return next.show();
}
};
Shepherd.prototype.start = function() {
this.currentStep = null;
return this.next();
};
return Shepherd;
})(Evented);
window.Shepherd = Shepherd;
}).call(this);
|
/* Copyright (c) 2006-2013 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the 2-clause BSD license.
* See license.txt in the OpenLayers distribution or repository for the
* full text of the license. */
/**
* @requires OpenLayers/Control.js
* @requires OpenLayers/Handler/Click.js
* @requires OpenLayers/Handler/Hover.js
* @requires OpenLayers/Request.js
* @requires OpenLayers/Format/WMSGetFeatureInfo.js
*/
/**
* Class: OpenLayers.Control.WMTSGetFeatureInfo
* The WMTSGetFeatureInfo control uses a WMTS query to get information about a
* point on the map. The information may be in a display-friendly format
* such as HTML, or a machine-friendly format such as GML, depending on the
* server's capabilities and the client's configuration. This control
* handles click or hover events, attempts to parse the results using an
* OpenLayers.Format, and fires a 'getfeatureinfo' event for each layer
* queried.
*
* Inherits from:
* - <OpenLayers.Control>
*/
OpenLayers.Control.WMTSGetFeatureInfo = OpenLayers.Class(OpenLayers.Control, {
/**
* APIProperty: hover
* {Boolean} Send GetFeatureInfo requests when mouse stops moving.
* Default is false.
*/
hover: false,
/**
* Property: requestEncoding
* {String} One of "KVP" or "REST". Only KVP encoding is supported at this
* time.
*/
requestEncoding: "KVP",
/**
* APIProperty: drillDown
* {Boolean} Drill down over all WMTS layers in the map. When
* using drillDown mode, hover is not possible. A getfeatureinfo event
* will be fired for each layer queried.
*/
drillDown: false,
/**
* APIProperty: maxFeatures
* {Integer} Maximum number of features to return from a WMTS query. This
* sets the feature_count parameter on WMTS GetFeatureInfo
* requests.
*/
maxFeatures: 10,
/** APIProperty: clickCallback
* {String} The click callback to register in the
* {<OpenLayers.Handler.Click>} object created when the hover
* option is set to false. Default is "click".
*/
clickCallback: "click",
/**
* Property: layers
* {Array(<OpenLayers.Layer.WMTS>)} The layers to query for feature info.
* If omitted, all map WMTS layers will be considered.
*/
layers: null,
/**
* APIProperty: queryVisible
* {Boolean} Filter out hidden layers when searching the map for layers to
* query. Default is true.
*/
queryVisible: true,
/**
* Property: infoFormat
* {String} The mimetype to request from the server
*/
infoFormat: 'text/html',
/**
* Property: vendorParams
* {Object} Additional parameters that will be added to the request, for
* WMTS implementations that support them. This could e.g. look like
* (start code)
* {
* radius: 5
* }
* (end)
*/
vendorParams: {},
/**
* Property: format
* {<OpenLayers.Format>} A format for parsing GetFeatureInfo responses.
* Default is <OpenLayers.Format.WMSGetFeatureInfo>.
*/
format: null,
/**
* Property: formatOptions
* {Object} Optional properties to set on the format (if one is not provided
* in the <format> property.
*/
formatOptions: null,
/**
* APIProperty: handlerOptions
* {Object} Additional options for the handlers used by this control, e.g.
* (start code)
* {
* "click": {delay: 100},
* "hover": {delay: 300}
* }
* (end)
*/
/**
* Property: handler
* {Object} Reference to the <OpenLayers.Handler> for this control
*/
handler: null,
/**
* Property: hoverRequest
* {<OpenLayers.Request>} contains the currently running hover request
* (if any).
*/
hoverRequest: null,
/**
* APIProperty: events
* {<OpenLayers.Events>} Events instance for listeners and triggering
* control specific events.
*
* Register a listener for a particular event with the following syntax:
* (code)
* control.events.register(type, obj, listener);
* (end)
*
* Supported event types (in addition to those from <OpenLayers.Control.events>):
* beforegetfeatureinfo - Triggered before each request is sent.
* The event object has an *xy* property with the position of the
* mouse click or hover event that triggers the request and a *layer*
* property referencing the layer about to be queried. If a listener
* returns false, the request will not be issued.
* getfeatureinfo - Triggered when a GetFeatureInfo response is received.
* The event object has a *text* property with the body of the
* response (String), a *features* property with an array of the
* parsed features, an *xy* property with the position of the mouse
* click or hover event that triggered the request, a *layer* property
* referencing the layer queried and a *request* property with the
* request itself. If drillDown is set to true, one event will be fired
* for each layer queried.
* exception - Triggered when a GetFeatureInfo request fails (with a
* status other than 200) or whenparsing fails. Listeners will receive
* an event with *request*, *xy*, and *layer* properties. In the case
* of a parsing error, the event will also contain an *error* property.
*/
/**
* Property: pending
* {Number} The number of pending requests.
*/
pending: 0,
/**
* Constructor: <OpenLayers.Control.WMTSGetFeatureInfo>
*
* Parameters:
* options - {Object}
*/
initialize: function(options) {
options = options || {};
options.handlerOptions = options.handlerOptions || {};
OpenLayers.Control.prototype.initialize.apply(this, [options]);
if (!this.format) {
this.format = new OpenLayers.Format.WMSGetFeatureInfo(
options.formatOptions
);
}
if (this.drillDown === true) {
this.hover = false;
}
if (this.hover) {
this.handler = new OpenLayers.Handler.Hover(
this, {
move: this.cancelHover,
pause: this.getInfoForHover
},
OpenLayers.Util.extend(
this.handlerOptions.hover || {}, {delay: 250}
)
);
} else {
var callbacks = {};
callbacks[this.clickCallback] = this.getInfoForClick;
this.handler = new OpenLayers.Handler.Click(
this, callbacks, this.handlerOptions.click || {}
);
}
},
/**
* Method: getInfoForClick
* Called on click
*
* Parameters:
* evt - {<OpenLayers.Event>}
*/
getInfoForClick: function(evt) {
this.request(evt.xy, {});
},
/**
* Method: getInfoForHover
* Pause callback for the hover handler
*
* Parameters:
* evt - {Object}
*/
getInfoForHover: function(evt) {
this.request(evt.xy, {hover: true});
},
/**
* Method: cancelHover
* Cancel callback for the hover handler
*/
cancelHover: function() {
if (this.hoverRequest) {
--this.pending;
if (this.pending <= 0) {
OpenLayers.Element.removeClass(this.map.viewPortDiv, "olCursorWait");
this.pending = 0;
}
this.hoverRequest.abort();
this.hoverRequest = null;
}
},
/**
* Method: findLayers
* Internal method to get the layers, independent of whether we are
* inspecting the map or using a client-provided array
*/
findLayers: function() {
var candidates = this.layers || this.map.layers;
var layers = [];
var layer;
for (var i=candidates.length-1; i>=0; --i) {
layer = candidates[i];
if (layer instanceof OpenLayers.Layer.WMTS &&
layer.requestEncoding === this.requestEncoding &&
(!this.queryVisible || layer.getVisibility())) {
layers.push(layer);
if (!this.drillDown || this.hover) {
break;
}
}
}
return layers;
},
/**
* Method: buildRequestOptions
* Build an object with the relevant options for the GetFeatureInfo request.
*
* Parameters:
* layer - {<OpenLayers.Layer.WMTS>} A WMTS layer.
* xy - {<OpenLayers.Pixel>} The position on the map where the
* mouse event occurred.
*/
buildRequestOptions: function(layer, xy) {
var loc = this.map.getLonLatFromPixel(xy);
var getTileUrl = layer.getURL(
new OpenLayers.Bounds(loc.lon, loc.lat, loc.lon, loc.lat)
);
var params = OpenLayers.Util.getParameters(getTileUrl);
var tileInfo = layer.getTileInfo(loc);
OpenLayers.Util.extend(params, {
service: "WMTS",
version: layer.version,
request: "GetFeatureInfo",
infoFormat: this.infoFormat,
i: tileInfo.i,
j: tileInfo.j
});
OpenLayers.Util.applyDefaults(params, this.vendorParams);
return {
url: OpenLayers.Util.isArray(layer.url) ? layer.url[0] : layer.url,
params: OpenLayers.Util.upperCaseObject(params),
callback: function(request) {
this.handleResponse(xy, request, layer);
},
scope: this
};
},
/**
* Method: request
* Sends a GetFeatureInfo request to the WMTS
*
* Parameters:
* xy - {<OpenLayers.Pixel>} The position on the map where the mouse event
* occurred.
* options - {Object} additional options for this method.
*
* Valid options:
* - *hover* {Boolean} true if we do the request for the hover handler
*/
request: function(xy, options) {
options = options || {};
var layers = this.findLayers();
if (layers.length > 0) {
var issue, layer;
for (var i=0, len=layers.length; i<len; i++) {
layer = layers[i];
issue = this.events.triggerEvent("beforegetfeatureinfo", {
xy: xy,
layer: layer
});
if (issue !== false) {
++this.pending;
var requestOptions = this.buildRequestOptions(layer, xy);
var request = OpenLayers.Request.GET(requestOptions);
if (options.hover === true) {
this.hoverRequest = request;
}
}
}
if (this.pending > 0) {
OpenLayers.Element.addClass(this.map.viewPortDiv, "olCursorWait");
}
}
},
/**
* Method: handleResponse
* Handler for the GetFeatureInfo response.
*
* Parameters:
* xy - {<OpenLayers.Pixel>} The position on the map where the mouse event
* occurred.
* request - {XMLHttpRequest} The request object.
* layer - {<OpenLayers.Layer.WMTS>} The queried layer.
*/
handleResponse: function(xy, request, layer) {
--this.pending;
if (this.pending <= 0) {
OpenLayers.Element.removeClass(this.map.viewPortDiv, "olCursorWait");
this.pending = 0;
}
if (request.status && (request.status < 200 || request.status >= 300)) {
this.events.triggerEvent("exception", {
xy: xy,
request: request,
layer: layer
});
} else {
var doc = request.responseXML;
if (!doc || !doc.documentElement) {
doc = request.responseText;
}
var features, except;
try {
features = this.format.read(doc);
} catch (error) {
except = true;
this.events.triggerEvent("exception", {
xy: xy,
request: request,
error: error,
layer: layer
});
}
if (!except) {
this.events.triggerEvent("getfeatureinfo", {
text: request.responseText,
features: features,
request: request,
xy: xy,
layer: layer
});
}
}
},
CLASS_NAME: "OpenLayers.Control.WMTSGetFeatureInfo"
});
|
function f() { /* infinite */ while (true) { } /* bar */ var each; } |
describe('uiValidate', function ($compile) {
var scope, compileAndDigest;
var trueValidator = function () {
return true;
};
var falseValidator = function () {
return false;
};
var passedValueValidator = function (valueToValidate) {
return valueToValidate;
};
beforeEach(module('ui'));
beforeEach(inject(function ($rootScope, $compile) {
scope = $rootScope.$new();
compileAndDigest = function (inputHtml, scope) {
var inputElm = angular.element(inputHtml);
var formElm = angular.element('<form name="form"></form>');
formElm.append(inputElm);
$compile(formElm)(scope);
scope.$digest();
return inputElm;
};
}));
describe('initial validation', function () {
it('should mark input as valid if initial model is valid', inject(function () {
scope.validate = trueValidator;
compileAndDigest('<input name="input" ng-model="value" ui-validate="\'validate($value)\'">', scope);
expect(scope.form.input.$valid).toBeTruthy();
expect(scope.form.input.$error).toEqual({validator: false});
}));
it('should mark input as invalid if initial model is invalid', inject(function () {
scope.validate = falseValidator;
compileAndDigest('<input name="input" ng-model="value" ui-validate="\'validate($value)\'">', scope);
expect(scope.form.input.$valid).toBeFalsy();
expect(scope.form.input.$error).toEqual({ validator: true });
}));
});
describe('validation on model change', function () {
it('should change valid state in response to model changes', inject(function () {
scope.value = false;
scope.validate = passedValueValidator;
compileAndDigest('<input name="input" ng-model="value" ui-validate="\'validate($value)\'">', scope);
expect(scope.form.input.$valid).toBeFalsy();
scope.$apply('value = true');
expect(scope.form.input.$valid).toBeTruthy();
}));
});
describe('validation on element change', function () {
var sniffer;
beforeEach(inject(function ($sniffer) {
sniffer = $sniffer;
}));
it('should change valid state in response to element events', function () {
scope.value = false;
scope.validate = passedValueValidator;
var inputElm = compileAndDigest('<input name="input" ng-model="value" ui-validate="\'validate($value)\'">', scope);
expect(scope.form.input.$valid).toBeFalsy();
inputElm.val('true');
inputElm.trigger((sniffer.hasEvent('input') ? 'input' : 'change'));
expect(scope.form.input.$valid).toBeTruthy();
});
});
describe('multiple validators with custom keys', function () {
it('should support multiple validators with custom keys', function () {
scope.validate1 = trueValidator;
scope.validate2 = falseValidator;
compileAndDigest('<input name="input" ng-model="value" ui-validate="{key1 : \'validate1($value)\', key2 : \'validate2($value)\'}">', scope);
expect(scope.form.input.$valid).toBeFalsy();
expect(scope.form.input.$error.key1).toBeFalsy();
expect(scope.form.input.$error.key2).toBeTruthy();
});
});
describe('uiValidateWatch', function(){
function validateWatch(watchMe) {
return watchMe;
};
beforeEach(function(){
scope.validateWatch = validateWatch;
});
it('should watch the string and refire the single validator', function () {
scope.watchMe = false;
compileAndDigest('<input name="input" ng-model="value" ui-validate="\'validateWatch(watchMe)\'" ui-validate-watch="\'watchMe\'">', scope);
expect(scope.form.input.$valid).toBe(false);
expect(scope.form.input.$error.validator).toBe(true);
scope.$apply('watchMe=true');
expect(scope.form.input.$valid).toBe(true);
expect(scope.form.input.$error.validator).toBe(false);
});
it('should watch the string and refire all validators', function () {
scope.watchMe = false;
compileAndDigest('<input name="input" ng-model="value" ui-validate="{foo:\'validateWatch(watchMe)\',bar:\'validateWatch(watchMe)\'}" ui-validate-watch="\'watchMe\'">', scope);
expect(scope.form.input.$valid).toBe(false);
expect(scope.form.input.$error.foo).toBe(true);
expect(scope.form.input.$error.bar).toBe(true);
scope.$apply('watchMe=true');
expect(scope.form.input.$valid).toBe(true);
expect(scope.form.input.$error.foo).toBe(false);
expect(scope.form.input.$error.bar).toBe(false);
});
it('should watch the all object attributes and each respective validator', function () {
scope.watchFoo = false;
scope.watchBar = false;
compileAndDigest('<input name="input" ng-model="value" ui-validate="{foo:\'validateWatch(watchFoo)\',bar:\'validateWatch(watchBar)\'}" ui-validate-watch="{foo:\'watchFoo\',bar:\'watchBar\'}">', scope);
expect(scope.form.input.$valid).toBe(false);
expect(scope.form.input.$error.foo).toBe(true);
expect(scope.form.input.$error.bar).toBe(true);
scope.$apply('watchFoo=true');
expect(scope.form.input.$valid).toBe(false);
expect(scope.form.input.$error.foo).toBe(false);
expect(scope.form.input.$error.bar).toBe(true);
scope.$apply('watchBar=true');
scope.$apply('watchFoo=false');
expect(scope.form.input.$valid).toBe(false);
expect(scope.form.input.$error.foo).toBe(true);
expect(scope.form.input.$error.bar).toBe(false);
scope.$apply('watchFoo=true');
expect(scope.form.input.$valid).toBe(true);
expect(scope.form.input.$error.foo).toBe(false);
expect(scope.form.input.$error.bar).toBe(false);
});
});
describe('error cases', function () {
it('should fail if ngModel not present', inject(function () {
expect(function () {
compileAndDigest('<input name="input" ui-validate="\'validate($value)\'">', scope);
}).toThrow(new Error('No controller: ngModel'));
}));
it('should have no effect if validate expression is empty', inject(function () {
compileAndDigest('<input ng-model="value" ui-validate="">', scope);
}));
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.