code
stringlengths
2
1.05M
define(['app', 'model/candidate'], function(App, CandidateCollection){ App.commands.setHandler('votePageDisplay', function(voter){ require(['views/vote', 'backbone'], function(VoteView, Backbone){ var list = new CandidateCollection(); list.fetch(); //Display only those candidates which are from the voter's constituency App.Main.show(new VoteView({ collection: list })); }) ; }); });
"use strict"; var platform_browser_dynamic_1 = require('@angular/platform-browser-dynamic'); var app_module_1 = require('./app/app.module'); //enableProdMode(); //Uncomment for production document.addEventListener('WebComponentsReady', function () { platform_browser_dynamic_1.platformBrowserDynamic().bootstrapModule(app_module_1.AppModule) .then(function (success) { return console.log('App bootstrapped'); }) .catch(function (err) { return console.error(err); }); }); /* var webComponentsFlag = false; document.addEventListener('WebComponentsReady',() =>{ if (!webComponentsFlag) platformBrowserDynamic().bootstrapModule(AppModule); webComponentsFlag = true; }); if (webComponentsFlag) platformBrowserDynamic().bootstrapModule(AppModule);*/
'use strict'; var util = require('util'), errors = module.exports = {}; errors.BaseError = function() { var tmp = Error.apply(this, arguments); tmp.name = this.name = 'QMFError'; this.message = tmp.message; if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor); }; util.inherits(errors.BaseError, Error); errors.AgentExceptionError = function(values) { var errorText = (values.error_text instanceof Buffer) ? values.error_text.toString() : values.error_text; errors.BaseError.call(this, errorText); this.name = 'QMFAgentExceptionError'; this.errorCode = values.error_code; this.errorText = errorText; }; util.inherits(errors.AgentExceptionError, errors.BaseError); errors.InvalidResponseError = function(opcode) { errors.BaseError.call(this, opcode); this.name = 'QMFInvalidResponseError'; this.opcode = opcode; }; util.inherits(errors.InvalidResponseError, errors.BaseError); errors.TimeoutError = function() { errors.BaseError.call(this, 'request timed out'); this.name = 'QMFTimeoutError'; }; util.inherits(errors.TimeoutError, errors.BaseError);
Slipmat.Views.LabelShow = Backbone.ModularView.extend({ tagName: "main", className: "group", template: JST["labels/show"], initialize: function (options) { this.router = options.router; this.listenTo(this.model, "sync change", this.render); }, events: { "submit": "addComment" }, render: function () { var content = this.template({ label: this.model }); this.$el.html(content); if (Slipmat.currentUser.isSignedIn()) { $textarea = $('<textarea class="form comment-form">'); this.$("#new-comment").prepend($textarea); } this.listContributors(); this.renderComments(); this.renderRecords(); return this; }, renderRecords: function () { var records = this.model.records(), template = JST["records/_record"], header = JST["layouts/_paginationHeader"]({ collection: records }), footer = JST["layouts/_paginationFooter"]({ collection: records }), $el = this.$(".content-records"); this.$(".pagination-header").html(header); this.$(".pagination-footer").html(footer); records.forEach(record => { var subview = template({ model: record }); $el.append(subview); }); } });
Meteor.startup(function () { // Notification email Router.route('/email/notification/:id?', { name: 'notification', where: 'server', action: function() { var notification = Herald.collection.findOne(this.params.id); var notificationContents = buildEmailNotification(notification); this.response.write(notificationContents.html); this.response.end(); } }); });
'use strict'; module.exports = { db: 'mongodb://lolo:tazkypass@dogen.mongohq.com:10048/todo-database', app: { title: 'TuDu - Development Environment' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: '/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: '/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: '/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: '/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: '/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
const WRAPPER = Symbol('wrapper'); /** * @function * @description Decorator function that convert a class method to a getter */ export default function getter( prototype, property, { initializer, value, get }, ) { return { configurable: true, enumerable: true, get() { if (!this[WRAPPER]) { this[WRAPPER] = {}; } if (!this[WRAPPER][property]) { const targetSymbol = Symbol(`${property}-target`); this[targetSymbol] = initializer ? this::initializer() : value || get; this[WRAPPER][property] = typeof this[targetSymbol] === 'function' ? () => this[targetSymbol]() : () => this[targetSymbol]; } return this[WRAPPER][property](); }, }; }
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2015 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define(['jquery.sap.global', './SplitContainerRenderer', 'sap/ui/core/Renderer'], function(jQuery, SplitContainerRenderer, Renderer) { "use strict"; /** * SplitApp renderer. * @namespace */ var SplitAppRenderer = { }; var SplitAppRenderer = Renderer.extend(SplitContainerRenderer); SplitAppRenderer.renderAttributes = function(oRm, oControl){ sap.m.BackgroundHelper.addBackgroundColorStyles(oRm, oControl.getBackgroundColor(), oControl.getBackgroundImage()); }; SplitAppRenderer.renderBeforeContent = function(oRm, oControl){ sap.m.BackgroundHelper.renderBackgroundImageTag(oRm, oControl, "sapMSplitContainerBG", oControl.getBackgroundImage(), oControl.getBackgroundRepeat(), oControl.getBackgroundOpacity()); }; return SplitAppRenderer; }, /* bExport= */ true);
import DS from 'ember-data'; import BackboneElement from 'ember-fhir/models/backbone-element'; const { belongsTo, hasMany } = DS; export default BackboneElement.extend({ resource: belongsTo('reference', { async: false }), param: hasMany('test-script-param', { async: true }) });
module.exports = function ( grunt ) { // Project configuration. grunt.initConfig({ pkg : grunt.file.readJSON( 'package.json' ), jshint : { options: { jshintrc: true }, files : ['src/javascripts/**/*.js'] }, browserify : { js: { src: 'src/javascripts/main.js', dest: 'dist/preamble.js' } }, usebanner: { dist: { options: { position: 'top', banner: '/* <%= pkg.title %> v<%= pkg.version %>' + ' - released on <%= grunt.template.today("yyyy-mm-dd") %>' + ' at <%= grunt.template.today("longTime") %>\n' + ' * <%= pkg.preamble.copyright %>\n' + ' * <%= pkg.preamble.distrights%>\n' + '*/', linebreak: true }, files: { src: [ 'dist/preamble.js', 'dist/preamble.js' ] } } }, watch : { js : { files : ['src/javascripts/**/*.js'], tasks : ['jshint'], options : { interrupt : true } }, browserify : { files : ['src/javascripts/**/*.js'], tasks : ['browserify'], options : { interrupt : true } }, banner : { files : ['dist/preamble.js'], tasks : ['usebanner'], options : { interrupt : true } } } }); // Load the plugins grunt.loadNpmTasks( 'grunt-contrib-watch' ); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-browserify'); grunt.loadNpmTasks('grunt-banner'); // Default task(s). grunt.registerTask( 'default', ['watch'] ); grunt.registerTask( 'dist', ['jshint', 'browserify', 'usebanner'] ); };
'use strict'; const User = require('../../models/admin/user'), Role = require('../../models/admin/role'), page = require('../../util/page'), _ = require('lodash'); module.exports = class UserController { /** * Display a list of users. */ static index(req, res) { page(User, req).then(data => { res.render('admin/user/index', data); }); } /** * Render the form for editing a user. */ static edit(req, res) { let id = req.params.id, view = 'admin/user/form', roles = {'admin': 'Admin'}; Role.where({}).then(cursor => { cursor.project({'name': 1}).forEach(role => { roles[role._id] = role.name; }, err => { if (id) { User.find(id).then(user => { res.render(view, {doc: user.data, roles}); }); } else { res.render(view, {doc: {}, roles}); } }); }); } /** * Save a user. */ static save(req, res) { let data = _.pick(req.body, _.concat(User.keys, 'password')); User.save(data, req.params.id).then( result => { req.flash('success', 'Saved successfully!'); res.redirect('/admin/users'); }, err =>{ _.pull(data, 'password'); req.flash('error', 'An error happened'); req.flash('old', data); res.redirect('back'); }); } /** * Delete a user. */ static delete(req, res) { User.delete(req.params.id).then( count => { req.flash('success', 'Deleted successfully!'); res.redirect('/admin/users'); }, err => { req.flash('error', 'An error happened'); res.redirect('back'); }); } }
/** * File * * @author Tijme Gommers <t.gommers@jetcat.nl> * @package server.helpers */ module.exports = { /** * @var Object */ fs: require('fs'), /** * File exists * * @param string Path to the file * @return boolean exists */ exists: function(file) { try { var stats = module.exports.fs.statSync(file); return true; } catch(e) { return false; } }, /** * Create a file * * @param string Path to the file * @param string Content of the file * @return boolean created */ create: function(file, content) { try { module.exports.fs.writeFileSync(file, content); } catch(e) { console.log(e); return false; } } }
/*! WebUploader 0.1.6 */ /** * @fileOverview 让内部各个部件的代码可以用[amd](https://github.com/amdjs/amdjs-api/wiki/AMD)模块定义方式组织起来。 * * AMD API 内部的简单不完全实现,请忽略。只有当WebUploader被合并成一个文件的时候才会引入。 */ (function (root, factory) { var modules = {}, // 内部require, 简单不完全实现。 // https://github.com/amdjs/amdjs-api/wiki/require _require = function (deps, callback) { var args, len, i; // 如果deps不是数组,则直接返回指定module if (typeof deps === 'string') { return getModule(deps); } else { args = []; for (len = deps.length, i = 0; i < len; i++) { args.push(getModule(deps[i])); } return callback.apply(null, args); } }, // 内部define,暂时不支持不指定id. _define = function (id, deps, factory) { if (arguments.length === 2) { factory = deps; deps = null; } _require(deps || [], function () { setModule(id, factory, arguments); }); }, // 设置module, 兼容CommonJs写法。 setModule = function (id, factory, args) { var module = { exports: factory }, returned; if (typeof factory === 'function') { args.length || (args = [_require, module.exports, module]); returned = factory.apply(null, args); returned !== undefined && (module.exports = returned); } modules[id] = module.exports; }, // 根据id获取module getModule = function (id) { var module = modules[id] || root[id]; if (!module) { throw new Error('`' + id + '` is undefined'); } return module; }, // 将所有modules,将路径ids装换成对象。 exportsTo = function (obj) { var key, host, parts, part, last, ucFirst; // make the first character upper case. ucFirst = function (str) { return str && (str.charAt(0).toUpperCase() + str.substr(1)); }; for (key in modules) { host = obj; if (!modules.hasOwnProperty(key)) { continue; } parts = key.split('/'); last = ucFirst(parts.pop()); while ((part = ucFirst(parts.shift()))) { host[part] = host[part] || {}; host = host[part]; } host[last] = modules[key]; } return obj; }, makeExport = function (dollar) { root.__dollar = dollar; // exports every module. return exportsTo(factory(root, _define, _require)); }, origin; if (typeof module === 'object' && typeof module.exports === 'object') { // For CommonJS and CommonJS-like environments where a proper window is present, module.exports = makeExport(); } else if (typeof define === 'function' && define.amd) { // Allow using this built library as an AMD module // in another project. That other project will only // see this AMD call, not the internal modules in // the closure below. define(['jquery'], makeExport); } else { // Browser globals case. Just assign the // result to a property on the global. origin = root.WebUploader; root.WebUploader = makeExport(); root.WebUploader.noConflict = function () { root.WebUploader = origin; }; } })(window, function (window, define, require) { /** * @fileOverview jQuery or Zepto * @require "jquery" * @require "zepto" */ define('dollar-third', [], function () { var req = window.require; var $ = window.__dollar || window.jQuery || window.Zepto || req('jquery') || req('zepto'); if (!$) { throw new Error('jQuery or Zepto not found!'); } return $; }); /** * @fileOverview Dom 操作相关 */ define('dollar', [ 'dollar-third' ], function (_) { return _; }); /** * 直接来源于jquery的代码。 * @fileOverview Promise/A+ * @beta */ define('promise-builtin', [ 'dollar' ], function ($) { var api; // 简单版Callbacks, 默认memory,可选once. function Callbacks(once) { var list = [], stack = !once && [], fire = function (data) { memory = data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for (; list && firingIndex < firingLength; firingIndex++) { list[firingIndex].apply(data[0], data[1]); } firing = false; if (list) { if (stack) { stack.length && fire(stack.shift()); } else { list = []; } } }, self = { add: function () { if (list) { var start = list.length; (function add(args) { $.each(args, function (_, arg) { var type = $.type(arg); if (type === 'function') { list.push(arg); } else if (arg && arg.length && type !== 'string') { add(arg); } }); })(arguments); if (firing) { firingLength = list.length; } else if (memory) { firingStart = start; fire(memory); } } return this; }, disable: function () { list = stack = memory = undefined; return this; }, // Lock the list in its current state lock: function () { stack = undefined; if (!memory) { self.disable(); } return this; }, fireWith: function (context, args) { if (list && (!fired || stack)) { args = args || []; args = [context, args.slice ? args.slice() : args]; if (firing) { stack.push(args); } else { fire(args); } } return this; }, fire: function () { self.fireWith(this, arguments); return this; } }, fired, firing, firingStart, firingLength, firingIndex, memory; return self; } function Deferred(func) { var tuples = [ // action, add listener, listener list, final state ['resolve', 'done', Callbacks(true), 'resolved'], ['reject', 'fail', Callbacks(true), 'rejected'], ['notify', 'progress', Callbacks()] ], state = 'pending', promise = { state: function () { return state; }, always: function () { deferred.done(arguments).fail(arguments); return this; }, then: function (/* fnDone, fnFail, fnProgress */) { var fns = arguments; return Deferred(function (newDefer) { $.each(tuples, function (i, tuple) { var action = tuple[0], fn = $.isFunction(fns[i]) && fns[i]; // deferred[ done | fail | progress ] for // forwarding actions to newDefer deferred[tuple[1]](function () { var returned; returned = fn && fn.apply(this, arguments); if (returned && $.isFunction(returned.promise)) { returned.promise() .done(newDefer.resolve) .fail(newDefer.reject) .progress(newDefer.notify); } else { newDefer[action + 'With']( this === promise ? newDefer.promise() : this, fn ? [returned] : arguments); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If dbhandle is provided, the promise aspect is added to the object promise: function (obj) { return obj != null ? $.extend(obj, promise) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods $.each(tuples, function (i, tuple) { var list = tuple[2], stateString = tuple[3]; // promise[ done | fail | progress ] = list.add promise[tuple[1]] = list.add; // Handle state if (stateString) { list.add(function () { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[i ^ 1][2].disable, tuples[2][2].lock); } // deferred[ resolve | reject | notify ] deferred[tuple[0]] = function () { deferred[tuple[0] + 'With'](this === deferred ? promise : this, arguments); return this; }; deferred[tuple[0] + 'With'] = list.fireWith; }); // Make the deferred a promise promise.promise(deferred); // Call given func if any if (func) { func.call(deferred, deferred); } // All done! return deferred; } api = { /** * 创建一个[Deferred](http://api.jquery.com/category/deferred-object/)对象。 * 详细的Deferred用法说明,请参照jQuery的API文档。 * * Deferred对象在钩子回掉函数中经常要用到,用来处理需要等待的异步操作。 * * @for Base * @method Deferred * @grammar Base.Deferred() => Deferred * @example * // 在文件开始发送前做些异步操作。 * // WebUploader会等待此异步操作完成后,开始发送文件。 * Uploader.register({ * 'before-send-file': 'doSomthingAsync' * }, { * * doSomthingAsync: function() { * var deferred = Base.Deferred(); * * // 模拟一次异步操作。 * setTimeout(deferred.resolve, 2000); * * return deferred.promise(); * } * }); */ Deferred: Deferred, /** * 判断传入的参数是否为一个promise对象。 * @method isPromise * @grammar Base.isPromise( anything ) => Boolean * @param {*} anything 检测对象。 * @return {Boolean} * @for Base * @example * console.log( Base.isPromise() ); // => false * console.log( Base.isPromise({ key: '123' }) ); // => false * console.log( Base.isPromise( Base.Deferred().promise() ) ); // => true * * // Deferred也是一个Promise * console.log( Base.isPromise( Base.Deferred() ) ); // => true */ isPromise: function (anything) { return anything && typeof anything.then === 'function'; }, /** * 返回一个promise,此promise在所有传入的promise都完成了后完成。 * 详细请查看[这里](http://api.jquery.com/jQuery.when/)。 * * @method when * @for Base * @grammar Base.when( promise1[, promise2[, promise3...]] ) => Promise */ when: function (subordinate /* , ..., subordinateN */) { var i = 0, slice = [].slice, resolveValues = slice.call(arguments), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || (subordinate && $.isFunction(subordinate.promise)) ? length : 0, // the master Deferred. If resolveValues consist of // only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : Deferred(), // Update function for both resolve and progress values updateFunc = function (i, contexts, values) { return function (value) { contexts[i] = this; values[i] = arguments.length > 1 ? slice.call(arguments) : value; if (values === progressValues) { deferred.notifyWith(contexts, values); } else if (!(--remaining)) { deferred.resolveWith(contexts, values); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if (length > 1) { progressValues = new Array(length); progressContexts = new Array(length); resolveContexts = new Array(length); for (; i < length; i++) { if (resolveValues[i] && $.isFunction(resolveValues[i].promise)) { resolveValues[i].promise() .done(updateFunc(i, resolveContexts, resolveValues)) .fail(deferred.reject) .progress(updateFunc(i, progressContexts, progressValues)); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if (!remaining) { deferred.resolveWith(resolveContexts, resolveValues); } return deferred.promise(); } }; return api; }); define('promise', [ 'promise-builtin' ], function ($) { return $; }); /** * @fileOverview 基础类方法。 */ /** * Web Uploader内部类的详细说明,以下提及的功能类,都可以在`WebUploader`这个变量中访问到。 * * As you know, Web Uploader的每个文件都是用过[AMD](https://github.com/amdjs/amdjs-api/wiki/AMD)规范中的`define`组织起来的, 每个Module都会有个module id. * 默认module id为该文件的路径,而此路径将会转化成名字空间存放在WebUploader中。如: * * * module `base`:WebUploader.Base * * module `file`: WebUploader.File * * module `lib/dnd`: WebUploader.Lib.Dnd * * module `runtime/html5/dnd`: WebUploader.Runtime.Html5.Dnd * * * 以下文档中对类的使用可能省略掉了`WebUploader`前缀。 * @module WebUploader * @title WebUploader API文档 */ define('base', [ 'dollar', 'promise' ], function ($, promise) { var noop = function () { }, call = Function.call; // http://jsperf.com/uncurrythis // 反科里化 function uncurryThis(fn) { return function () { return call.apply(fn, arguments); }; } function bindFn(fn, context) { return function () { return fn.apply(context, arguments); }; } function createObject(proto) { var f; if (Object.create) { return Object.create(proto); } else { f = function () { }; f.prototype = proto; return new f(); } } /** * 基础类,提供一些简单常用的方法。 * @class Base */ return { /** * @property {String} version 当前版本号。 */ version: '0.1.6', /** * @property {jQuery|Zepto} $ 引用依赖的jQuery或者Zepto对象。 */ $: $, Deferred: promise.Deferred, isPromise: promise.isPromise, when: promise.when, /** * @description 简单的浏览器检查结果。 * * * `webkit` webkit版本号,如果浏览器为非webkit内核,此属性为`undefined`。 * * `chrome` chrome浏览器版本号,如果浏览器为chrome,此属性为`undefined`。 * * `ie` ie浏览器版本号,如果浏览器为非ie,此属性为`undefined`。**暂不支持ie10+** * * `firefox` firefox浏览器版本号,如果浏览器为非firefox,此属性为`undefined`。 * * `safari` safari浏览器版本号,如果浏览器为非safari,此属性为`undefined`。 * * `opera` opera浏览器版本号,如果浏览器为非opera,此属性为`undefined`。 * * @property {Object} [browser] */ browser: (function (ua) { var ret = {}, webkit = ua.match(/WebKit\/([\d.]+)/), chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/), ie = ua.match(/MSIE\s([\d\.]+)/) || ua.match(/(?:trident)(?:.*rv:([\w.]+))?/i), firefox = ua.match(/Firefox\/([\d.]+)/), safari = ua.match(/Safari\/([\d.]+)/), opera = ua.match(/OPR\/([\d.]+)/); webkit && (ret.webkit = parseFloat(webkit[1])); chrome && (ret.chrome = parseFloat(chrome[1])); ie && (ret.ie = parseFloat(ie[1])); firefox && (ret.firefox = parseFloat(firefox[1])); safari && (ret.safari = parseFloat(safari[1])); opera && (ret.opera = parseFloat(opera[1])); return ret; })(navigator.userAgent), /** * @description 操作系统检查结果。 * * * `android` 如果在android浏览器环境下,此值为对应的android版本号,否则为`undefined`。 * * `ios` 如果在ios浏览器环境下,此值为对应的ios版本号,否则为`undefined`。 * @property {Object} [os] */ os: (function (ua) { var ret = {}, // osx = !!ua.match( /\(Macintosh\; Intel / ), android = ua.match(/(?:Android);?[\s\/]+([\d.]+)?/), ios = ua.match(/(?:iPad|iPod|iPhone).*OS\s([\d_]+)/); // osx && (ret.osx = true); android && (ret.android = parseFloat(android[1])); ios && (ret.ios = parseFloat(ios[1].replace(/_/g, '.'))); return ret; })(navigator.userAgent), /** * 实现类与类之间的继承。 * @method inherits * @grammar Base.inherits( super ) => child * @grammar Base.inherits( super, protos ) => child * @grammar Base.inherits( super, protos, statics ) => child * @param {Class} super 父类 * @param {Object | Function} [protos] 子类或者对象。如果对象中包含constructor,子类将是用此属性值。 * @param {Function} [protos.constructor] 子类构造器,不指定的话将创建个临时的直接执行父类构造器的方法。 * @param {Object} [statics] 静态属性或方法。 * @return {Class} 返回子类。 * @example * function Person() { * console.log( 'Super' ); * } * Person.prototype.hello = function() { * console.log( 'hello' ); * }; * * var Manager = Base.inherits( Person, { * world: function() { * console.log( 'World' ); * } * }); * * // 因为没有指定构造器,父类的构造器将会执行。 * var instance = new Manager(); // => Super * * // 继承子父类的方法 * instance.hello(); // => hello * instance.world(); // => World * * // 子类的__super__属性指向父类 * console.log( Manager.__super__ === Person ); // => true */ inherits: function (Super, protos, staticProtos) { var child; if (typeof protos === 'function') { child = protos; protos = null; } else if (protos && protos.hasOwnProperty('constructor')) { child = protos.constructor; } else { child = function () { return Super.apply(this, arguments); }; } // 复制静态方法 $.extend(true, child, Super, staticProtos || {}); /* jshint camelcase: false */ // 让子类的__super__属性指向父类。 child.__super__ = Super.prototype; // 构建原型,添加原型方法或属性。 // 暂时用Object.create实现。 child.prototype = createObject(Super.prototype); protos && $.extend(true, child.prototype, protos); return child; }, /** * 一个不做任何事情的方法。可以用来赋值给默认的callback. * @method noop */ noop: noop, /** * 返回一个新的方法,此方法将已指定的`context`来执行。 * @grammar Base.bindFn( fn, context ) => Function * @method bindFn * @example * var doSomething = function() { * console.log( this.name ); * }, * dbhandle = { * name: 'Object Name' * }, * aliasFn = Base.bind( doSomething, dbhandle ); * * aliasFn(); // => Object Name * */ bindFn: bindFn, /** * 引用Console.log如果存在的话,否则引用一个[空函数noop](#WebUploader:Base.noop)。 * @grammar Base.log( args... ) => undefined * @method log */ log: (function () { if (window.console) { return bindFn(console.log, console); } return noop; })(), nextTick: (function () { return function (cb) { setTimeout(cb, 1); }; // @bug 当浏览器不在当前窗口时就停了。 // var next = window.requestAnimationFrame || // window.webkitRequestAnimationFrame || // window.mozRequestAnimationFrame || // function( cb ) { // window.setTimeout( cb, 1000 / 60 ); // }; // // fix: Uncaught TypeError: Illegal invocation // return bindFn( next, window ); })(), /** * 被[uncurrythis](http://www.2ality.com/2011/11/uncurrying-this.html)的数组slice方法。 * 将用来将非数组对象转化成数组对象。 * @grammar Base.slice( target, start[, end] ) => Array * @method slice * @example * function doSomthing() { * var args = Base.slice( arguments, 1 ); * console.log( args ); * } * * doSomthing( 'ignored', 'arg2', 'arg3' ); // => Array ["arg2", "arg3"] */ slice: uncurryThis([].slice), /** * 生成唯一的ID * @method guid * @grammar Base.guid() => String * @grammar Base.guid( prefx ) => String */ guid: (function () { var counter = 0; return function (prefix) { var guid = (+new Date()).toString(32), i = 0; for (; i < 5; i++) { guid += Math.floor(Math.random() * 65535).toString(32); } return (prefix || 'wu_') + guid + (counter++).toString(32); }; })(), /** * 格式化文件大小, 输出成带单位的字符串 * @method formatSize * @grammar Base.formatSize( size ) => String * @grammar Base.formatSize( size, pointLength ) => String * @grammar Base.formatSize( size, pointLength, units ) => String * @param {Number} size 文件大小 * @param {Number} [pointLength=2] 精确到的小数点数。 * @param {Array} [units=[ 'B', 'K', 'M', 'G', 'TB' ]] 单位数组。从字节,到千字节,一直往上指定。如果单位数组里面只指定了到了K(千字节),同时文件大小大于M, 此方法的输出将还是显示成多少K. * @example * console.log( Base.formatSize( 100 ) ); // => 100B * console.log( Base.formatSize( 1024 ) ); // => 1.00K * console.log( Base.formatSize( 1024, 0 ) ); // => 1K * console.log( Base.formatSize( 1024 * 1024 ) ); // => 1.00M * console.log( Base.formatSize( 1024 * 1024 * 1024 ) ); // => 1.00G * console.log( Base.formatSize( 1024 * 1024 * 1024, 0, ['B', 'KB', 'MB'] ) ); // => 1024MB */ formatSize: function (size, pointLength, units) { var unit; units = units || ['B', 'K', 'M', 'G', 'TB']; while ((unit = units.shift()) && size > 1024) { size = size / 1024; } return (unit === 'B' ? size : size.toFixed(pointLength || 2)) + unit; } }; }); /** * 事件处理类,可以独立使用,也可以扩展给对象使用。 * @fileOverview Mediator */ define('mediator', [ 'base' ], function (Base) { var $ = Base.$, slice = [].slice, separator = /\s+/, protos; // 根据条件过滤出事件handlers. function findHandlers(arr, name, callback, context) { return $.grep(arr, function (handler) { return handler && (!name || handler.e === name) && (!callback || handler.cb === callback || handler.cb._cb === callback) && (!context || handler.ctx === context); }); } function eachEvent(events, callback, iterator) { // 不支持对象,只支持多个event用空格隔开 $.each((events || '').split(separator), function (_, key) { iterator(key, callback); }); } function triggerHanders(events, args) { var stoped = false, i = -1, len = events.length, handler; while (++i < len) { handler = events[i]; if (handler.cb.apply(handler.ctx2, args) === false) { stoped = true; break; } } return !stoped; } protos = { /** * 绑定事件。 * * `callback`方法在执行时,arguments将会来源于trigger的时候携带的参数。如 * ```javascript * var dbhandle = {}; * * // 使得obj有事件行为 * Mediator.installTo( dbhandle ); * * dbhandle.on( 'testa', function( arg1, arg2 ) { * console.log( arg1, arg2 ); // => 'arg1', 'arg2' * }); * * dbhandle.trigger( 'testa', 'arg1', 'arg2' ); * ``` * * 如果`callback`中,某一个方法`return false`了,则后续的其他`callback`都不会被执行到。 * 切会影响到`trigger`方法的返回值,为`false`。 * * `on`还可以用来添加一个特殊事件`all`, 这样所有的事件触发都会响应到。同时此类`callback`中的arguments有一个不同处, * 就是第一个参数为`type`,记录当前是什么事件在触发。此类`callback`的优先级比脚低,会再正常`callback`执行完后触发。 * ```javascript * dbhandle.on( 'all', function( type, arg1, arg2 ) { * console.log( type, arg1, arg2 ); // => 'testa', 'arg1', 'arg2' * }); * ``` * * @method on * @grammar on( name, callback[, context] ) => self * @param {String} name 事件名,支持多个事件用空格隔开 * @param {Function} callback 事件处理器 * @param {Object} [context] 事件处理器的上下文。 * @return {self} 返回自身,方便链式 * @chainable * @class Mediator */ on: function (name, callback, context) { var me = this, set; if (!callback) { return this; } set = this._events || (this._events = []); eachEvent(name, callback, function (name, callback) { var handler = {e: name}; handler.cb = callback; handler.ctx = context; handler.ctx2 = context || me; handler.id = set.length; set.push(handler); }); return this; }, /** * 绑定事件,且当handler执行完后,自动解除绑定。 * @method once * @grammar once( name, callback[, context] ) => self * @param {String} name 事件名 * @param {Function} callback 事件处理器 * @param {Object} [context] 事件处理器的上下文。 * @return {self} 返回自身,方便链式 * @chainable */ once: function (name, callback, context) { var me = this; if (!callback) { return me; } eachEvent(name, callback, function (name, callback) { var once = function () { me.off(name, once); return callback.apply(context || me, arguments); }; once._cb = callback; me.on(name, once, context); }); return me; }, /** * 解除事件绑定 * @method off * @grammar off( [name[, callback[, context] ] ] ) => self * @param {String} [name] 事件名 * @param {Function} [callback] 事件处理器 * @param {Object} [context] 事件处理器的上下文。 * @return {self} 返回自身,方便链式 * @chainable */ off: function (name, cb, ctx) { var events = this._events; if (!events) { return this; } if (!name && !cb && !ctx) { this._events = []; return this; } eachEvent(name, cb, function (name, cb) { $.each(findHandlers(events, name, cb, ctx), function () { delete events[this.id]; }); }); return this; }, /** * 触发事件 * @method trigger * @grammar trigger( name[, args...] ) => self * @param {String} type 事件名 * @param {*} [...] 任意参数 * @return {Boolean} 如果handler中return false了,则返回false, 否则返回true */ trigger: function (type) { var args, events, allEvents; if (!this._events || !type) { return this; } args = slice.call(arguments, 1); events = findHandlers(this._events, type); allEvents = findHandlers(this._events, 'all'); return triggerHanders(events, args) && triggerHanders(allEvents, arguments); } }; /** * 中介者,它本身是个单例,但可以通过[installTo](#WebUploader:Mediator:installTo)方法,使任何对象具备事件行为。 * 主要目的是负责模块与模块之间的合作,降低耦合度。 * * @class Mediator */ return $.extend({ /** * 可以通过这个接口,使任何对象具备事件功能。 * @method installTo * @param {Object} obj 需要具备事件行为的对象。 * @return {Object} 返回obj. */ installTo: function (obj) { return $.extend(obj, protos); } }, protos); }); /** * @fileOverview Uploader上传类 */ define('uploader', [ 'base', 'mediator' ], function (Base, Mediator) { var $ = Base.$; /** * 上传入口类。 * @class Uploader * @constructor * @grammar new Uploader( opts ) => Uploader * @example * var uploader = WebUploader.Uploader({ * swf: 'path_of_swf/Uploader.swf', * * // 开起分片上传。 * chunked: true * }); */ function Uploader(opts) { this.options = $.extend(true, {}, Uploader.options, opts); this._init(this.options); } // default Options // widgets中有相应扩展 Uploader.options = {}; Mediator.installTo(Uploader.prototype); // 批量添加纯命令式方法。 $.each({ upload: 'start-upload', stop: 'stop-upload', getFile: 'get-file', getFiles: 'get-files', addFile: 'add-file', addFiles: 'add-file', sort: 'sort-files', removeFile: 'remove-file', cancelFile: 'cancel-file', skipFile: 'skip-file', retry: 'retry', isInProgress: 'is-in-progress', makeThumb: 'make-thumb', md5File: 'md5-file', getDimension: 'get-dimension', addButton: 'add-btn', predictRuntimeType: 'predict-runtime-type', refresh: 'refresh', disable: 'disable', enable: 'enable', reset: 'reset' }, function (fn, command) { Uploader.prototype[fn] = function () { return this.request(command, arguments); }; }); $.extend(Uploader.prototype, { state: 'pending', _init: function (opts) { var me = this; me.request('init', opts, function () { me.state = 'ready'; me.trigger('ready'); }); }, /** * 获取或者设置Uploader配置项。 * @method option * @grammar option( key ) => * * @grammar option( key, val ) => self * @example * * // 初始状态图片上传前不会压缩 * var uploader = new WebUploader.Uploader({ * compress: null; * }); * * // 修改后图片上传前,尝试将图片压缩到1600 * 1600 * uploader.option( 'compress', { * width: 1600, * height: 1600 * }); */ option: function (key, val) { var opts = this.options; // setter if (arguments.length > 1) { if ($.isPlainObject(val) && $.isPlainObject(opts[key])) { $.extend(opts[key], val); } else { opts[key] = val; } } else { // getter return key ? opts[key] : opts; } }, /** * 获取文件统计信息。返回一个包含一下信息的对象。 * * `successNum` 上传成功的文件数 * * `progressNum` 上传中的文件数 * * `cancelNum` 被删除的文件数 * * `invalidNum` 无效的文件数 * * `uploadFailNum` 上传失败的文件数 * * `queueNum` 还在队列中的文件数 * * `interruptNum` 被暂停的文件数 * @method getStats * @grammar getStats() => Object */ getStats: function () { // return this._mgr.getStats.apply( this._mgr, arguments ); var stats = this.request('get-stats'); return stats ? { successNum: stats.numOfSuccess, progressNum: stats.numOfProgress, // who care? // queueFailNum: 0, cancelNum: stats.numOfCancel, invalidNum: stats.numOfInvalid, uploadFailNum: stats.numOfUploadFailed, queueNum: stats.numOfQueue, interruptNum: stats.numofInterrupt } : {}; }, // 需要重写此方法来来支持opts.onEvent和instance.onEvent的处理器 trigger: function (type/*, args...*/) { var args = [].slice.call(arguments, 1), opts = this.options, name = 'on' + type.substring(0, 1).toUpperCase() + type.substring(1); if ( // 调用通过on方法注册的handler. Mediator.trigger.apply(this, arguments) === false || // 调用opts.onEvent $.isFunction(opts[name]) && opts[name].apply(this, args) === false || // 调用this.onEvent $.isFunction(this[name]) && this[name].apply(this, args) === false || // 广播所有uploader的事件。 Mediator.trigger.apply(Mediator, [this, type].concat(args)) === false) { return false; } return true; }, /** * 销毁 webuploader 实例 * @method destroy * @grammar destroy() => undefined */ destroy: function () { this.request('destroy', arguments); this.off(); }, // widgets/widget.js将补充此方法的详细文档。 request: Base.noop }); /** * 创建Uploader实例,等同于new Uploader( opts ); * @method create * @class Base * @static * @grammar Base.create( opts ) => Uploader */ Base.create = Uploader.create = function (opts) { return new Uploader(opts); }; // 暴露Uploader,可以通过它来扩展业务逻辑。 Base.Uploader = Uploader; return Uploader; }); /** * @fileOverview Runtime管理器,负责Runtime的选择, 连接 */ define('runtime/runtime', [ 'base', 'mediator' ], function (Base, Mediator) { var $ = Base.$, factories = {}, // 获取对象的第一个key getFirstKey = function (obj) { for (var key in obj) { if (obj.hasOwnProperty(key)) { return key; } } return null; }; // 接口类。 function Runtime(options) { this.options = $.extend({ container: document.body }, options); this.uid = Base.guid('rt_'); } $.extend(Runtime.prototype, { getContainer: function () { var opts = this.options, parent, container; if (this._container) { return this._container; } parent = $(opts.container || document.body); container = $(document.createElement('div')); container.attr('id', 'rt_' + this.uid); container.css({ position: 'absolute', top: '0px', left: '0px', width: '1px', height: '1px', overflow: 'hidden' }); parent.append(container); parent.addClass('webuploader-container'); this._container = container; this._parent = parent; return container; }, init: Base.noop, exec: Base.noop, destroy: function () { this._container && this._container.remove(); this._parent && this._parent.removeClass('webuploader-container'); this.off(); } }); Runtime.orders = 'html5,flash'; /** * 添加Runtime实现。 * @param {String} type 类型 * @param {Runtime} factory 具体Runtime实现。 */ Runtime.addRuntime = function (type, factory) { factories[type] = factory; }; Runtime.hasRuntime = function (type) { return !!(type ? factories[type] : getFirstKey(factories)); }; Runtime.create = function (opts, orders) { var type, runtime; orders = orders || Runtime.orders; $.each(orders.split(/\s*,\s*/g), function () { if (factories[this]) { type = this; return false; } }); type = type || getFirstKey(factories); if (!type) { throw new Error('Runtime Error'); } runtime = new factories[type](opts); return runtime; }; Mediator.installTo(Runtime.prototype); return Runtime; }); /** * @fileOverview Runtime管理器,负责Runtime的选择, 连接 */ define('runtime/client', [ 'base', 'mediator', 'runtime/runtime' ], function (Base, Mediator, Runtime) { var cache; cache = (function () { var obj = {}; return { add: function (runtime) { obj[runtime.uid] = runtime; }, get: function (ruid, standalone) { var i; if (ruid) { return obj[ruid]; } for (i in obj) { // 有些类型不能重用,比如filepicker. if (standalone && obj[i].__standalone) { continue; } return obj[i]; } return null; }, remove: function (runtime) { delete obj[runtime.uid]; } }; })(); function RuntimeClient(component, standalone) { var deferred = Base.Deferred(), runtime; this.uid = Base.guid('client_'); // 允许runtime没有初始化之前,注册一些方法在初始化后执行。 this.runtimeReady = function (cb) { return deferred.done(cb); }; this.connectRuntime = function (opts, cb) { // already connected. if (runtime) { throw new Error('already connected!'); } deferred.done(cb); if (typeof opts === 'string' && cache.get(opts)) { runtime = cache.get(opts); } // 像filePicker只能独立存在,不能公用。 runtime = runtime || cache.get(null, standalone); // 需要创建 if (!runtime) { runtime = Runtime.create(opts, opts.runtimeOrder); runtime.__promise = deferred.promise(); runtime.once('ready', deferred.resolve); runtime.init(); cache.add(runtime); runtime.__client = 1; } else { // 来自cache Base.$.extend(runtime.options, opts); runtime.__promise.then(deferred.resolve); runtime.__client++; } standalone && (runtime.__standalone = standalone); return runtime; }; this.getRuntime = function () { return runtime; }; this.disconnectRuntime = function () { if (!runtime) { return; } runtime.__client--; if (runtime.__client <= 0) { cache.remove(runtime); delete runtime.__promise; runtime.destroy(); } runtime = null; }; this.exec = function () { if (!runtime) { return; } var args = Base.slice(arguments); component && args.unshift(component); return runtime.exec.apply(this, args); }; this.getRuid = function () { return runtime && runtime.uid; }; this.destroy = (function (destroy) { return function () { destroy && destroy.apply(this, arguments); this.trigger('destroy'); this.off(); this.exec('destroy'); this.disconnectRuntime(); }; })(this.destroy); } Mediator.installTo(RuntimeClient.prototype); return RuntimeClient; }); /** * @fileOverview Blob */ define('lib/blob', [ 'base', 'runtime/client' ], function (Base, RuntimeClient) { function Blob(ruid, source) { var me = this; me.source = source; me.ruid = ruid; this.size = source.size || 0; // 如果没有指定 mimetype, 但是知道文件后缀。 if (!source.type && this.ext && ~'jpg,jpeg,png,gif,bmp'.indexOf(this.ext)) { this.type = 'image/' + (this.ext === 'jpg' ? 'jpeg' : this.ext); } else { this.type = source.type || 'application/octet-stream'; } RuntimeClient.call(me, 'Blob'); this.uid = source.uid || this.uid; if (ruid) { me.connectRuntime(ruid); } } Base.inherits(RuntimeClient, { constructor: Blob, slice: function (start, end) { return this.exec('slice', start, end); }, getSource: function () { return this.source; } }); return Blob; }); /** * 为了统一化Flash的File和HTML5的File而存在。 * 以至于要调用Flash里面的File,也可以像调用HTML5版本的File一下。 * @fileOverview File */ define('lib/file', [ 'base', 'lib/blob' ], function (Base, Blob) { var uid = 1, rExt = /\.([^.]+)$/; function File(ruid, file) { var ext; this.name = file.name || ('untitled' + uid++); ext = rExt.exec(file.name) ? RegExp.$1.toLowerCase() : ''; // todo 支持其他类型文件的转换。 // 如果有 mimetype, 但是文件名里面没有找出后缀规律 if (!ext && file.type) { ext = /\/(jpg|jpeg|png|gif|bmp)$/i.exec(file.type) ? RegExp.$1.toLowerCase() : ''; this.name += '.' + ext; } this.ext = ext; this.lastModifiedDate = file.lastModifiedDate || (new Date()).toLocaleString(); Blob.apply(this, arguments); } return Base.inherits(Blob, File); }); /** * @fileOverview 错误信息 */ define('lib/filepicker', [ 'base', 'runtime/client', 'lib/file' ], function (Base, RuntimeClient, File) { var $ = Base.$; function FilePicker(opts) { opts = this.options = $.extend({}, FilePicker.options, opts); opts.container = $(opts.id); if (!opts.container.length) { throw new Error('按钮指定错误'); } opts.innerHTML = opts.innerHTML || opts.label || opts.container.html() || ''; opts.button = $(opts.button || document.createElement('div')); opts.button.html(opts.innerHTML); opts.container.html(opts.button); RuntimeClient.call(this, 'FilePicker', true); } FilePicker.options = { button: null, container: null, label: null, innerHTML: null, multiple: true, accept: null, name: 'file', style: 'webuploader-pick' //pick element class attribute, default is "webuploader-pick" }; Base.inherits(RuntimeClient, { constructor: FilePicker, init: function () { var me = this, opts = me.options, button = opts.button, style = opts.style; if (style) button.addClass('webuploader-pick'); me.on('all', function (type) { var files; switch (type) { case 'mouseenter': if (style) button.addClass('webuploader-pick-hover'); break; case 'mouseleave': if (style) button.removeClass('webuploader-pick-hover'); break; case 'change': files = me.exec('getFiles'); me.trigger('select', $.map(files, function (file) { file = new File(me.getRuid(), file); // 记录来源。 file._refer = opts.container; return file; }), opts.container); break; } }); me.connectRuntime(opts, function () { me.refresh(); me.exec('init', opts); me.trigger('ready'); }); this._resizeHandler = Base.bindFn(this.refresh, this); $(window).on('resize', this._resizeHandler); }, refresh: function () { var shimContainer = this.getRuntime().getContainer(), button = this.options.button, width = button.outerWidth ? button.outerWidth() : button.width(), height = button.outerHeight ? button.outerHeight() : button.height(), pos = button.offset(); width && height && shimContainer.css({ bottom: 'auto', right: 'auto', width: width + 'px', height: height + 'px' }).offset(pos); }, enable: function () { var btn = this.options.button; btn.removeClass('webuploader-pick-disable'); this.refresh(); }, disable: function () { var btn = this.options.button; this.getRuntime().getContainer().css({ top: '-99999px' }); btn.addClass('webuploader-pick-disable'); }, destroy: function () { var btn = this.options.button; $(window).off('resize', this._resizeHandler); btn.removeClass('webuploader-pick-disable webuploader-pick-hover ' + 'webuploader-pick'); } }); return FilePicker; }); /** * @fileOverview 组件基类。 */ define('widgets/widget', [ 'base', 'uploader' ], function (Base, Uploader) { var $ = Base.$, _init = Uploader.prototype._init, _destroy = Uploader.prototype.destroy, IGNORE = {}, widgetClass = []; function isArrayLike(obj) { if (!obj) { return false; } var length = obj.length, type = $.type(obj); if (obj.nodeType === 1 && length) { return true; } return type === 'array' || type !== 'function' && type !== 'string' && (length === 0 || typeof length === 'number' && length > 0 && (length - 1) in obj); } function Widget(uploader) { this.owner = uploader; this.options = uploader.options; } $.extend(Widget.prototype, { init: Base.noop, // 类Backbone的事件监听声明,监听uploader实例上的事件 // widget直接无法监听事件,事件只能通过uploader来传递 invoke: function (apiName, args) { /* { 'make-thumb': 'makeThumb' } */ var map = this.responseMap; // 如果无API响应声明则忽略 if (!map || !(apiName in map) || !(map[apiName] in this) || !$.isFunction(this[map[apiName]])) { return IGNORE; } return this[map[apiName]].apply(this, args); }, /** * 发送命令。当传入`callback`或者`handler`中返回`promise`时。返回一个当所有`handler`中的promise都完成后完成的新`promise`。 * @method request * @grammar request( command, args ) => * | Promise * @grammar request( command, args, callback ) => Promise * @for Uploader */ request: function () { return this.owner.request.apply(this.owner, arguments); } }); // 扩展Uploader. $.extend(Uploader.prototype, { /** * @property {String | Array} [disableWidgets=undefined] * @namespace options * @for Uploader * @description 默认所有 Uploader.register 了的 widget 都会被加载,如果禁用某一部分,请通过此 option 指定黑名单。 */ // 覆写_init用来初始化widgets _init: function () { var me = this, widgets = me._widgets = [], deactives = me.options.disableWidgets || ''; $.each(widgetClass, function (_, klass) { (!deactives || !~deactives.indexOf(klass._name)) && widgets.push(new klass(me)); }); return _init.apply(me, arguments); }, request: function (apiName, args, callback) { var i = 0, widgets = this._widgets, len = widgets && widgets.length, rlts = [], dfds = [], widget, rlt, promise, key; args = isArrayLike(args) ? args : [args]; for (; i < len; i++) { widget = widgets[i]; rlt = widget.invoke(apiName, args); if (rlt !== IGNORE) { // Deferred对象 if (Base.isPromise(rlt)) { dfds.push(rlt); } else { rlts.push(rlt); } } } // 如果有callback,则用异步方式。 if (callback || dfds.length) { promise = Base.when.apply(Base, dfds); key = promise.pipe ? 'pipe' : 'then'; // 很重要不能删除。删除了会死循环。 // 保证执行顺序。让callback总是在下一个 tick 中执行。 return promise[key](function () { var deferred = Base.Deferred(), args = arguments; if (args.length === 1) { args = args[0]; } setTimeout(function () { deferred.resolve(args); }, 1); return deferred.promise(); })[callback ? key : 'done'](callback || Base.noop); } else { return rlts[0]; } }, destroy: function () { _destroy.apply(this, arguments); this._widgets = null; } }); /** * 添加组件 * @grammar Uploader.register(proto); * @grammar Uploader.register(map, proto); * @param {object} responseMap API 名称与函数实现的映射 * @param {object} proto 组件原型,构造函数通过 constructor 属性定义 * @method Uploader.register * @for Uploader * @example * Uploader.register({ * 'make-thumb': 'makeThumb' * }, { * init: function( options ) {}, * makeThumb: function() {} * }); * * Uploader.register({ * 'make-thumb': function() { * * } * }); */ Uploader.register = Widget.register = function (responseMap, widgetProto) { var map = {init: 'init', destroy: 'destroy', name: 'anonymous'}, klass; if (arguments.length === 1) { widgetProto = responseMap; // 自动生成 map 表。 $.each(widgetProto, function (key) { if (key[0] === '_' || key === 'name') { key === 'name' && (map.name = widgetProto.name); return; } map[key.replace(/[A-Z]/g, '-$&').toLowerCase()] = key; }); } else { map = $.extend(map, responseMap); } widgetProto.responseMap = map; klass = Base.inherits(Widget, widgetProto); klass._name = map.name; widgetClass.push(klass); return klass; }; /** * 删除插件,只有在注册时指定了名字的才能被删除。 * @grammar Uploader.unRegister(name); * @param {string} name 组件名字 * @method Uploader.unRegister * @for Uploader * @example * * Uploader.register({ * name: 'custom', * * 'make-thumb': function() { * * } * }); * * Uploader.unRegister('custom'); */ Uploader.unRegister = Widget.unRegister = function (name) { if (!name || name === 'anonymous') { return; } // 删除指定的插件。 for (var i = widgetClass.length; i--;) { if (widgetClass[i]._name === name) { widgetClass.splice(i, 1) } } }; return Widget; }); /** * @fileOverview 文件选择相关 */ define('widgets/filepicker', [ 'base', 'uploader', 'lib/filepicker', 'widgets/widget' ], function (Base, Uploader, FilePicker) { var $ = Base.$; $.extend(Uploader.options, { /** * @property {Selector | Object} [pick=undefined] * @namespace options * @for Uploader * @description 指定选择文件的按钮容器,不指定则不创建按钮。 * * * `id` {Seletor|dom} 指定选择文件的按钮容器,不指定则不创建按钮。**注意** 这里虽然写的是 id, 但是不是只支持 id, 还支持 class, 或者 dom 节点。 * * `label` {String} 请采用 `innerHTML` 代替 * * `innerHTML` {String} 指定按钮文字。不指定时优先从指定的容器中看是否自带文字。 * * `multiple` {Boolean} 是否开起同时选择多个文件能力。 */ pick: null, /** * @property {Arroy} [accept=null] * @namespace options * @for Uploader * @description 指定接受哪些类型的文件。 由于目前还有ext转mimeType表,所以这里需要分开指定。 * * * `title` {String} 文字描述 * * `extensions` {String} 允许的文件后缀,不带点,多个用逗号分割。 * * `mimeTypes` {String} 多个用逗号分割。 * * 如: * * ``` * { * title: 'Images', * extensions: 'gif,jpg,jpeg,bmp,png', * mimeTypes: 'image/*' * } * ``` */ accept: null/*{ title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' }*/ }); return Uploader.register({ name: 'picker', init: function (opts) { this.pickers = []; return opts.pick && this.addBtn(opts.pick); }, refresh: function () { $.each(this.pickers, function () { this.refresh(); }); }, /** * @method addBtn * @for Uploader * @grammar addBtn( pick ) => Promise * @description * 添加文件选择按钮,如果一个按钮不够,需要调用此方法来添加。参数跟[options.pick](#WebUploader:Uploader:options)一致。 * @example * uploader.addBtn({ * id: '#btnContainer', * innerHTML: '选择文件' * }); */ addBtn: function (pick) { var me = this, opts = me.options, accept = opts.accept, promises = []; if (!pick) { return; } $.isPlainObject(pick) || (pick = { id: pick }); $(pick.id).each(function () { var options, picker, deferred; deferred = Base.Deferred(); options = $.extend({}, pick, { accept: $.isPlainObject(accept) ? [accept] : accept, swf: opts.swf, runtimeOrder: opts.runtimeOrder, id: this }); picker = new FilePicker(options); picker.once('ready', deferred.resolve); picker.on('select', function (files) { me.owner.request('add-file', [files]); }); picker.on('dialogopen', function () { me.owner.trigger('dialogOpen', picker.button); }); picker.init(); me.pickers.push(picker); promises.push(deferred.promise()); }); return Base.when.apply(Base, promises); }, disable: function () { $.each(this.pickers, function () { this.disable(); }); }, enable: function () { $.each(this.pickers, function () { this.enable(); }); }, destroy: function () { $.each(this.pickers, function () { this.destroy(); }); this.pickers = null; } }); }); /** * @fileOverview Image */ define('lib/image', [ 'base', 'runtime/client', 'lib/blob' ], function (Base, RuntimeClient, Blob) { var $ = Base.$; // 构造器。 function Image(opts) { this.options = $.extend({}, Image.options, opts); RuntimeClient.call(this, 'Image'); this.on('load', function () { this._info = this.exec('info'); this._meta = this.exec('meta'); }); } // 默认选项。 Image.options = { // 默认的图片处理质量 quality: 90, // 是否裁剪 crop: false, // 是否保留头部信息 preserveHeaders: false, // 是否允许放大。 allowMagnify: false }; // 继承RuntimeClient. Base.inherits(RuntimeClient, { constructor: Image, info: function (val) { // setter if (val) { this._info = val; return this; } // getter return this._info; }, meta: function (val) { // setter if (val) { this._meta = val; return this; } // getter return this._meta; }, loadFromBlob: function (blob) { var me = this, ruid = blob.getRuid(); this.connectRuntime(ruid, function () { me.exec('init', me.options); me.exec('loadFromBlob', blob); }); }, resize: function () { var args = Base.slice(arguments); return this.exec.apply(this, ['resize'].concat(args)); }, crop: function () { var args = Base.slice(arguments); return this.exec.apply(this, ['crop'].concat(args)); }, getAsDataUrl: function (type) { return this.exec('getAsDataUrl', type); }, getAsBlob: function (type) { var blob = this.exec('getAsBlob', type); return new Blob(this.getRuid(), blob); } }); return Image; }); /** * @fileOverview 图片操作, 负责预览图片和上传前压缩图片 */ define('widgets/image', [ 'base', 'uploader', 'lib/image', 'widgets/widget' ], function (Base, Uploader, Image) { var $ = Base.$, throttle; // 根据要处理的文件大小来节流,一次不能处理太多,会卡。 throttle = (function (max) { var occupied = 0, waiting = [], tick = function () { var item; while (waiting.length && occupied < max) { item = waiting.shift(); occupied += item[0]; item[1](); } }; return function (emiter, size, cb) { waiting.push([size, cb]); emiter.once('destroy', function () { occupied -= size; setTimeout(tick, 1); }); setTimeout(tick, 1); }; })(5 * 1024 * 1024); $.extend(Uploader.options, { /** * @property {Object} [thumb] * @namespace options * @for Uploader * @description 配置生成缩略图的选项。 * * 默认为: * * ```javascript * { * width: 110, * height: 110, * * // 图片质量,只有type为`image/jpeg`的时候才有效。 * quality: 70, * * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false. * allowMagnify: true, * * // 是否允许裁剪。 * crop: true, * * // 为空的话则保留原有图片格式。 * // 否则强制转换成指定的类型。 * type: 'image/jpeg' * } * ``` */ thumb: { width: 110, height: 110, quality: 70, allowMagnify: true, crop: true, preserveHeaders: false, // 为空的话则保留原有图片格式。 // 否则强制转换成指定的类型。 // IE 8下面 base64 大小不能超过 32K 否则预览失败,而非 jpeg 编码的图片很可 // 能会超过 32k, 所以这里设置成预览的时候都是 image/jpeg type: 'image/jpeg' }, /** * @property {Object} [compress] * @namespace options * @for Uploader * @description 配置压缩的图片的选项。如果此选项为`false`, 则图片在上传前不进行压缩。 * * 默认为: * * ```javascript * { * width: 1600, * height: 1600, * * // 图片质量,只有type为`image/jpeg`的时候才有效。 * quality: 90, * * // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false. * allowMagnify: false, * * // 是否允许裁剪。 * crop: false, * * // 是否保留头部meta信息。 * preserveHeaders: true, * * // 如果发现压缩后文件大小比原来还大,则使用原来图片 * // 此属性可能会影响图片自动纠正功能 * noCompressIfLarger: false, * * // 单位字节,如果图片大小小于此值,不会采用压缩。 * compressSize: 0 * } * ``` */ compress: { width: 1600, height: 1600, quality: 90, allowMagnify: false, crop: false, preserveHeaders: true } }); return Uploader.register({ name: 'image', /** * 生成缩略图,此过程为异步,所以需要传入`callback`。 * 通常情况在图片加入队里后调用此方法来生成预览图以增强交互效果。 * * 当 width 或者 height 的值介于 0 - 1 时,被当成百分比使用。 * * `callback`中可以接收到两个参数。 * * 第一个为error,如果生成缩略图有错误,此error将为真。 * * 第二个为ret, 缩略图的Data URL值。 * * **注意** * Date URL在IE6/7中不支持,所以不用调用此方法了,直接显示一张暂不支持预览图片好了。 * 也可以借助服务端,将 base64 数据传给服务端,生成一个临时文件供预览。 * * @method makeThumb * @grammar makeThumb( file, callback ) => undefined * @grammar makeThumb( file, callback, width, height ) => undefined * @for Uploader * @example * * uploader.on( 'fileQueued', function( file ) { * var $li = ...; * * uploader.makeThumb( file, function( error, ret ) { * if ( error ) { * $li.text('预览错误'); * } else { * $li.append('<img alt="" src="' + ret + '" />'); * } * }); * * }); */ makeThumb: function (file, cb, width, height) { var opts, image; file = this.request('get-file', file); // 只预览图片格式。 if (!file.type.match(/^image/)) { cb(true); return; } opts = $.extend({}, this.options.thumb); // 如果传入的是object. if ($.isPlainObject(width)) { opts = $.extend(opts, width); width = null; } width = width || opts.width; height = height || opts.height; image = new Image(opts); image.once('load', function () { file._info = file._info || image.info(); file._meta = file._meta || image.meta(); // 如果 width 的值介于 0 - 1 // 说明设置的是百分比。 if (width <= 1 && width > 0) { width = file._info.width * width; } // 同样的规则应用于 height if (height <= 1 && height > 0) { height = file._info.height * height; } image.resize(width, height); }); // 当 resize 完后 image.once('complete', function () { cb(false, image.getAsDataUrl(opts.type)); image.destroy(); }); image.once('error', function (reason) { cb(reason || true); image.destroy(); }); throttle(image, file.source.size, function () { file._info && image.info(file._info); file._meta && image.meta(file._meta); image.loadFromBlob(file.source); }); }, beforeSendFile: function (file) { var opts = this.options.compress || this.options.resize, compressSize = opts && opts.compressSize || 0, noCompressIfLarger = opts && opts.noCompressIfLarger || false, image, deferred; file = this.request('get-file', file); // 只压缩 jpeg 图片格式。 // gif 可能会丢失针 // bmp png 基本上尺寸都不大,且压缩比比较小。 if (!opts || !~'image/jpeg,image/jpg'.indexOf(file.type) || file.size < compressSize || file._compressed) { return; } opts = $.extend({}, opts); deferred = Base.Deferred(); image = new Image(opts); deferred.always(function () { image.destroy(); image = null; }); image.once('error', deferred.reject); image.once('load', function () { var width = opts.width, height = opts.height; file._info = file._info || image.info(); file._meta = file._meta || image.meta(); // 如果 width 的值介于 0 - 1 // 说明设置的是百分比。 if (width <= 1 && width > 0) { width = file._info.width * width; } // 同样的规则应用于 height if (height <= 1 && height > 0) { height = file._info.height * height; } image.resize(width, height); }); image.once('complete', function () { var blob, size; // 移动端 UC / qq 浏览器的无图模式下 // ctx.getImageData 处理大图的时候会报 Exception // INDEX_SIZE_ERR: DOM Exception 1 try { blob = image.getAsBlob(opts.type); size = file.size; // 如果压缩后,比原来还大则不用压缩后的。 if (!noCompressIfLarger || blob.size < size) { // file.source.destroy && file.source.destroy(); file.source = blob; file.size = blob.size; file.trigger('resize', blob.size, size); } // 标记,避免重复压缩。 file._compressed = true; deferred.resolve(); } catch (e) { // 出错了直接继续,让其上传原始图片 deferred.resolve(); } }); file._info && image.info(file._info); file._meta && image.meta(file._meta); image.loadFromBlob(file.source); return deferred.promise(); } }); }); /** * @fileOverview 文件属性封装 */ define('file', [ 'base', 'mediator' ], function (Base, Mediator) { var $ = Base.$, idPrefix = 'WU_FILE_', idSuffix = 0, rExt = /\.([^.]+)$/, statusMap = {}; function gid() { return idPrefix + idSuffix++; } /** * 文件类 * @class File * @constructor 构造函数 * @grammar new File( source ) => File * @param {Lib.File} source [lib.File](#Lib.File)实例, 此source对象是带有Runtime信息的。 */ function WUFile(source) { /** * 文件名,包括扩展名(后缀) * @property name * @type {string} */ this.name = source.name || 'Untitled'; /** * 文件体积(字节) * @property size * @type {uint} * @default 0 */ this.size = source.size || 0; /** * 文件MIMETYPE类型,与文件类型的对应关系请参考[http://t.cn/z8ZnFny](http://t.cn/z8ZnFny) * @property type * @type {string} * @default 'application/octet-stream' */ this.type = source.type || 'application/octet-stream'; /** * 文件最后修改日期 * @property lastModifiedDate * @type {int} * @default 当前时间戳 */ this.lastModifiedDate = source.lastModifiedDate || (new Date() * 1); /** * 文件ID,每个对象具有唯一ID,与文件名无关 * @property id * @type {string} */ this.id = gid(); /** * 文件扩展名,通过文件名获取,例如test.png的扩展名为png * @property ext * @type {string} */ this.ext = rExt.exec(this.name) ? RegExp.$1 : ''; /** * 状态文字说明。在不同的status语境下有不同的用途。 * @property statusText * @type {string} */ this.statusText = ''; // 存储文件状态,防止通过属性直接修改 statusMap[this.id] = WUFile.Status.INITED; this.source = source; this.loaded = 0; this.on('error', function (msg) { this.setStatus(WUFile.Status.ERROR, msg); }); } $.extend(WUFile.prototype, { /** * 设置状态,状态变化时会触发`change`事件。 * @method setStatus * @grammar setStatus( status[, statusText] ); * @param {File.Status|String} status [文件状态值](#WebUploader:File:File.Status) * @param {String} [statusText=''] 状态说明,常在error时使用,用http, abort,server等来标记是由于什么原因导致文件错误。 */ setStatus: function (status, text) { var prevStatus = statusMap[this.id]; typeof text !== 'undefined' && (this.statusText = text); if (status !== prevStatus) { statusMap[this.id] = status; /** * 文件状态变化 * @event statuschange */ this.trigger('statuschange', status, prevStatus); } }, /** * 获取文件状态 * @return {File.Status} * @example 文件状态具体包括以下几种类型: { // 初始化 INITED: 0, // 已入队列 QUEUED: 1, // 正在上传 PROGRESS: 2, // 上传出错 ERROR: 3, // 上传成功 COMPLETE: 4, // 上传取消 CANCELLED: 5 } */ getStatus: function () { return statusMap[this.id]; }, /** * 获取文件原始信息。 * @return {*} */ getSource: function () { return this.source; }, destroy: function () { this.off(); delete statusMap[this.id]; } }); Mediator.installTo(WUFile.prototype); /** * 文件状态值,具体包括以下几种类型: * * `inited` 初始状态 * * `queued` 已经进入队列, 等待上传 * * `progress` 上传中 * * `complete` 上传完成。 * * `error` 上传出错,可重试 * * `interrupt` 上传中断,可续传。 * * `invalid` 文件不合格,不能重试上传。会自动从队列中移除。 * * `cancelled` 文件被移除。 * @property {Object} Status * @namespace File * @class File * @static */ WUFile.Status = { INITED: 'inited', // 初始状态 QUEUED: 'queued', // 已经进入队列, 等待上传 PROGRESS: 'progress', // 上传中 ERROR: 'error', // 上传出错,可重试 COMPLETE: 'complete', // 上传完成。 CANCELLED: 'cancelled', // 上传取消。 INTERRUPT: 'interrupt', // 上传中断,可续传。 INVALID: 'invalid' // 文件不合格,不能重试上传。 }; return WUFile; }); /** * @fileOverview 文件队列 */ define('queue', [ 'base', 'mediator', 'file' ], function (Base, Mediator, WUFile) { var $ = Base.$, STATUS = WUFile.Status; /** * 文件队列, 用来存储各个状态中的文件。 * @class Queue * @extends Mediator */ function Queue() { /** * 统计文件数。 * * `numOfQueue` 队列中的文件数。 * * `numOfSuccess` 上传成功的文件数 * * `numOfCancel` 被取消的文件数 * * `numOfProgress` 正在上传中的文件数 * * `numOfUploadFailed` 上传错误的文件数。 * * `numOfInvalid` 无效的文件数。 * * `numofDeleted` 被移除的文件数。 * @property {Object} stats */ this.stats = { numOfQueue: 0, numOfSuccess: 0, numOfCancel: 0, numOfProgress: 0, numOfUploadFailed: 0, numOfInvalid: 0, numofDeleted: 0, numofInterrupt: 0 }; // 上传队列,仅包括等待上传的文件 this._queue = []; // 存储所有文件 this._map = {}; } $.extend(Queue.prototype, { /** * 将新文件加入对队列尾部 * * @method append * @param {File} file 文件对象 */ append: function (file) { this._queue.push(file); this._fileAdded(file); return this; }, /** * 将新文件加入对队列头部 * * @method prepend * @param {File} file 文件对象 */ prepend: function (file) { this._queue.unshift(file); this._fileAdded(file); return this; }, /** * 获取文件对象 * * @method getFile * @param {String} fileId 文件ID * @return {File} */ getFile: function (fileId) { if (typeof fileId !== 'string') { return fileId; } return this._map[fileId]; }, /** * 从队列中取出一个指定状态的文件。 * @grammar fetch( status ) => File * @method fetch * @param {String} status [文件状态值](#WebUploader:File:File.Status) * @return {File} [File](#WebUploader:File) */ fetch: function (status) { var len = this._queue.length, i, file; status = status || STATUS.QUEUED; for (i = 0; i < len; i++) { file = this._queue[i]; if (status === file.getStatus()) { return file; } } return null; }, /** * 对队列进行排序,能够控制文件上传顺序。 * @grammar sort( fn ) => undefined * @method sort * @param {Function} fn 排序方法 */ sort: function (fn) { if (typeof fn === 'function') { this._queue.sort(fn); } }, /** * 获取指定类型的文件列表, 列表中每一个成员为[File](#WebUploader:File)对象。 * @grammar getFiles( [status1[, status2 ...]] ) => Array * @method getFiles * @param {String} [status] [文件状态值](#WebUploader:File:File.Status) */ getFiles: function () { var sts = [].slice.call(arguments, 0), ret = [], i = 0, len = this._queue.length, file; for (; i < len; i++) { file = this._queue[i]; if (sts.length && !~$.inArray(file.getStatus(), sts)) { continue; } ret.push(file); } return ret; }, /** * 在队列中删除文件。 * @grammar removeFile( file ) => Array * @method removeFile * @param {File} 文件对象。 */ removeFile: function (file) { var me = this, existing = this._map[file.id]; if (existing) { delete this._map[file.id]; file.destroy(); this.stats.numofDeleted++; } }, _fileAdded: function (file) { var me = this, existing = this._map[file.id]; if (!existing) { this._map[file.id] = file; file.on('statuschange', function (cur, pre) { me._onFileStatusChange(cur, pre); }); } }, _onFileStatusChange: function (curStatus, preStatus) { var stats = this.stats; switch (preStatus) { case STATUS.PROGRESS: stats.numOfProgress--; break; case STATUS.QUEUED: stats.numOfQueue--; break; case STATUS.ERROR: stats.numOfUploadFailed--; break; case STATUS.INVALID: stats.numOfInvalid--; break; case STATUS.INTERRUPT: stats.numofInterrupt--; break; } switch (curStatus) { case STATUS.QUEUED: stats.numOfQueue++; break; case STATUS.PROGRESS: stats.numOfProgress++; break; case STATUS.ERROR: stats.numOfUploadFailed++; break; case STATUS.COMPLETE: stats.numOfSuccess++; break; case STATUS.CANCELLED: stats.numOfCancel++; break; case STATUS.INVALID: stats.numOfInvalid++; break; case STATUS.INTERRUPT: stats.numofInterrupt++; break; } } }); Mediator.installTo(Queue.prototype); return Queue; }); /** * @fileOverview 队列 */ define('widgets/queue', [ 'base', 'uploader', 'queue', 'file', 'lib/file', 'runtime/client', 'widgets/widget' ], function (Base, Uploader, Queue, WUFile, File, RuntimeClient) { var $ = Base.$, rExt = /\.\w+$/, Status = WUFile.Status; return Uploader.register({ name: 'queue', init: function (opts) { var me = this, deferred, len, i, item, arr, accept, runtime; if ($.isPlainObject(opts.accept)) { opts.accept = [opts.accept]; } // accept中的中生成匹配正则。 if (opts.accept) { arr = []; for (i = 0, len = opts.accept.length; i < len; i++) { item = opts.accept[i].extensions; item && arr.push(item); } if (arr.length) { accept = '\\.' + arr.join(',') .replace(/,/g, '$|\\.') .replace(/\*/g, '.*') + '$'; } me.accept = new RegExp(accept, 'i'); } me.queue = new Queue(); me.stats = me.queue.stats; // 如果当前不是html5运行时,那就算了。 // 不执行后续操作 if (this.request('predict-runtime-type') !== 'html5') { return; } // 创建一个 html5 运行时的 placeholder // 以至于外部添加原生 File 对象的时候能正确包裹一下供 webuploader 使用。 deferred = Base.Deferred(); this.placeholder = runtime = new RuntimeClient('Placeholder'); runtime.connectRuntime({ runtimeOrder: 'html5' }, function () { me._ruid = runtime.getRuid(); deferred.resolve(); }); return deferred.promise(); }, // 为了支持外部直接添加一个原生File对象。 _wrapFile: function (file) { if (!(file instanceof WUFile)) { if (!(file instanceof File)) { if (!this._ruid) { throw new Error('Can\'t add external files.'); } file = new File(this._ruid, file); } file = new WUFile(file); } return file; }, // 判断文件是否可以被加入队列 acceptFile: function (file) { var invalid = !file || !file.size || this.accept && // 如果名字中有后缀,才做后缀白名单处理。 rExt.exec(file.name) && !this.accept.test(file.name); return !invalid; }, /** * @event beforeFileQueued * @param {File} file File对象 * @description 当文件被加入队列之前触发,此事件的handler返回值为`false`,则此文件不会被添加进入队列。 * @for Uploader */ /** * @event fileQueued * @param {File} file File对象 * @description 当文件被加入队列以后触发。 * @for Uploader */ _addFile: function (file) { var me = this; file = me._wrapFile(file); // 不过类型判断允许不允许,先派送 `beforeFileQueued` if (!me.owner.trigger('beforeFileQueued', file)) { return; } // 类型不匹配,则派送错误事件,并返回。 if (!me.acceptFile(file)) { me.owner.trigger('error', 'Q_TYPE_DENIED', file); return; } me.queue.append(file); me.owner.trigger('fileQueued', file); return file; }, getFile: function (fileId) { return this.queue.getFile(fileId); }, /** * @event filesQueued * @param {File} files 数组,内容为原始File(lib/File)对象。 * @description 当一批文件添加进队列以后触发。 * @for Uploader */ /** * @property {Boolean} [auto=false] * @namespace options * @for Uploader * @description 设置为 true 后,不需要手动调用上传,有文件选择即开始上传。 * */ /** * @method addFiles * @grammar addFiles( file ) => undefined * @grammar addFiles( [file1, file2 ...] ) => undefined * @param {Array of File or File} [files] Files 对象 数组 * @description 添加文件到队列 * @for Uploader */ addFile: function (files) { var me = this; if (!files.length) { files = [files]; } files = $.map(files, function (file) { return me._addFile(file); }); if (files.length) { me.owner.trigger('filesQueued', files); if (me.options.auto) { setTimeout(function () { me.request('start-upload'); }, 20); } } }, getStats: function () { return this.stats; }, /** * @event fileDequeued * @param {File} file File对象 * @description 当文件被移除队列后触发。 * @for Uploader */ /** * @method removeFile * @grammar removeFile( file ) => undefined * @grammar removeFile( id ) => undefined * @grammar removeFile( file, true ) => undefined * @grammar removeFile( id, true ) => undefined * @param {File|id} file File对象或这File对象的id * @description 移除某一文件, 默认只会标记文件状态为已取消,如果第二个参数为 `true` 则会从 queue 中移除。 * @for Uploader * @example * * $li.on('click', '.remove-this', function() { * uploader.removeFile( file ); * }) */ removeFile: function (file, remove) { var me = this; file = file.id ? file : me.queue.getFile(file); this.request('cancel-file', file); if (remove) { this.queue.removeFile(file); } }, /** * @method getFiles * @grammar getFiles() => Array * @grammar getFiles( status1, status2, status... ) => Array * @description 返回指定状态的文件集合,不传参数将返回所有状态的文件。 * @for Uploader * @example * console.log( uploader.getFiles() ); // => all files * console.log( uploader.getFiles('error') ) // => all error files. */ getFiles: function () { return this.queue.getFiles.apply(this.queue, arguments); }, fetchFile: function () { return this.queue.fetch.apply(this.queue, arguments); }, /** * @method retry * @grammar retry() => undefined * @grammar retry( file ) => undefined * @description 重试上传,重试指定文件,或者从出错的文件开始重新上传。 * @for Uploader * @example * function retry() { * uploader.retry(); * } */ retry: function (file, noForceStart) { var me = this, files, i, len; if (file) { file = file.id ? file : me.queue.getFile(file); file.setStatus(Status.QUEUED); noForceStart || me.request('start-upload'); return; } files = me.queue.getFiles(Status.ERROR); i = 0; len = files.length; for (; i < len; i++) { file = files[i]; file.setStatus(Status.QUEUED); } me.request('start-upload'); }, /** * @method sort * @grammar sort( fn ) => undefined * @description 排序队列中的文件,在上传之前调整可以控制上传顺序。 * @for Uploader */ sortFiles: function () { return this.queue.sort.apply(this.queue, arguments); }, /** * @event reset * @description 当 uploader 被重置的时候触发。 * @for Uploader */ /** * @method reset * @grammar reset() => undefined * @description 重置uploader。目前只重置了队列。 * @for Uploader * @example * uploader.reset(); */ reset: function () { this.owner.trigger('reset'); this.queue = new Queue(); this.stats = this.queue.stats; }, destroy: function () { this.reset(); this.placeholder && this.placeholder.destroy(); } }); }); /** * @fileOverview 添加获取Runtime相关信息的方法。 */ define('widgets/runtime', [ 'uploader', 'runtime/runtime', 'widgets/widget' ], function (Uploader, Runtime) { Uploader.support = function () { return Runtime.hasRuntime.apply(Runtime, arguments); }; /** * @property {Object} [runtimeOrder=html5,flash] * @namespace options * @for Uploader * @description 指定运行时启动顺序。默认会想尝试 html5 是否支持,如果支持则使用 html5, 否则则使用 flash. * * 可以将此值设置成 `flash`,来强制使用 flash 运行时。 */ return Uploader.register({ name: 'runtime', init: function () { if (!this.predictRuntimeType()) { throw Error('Runtime Error'); } }, /** * 预测Uploader将采用哪个`Runtime` * @grammar predictRuntimeType() => String * @method predictRuntimeType * @for Uploader */ predictRuntimeType: function () { var orders = this.options.runtimeOrder || Runtime.orders, type = this.type, i, len; if (!type) { orders = orders.split(/\s*,\s*/g); for (i = 0, len = orders.length; i < len; i++) { if (Runtime.hasRuntime(orders[i])) { this.type = type = orders[i]; break; } } } return type; } }); }); /** * @fileOverview Transport */ define('lib/transport', [ 'base', 'runtime/client', 'mediator' ], function (Base, RuntimeClient, Mediator) { var $ = Base.$; function Transport(opts) { var me = this; opts = me.options = $.extend(true, {}, Transport.options, opts || {}); RuntimeClient.call(this, 'Transport'); this._blob = null; this._formData = opts.formData || {}; this._headers = opts.headers || {}; this.on('progress', this._timeout); this.on('load error', function () { me.trigger('progress', 1); clearTimeout(me._timer); }); } Transport.options = { server: '', method: 'POST', // 跨域时,是否允许携带cookie, 只有html5 runtime才有效 withCredentials: false, fileVal: 'file', timeout: 2 * 60 * 1000, // 2分钟 formData: {}, headers: {}, sendAsBinary: false }; $.extend(Transport.prototype, { // 添加Blob, 只能添加一次,最后一次有效。 appendBlob: function (key, blob, filename) { var me = this, opts = me.options; if (me.getRuid()) { me.disconnectRuntime(); } // 连接到blob归属的同一个runtime. me.connectRuntime(blob.ruid, function () { me.exec('init'); }); me._blob = blob; opts.fileVal = key || opts.fileVal; opts.filename = filename || opts.filename; }, // 添加其他字段 append: function (key, value) { if (typeof key === 'object') { $.extend(this._formData, key); } else { this._formData[key] = value; } }, setRequestHeader: function (key, value) { if (typeof key === 'object') { $.extend(this._headers, key); } else { this._headers[key] = value; } }, send: function (method) { this.exec('send', method); this._timeout(); }, abort: function () { clearTimeout(this._timer); return this.exec('abort'); }, destroy: function () { this.trigger('destroy'); this.off(); this.exec('destroy'); this.disconnectRuntime(); }, getResponse: function () { return this.exec('getResponse'); }, getResponseAsJson: function () { return this.exec('getResponseAsJson'); }, getStatus: function () { return this.exec('getStatus'); }, _timeout: function () { var me = this, duration = me.options.timeout; if (!duration) { return; } clearTimeout(me._timer); me._timer = setTimeout(function () { me.abort(); me.trigger('error', 'timeout'); }, duration); } }); // 让Transport具备事件功能。 Mediator.installTo(Transport.prototype); return Transport; }); /** * @fileOverview 负责文件上传相关。 */ define('widgets/upload', [ 'base', 'uploader', 'file', 'lib/transport', 'widgets/widget' ], function (Base, Uploader, WUFile, Transport) { var $ = Base.$, isPromise = Base.isPromise, Status = WUFile.Status; // 添加默认配置项 $.extend(Uploader.options, { /** * @property {Boolean} [prepareNextFile=false] * @namespace options * @for Uploader * @description 是否允许在文件传输时提前把下一个文件准备好。 * 对于一个文件的准备工作比较耗时,比如图片压缩,md5序列化。 * 如果能提前在当前文件传输期处理,可以节省总体耗时。 */ prepareNextFile: false, /** * @property {Boolean} [chunked=false] * @namespace options * @for Uploader * @description 是否要分片处理大文件上传。 */ chunked: false, /** * @property {Boolean} [chunkSize=5242880] * @namespace options * @for Uploader * @description 如果要分片,分多大一片? 默认大小为5M. */ chunkSize: 5 * 1024 * 1024, /** * @property {Boolean} [chunkRetry=2] * @namespace options * @for Uploader * @description 如果某个分片由于网络问题出错,允许自动重传多少次? */ chunkRetry: 2, /** * @property {Boolean} [threads=3] * @namespace options * @for Uploader * @description 上传并发数。允许同时最大上传进程数。 */ threads: 3, /** * @property {Object} [formData={}] * @namespace options * @for Uploader * @description 文件上传请求的参数表,每次发送都会发送此对象中的参数。 */ formData: {} /** * @property {Object} [fileVal='file'] * @namespace options * @for Uploader * @description 设置文件上传域的name。 */ /** * @property {Object} [sendAsBinary=false] * @namespace options * @for Uploader * @description 是否已二进制的流的方式发送文件,这样整个上传内容`php://input`都为文件内容, * 其他参数在$_GET数组中。 */ }); // 负责将文件切片。 function CuteFile(file, chunkSize) { var pending = [], blob = file.source, total = blob.size, chunks = chunkSize ? Math.ceil(total / chunkSize) : 1, start = 0, index = 0, len, api; api = { file: file, has: function () { return !!pending.length; }, shift: function () { return pending.shift(); }, unshift: function (block) { pending.unshift(block); } }; while (index < chunks) { len = Math.min(chunkSize, total - start); pending.push({ file: file, start: start, end: chunkSize ? (start + len) : total, total: total, chunks: chunks, chunk: index++, cuted: api }); start += len; } file.blocks = pending.concat(); file.remaning = pending.length; return api; } Uploader.register({ name: 'upload', init: function () { var owner = this.owner, me = this; this.runing = false; this.progress = false; owner .on('startUpload', function () { me.progress = true; }) .on('uploadFinished', function () { me.progress = false; }); // 记录当前正在传的数据,跟threads相关 this.pool = []; // 缓存分好片的文件。 this.stack = []; // 缓存即将上传的文件。 this.pending = []; // 跟踪还有多少分片在上传中但是没有完成上传。 this.remaning = 0; this.__tick = Base.bindFn(this._tick, this); // 销毁上传相关的属性。 owner.on('uploadComplete', function (file) { // 把其他块取消了。 file.blocks && $.each(file.blocks, function (_, v) { v.transport && (v.transport.abort(), v.transport.destroy()); delete v.transport; }); delete file.blocks; delete file.remaning; }); }, reset: function () { this.request('stop-upload', true); this.runing = false; this.pool = []; this.stack = []; this.pending = []; this.remaning = 0; this._trigged = false; this._promise = null; }, /** * @event startUpload * @description 当开始上传流程时触发。 * @for Uploader */ /** * 开始上传。此方法可以从初始状态调用开始上传流程,也可以从暂停状态调用,继续上传流程。 * * 可以指定开始某一个文件。 * @grammar upload() => undefined * @grammar upload( file | fileId) => undefined * @method upload * @for Uploader */ startUpload: function (file) { var me = this; // 移出invalid的文件 $.each(me.request('get-files', Status.INVALID), function () { me.request('remove-file', this); }); // 如果指定了开始某个文件,则只开始指定的文件。 if (file) { file = file.id ? file : me.request('get-file', file); if (file.getStatus() === Status.INTERRUPT) { file.setStatus(Status.QUEUED); $.each(me.pool, function (_, v) { // 之前暂停过。 if (v.file !== file) { return; } v.transport && v.transport.send(); file.setStatus(Status.PROGRESS); }); } else if (file.getStatus() !== Status.PROGRESS) { file.setStatus(Status.QUEUED); } } else { $.each(me.request('get-files', [Status.INITED]), function () { this.setStatus(Status.QUEUED); }); } if (me.runing) { return Base.nextTick(me.__tick); } me.runing = true; var files = []; // 如果有暂停的,则续传 file || $.each(me.pool, function (_, v) { var file = v.file; if (file.getStatus() === Status.INTERRUPT) { me._trigged = false; files.push(file); v.transport && v.transport.send(); } }); $.each(files, function () { this.setStatus(Status.PROGRESS); }); file || $.each(me.request('get-files', Status.INTERRUPT), function () { this.setStatus(Status.PROGRESS); }); me._trigged = false; Base.nextTick(me.__tick); me.owner.trigger('startUpload'); }, /** * @event stopUpload * @description 当开始上传流程暂停时触发。 * @for Uploader */ /** * 暂停上传。第一个参数为是否中断上传当前正在上传的文件。 * * 如果第一个参数是文件,则只暂停指定文件。 * @grammar stop() => undefined * @grammar stop( true ) => undefined * @grammar stop( file ) => undefined * @method stop * @for Uploader */ stopUpload: function (file, interrupt) { var me = this, block; if (file === true) { interrupt = file; file = null; } if (me.runing === false) { return; } // 如果只是暂停某个文件。 if (file) { file = file.id ? file : me.request('get-file', file); if (file.getStatus() !== Status.PROGRESS && file.getStatus() !== Status.QUEUED) { return; } file.setStatus(Status.INTERRUPT); $.each(me.pool, function (_, v) { // 只 abort 指定的文件。 if (v.file === file) { block = v; return false; } }); block.transport && block.transport.abort(); if (interrupt) { me._putback(block); me._popBlock(block); } return Base.nextTick(me.__tick); } me.runing = false; // 正在准备中的文件。 if (this._promise && this._promise.file) { this._promise.file.setStatus(Status.INTERRUPT); } interrupt && $.each(me.pool, function (_, v) { v.transport && v.transport.abort(); v.file.setStatus(Status.INTERRUPT); }); me.owner.trigger('stopUpload'); }, /** * @method cancelFile * @grammar cancelFile( file ) => undefined * @grammar cancelFile( id ) => undefined * @param {File|id} file File对象或这File对象的id * @description 标记文件状态为已取消, 同时将中断文件传输。 * @for Uploader * @example * * $li.on('click', '.remove-this', function() { * uploader.cancelFile( file ); * }) */ cancelFile: function (file) { file = file.id ? file : this.request('get-file', file); // 如果正在上传。 file.blocks && $.each(file.blocks, function (_, v) { var _tr = v.transport; if (_tr) { _tr.abort(); _tr.destroy(); delete v.transport; } }); file.setStatus(Status.CANCELLED); this.owner.trigger('fileDequeued', file); }, /** * 判断`Uplaode`r是否正在上传中。 * @grammar isInProgress() => Boolean * @method isInProgress * @for Uploader */ isInProgress: function () { return !!this.progress; }, _getStats: function () { return this.request('get-stats'); }, /** * 掉过一个文件上传,直接标记指定文件为已上传状态。 * @grammar skipFile( file ) => undefined * @method skipFile * @for Uploader */ skipFile: function (file, status) { file = file.id ? file : this.request('get-file', file); file.setStatus(status || Status.COMPLETE); file.skipped = true; // 如果正在上传。 file.blocks && $.each(file.blocks, function (_, v) { var _tr = v.transport; if (_tr) { _tr.abort(); _tr.destroy(); delete v.transport; } }); this.owner.trigger('uploadSkip', file); }, /** * @event uploadFinished * @description 当所有文件上传结束时触发。 * @for Uploader */ _tick: function () { var me = this, opts = me.options, fn, val; // 上一个promise还没有结束,则等待完成后再执行。 if (me._promise) { return me._promise.always(me.__tick); } // 还有位置,且还有文件要处理的话。 if (me.pool.length < opts.threads && (val = me._nextBlock())) { me._trigged = false; fn = function (val) { me._promise = null; // 有可能是reject过来的,所以要检测val的类型。 val && val.file && me._startSend(val); Base.nextTick(me.__tick); }; me._promise = isPromise(val) ? val.always(fn) : fn(val); // 没有要上传的了,且没有正在传输的了。 } else if (!me.remaning && !me._getStats().numOfQueue && !me._getStats().numofInterrupt) { me.runing = false; me._trigged || Base.nextTick(function () { me.owner.trigger('uploadFinished'); }); me._trigged = true; } }, _putback: function (block) { var idx; block.cuted.unshift(block); idx = this.stack.indexOf(block.cuted); if (!~idx) { this.stack.unshift(block.cuted); } }, _getStack: function () { var i = 0, act; while ((act = this.stack[i++])) { if (act.has() && act.file.getStatus() === Status.PROGRESS) { return act; } else if (!act.has() || act.file.getStatus() !== Status.PROGRESS && act.file.getStatus() !== Status.INTERRUPT) { // 把已经处理完了的,或者,状态为非 progress(上传中)、 // interupt(暂停中) 的移除。 this.stack.splice(--i, 1); } } return null; }, _nextBlock: function () { var me = this, opts = me.options, act, next, done, preparing; // 如果当前文件还有没有需要传输的,则直接返回剩下的。 if ((act = this._getStack())) { // 是否提前准备下一个文件 if (opts.prepareNextFile && !me.pending.length) { me._prepareNextFile(); } return act.shift(); // 否则,如果正在运行,则准备下一个文件,并等待完成后返回下个分片。 } else if (me.runing) { // 如果缓存中有,则直接在缓存中取,没有则去queue中取。 if (!me.pending.length && me._getStats().numOfQueue) { me._prepareNextFile(); } next = me.pending.shift(); done = function (file) { if (!file) { return null; } act = CuteFile(file, opts.chunked ? opts.chunkSize : 0); me.stack.push(act); return act.shift(); }; // 文件可能还在prepare中,也有可能已经完全准备好了。 if (isPromise(next)) { preparing = next.file; next = next[next.pipe ? 'pipe' : 'then'](done); next.file = preparing; return next; } return done(next); } }, /** * @event uploadStart * @param {File} file File对象 * @description 某个文件开始上传前触发,一个文件只会触发一次。 * @for Uploader */ _prepareNextFile: function () { var me = this, file = me.request('fetch-file'), pending = me.pending, promise; if (file) { promise = me.request('before-send-file', file, function () { // 有可能文件被skip掉了。文件被skip掉后,状态坑定不是Queued. if (file.getStatus() === Status.PROGRESS || file.getStatus() === Status.INTERRUPT) { return file; } return me._finishFile(file); }); me.owner.trigger('uploadStart', file); file.setStatus(Status.PROGRESS); promise.file = file; // 如果还在pending中,则替换成文件本身。 promise.done(function () { var idx = $.inArray(promise, pending); ~idx && pending.splice(idx, 1, file); }); // befeore-send-file的钩子就有错误发生。 promise.fail(function (reason) { file.setStatus(Status.ERROR, reason); me.owner.trigger('uploadError', file, reason); me.owner.trigger('uploadComplete', file); }); pending.push(promise); } }, // 让出位置了,可以让其他分片开始上传 _popBlock: function (block) { var idx = $.inArray(block, this.pool); this.pool.splice(idx, 1); block.file.remaning--; this.remaning--; }, // 开始上传,可以被掉过。如果promise被reject了,则表示跳过此分片。 _startSend: function (block) { var me = this, file = block.file, promise; // 有可能在 before-send-file 的 promise 期间改变了文件状态。 // 如:暂停,取消 // 我们不能中断 promise, 但是可以在 promise 完后,不做上传操作。 if (file.getStatus() !== Status.PROGRESS) { // 如果是中断,则还需要放回去。 if (file.getStatus() === Status.INTERRUPT) { me._putback(block); } return; } me.pool.push(block); me.remaning++; // 如果没有分片,则直接使用原始的。 // 不会丢失content-type信息。 block.blob = block.chunks === 1 ? file.source : file.source.slice(block.start, block.end); // hook, 每个分片发送之前可能要做些异步的事情。 promise = me.request('before-send', block, function () { // 有可能文件已经上传出错了,所以不需要再传输了。 if (file.getStatus() === Status.PROGRESS) { me._doSend(block); } else { me._popBlock(block); Base.nextTick(me.__tick); } }); // 如果为fail了,则跳过此分片。 promise.fail(function () { if (file.remaning === 1) { me._finishFile(file).always(function () { block.percentage = 1; me._popBlock(block); me.owner.trigger('uploadComplete', file); Base.nextTick(me.__tick); }); } else { block.percentage = 1; me.updateFileProgress(file); me._popBlock(block); Base.nextTick(me.__tick); } }); }, /** * @event uploadBeforeSend * @param {Object} object * @param {Object} data 默认的上传参数,可以扩展此对象来控制上传参数。 * @param {Object} headers 可以扩展此对象来控制上传头部。 * @description 当某个文件的分块在发送前触发,主要用来询问是否要添加附带参数,大文件在开起分片上传的前提下此事件可能会触发多次。 * @for Uploader */ /** * @event uploadAccept * @param {Object} object * @param {Object} ret 服务端的返回数据,json格式,如果服务端不是json格式,从ret._raw中取数据,自行解析。 * @description 当某个文件上传到服务端响应后,会派送此事件来询问服务端响应是否有效。如果此事件handler返回值为`false`, 则此文件将派送`server`类型的`uploadError`事件。 * @for Uploader */ /** * @event uploadProgress * @param {File} file File对象 * @param {Number} percentage 上传进度 * @description 上传过程中触发,携带上传进度。 * @for Uploader */ /** * @event uploadError * @param {File} file File对象 * @param {String} reason 出错的code * @description 当文件上传出错时触发。 * @for Uploader */ /** * @event uploadSuccess * @param {File} file File对象 * @param {Object} response 服务端返回的数据 * @description 当文件上传成功时触发。 * @for Uploader */ /** * @event uploadComplete * @param {File} [file] File对象 * @description 不管成功或者失败,文件上传完成时触发。 * @for Uploader */ // 做上传操作。 _doSend: function (block) { var me = this, owner = me.owner, opts = me.options, file = block.file, tr = new Transport(opts), data = $.extend({}, opts.formData), headers = $.extend({}, opts.headers), requestAccept, ret; block.transport = tr; tr.on('destroy', function () { delete block.transport; me._popBlock(block); Base.nextTick(me.__tick); }); // 广播上传进度。以文件为单位。 tr.on('progress', function (percentage) { block.percentage = percentage; me.updateFileProgress(file); }); // 用来询问,是否返回的结果是有错误的。 requestAccept = function (reject) { var fn; ret = tr.getResponseAsJson() || {}; ret._raw = tr.getResponse(); fn = function (value) { reject = value; }; // 服务端响应了,不代表成功了,询问是否响应正确。 if (!owner.trigger('uploadAccept', block, ret, fn)) { reject = reject || 'server'; } return reject; }; // 尝试重试,然后广播文件上传出错。 tr.on('error', function (type, flag) { block.retried = block.retried || 0; // 自动重试 if (block.chunks > 1 && ~'http,abort'.indexOf(type) && block.retried < opts.chunkRetry) { block.retried++; tr.send(); } else { // http status 500 ~ 600 if (!flag && type === 'server') { type = requestAccept(type); } file.setStatus(Status.ERROR, type); owner.trigger('uploadError', file, type); owner.trigger('uploadComplete', file); } }); // 上传成功 tr.on('load', function () { var reason; // 如果非预期,转向上传出错。 if ((reason = requestAccept())) { tr.trigger('error', reason, true); return; } // 全部上传完成。 if (file.remaning === 1) { me._finishFile(file, ret); } else { tr.destroy(); } }); // 配置默认的上传字段。 data = $.extend(data, { id: file.id, name: file.name, type: file.type, lastModifiedDate: file.lastModifiedDate, size: file.size }); block.chunks > 1 && $.extend(data, { chunks: block.chunks, chunk: block.chunk }); // 在发送之间可以添加字段什么的。。。 // 如果默认的字段不够使用,可以通过监听此事件来扩展 owner.trigger('uploadBeforeSend', block, data, headers); // 开始发送。 tr.appendBlob(opts.fileVal, block.blob, file.name); tr.append(data); tr.setRequestHeader(headers); tr.send(); }, // 完成上传。 _finishFile: function (file, ret, hds) { var owner = this.owner; return owner .request('after-send-file', arguments, function () { file.setStatus(Status.COMPLETE); owner.trigger('uploadSuccess', file, ret, hds); }) .fail(function (reason) { // 如果外部已经标记为invalid什么的,不再改状态。 if (file.getStatus() === Status.PROGRESS) { file.setStatus(Status.ERROR, reason); } owner.trigger('uploadError', file, reason); }) .always(function () { owner.trigger('uploadComplete', file); }); }, updateFileProgress: function (file) { var totalPercent = 0, uploaded = 0; if (!file.blocks) { return; } $.each(file.blocks, function (_, v) { uploaded += (v.percentage || 0) * (v.end - v.start); }); totalPercent = uploaded / file.size; this.owner.trigger('uploadProgress', file, totalPercent || 0); } }); }); /** * @fileOverview 日志组件,主要用来收集错误信息,可以帮助 webuploader 更好的定位问题和发展。 * * 如果您不想要启用此功能,请在打包的时候去掉 log 模块。 * * 或者可以在初始化的时候通过 options.disableWidgets 属性禁用。 * * 如: * WebUploader.create({ * ... * * disableWidgets: 'log', * * ... * }) */ define('widgets/log', [ 'base', 'uploader', 'widgets/widget' ], function (Base, Uploader) { var $ = Base.$, logUrl = ' http://static.tieba.baidu.com/tb/pms/img/st.gif??', product = (location.hostname || location.host || 'protected').toLowerCase(), // 只针对 baidu 内部产品用户做统计功能。 enable = product && /baidu/i.exec(product), base; if (!enable) { return; } base = { dv: 3, master: 'webuploader', online: /test/.exec(product) ? 0 : 1, module: '', product: product, type: 0 }; function send(data) { var obj = $.extend({}, base, data), url = logUrl.replace(/^(.*)\?/, '$1' + $.param(obj)), image = new Image(); image.src = url; } return Uploader.register({ name: 'log', init: function () { var owner = this.owner, count = 0, size = 0; owner .on('error', function (code) { send({ type: 2, c_error_code: code }); }) .on('uploadError', function (file, reason) { send({ type: 2, c_error_code: 'UPLOAD_ERROR', c_reason: '' + reason }); }) .on('uploadComplete', function (file) { count++; size += file.size; }).on('uploadFinished', function () { send({ c_count: count, c_size: size }); count = size = 0; }); send({ c_usage: 1 }); } }); }); /** * @fileOverview Runtime管理器,负责Runtime的选择, 连接 */ define('runtime/compbase', [], function () { function CompBase(owner, runtime) { this.owner = owner; this.options = owner.options; this.getRuntime = function () { return runtime; }; this.getRuid = function () { return runtime.uid; }; this.trigger = function () { return owner.trigger.apply(owner, arguments); }; } return CompBase; }); /** * @fileOverview Html5Runtime */ define('runtime/html5/runtime', [ 'base', 'runtime/runtime', 'runtime/compbase' ], function (Base, Runtime, CompBase) { var type = 'html5', components = {}; function Html5Runtime() { var pool = {}, me = this, destroy = this.destroy; Runtime.apply(me, arguments); me.type = type; // 这个方法的调用者,实际上是RuntimeClient me.exec = function (comp, fn/*, args...*/) { var client = this, uid = client.uid, args = Base.slice(arguments, 2), instance; if (components[comp]) { instance = pool[uid] = pool[uid] || new components[comp](client, me); if (instance[fn]) { return instance[fn].apply(instance, args); } } }; me.destroy = function () { // @todo 删除池子中的所有实例 return destroy && destroy.apply(this, arguments); }; } Base.inherits(Runtime, { constructor: Html5Runtime, // 不需要连接其他程序,直接执行callback init: function () { var me = this; setTimeout(function () { me.trigger('ready'); }, 1); } }); // 注册Components Html5Runtime.register = function (name, component) { var klass = components[name] = Base.inherits(CompBase, component); return klass; }; // 注册html5运行时。 // 只有在支持的前提下注册。 if (window.Blob && window.FileReader && window.DataView) { Runtime.addRuntime(type, Html5Runtime); } return Html5Runtime; }); /** * @fileOverview Blob Html实现 */ define('runtime/html5/blob', [ 'runtime/html5/runtime', 'lib/blob' ], function (Html5Runtime, Blob) { return Html5Runtime.register('Blob', { slice: function (start, end) { var blob = this.owner.source, slice = blob.slice || blob.webkitSlice || blob.mozSlice; blob = slice.call(blob, start, end); return new Blob(this.getRuid(), blob); } }); }); /** * @fileOverview FilePicker */ define('runtime/html5/filepicker', [ 'base', 'runtime/html5/runtime' ], function (Base, Html5Runtime) { var $ = Base.$; return Html5Runtime.register('FilePicker', { init: function () { var container = this.getRuntime().getContainer(), me = this, owner = me.owner, opts = me.options, label = this.label = $(document.createElement('label')), input = this.input = $(document.createElement('input')), arr, i, len, mouseHandler; input.attr('type', 'file'); input.attr('capture', 'camera'); input.attr('name', opts.name); input.addClass('webuploader-element-invisible'); label.on('click', function (e) { input.trigger('click'); e.stopPropagation(); owner.trigger('dialogopen'); }); label.css({ opacity: 0, width: '100%', height: '100%', display: 'block', cursor: 'pointer', background: '#ffffff' }); if (opts.multiple) { input.attr('multiple', 'multiple'); } // @todo Firefox不支持单独指定后缀 if (opts.accept && opts.accept.length > 0) { arr = []; for (i = 0, len = opts.accept.length; i < len; i++) { arr.push(opts.accept[i].mimeTypes); } input.attr('accept', arr.join(',')); } container.append(input); container.append(label); mouseHandler = function (e) { owner.trigger(e.type); }; input.on('change', function (e) { var fn = arguments.callee, clone; me.files = e.target.files; // reset input clone = this.cloneNode(true); clone.value = null; this.parentNode.replaceChild(clone, this); input.off(); input = $(clone).on('change', fn) .on('mouseenter mouseleave', mouseHandler); owner.trigger('change'); }); label.on('mouseenter mouseleave', mouseHandler); }, getFiles: function () { return this.files; }, destroy: function () { this.input.off(); this.label.off(); } }); }); /** * Terms: * * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer * @fileOverview Image控件 */ define('runtime/html5/util', [ 'base' ], function (Base) { var urlAPI = window.createObjectURL && window || window.URL && URL.revokeObjectURL && URL || window.webkitURL, createObjectURL = Base.noop, revokeObjectURL = createObjectURL; if (urlAPI) { // 更安全的方式调用,比如android里面就能把context改成其他的对象。 createObjectURL = function () { return urlAPI.createObjectURL.apply(urlAPI, arguments); }; revokeObjectURL = function () { return urlAPI.revokeObjectURL.apply(urlAPI, arguments); }; } return { createObjectURL: createObjectURL, revokeObjectURL: revokeObjectURL, dataURL2Blob: function (dataURI) { var byteStr, intArray, ab, i, mimetype, parts; parts = dataURI.split(','); if (~parts[0].indexOf('base64')) { byteStr = atob(parts[1]); } else { byteStr = decodeURIComponent(parts[1]); } ab = new ArrayBuffer(byteStr.length); intArray = new Uint8Array(ab); for (i = 0; i < byteStr.length; i++) { intArray[i] = byteStr.charCodeAt(i); } mimetype = parts[0].split(':')[1].split(';')[0]; return this.arrayBufferToBlob(ab, mimetype); }, dataURL2ArrayBuffer: function (dataURI) { var byteStr, intArray, i, parts; parts = dataURI.split(','); if (~parts[0].indexOf('base64')) { byteStr = atob(parts[1]); } else { byteStr = decodeURIComponent(parts[1]); } intArray = new Uint8Array(byteStr.length); for (i = 0; i < byteStr.length; i++) { intArray[i] = byteStr.charCodeAt(i); } return intArray.buffer; }, arrayBufferToBlob: function (buffer, type) { var builder = window.BlobBuilder || window.WebKitBlobBuilder, bb; // android不支持直接new Blob, 只能借助blobbuilder. if (builder) { bb = new builder(); bb.append(buffer); return bb.getBlob(type); } return new Blob([buffer], type ? {type: type} : {}); }, // 抽出来主要是为了解决android下面canvas.toDataUrl不支持jpeg. // 你得到的结果是png. canvasToDataUrl: function (canvas, type, quality) { return canvas.toDataURL(type, quality / 100); }, // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。 parseMeta: function (blob, callback) { callback(false, {}); }, // imagemeat会复写这个方法,如果用户选择加载那个文件了的话。 updateImageHead: function (data) { return data; } }; }); /** * Terms: * * Uint8Array, FileReader, BlobBuilder, atob, ArrayBuffer * @fileOverview Image控件 */ define('runtime/html5/imagemeta', [ 'runtime/html5/util' ], function (Util) { var api; api = { parsers: { 0xffe1: [] }, maxMetaDataSize: 262144, parse: function (blob, cb) { var me = this, fr = new FileReader(); fr.onload = function () { cb(false, me._parse(this.result)); fr = fr.onload = fr.onerror = null; }; fr.onerror = function (e) { cb(e.message); fr = fr.onload = fr.onerror = null; }; blob = blob.slice(0, me.maxMetaDataSize); fr.readAsArrayBuffer(blob.getSource()); }, _parse: function (buffer, noParse) { if (buffer.byteLength < 6) { return; } var dataview = new DataView(buffer), offset = 2, maxOffset = dataview.byteLength - 4, headLength = offset, ret = {}, markerBytes, markerLength, parsers, i; if (dataview.getUint16(0) === 0xffd8) { while (offset < maxOffset) { markerBytes = dataview.getUint16(offset); if (markerBytes >= 0xffe0 && markerBytes <= 0xffef || markerBytes === 0xfffe) { markerLength = dataview.getUint16(offset + 2) + 2; if (offset + markerLength > dataview.byteLength) { break; } parsers = api.parsers[markerBytes]; if (!noParse && parsers) { for (i = 0; i < parsers.length; i += 1) { parsers[i].call(api, dataview, offset, markerLength, ret); } } offset += markerLength; headLength = offset; } else { break; } } if (headLength > 6) { if (buffer.slice) { ret.imageHead = buffer.slice(2, headLength); } else { // Workaround for IE10, which does not yet // support ArrayBuffer.slice: ret.imageHead = new Uint8Array(buffer) .subarray(2, headLength); } } } return ret; }, updateImageHead: function (buffer, head) { var data = this._parse(buffer, true), buf1, buf2, bodyoffset; bodyoffset = 2; if (data.imageHead) { bodyoffset = 2 + data.imageHead.byteLength; } if (buffer.slice) { buf2 = buffer.slice(bodyoffset); } else { buf2 = new Uint8Array(buffer).subarray(bodyoffset); } buf1 = new Uint8Array(head.byteLength + 2 + buf2.byteLength); buf1[0] = 0xFF; buf1[1] = 0xD8; buf1.set(new Uint8Array(head), 2); buf1.set(new Uint8Array(buf2), head.byteLength + 2); return buf1.buffer; } }; Util.parseMeta = function () { return api.parse.apply(api, arguments); }; Util.updateImageHead = function () { return api.updateImageHead.apply(api, arguments); }; return api; }); /** * 代码来自于:https://github.com/blueimp/JavaScript-Load-Image * 暂时项目中只用了orientation. * * 去除了 Exif Sub IFD Pointer, GPS Info IFD Pointer, Exif Thumbnail. * @fileOverview EXIF解析 */ // Sample // ==================================== // Make : Apple // Model : iPhone 4S // Orientation : 1 // XResolution : 72 [72/1] // YResolution : 72 [72/1] // ResolutionUnit : 2 // Software : QuickTime 7.7.1 // DateTime : 2013:09:01 22:53:55 // ExifIFDPointer : 190 // ExposureTime : 0.058823529411764705 [1/17] // FNumber : 2.4 [12/5] // ExposureProgram : Normal program // ISOSpeedRatings : 800 // ExifVersion : 0220 // DateTimeOriginal : 2013:09:01 22:52:51 // DateTimeDigitized : 2013:09:01 22:52:51 // ComponentsConfiguration : YCbCr // ShutterSpeedValue : 4.058893515764426 // ApertureValue : 2.5260688216892597 [4845/1918] // BrightnessValue : -0.3126686601998395 // MeteringMode : Pattern // Flash : Flash did not fire, compulsory flash mode // FocalLength : 4.28 [107/25] // SubjectArea : [4 values] // FlashpixVersion : 0100 // ColorSpace : 1 // PixelXDimension : 2448 // PixelYDimension : 3264 // SensingMethod : One-chip color area sensor // ExposureMode : 0 // WhiteBalance : Auto white balance // FocalLengthIn35mmFilm : 35 // SceneCaptureType : Standard define('runtime/html5/imagemeta/exif', [ 'base', 'runtime/html5/imagemeta' ], function (Base, ImageMeta) { var EXIF = {}; EXIF.ExifMap = function () { return this; }; EXIF.ExifMap.prototype.map = { 'Orientation': 0x0112 }; EXIF.ExifMap.prototype.get = function (id) { return this[id] || this[this.map[id]]; }; EXIF.exifTagTypes = { // byte, 8-bit unsigned int: 1: { getValue: function (dataView, dataOffset) { return dataView.getUint8(dataOffset); }, size: 1 }, // ascii, 8-bit byte: 2: { getValue: function (dataView, dataOffset) { return String.fromCharCode(dataView.getUint8(dataOffset)); }, size: 1, ascii: true }, // short, 16 bit int: 3: { getValue: function (dataView, dataOffset, littleEndian) { return dataView.getUint16(dataOffset, littleEndian); }, size: 2 }, // long, 32 bit int: 4: { getValue: function (dataView, dataOffset, littleEndian) { return dataView.getUint32(dataOffset, littleEndian); }, size: 4 }, // rational = two long values, // first is numerator, second is denominator: 5: { getValue: function (dataView, dataOffset, littleEndian) { return dataView.getUint32(dataOffset, littleEndian) / dataView.getUint32(dataOffset + 4, littleEndian); }, size: 8 }, // slong, 32 bit signed int: 9: { getValue: function (dataView, dataOffset, littleEndian) { return dataView.getInt32(dataOffset, littleEndian); }, size: 4 }, // srational, two slongs, first is numerator, second is denominator: 10: { getValue: function (dataView, dataOffset, littleEndian) { return dataView.getInt32(dataOffset, littleEndian) / dataView.getInt32(dataOffset + 4, littleEndian); }, size: 8 } }; // undefined, 8-bit byte, value depending on field: EXIF.exifTagTypes[7] = EXIF.exifTagTypes[1]; EXIF.getExifValue = function (dataView, tiffOffset, offset, type, length, littleEndian) { var tagType = EXIF.exifTagTypes[type], tagSize, dataOffset, values, i, str, c; if (!tagType) { Base.log('Invalid Exif data: Invalid tag type.'); return; } tagSize = tagType.size * length; // Determine if the value is contained in the dataOffset bytes, // or if the value at the dataOffset is a pointer to the actual data: dataOffset = tagSize > 4 ? tiffOffset + dataView.getUint32(offset + 8, littleEndian) : (offset + 8); if (dataOffset + tagSize > dataView.byteLength) { Base.log('Invalid Exif data: Invalid data offset.'); return; } if (length === 1) { return tagType.getValue(dataView, dataOffset, littleEndian); } values = []; for (i = 0; i < length; i += 1) { values[i] = tagType.getValue(dataView, dataOffset + i * tagType.size, littleEndian); } if (tagType.ascii) { str = ''; // Concatenate the chars: for (i = 0; i < values.length; i += 1) { c = values[i]; // Ignore the terminating NULL byte(s): if (c === '\u0000') { break; } str += c; } return str; } return values; }; EXIF.parseExifTag = function (dataView, tiffOffset, offset, littleEndian, data) { var tag = dataView.getUint16(offset, littleEndian); data.exif[tag] = EXIF.getExifValue(dataView, tiffOffset, offset, dataView.getUint16(offset + 2, littleEndian), // tag type dataView.getUint32(offset + 4, littleEndian), // tag length littleEndian); }; EXIF.parseExifTags = function (dataView, tiffOffset, dirOffset, littleEndian, data) { var tagsNumber, dirEndOffset, i; if (dirOffset + 6 > dataView.byteLength) { Base.log('Invalid Exif data: Invalid directory offset.'); return; } tagsNumber = dataView.getUint16(dirOffset, littleEndian); dirEndOffset = dirOffset + 2 + 12 * tagsNumber; if (dirEndOffset + 4 > dataView.byteLength) { Base.log('Invalid Exif data: Invalid directory size.'); return; } for (i = 0; i < tagsNumber; i += 1) { this.parseExifTag(dataView, tiffOffset, dirOffset + 2 + 12 * i, // tag offset littleEndian, data); } // Return the offset to the next directory: return dataView.getUint32(dirEndOffset, littleEndian); }; // EXIF.getExifThumbnail = function(dataView, offset, length) { // var hexData, // i, // b; // if (!length || offset + length > dataView.byteLength) { // Base.log('Invalid Exif data: Invalid thumbnail data.'); // return; // } // hexData = []; // for (i = 0; i < length; i += 1) { // b = dataView.getUint8(offset + i); // hexData.push((b < 16 ? '0' : '') + b.toString(16)); // } // return 'data:image/jpeg,%' + hexData.join('%'); // }; EXIF.parseExifData = function (dataView, offset, length, data) { var tiffOffset = offset + 10, littleEndian, dirOffset; // Check for the ASCII code for "Exif" (0x45786966): if (dataView.getUint32(offset + 4) !== 0x45786966) { // No Exif data, might be XMP data instead return; } if (tiffOffset + 8 > dataView.byteLength) { Base.log('Invalid Exif data: Invalid segment size.'); return; } // Check for the two null bytes: if (dataView.getUint16(offset + 8) !== 0x0000) { Base.log('Invalid Exif data: Missing byte alignment offset.'); return; } // Check the byte alignment: switch (dataView.getUint16(tiffOffset)) { case 0x4949: littleEndian = true; break; case 0x4D4D: littleEndian = false; break; default: Base.log('Invalid Exif data: Invalid byte alignment marker.'); return; } // Check for the TIFF tag marker (0x002A): if (dataView.getUint16(tiffOffset + 2, littleEndian) !== 0x002A) { Base.log('Invalid Exif data: Missing TIFF marker.'); return; } // Retrieve the directory offset bytes, usually 0x00000008 or 8 decimal: dirOffset = dataView.getUint32(tiffOffset + 4, littleEndian); // Create the exif object to store the tags: data.exif = new EXIF.ExifMap(); // Parse the tags of the main image directory and retrieve the // offset to the next directory, usually the thumbnail directory: dirOffset = EXIF.parseExifTags(dataView, tiffOffset, tiffOffset + dirOffset, littleEndian, data); // 尝试读取缩略图 // if ( dirOffset ) { // thumbnailData = {exif: {}}; // dirOffset = EXIF.parseExifTags( // dataView, // tiffOffset, // tiffOffset + dirOffset, // littleEndian, // thumbnailData // ); // // Check for JPEG Thumbnail offset: // if (thumbnailData.exif[0x0201]) { // data.exif.Thumbnail = EXIF.getExifThumbnail( // dataView, // tiffOffset + thumbnailData.exif[0x0201], // thumbnailData.exif[0x0202] // Thumbnail data length // ); // } // } }; ImageMeta.parsers[0xffe1].push(EXIF.parseExifData); return EXIF; }); /** * @fileOverview Image */ define('runtime/html5/image', [ 'base', 'runtime/html5/runtime', 'runtime/html5/util' ], function (Base, Html5Runtime, Util) { var BLANK = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs%3D'; return Html5Runtime.register('Image', { // flag: 标记是否被修改过。 modified: false, init: function () { var me = this, img = new Image(); img.onload = function () { me._info = { type: me.type, width: this.width, height: this.height }; //debugger; // 读取meta信息。 if (!me._metas && 'image/jpeg' === me.type) { Util.parseMeta(me._blob, function (error, ret) { me._metas = ret; me.owner.trigger('load'); }); } else { me.owner.trigger('load'); } }; img.onerror = function () { me.owner.trigger('error'); }; me._img = img; }, loadFromBlob: function (blob) { var me = this, img = me._img; me._blob = blob; me.type = blob.type; img.src = Util.createObjectURL(blob.getSource()); me.owner.once('load', function () { Util.revokeObjectURL(img.src); }); }, resize: function (width, height) { var canvas = this._canvas || (this._canvas = document.createElement('canvas')); this._resize(this._img, canvas, width, height); this._blob = null; // 没用了,可以删掉了。 this.modified = true; this.owner.trigger('complete', 'resize'); }, crop: function (x, y, w, h, s) { var cvs = this._canvas || (this._canvas = document.createElement('canvas')), opts = this.options, img = this._img, iw = img.naturalWidth, ih = img.naturalHeight, orientation = this.getOrientation(); s = s || 1; // todo 解决 orientation 的问题。 // values that require 90 degree rotation // if ( ~[ 5, 6, 7, 8 ].indexOf( orientation ) ) { // switch ( orientation ) { // case 6: // tmp = x; // x = y; // y = iw * s - tmp - w; // console.log(ih * s, tmp, w) // break; // } // (w ^= h, h ^= w, w ^= h); // } cvs.width = w; cvs.height = h; opts.preserveHeaders || this._rotate2Orientaion(cvs, orientation); this._renderImageToCanvas(cvs, img, -x, -y, iw * s, ih * s); this._blob = null; // 没用了,可以删掉了。 this.modified = true; this.owner.trigger('complete', 'crop'); }, getAsBlob: function (type) { var blob = this._blob, opts = this.options, canvas; type = type || this.type; // blob需要重新生成。 if (this.modified || this.type !== type) { canvas = this._canvas; if (type === 'image/jpeg') { blob = Util.canvasToDataUrl(canvas, type, opts.quality); if (opts.preserveHeaders && this._metas && this._metas.imageHead) { blob = Util.dataURL2ArrayBuffer(blob); blob = Util.updateImageHead(blob, this._metas.imageHead); blob = Util.arrayBufferToBlob(blob, type); return blob; } } else { blob = Util.canvasToDataUrl(canvas, type); } blob = Util.dataURL2Blob(blob); } return blob; }, getAsDataUrl: function (type) { var opts = this.options; type = type || this.type; if (type === 'image/jpeg') { return Util.canvasToDataUrl(this._canvas, type, opts.quality); } else { return this._canvas.toDataURL(type); } }, getOrientation: function () { return this._metas && this._metas.exif && this._metas.exif.get('Orientation') || 1; }, info: function (val) { // setter if (val) { this._info = val; return this; } // getter return this._info; }, meta: function (val) { // setter if (val) { this._metas = val; return this; } // getter return this._metas; }, destroy: function () { var canvas = this._canvas; this._img.onload = null; if (canvas) { canvas.getContext('2d') .clearRect(0, 0, canvas.width, canvas.height); canvas.width = canvas.height = 0; this._canvas = null; } // 释放内存。非常重要,否则释放不了image的内存。 this._img.src = BLANK; this._img = this._blob = null; }, _resize: function (img, cvs, width, height) { var opts = this.options, naturalWidth = img.width, naturalHeight = img.height, orientation = this.getOrientation(), scale, w, h, x, y; // values that require 90 degree rotation if (~[5, 6, 7, 8].indexOf(orientation)) { // 交换width, height的值。 width ^= height; height ^= width; width ^= height; } scale = Math[opts.crop ? 'max' : 'min'](width / naturalWidth, height / naturalHeight); // 不允许放大。 opts.allowMagnify || (scale = Math.min(1, scale)); w = naturalWidth * scale; h = naturalHeight * scale; if (opts.crop) { cvs.width = width; cvs.height = height; } else { cvs.width = w; cvs.height = h; } x = (cvs.width - w) / 2; y = (cvs.height - h) / 2; opts.preserveHeaders || this._rotate2Orientaion(cvs, orientation); this._renderImageToCanvas(cvs, img, x, y, w, h); }, _rotate2Orientaion: function (canvas, orientation) { var width = canvas.width, height = canvas.height, ctx = canvas.getContext('2d'); switch (orientation) { case 5: case 6: case 7: case 8: canvas.width = height; canvas.height = width; break; } switch (orientation) { case 2: // horizontal flip ctx.translate(width, 0); ctx.scale(-1, 1); break; case 3: // 180 rotate left ctx.translate(width, height); ctx.rotate(Math.PI); break; case 4: // vertical flip ctx.translate(0, height); ctx.scale(1, -1); break; case 5: // vertical flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.scale(1, -1); break; case 6: // 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(0, -height); break; case 7: // horizontal flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(width, -height); ctx.scale(-1, 1); break; case 8: // 90 rotate left ctx.rotate(-0.5 * Math.PI); ctx.translate(-width, 0); break; } }, // https://github.com/stomita/ios-imagefile-megapixel/ // blob/master/src/megapix-image.js _renderImageToCanvas: (function () { // 如果不是ios, 不需要这么复杂! if (!Base.os.ios) { return function (canvas) { var args = Base.slice(arguments, 1), ctx = canvas.getContext('2d'); ctx.drawImage.apply(ctx, args); }; } /** * Detecting vertical squash in loaded image. * Fixes a bug which squash image vertically while drawing into * canvas for some images. */ function detectVerticalSquash(img, iw, ih) { var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d'), sy = 0, ey = ih, py = ih, data, alpha, ratio; canvas.width = 1; canvas.height = ih; ctx.drawImage(img, 0, 0); data = ctx.getImageData(0, 0, 1, ih).data; // search image edge pixel position in case // it is squashed vertically. while (py > sy) { alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } ratio = (py / ih); return (ratio === 0) ? 1 : ratio; } // fix ie7 bug // http://stackoverflow.com/questions/11929099/ // html5-canvas-drawimage-ratio-bug-ios if (Base.os.ios >= 7) { return function (canvas, img, x, y, w, h) { var iw = img.naturalWidth, ih = img.naturalHeight, vertSquashRatio = detectVerticalSquash(img, iw, ih); return canvas.getContext('2d').drawImage(img, 0, 0, iw * vertSquashRatio, ih * vertSquashRatio, x, y, w, h); }; } /** * Detect subsampling in loaded image. * In iOS, larger images than 2M pixels may be * subsampled in rendering. */ function detectSubsampling(img) { var iw = img.naturalWidth, ih = img.naturalHeight, canvas, ctx; // subsampling may happen overmegapixel image if (iw * ih > 1024 * 1024) { canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; ctx = canvas.getContext('2d'); ctx.drawImage(img, -iw + 1, 0); // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering // edge pixel or not. if alpha value is 0 // image is not covering, hence subsampled. return ctx.getImageData(0, 0, 1, 1).data[3] === 0; } else { return false; } } return function (canvas, img, x, y, width, height) { var iw = img.naturalWidth, ih = img.naturalHeight, ctx = canvas.getContext('2d'), subsampled = detectSubsampling(img), doSquash = this.type === 'image/jpeg', d = 1024, sy = 0, dy = 0, tmpCanvas, tmpCtx, vertSquashRatio, dw, dh, sx, dx; if (subsampled) { iw /= 2; ih /= 2; } ctx.save(); tmpCanvas = document.createElement('canvas'); tmpCanvas.width = tmpCanvas.height = d; tmpCtx = tmpCanvas.getContext('2d'); vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1; dw = Math.ceil(d * width / iw); dh = Math.ceil(d * height / ih / vertSquashRatio); while (sy < ih) { sx = 0; dx = 0; while (sx < iw) { tmpCtx.clearRect(0, 0, d, d); tmpCtx.drawImage(img, -sx, -sy); ctx.drawImage(tmpCanvas, 0, 0, d, d, x + dx, y + dy, dw, dh); sx += d; dx += dw; } sy += d; dy += dh; } ctx.restore(); tmpCanvas = tmpCtx = null; }; })() }); }); /** * 这个方式性能不行,但是可以解决android里面的toDataUrl的bug * android里面toDataUrl('image/jpege')得到的结果却是png. * * 所以这里没辙,只能借助这个工具 * @fileOverview jpeg encoder */ define('runtime/html5/jpegencoder', [], function (require, exports, module) { /* Copyright (c) 2008, Adobe Systems Incorporated 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 Adobe Systems Incorporated nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009 Basic GUI blocking jpeg encoder */ function JPEGEncoder(quality) { var self = this; var fround = Math.round; var ffloor = Math.floor; var YTable = new Array(64); var UVTable = new Array(64); var fdtbl_Y = new Array(64); var fdtbl_UV = new Array(64); var YDC_HT; var UVDC_HT; var YAC_HT; var UVAC_HT; var bitcode = new Array(65535); var category = new Array(65535); var outputfDCTQuant = new Array(64); var DU = new Array(64); var byteout = []; var bytenew = 0; var bytepos = 7; var YDU = new Array(64); var UDU = new Array(64); var VDU = new Array(64); var clt = new Array(256); var RGB_YUV_TABLE = new Array(2048); var currentQuality; var ZigZag = [ 0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63 ]; var std_dc_luminance_nrcodes = [0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]; var std_dc_luminance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; var std_ac_luminance_nrcodes = [0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d]; var std_ac_luminance_values = [ 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa ]; var std_dc_chrominance_nrcodes = [0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]; var std_dc_chrominance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; var std_ac_chrominance_nrcodes = [0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77]; var std_ac_chrominance_values = [ 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa ]; function initQuantTables(sf) { var YQT = [ 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99 ]; for (var i = 0; i < 64; i++) { var t = ffloor((YQT[i] * sf + 50) / 100); if (t < 1) { t = 1; } else if (t > 255) { t = 255; } YTable[ZigZag[i]] = t; } var UVQT = [ 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99 ]; for (var j = 0; j < 64; j++) { var u = ffloor((UVQT[j] * sf + 50) / 100); if (u < 1) { u = 1; } else if (u > 255) { u = 255; } UVTable[ZigZag[j]] = u; } var aasf = [ 1.0, 1.387039845, 1.306562965, 1.175875602, 1.0, 0.785694958, 0.541196100, 0.275899379 ]; var k = 0; for (var row = 0; row < 8; row++) { for (var col = 0; col < 8; col++) { fdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0)); fdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0)); k++; } } } function computeHuffmanTbl(nrcodes, std_table) { var codevalue = 0; var pos_in_table = 0; var HT = new Array(); for (var k = 1; k <= 16; k++) { for (var j = 1; j <= nrcodes[k]; j++) { HT[std_table[pos_in_table]] = []; HT[std_table[pos_in_table]][0] = codevalue; HT[std_table[pos_in_table]][1] = k; pos_in_table++; codevalue++; } codevalue *= 2; } return HT; } function initHuffmanTbl() { YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes, std_dc_luminance_values); UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes, std_dc_chrominance_values); YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes, std_ac_luminance_values); UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes, std_ac_chrominance_values); } function initCategoryNumber() { var nrlower = 1; var nrupper = 2; for (var cat = 1; cat <= 15; cat++) { //Positive numbers for (var nr = nrlower; nr < nrupper; nr++) { category[32767 + nr] = cat; bitcode[32767 + nr] = []; bitcode[32767 + nr][1] = cat; bitcode[32767 + nr][0] = nr; } //Negative numbers for (var nrneg = -(nrupper - 1); nrneg <= -nrlower; nrneg++) { category[32767 + nrneg] = cat; bitcode[32767 + nrneg] = []; bitcode[32767 + nrneg][1] = cat; bitcode[32767 + nrneg][0] = nrupper - 1 + nrneg; } nrlower <<= 1; nrupper <<= 1; } } function initRGBYUVTable() { for (var i = 0; i < 256; i++) { RGB_YUV_TABLE[i] = 19595 * i; RGB_YUV_TABLE[(i + 256) >> 0] = 38470 * i; RGB_YUV_TABLE[(i + 512) >> 0] = 7471 * i + 0x8000; RGB_YUV_TABLE[(i + 768) >> 0] = -11059 * i; RGB_YUV_TABLE[(i + 1024) >> 0] = -21709 * i; RGB_YUV_TABLE[(i + 1280) >> 0] = 32768 * i + 0x807FFF; RGB_YUV_TABLE[(i + 1536) >> 0] = -27439 * i; RGB_YUV_TABLE[(i + 1792) >> 0] = -5329 * i; } } // IO functions function writeBits(bs) { var value = bs[0]; var posval = bs[1] - 1; while (posval >= 0) { if (value & (1 << posval)) { bytenew |= (1 << bytepos); } posval--; bytepos--; if (bytepos < 0) { if (bytenew == 0xFF) { writeByte(0xFF); writeByte(0); } else { writeByte(bytenew); } bytepos = 7; bytenew = 0; } } } function writeByte(value) { byteout.push(clt[value]); // write char directly instead of converting later } function writeWord(value) { writeByte((value >> 8) & 0xFF); writeByte((value ) & 0xFF); } // DCT & quantization core function fDCTQuant(data, fdtbl) { var d0, d1, d2, d3, d4, d5, d6, d7; /* Pass 1: process rows. */ var dataOff = 0; var i; var I8 = 8; var I64 = 64; for (i = 0; i < I8; ++i) { d0 = data[dataOff]; d1 = data[dataOff + 1]; d2 = data[dataOff + 2]; d3 = data[dataOff + 3]; d4 = data[dataOff + 4]; d5 = data[dataOff + 5]; d6 = data[dataOff + 6]; d7 = data[dataOff + 7]; var tmp0 = d0 + d7; var tmp7 = d0 - d7; var tmp1 = d1 + d6; var tmp6 = d1 - d6; var tmp2 = d2 + d5; var tmp5 = d2 - d5; var tmp3 = d3 + d4; var tmp4 = d3 - d4; /* Even part */ var tmp10 = tmp0 + tmp3; /* phase 2 */ var tmp13 = tmp0 - tmp3; var tmp11 = tmp1 + tmp2; var tmp12 = tmp1 - tmp2; data[dataOff] = tmp10 + tmp11; /* phase 3 */ data[dataOff + 4] = tmp10 - tmp11; var z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */ data[dataOff + 2] = tmp13 + z1; /* phase 5 */ data[dataOff + 6] = tmp13 - z1; /* Odd part */ tmp10 = tmp4 + tmp5; /* phase 2 */ tmp11 = tmp5 + tmp6; tmp12 = tmp6 + tmp7; /* The rotator is modified from fig 4-8 to avoid extra negations. */ var z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */ var z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */ var z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */ var z3 = tmp11 * 0.707106781; /* c4 */ var z11 = tmp7 + z3; /* phase 5 */ var z13 = tmp7 - z3; data[dataOff + 5] = z13 + z2; /* phase 6 */ data[dataOff + 3] = z13 - z2; data[dataOff + 1] = z11 + z4; data[dataOff + 7] = z11 - z4; dataOff += 8; /* advance pointer to next row */ } /* Pass 2: process columns. */ dataOff = 0; for (i = 0; i < I8; ++i) { d0 = data[dataOff]; d1 = data[dataOff + 8]; d2 = data[dataOff + 16]; d3 = data[dataOff + 24]; d4 = data[dataOff + 32]; d5 = data[dataOff + 40]; d6 = data[dataOff + 48]; d7 = data[dataOff + 56]; var tmp0p2 = d0 + d7; var tmp7p2 = d0 - d7; var tmp1p2 = d1 + d6; var tmp6p2 = d1 - d6; var tmp2p2 = d2 + d5; var tmp5p2 = d2 - d5; var tmp3p2 = d3 + d4; var tmp4p2 = d3 - d4; /* Even part */ var tmp10p2 = tmp0p2 + tmp3p2; /* phase 2 */ var tmp13p2 = tmp0p2 - tmp3p2; var tmp11p2 = tmp1p2 + tmp2p2; var tmp12p2 = tmp1p2 - tmp2p2; data[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */ data[dataOff + 32] = tmp10p2 - tmp11p2; var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */ data[dataOff + 16] = tmp13p2 + z1p2; /* phase 5 */ data[dataOff + 48] = tmp13p2 - z1p2; /* Odd part */ tmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */ tmp11p2 = tmp5p2 + tmp6p2; tmp12p2 = tmp6p2 + tmp7p2; /* The rotator is modified from fig 4-8 to avoid extra negations. */ var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */ var z2p2 = 0.541196100 * tmp10p2 + z5p2; /* c2-c6 */ var z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */ var z3p2 = tmp11p2 * 0.707106781; /* c4 */ var z11p2 = tmp7p2 + z3p2; /* phase 5 */ var z13p2 = tmp7p2 - z3p2; data[dataOff + 40] = z13p2 + z2p2; /* phase 6 */ data[dataOff + 24] = z13p2 - z2p2; data[dataOff + 8] = z11p2 + z4p2; data[dataOff + 56] = z11p2 - z4p2; dataOff++; /* advance pointer to next column */ } // Quantize/descale the coefficients var fDCTQuant; for (i = 0; i < I64; ++i) { // Apply the quantization and scaling factor & Round to nearest integer fDCTQuant = data[i] * fdtbl[i]; outputfDCTQuant[i] = (fDCTQuant > 0.0) ? ((fDCTQuant + 0.5) | 0) : ((fDCTQuant - 0.5) | 0); //outputfDCTQuant[i] = fround(fDCTQuant); } return outputfDCTQuant; } function writeAPP0() { writeWord(0xFFE0); // marker writeWord(16); // length writeByte(0x4A); // J writeByte(0x46); // F writeByte(0x49); // I writeByte(0x46); // F writeByte(0); // = "JFIF",'\0' writeByte(1); // versionhi writeByte(1); // versionlo writeByte(0); // xyunits writeWord(1); // xdensity writeWord(1); // ydensity writeByte(0); // thumbnwidth writeByte(0); // thumbnheight } function writeSOF0(width, height) { writeWord(0xFFC0); // marker writeWord(17); // length, truecolor YUV JPG writeByte(8); // precision writeWord(height); writeWord(width); writeByte(3); // nrofcomponents writeByte(1); // IdY writeByte(0x11); // HVY writeByte(0); // QTY writeByte(2); // IdU writeByte(0x11); // HVU writeByte(1); // QTU writeByte(3); // IdV writeByte(0x11); // HVV writeByte(1); // QTV } function writeDQT() { writeWord(0xFFDB); // marker writeWord(132); // length writeByte(0); for (var i = 0; i < 64; i++) { writeByte(YTable[i]); } writeByte(1); for (var j = 0; j < 64; j++) { writeByte(UVTable[j]); } } function writeDHT() { writeWord(0xFFC4); // marker writeWord(0x01A2); // length writeByte(0); // HTYDCinfo for (var i = 0; i < 16; i++) { writeByte(std_dc_luminance_nrcodes[i + 1]); } for (var j = 0; j <= 11; j++) { writeByte(std_dc_luminance_values[j]); } writeByte(0x10); // HTYACinfo for (var k = 0; k < 16; k++) { writeByte(std_ac_luminance_nrcodes[k + 1]); } for (var l = 0; l <= 161; l++) { writeByte(std_ac_luminance_values[l]); } writeByte(1); // HTUDCinfo for (var m = 0; m < 16; m++) { writeByte(std_dc_chrominance_nrcodes[m + 1]); } for (var n = 0; n <= 11; n++) { writeByte(std_dc_chrominance_values[n]); } writeByte(0x11); // HTUACinfo for (var o = 0; o < 16; o++) { writeByte(std_ac_chrominance_nrcodes[o + 1]); } for (var p = 0; p <= 161; p++) { writeByte(std_ac_chrominance_values[p]); } } function writeSOS() { writeWord(0xFFDA); // marker writeWord(12); // length writeByte(3); // nrofcomponents writeByte(1); // IdY writeByte(0); // HTY writeByte(2); // IdU writeByte(0x11); // HTU writeByte(3); // IdV writeByte(0x11); // HTV writeByte(0); // Ss writeByte(0x3f); // Se writeByte(0); // Bf } function processDU(CDU, fdtbl, DC, HTDC, HTAC) { var EOB = HTAC[0x00]; var M16zeroes = HTAC[0xF0]; var pos; var I16 = 16; var I63 = 63; var I64 = 64; var DU_DCT = fDCTQuant(CDU, fdtbl); //ZigZag reorder for (var j = 0; j < I64; ++j) { DU[ZigZag[j]] = DU_DCT[j]; } var Diff = DU[0] - DC; DC = DU[0]; //Encode DC if (Diff == 0) { writeBits(HTDC[0]); // Diff might be 0 } else { pos = 32767 + Diff; writeBits(HTDC[category[pos]]); writeBits(bitcode[pos]); } //Encode ACs var end0pos = 63; // was const... which is crazy for (; (end0pos > 0) && (DU[end0pos] == 0); end0pos--) { } ; //end0pos = first element in reverse order !=0 if (end0pos == 0) { writeBits(EOB); return DC; } var i = 1; var lng; while (i <= end0pos) { var startpos = i; for (; (DU[i] == 0) && (i <= end0pos); ++i) { } var nrzeroes = i - startpos; if (nrzeroes >= I16) { lng = nrzeroes >> 4; for (var nrmarker = 1; nrmarker <= lng; ++nrmarker) writeBits(M16zeroes); nrzeroes = nrzeroes & 0xF; } pos = 32767 + DU[i]; writeBits(HTAC[(nrzeroes << 4) + category[pos]]); writeBits(bitcode[pos]); i++; } if (end0pos != I63) { writeBits(EOB); } return DC; } function initCharLookupTable() { var sfcc = String.fromCharCode; for (var i = 0; i < 256; i++) { ///// ACHTUNG // 255 clt[i] = sfcc(i); } } this.encode = function (image, quality) // image data object { // var time_start = new Date().getTime(); if (quality) setQuality(quality); // Initialize bit writer byteout = new Array(); bytenew = 0; bytepos = 7; // Add JPEG headers writeWord(0xFFD8); // SOI writeAPP0(); writeDQT(); writeSOF0(image.width, image.height); writeDHT(); writeSOS(); // Encode 8x8 macroblocks var DCY = 0; var DCU = 0; var DCV = 0; bytenew = 0; bytepos = 7; this.encode.displayName = "_encode_"; var imageData = image.data; var width = image.width; var height = image.height; var quadWidth = width * 4; var tripleWidth = width * 3; var x, y = 0; var r, g, b; var start, p, col, row, pos; while (y < height) { x = 0; while (x < quadWidth) { start = quadWidth * y + x; p = start; col = -1; row = 0; for (pos = 0; pos < 64; pos++) { row = pos >> 3;// /8 col = ( pos & 7 ) * 4; // %8 p = start + ( row * quadWidth ) + col; if (y + row >= height) { // padding bottom p -= (quadWidth * (y + 1 + row - height)); } if (x + col >= quadWidth) { // padding right p -= ((x + col) - quadWidth + 4) } r = imageData[p++]; g = imageData[p++]; b = imageData[p++]; /* // calculate YUV values dynamically YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80 UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b)); VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b)); */ // use lookup table (slightly faster) YDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256) >> 0] + RGB_YUV_TABLE[(b + 512) >> 0]) >> 16) - 128; UDU[pos] = ((RGB_YUV_TABLE[(r + 768) >> 0] + RGB_YUV_TABLE[(g + 1024) >> 0] + RGB_YUV_TABLE[(b + 1280) >> 0]) >> 16) - 128; VDU[pos] = ((RGB_YUV_TABLE[(r + 1280) >> 0] + RGB_YUV_TABLE[(g + 1536) >> 0] + RGB_YUV_TABLE[(b + 1792) >> 0]) >> 16) - 128; } DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT); DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT); DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT); x += 32; } y += 8; } //////////////////////////////////////////////////////////////// // Do the bit alignment of the EOI marker if (bytepos >= 0) { var fillbits = []; fillbits[1] = bytepos + 1; fillbits[0] = (1 << (bytepos + 1)) - 1; writeBits(fillbits); } writeWord(0xFFD9); //EOI var jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join('')); byteout = []; // benchmarking // var duration = new Date().getTime() - time_start; // console.log('Encoding time: '+ currentQuality + 'ms'); // return jpegDataUri } function setQuality(quality) { if (quality <= 0) { quality = 1; } if (quality > 100) { quality = 100; } if (currentQuality == quality) return // don't recalc if unchanged var sf = 0; if (quality < 50) { sf = Math.floor(5000 / quality); } else { sf = Math.floor(200 - quality * 2); } initQuantTables(sf); currentQuality = quality; // console.log('Quality set to: '+quality +'%'); } function init() { // var time_start = new Date().getTime(); if (!quality) quality = 50; // Create tables initCharLookupTable() initHuffmanTbl(); initCategoryNumber(); initRGBYUVTable(); setQuality(quality); // var duration = new Date().getTime() - time_start; // console.log('Initialization '+ duration + 'ms'); } init(); }; JPEGEncoder.encode = function (data, quality) { var encoder = new JPEGEncoder(quality); return encoder.encode(data); } return JPEGEncoder; }); /** * @fileOverview Fix android canvas.toDataUrl bug. */ define('runtime/html5/androidpatch', [ 'runtime/html5/util', 'runtime/html5/jpegencoder', 'base' ], function (Util, encoder, Base) { var origin = Util.canvasToDataUrl, supportJpeg; Util.canvasToDataUrl = function (canvas, type, quality) { var ctx, w, h, fragement, parts; // 非android手机直接跳过。 if (!Base.os.android) { return origin.apply(null, arguments); } // 检测是否canvas支持jpeg导出,根据数据格式来判断。 // JPEG 前两位分别是:255, 216 if (type === 'image/jpeg' && typeof supportJpeg === 'undefined') { fragement = origin.apply(null, arguments); parts = fragement.split(','); if (~parts[0].indexOf('base64')) { fragement = atob(parts[1]); } else { fragement = decodeURIComponent(parts[1]); } fragement = fragement.substring(0, 2); supportJpeg = fragement.charCodeAt(0) === 255 && fragement.charCodeAt(1) === 216; } // 只有在android环境下才修复 if (type === 'image/jpeg' && !supportJpeg) { w = canvas.width; h = canvas.height; ctx = canvas.getContext('2d'); return encoder.encode(ctx.getImageData(0, 0, w, h), quality); } return origin.apply(null, arguments); }; }); /** * @fileOverview Transport * @todo 支持chunked传输,优势: * 可以将大文件分成小块,挨个传输,可以提高大文件成功率,当失败的时候,也只需要重传那小部分, * 而不需要重头再传一次。另外断点续传也需要用chunked方式。 */ define('runtime/html5/transport', [ 'base', 'runtime/html5/runtime' ], function (Base, Html5Runtime) { var noop = Base.noop, $ = Base.$; return Html5Runtime.register('Transport', { init: function () { this._status = 0; this._response = null; }, send: function () { var owner = this.owner, opts = this.options, xhr = this._initAjax(), blob = owner._blob, server = opts.server, formData, binary, fr; if (opts.sendAsBinary) { server += (/\?/.test(server) ? '&' : '?') + $.param(owner._formData); binary = blob.getSource(); } else { formData = new FormData(); $.each(owner._formData, function (k, v) { formData.append(k, v); }); formData.append(opts.fileVal, blob.getSource(), opts.filename || owner._formData.name || ''); } if (opts.withCredentials && 'withCredentials' in xhr) { xhr.open(opts.method, server, true); xhr.withCredentials = true; } else { xhr.open(opts.method, server); } this._setRequestHeader(xhr, opts.headers); if (binary) { // 强制设置成 content-type 为文件流。 xhr.overrideMimeType && xhr.overrideMimeType('application/octet-stream'); // android直接发送blob会导致服务端接收到的是空文件。 // bug详情。 // https://code.google.com/p/android/issues/detail?id=39882 // 所以先用fileReader读取出来再通过arraybuffer的方式发送。 if (Base.os.android) { fr = new FileReader(); fr.onload = function () { xhr.send(this.result); fr = fr.onload = null; }; fr.readAsArrayBuffer(binary); } else { xhr.send(binary); } } else { xhr.send(formData); } }, getResponse: function () { return this._response; }, getResponseAsJson: function () { return this._parseJson(this._response); }, getStatus: function () { return this._status; }, abort: function () { var xhr = this._xhr; if (xhr) { xhr.upload.onprogress = noop; xhr.onreadystatechange = noop; xhr.abort(); this._xhr = xhr = null; } }, destroy: function () { this.abort(); }, _initAjax: function () { var me = this, xhr = new XMLHttpRequest(), opts = this.options; if (opts.withCredentials && !('withCredentials' in xhr) && typeof XDomainRequest !== 'undefined') { xhr = new XDomainRequest(); } xhr.upload.onprogress = function (e) { var percentage = 0; if (e.lengthComputable) { percentage = e.loaded / e.total; } return me.trigger('progress', percentage); }; xhr.onreadystatechange = function () { if (xhr.readyState !== 4) { return; } xhr.upload.onprogress = noop; xhr.onreadystatechange = noop; me._xhr = null; me._status = xhr.status; if (xhr.status >= 200 && xhr.status < 300) { me._response = xhr.responseText; return me.trigger('load'); } else if (xhr.status >= 500 && xhr.status < 600) { me._response = xhr.responseText; return me.trigger('error', 'server'); } return me.trigger('error', me._status ? 'http' : 'abort'); }; me._xhr = xhr; return xhr; }, _setRequestHeader: function (xhr, headers) { $.each(headers, function (key, val) { xhr.setRequestHeader(key, val); }); }, _parseJson: function (str) { var json; try { json = JSON.parse(str); } catch (ex) { json = {}; } return json; } }); }); define('webuploader', [ 'base', 'widgets/filepicker', 'widgets/image', 'widgets/queue', 'widgets/runtime', 'widgets/upload', 'widgets/log', 'runtime/html5/blob', 'runtime/html5/filepicker', 'runtime/html5/imagemeta/exif', 'runtime/html5/image', 'runtime/html5/androidpatch', 'runtime/html5/transport' ], function (Base) { return Base; }); return require('webuploader'); });
// https://www.creare.co.uk/blog/js/js-eu-cookie-law-banner // Creare's 'Implied Consent' EU Cookie Law Banner v:2.4 // Conceived by Robert Kent, James Bavington & Tom Foyster var cookieDuration = 365; // Number of days before the cookie expires, and the banner reappears var cookieName = 'EuCookieLawCompliance'; // Name of our cookie var cookieValue = 'on'; // Value of cookie function createBanner() { var bodytag = document.getElementsByTagName('body')[0]; var div = document.createElement('div'); div.setAttribute('id', 'cookie-law-banner'); div.innerHTML = '<i class="icon-info-circle distanced"></i>This website uses cookies. We do not use cookies for evil. By continuing we assume your permission to deploy cookies. <button type="button" onclick="createCookie();">Alright</button>'; bodytag.appendChild(div); // Adds the Cookie Law Banner just before the closing </body> tag // or // bodytag.insertBefore(div, bodytag.firstChild); // Adds the Cookie Law Banner just after the opening <body> tag // document.getElementsByTagName('body')[0].className += ' cookiebanner'; //Adds a class tothe <body> tag when the banner is visible } function createCookie() { var expires; if (window.cookieDuration) { var date = new Date(); date.setTime(date.getTime() + (window.cookieDuration * 24 * 60 * 60 * 1000)); expires = '; expires=' + date.toGMTString(); } else { expires = ''; } document.cookie = window.cookieName + '=' + window.cookieValue + expires + '; path=/'; var element = document.getElementById('cookie-law-banner'); element.parentNode.removeChild(element); } function checkCookie(name) { var nameEQ = name + '='; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; } function eraseCookie(name) { createCookie(name, '', -1); } window.onload = function () { if (checkCookie(window.cookieName) != window.cookieValue) { createBanner(); } };
// flow-typed signature: 715c8753230e19bbaff4d8c2ee503f1a // flow-typed version: <<STUB>>/babel-preset-stage-0_v^6.22.0/flow_v0.47.0 /** * This is an autogenerated libdef stub for: * * 'babel-preset-stage-0' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'babel-preset-stage-0' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'babel-preset-stage-0/lib/index' { declare module.exports: any; } // Filename aliases declare module 'babel-preset-stage-0/lib/index.js' { declare module.exports: $Exports<'babel-preset-stage-0/lib/index'>; }
$(document).ready(function() { // <editor-fold defaultstate="collapsed" desc="Fonctions globales"> function addAjaxLoading(element, id) { var loadingImage = $('#loading-image-path').attr('value'); element.parent('div').append('<img id="' + id + '" src="' + loadingImage + '" alt="loading" />'); } function eraseLocal() { document.getElementById("caesar_resourceBundle_resourceType_local").value = ""; } function eraseURL() { document.getElementById("caesar_resourceBundle_resourceType_url").value = ""; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Chargement de l'image"> function handleFileSelect(evt) { var files = evt.target.files; // FileList object // Loop through the FileList and render image files as thumbnails. for (var i = 0, f; i < files.length; i++) { f = files[i]; // Only process image files. if (!f.type.match('image.*')) { continue; } var reader = new FileReader(); // Closure to capture the file information. reader.onload = (function(theFile) { return function(e) { // Render thumbnail. var img = document.getElementById('resource-img'); img.src = e.target.result; document.getElementById('caesar_resourceBundle_resourceType_path').value = e.target.result; img.title = escape(theFile.name); }; })(f); // Read in the image file as a data URL. reader.readAsDataURL(f); } } document.getElementById('caesar_resourceBundle_resourceType_local').addEventListener('change', handleFileSelect, false); document.getElementById("caesar_resourceBundle_resourceType_url").addEventListener('click', eraseURL); document.getElementById('apply-image').addEventListener('click', function() { var a = document.getElementById('caesar_resourceBundle_resourceType_url'); eraseLocal(); var img = document.getElementById('resource-img'); img.src = a.value; document.getElementById('caesar_resourceBundle_resourceType_path').value = a.value; }, false); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Webmining"> var webmining = false; var disabled = false; function isWebminingPossible() { var code = $('.resource-code').val(); if (code === "" || !isValidIsbn(code)) { disabled = true; $("a.web-mining-button").removeClass("bubble-button"); $("a.web-mining-button").addClass("disabled-webmining-button"); } else { $("a.web-mining-button").addClass("bubble-button"); $("a.web-mining-button").removeClass("disabled-webmining-button"); disabled = false; } } $('.resource-code').keyup(isWebminingPossible); isWebminingPossible(); //On cache la fenêtre modale si on appuie sur le bouton close. $(".btn").click(function(e) { $("#modal").removeClass("modal-visible"); e.preventDefault(); return false; }); $('.web-mining-button').hover(function() { if (!$('a.web-mining-button').hasClass('disabled-webmining-button')) { $(".web-mining-to-color").addClass('notify-web-mining'); $(".web-mining-to-color").removeClass('unnotify-web-mining'); } }, function() { $(".web-mining-to-color").removeClass('notify-web-mining'); $(".web-mining-to-color").addClass('unnotify-web-mining'); }); $("a.web-mining-button").on('click.webmining', function(e) { if (webmining || disabled) { return; } webmining = true; addAjaxLoading($('a.web-mining-button'), 'loading-webmining'); $("a.web-mining-button").addClass("disabled-webmining-button"); $("a.web-mining-button").removeClass("bubble-button"); var url = $('.webmining-url').attr('value'); url += '/' + $('.resource-code').val(); $.ajax({ type: "POST", url: url, cache: false, success: function(json) { var resource = JSON && JSON.parse(json) || $.parseJSON(json); if (resource.description.length === 0) { $(".web-mining-image-url").attr('value', ""); $(".web-mining-description").val(""); $("#modal").addClass("modal-visible"); } else { $(".web-mining-image-url").attr('value', resource.image); $(".web-mining-description").val(resource.description); } $(".web-mining-long-description").text(resource.longDescription.replace(/\\r\\n/g, '\r\n')); $("a.web-mining-button").removeClass("disabled-webmining-button"); $("a.web-mining-button").addClass("bubble-button"); if ($('#apply-image').attr('value') !== "") { $('#apply-image').click(); } else { document.getElementById('caesar_resourceBundle_resourceType_path').value = ""; } $('#loading-webmining').remove(); webmining = false; }, error: function() { $("a.web-mining-button").removeClass("disabled-webmining-button"); $("a.web-mining-button").addClass("bubble-button"); $('#loading-webmining').remove(); webmining = false; } }); e.preventDefault(); return false; }); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Skeleton"> $("#clearSkeleton").on('click', function(e) { var url = $('.empty-skeleton-url').attr('value'); $.ajax({ type: "POST", url: url, cache: false, success: function(skeleton) { $(".web-mining-long-description").text(skeleton.replace(/\\r\\n/g, '\r\n')); } }); e.preventDefault(); return false; }); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Chargement description emplacement"> var onChange = false; $("select.shelf-selection").change(function(e) { if (!onChange) { onChange = true; addAjaxLoading($('.shelf-selection'), 'loading-description'); var url = $('.shelf-description-url').attr('value'); url += '/' + $(this).find(":selected").attr('value'); $.ajax({ type: "POST", url: url, cache: false, success: function(data) { $('.shelf-description').html(data); $('.shelf-description').css('display', 'block'); $('#loading-description').remove(); onChange = false; }, error: function(xhr, ajaxOptions, thrownError) { $('.shelf-description').css('display', 'none'); $('#loading-description').remove(); onChange = false; } }); } e.preventDefault(); return false; }); // </editor-fold> });
import copySitecoreLibraries from './tasks/copy-sitecore-libraries'; import deploy from './tasks/deploy'; import nugetRestore from './tasks/nuget-restore'; import publishProjects from './tasks/publish-projects'; import publishTDS from './tasks/publish-tds'; export { copySitecoreLibraries, deploy, nugetRestore, publishProjects, publishTDS, };
'use strict' const path = require('path') const utils = require('./utils') const webpack = require('webpack') const config = require('../config') const merge = require('webpack-merge') const baseWebpackConfig = require('./webpack.base.conf') const CopyWebpackPlugin = require('copy-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') const MiniCssExtractPlugin = require("mini-css-extract-plugin") const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') const VueLoaderPlugin = require("vue-loader/lib/plugin"); const pp = require('../package') const env = process.env.NODE_ENV === 'testing' ? require('../config/test.env') : config.build.env const webpackConfig = merge(baseWebpackConfig, { mode: 'production', module: { rules: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true }) }, devtool: config.build.productionSourceMap ? '#source-map' : false, output: { path: config.build.assetsRoot, filename: utils.assetsPath('js/[name].[chunkhash].js'), chunkFilename: utils.assetsPath('js/[id].[chunkhash].js'), publicPath: ['/', pp.aliasName, '/'].join('') }, optimization: { // minimize: true, splitChunks: { cacheGroups: { commons: { test: /[\\/]node_modules[\\/]/, name: "vendor", chunks: "all" } } } }, plugins: [ new VueLoaderPlugin(), // http://vuejs.github.io/vue-loader/en/workflow/production.html new webpack.DefinePlugin({ 'process.env': env }), // UglifyJs do not support ES6+, you can also use babel-minify for better treeshaking: https://github.com/babel/minify // new webpack.optimize.UglifyJsPlugin({ // compress: { // warnings: false // }, // sourceMap: true // }), // extract css into its own file new MiniCssExtractPlugin({ filename: utils.assetsPath('css/[name].[contenthash].css'), //utils.assetsPath('css/[name].[contenthash].css') chunkFilename: utils.assetsPath('css/[name].[contenthash].css') }), // Compress extracted CSS. We are using this plugin so that possible // duplicated CSS from different components can be deduped. new OptimizeCSSPlugin({ cssProcessorOptions: { safe: true } }), // generate dist index.html with correct asset hash for caching. // you can customize output by editing /index.html // see https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ filename: process.env.NODE_ENV === 'testing' ? 'index.html' : config.build.index, template: 'index.html', inject: true, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true // more options: // https://github.com/kangax/html-minifier#options-quick-reference }, chunks: ['vendor', 'manifest', 'index'], // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: 'dependency' }), new HtmlWebpackPlugin({ filename: process.env.NODE_ENV === 'testing' ? 'index.html' : config.build.demo, template: 'index.html', inject: true, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true // more options: // https://github.com/kangax/html-minifier#options-quick-reference }, chunks: ['vendor', 'manifest', 'demo/index'], // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: 'dependency' }), // keep module.id stable when vender modules does not change new webpack.HashedModuleIdsPlugin(), // split vendor js into its own file // new webpack.optimize.CommonsChunkPlugin({ // name: 'vendor', // minChunks: function (module) { // if(module.resource && (/^.*\.(css|scss)$/).test(module.resource)) { // return false; // } // // any required modules inside node_modules are extracted to vendor // return ( // module.resource && // /\.js$/.test(module.resource) && // module.resource.indexOf( // path.join(__dirname, '../node_modules') // ) === 0 // ) // } // }), // extract webpack runtime and module manifest to its own file in order to // prevent vendor hash from being updated whenever app bundle is updated // new webpack.optimize.CommonsChunkPlugin({ // name: 'manifest', // chunks: ['vendor'] // }), // copy custom static assets new CopyWebpackPlugin([ { from: path.resolve(__dirname, '../static'), to: config.build.assetsSubDirectory, ignore: ['.*'] } ]) ] }) if (config.build.productionGzip) { // const CompressionWebpackPlugin = require('compression-webpack-plugin') // webpackConfig.plugins.push( // new CompressionWebpackPlugin({ // asset: '[path].gz[query]', // algorithm: 'gzip', // test: new RegExp( // '\\.(' + // config.build.productionGzipExtensions.join('|') + // ')$' // ), // threshold: 10240, // minRatio: 0.8 // }) // ) } if (config.build.bundleAnalyzerReport) { const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin webpackConfig.plugins.push(new BundleAnalyzerPlugin()) } module.exports = webpackConfig
import {h, div, h1, h2} from '@cycle/dom' const view = props$ => { return props$.map(x => { return div('.page2', [ h1('.content-subhead', ['Page 2']), h1([`This is the second Page`]), h2(['Counter : ' + x]) ]) }); }; export default view
export const TYPE = { PUBLIC: 'public', LINK: 'link', USER: 'user', PRIVATE: 'private', }; export const SHARE_TYPE = { PUBLIC: 'public', LINK: 'link', USER: 'user', PRIVATE: 'private', };
Boom.SecretTrigger = function( params ){ this.type = params.type || Boom.Assets.world.ENTITY.MISSING; this.position = params.position; this.interactable = params.interactable || false; this.triggered = false; Boom.Entity.call(this, {name: 'TRIGGER_SECRET', }); }; Boom.SecretTrigger.prototype = Boom.inherit(Boom.Entity, { constructor: Boom.SecretTrigger, init: function() { //Call super Boom.Entity.prototype.init.call(this); this.load(); }, load: function(){ //Call super Boom.Entity.prototype.load.call(this); }, update: function(){ console.log("updating and stuff"); //Call super Boom.Entity.prototype.update.call(this); }, dispose: function(){ //Call super Boom.Entity.prototype.dispose.call(this); }, trigger: function(){ if(!this.triggered){ this.triggered = true; this.process(); $(Boom.Constants.UI.ELEMENT.SECRET).show(200); $(Boom.Constants.UI.ELEMENT.SECRET).hide(5000); //Check if any entities are on this position - and trigger it if exists Boom.GameGrid.triggerEntity( this.triggered, this.position, { open: true } ); } }, //Registers the entity as a player-used entity process: function(){ Boom.Constants.UI.PLAYER.STATS.SECRETS++; //Call super Boom.Entity.prototype.process.call(this); }, //Adds entity to world-total in statistics register: function(){ Boom.Constants.World.STATS.SECRETS++; //Call super Boom.Entity.prototype.register.call(this); }, });
/* * fingerprintJS 0.5.4 - Fast browser fingerprint library * https://github.com/Valve/fingerprintjs * Copyright (c) 2013 Valentin Vasilyev (valentin.vasilyev@outlook.com) * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license. * * 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 <COPYRIGHT HOLDER> 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. */ ;(function (name, context, definition) { if (typeof module !== 'undefined' && module.exports) { module.exports = definition(); } else if (typeof define === 'function' && define.amd) { define(definition); } else { context[name] = definition(); } })('Fingerprint', this, function () { 'use strict'; var Fingerprint = function (options) { var nativeForEach, nativeMap; nativeForEach = Array.prototype.forEach; nativeMap = Array.prototype.map; this.each = function (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++) { if (iterator.call(context, obj[i], i, obj) === {}) return; } } else { for (var key in obj) { if (obj.hasOwnProperty(key)) { if (iterator.call(context, obj[key], key, obj) === {}) return; } } } }; this.map = function(obj, iterator, context) { var results = []; // Not using strict equality so that this acts as a // shortcut to checking for `null` and `undefined`. if (obj == null) return results; if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); this.each(obj, function(value, index, list) { results[results.length] = iterator.call(context, value, index, list); }); return results; }; if (typeof options == 'object'){ this.hasher = options.hasher; this.screen_resolution = options.screen_resolution; this.screen_orientation = options.screen_orientation; this.canvas = options.canvas; this.ie_activex = options.ie_activex; } else if(typeof options == 'function'){ this.hasher = options; } }; Fingerprint.prototype = { get: function(){ var keys = []; keys.push(navigator.userAgent); keys.push(navigator.language); keys.push(screen.colorDepth); if (this.screen_resolution) { var resolution = this.getScreenResolution(); if (typeof resolution !== 'undefined'){ // headless browsers, such as phantomjs keys.push(resolution.join('x')); } } keys.push(new Date().getTimezoneOffset()); keys.push(this.hasSessionStorage()); keys.push(this.hasLocalStorage()); keys.push(!!window.indexedDB); //body might not be defined at this point or removed programmatically if(document.body){ keys.push(typeof(document.body.addBehavior)); } else { keys.push(typeof undefined); } keys.push(typeof(window.openDatabase)); keys.push(navigator.cpuClass); keys.push(navigator.platform); keys.push(navigator.doNotTrack); keys.push(this.getPluginsString()); if(this.canvas && this.isCanvasSupported()){ keys.push(this.getCanvasFingerprint()); } if(this.hasher){ return this.hasher(keys.join('###'), 31); } else { return this.murmurhash3_32_gc(keys.join('###'), 31); } }, /** * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011) * * @author <a href="mailto:gary.court@gmail.com">Gary Court</a> * @see http://github.com/garycourt/murmurhash-js * @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a> * @see http://sites.google.com/site/murmurhash/ * * @param {string} key ASCII only * @param {number} seed Positive integer only * @return {number} 32-bit positive integer hash */ murmurhash3_32_gc: function(key, seed) { var remainder, bytes, h1, h1b, c1, c2, k1, i; remainder = key.length & 3; // key.length % 4 bytes = key.length - remainder; h1 = seed; c1 = 0xcc9e2d51; c2 = 0x1b873593; i = 0; while (i < bytes) { k1 = ((key.charCodeAt(i) & 0xff)) | ((key.charCodeAt(++i) & 0xff) << 8) | ((key.charCodeAt(++i) & 0xff) << 16) | ((key.charCodeAt(++i) & 0xff) << 24); ++i; k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff; h1 ^= k1; h1 = (h1 << 13) | (h1 >>> 19); h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff; h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16)); } k1 = 0; switch (remainder) { case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16; case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8; case 1: k1 ^= (key.charCodeAt(i) & 0xff); k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; h1 ^= k1; } h1 ^= key.length; h1 ^= h1 >>> 16; h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff; h1 ^= h1 >>> 13; h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff; h1 ^= h1 >>> 16; return h1 >>> 0; }, // https://bugzilla.mozilla.org/show_bug.cgi?id=781447 hasLocalStorage: function () { try{ return !!window.localStorage; } catch(e) { return true; // SecurityError when referencing it means it exists } }, hasSessionStorage: function () { try{ return !!window.sessionStorage; } catch(e) { return true; // SecurityError when referencing it means it exists } }, isCanvasSupported: function () { var elem = document.createElement('canvas'); return !!(elem.getContext && elem.getContext('2d')); }, isIE: function () { if(navigator.appName === 'Microsoft Internet Explorer') { return true; } else if(navigator.appName === 'Netscape' && /Trident/.test(navigator.userAgent)){// IE 11 return true; } return false; }, getPluginsString: function () { if(this.isIE() && this.ie_activex){ return this.getIEPluginsString(); } else { return this.getRegularPluginsString(); } }, getRegularPluginsString: function () { return this.map(navigator.plugins, function (p) { var mimeTypes = this.map(p, function(mt){ return [mt.type, mt.suffixes].join('~'); }).join(','); return [p.name, p.description, mimeTypes].join('::'); }, this).join(';'); }, getIEPluginsString: function () { if(window.ActiveXObject){ var names = ['ShockwaveFlash.ShockwaveFlash',//flash plugin 'AcroPDF.PDF', // Adobe PDF reader 7+ 'PDF.PdfCtrl', // Adobe PDF reader 6 and earlier, brrr 'QuickTime.QuickTime', // QuickTime // 5 versions of real players 'rmocx.RealPlayer G2 Control', 'rmocx.RealPlayer G2 Control.1', 'RealPlayer.RealPlayer(tm) ActiveX Control (32-bit)', 'RealVideo.RealVideo(tm) ActiveX Control (32-bit)', 'RealPlayer', 'SWCtl.SWCtl', // ShockWave player 'WMPlayer.OCX', // Windows media player 'AgControl.AgControl', // Silverlight 'Skype.Detection']; // starting to detect plugins in IE return this.map(names, function(name){ try{ new ActiveXObject(name); return name; } catch(e){ return null; } }).join(';'); } else { return ""; // behavior prior version 0.5.0, not breaking backwards compat. } }, getScreenResolution: function () { var resolution; if(this.screen_orientation){ resolution = (screen.height > screen.width) ? [screen.height, screen.width] : [screen.width, screen.height]; }else{ resolution = [screen.height, screen.width]; } return resolution; }, getCanvasFingerprint: function () { var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); // https://www.browserleaks.com/canvas#how-does-it-work var txt = 'http://valve.github.io'; ctx.textBaseline = "top"; ctx.font = "14px 'Arial'"; ctx.textBaseline = "alphabetic"; ctx.fillStyle = "#f60"; ctx.fillRect(125,1,62,20); ctx.fillStyle = "#069"; ctx.fillText(txt, 2, 15); ctx.fillStyle = "rgba(102, 204, 0, 0.7)"; ctx.fillText(txt, 4, 17); return canvas.toDataURL(); } }; return Fingerprint; });
import React from 'react'; import { expect } from 'chai'; import { shallow } from 'enzyme'; import H1, { styles } from './index'; describe('<H1 />', () => { it('should correctly render children, when text', () => { const wrapper = shallow(<H1>Title</H1>); expect(wrapper.text()).to.equal('Title'); }); it('should append a className to the default, if provided', () => { const wrapper = shallow(<H1 className="test-class">Title H1</H1>); expect(wrapper.prop('className')).to.equal(`test-class ${styles.h1}`); }); it('should use the default className from the stylesheet, if not provided', () => { const wrapper = shallow(<H1>Title H1</H1>); expect(wrapper.prop('className')).to.equal(styles.h1); }); });
'use strict'; var elements = require('../elements'); /** * Show the element (remove the class .hidden) * * @name Element#show * @method * */ /** * Show the elements (remove the class .hidden) * * @name ElementsArray#show * @method */ elements.addMethodWithoutArgumentsReturnThis('show'); /** * Hide the element (add the class .hidden) * * @name Element#hide * @method * */ /** * Hide the elements (add the class .hidden) * * @name ElementsArray#hide * @method */ elements.addMethodWithoutArgumentsReturnThis('hide'); /** * Toggle an element's visibility using the hidden class * * @name Element#toggle * @method * */ /** * Toggle an element's visibility using the hidden class * * @name ElementsArray#toggle * @method */ elements.addMethodWithoutArgumentsReturnThis('toggle'); /** * Return if an element's visibility * * @name Element#isVisible * @method * */ /** * Return a map of element's visibility * * @name ElementsArray#isVisible * @method */ elements.addMethodWithoutArgumentsReturnResult('isVisible'); //# sourceMappingURL=visibility.js.map
// Copyright StrongLoop 2014 Arc.controller('ArcMainController', [ '$scope', 'ArcUserService', '$log', '$rootScope', 'LandingService', function($scope, ArcUserService, $log, $rootScope, LandingService){ $scope.suiteIA = { apps: [] }; //set help id for app modules $scope.$watch('suiteIA.appId', function(newVal){ if ( !newVal ) return; $rootScope.helpId = newVal; }); $scope.isAuthUser = function(){ return ArcUserService.isAuthUser(); }; $scope.pageClick = function($event){ $rootScope.$broadcast('pageClick', $event); }; $scope.supportAppController = false; LandingService.getApps().$promise .then(function(response) { var buildApp = response.results.filter(function(d) { return d.id === 'build-deploy'; }); if (buildApp.length) { $scope.supportAppController = buildApp[0].supportsCurrentProject; } }); }]); Arc.controller('HomeMainController',[ '$scope', '$location', function($scope, $location){ var viewModel = {}; viewModel.message = 'StrongLoop Arc'; $scope.viewModel = viewModel; } ]); /* * * */ Arc.controller('GlobalNavController',[ '$scope', 'ArcUserService', '$location', function($scope, ArcUserService, $location) { $scope.isAuthUser = function(){ return ArcUserService.getCurrentUserId(); }; } ]);
Template.modalEditLanguages.events({ "submit form": function (event) { event.preventDefault(); var name = event.target["language-name"].value.trim(), project = event.target["project-id"].value; if (name) { Meteor.call('addLanguage', project, name, function (error, res) { if (error) Materialize.toast(error.reason, 5000); else { event.target["language-name"].value = ""; $('#modal-edit-languages').closeModal(); } }); } }, 'click [data-action="remove-language"]': function (event) { event.preventDefault(); var $el = $(event.currentTarget), project = $el.data('project'), language = $el.text(); Meteor.call('removeLanguage', project, language, function (error, res) { if (error) Materialize.toast(error.reason, 5000); //else $el.remove(); }); } });
var EventEmitter = require('events').EventEmitter; var util = require('util'); var MongoClient = require('mongodb').MongoClient; var Channel = require('./channel'); /** * Connection constructor. * * @param {String|Db} uri string or Db instance * @param {Object} mongo driver options * @api public */ function Connection(uri, options) { var self = this; options || (options = {}); options.autoReconnect != null || (options.autoReconnect = true); // It's a Db instance. if (uri.collection) { this.db = uri; } else { MongoClient.connect(uri, options, function (err, db) { if (err) return self.emit('error', err); self.db = db; self.emit('connect', db); db.on('error', function (err) { self.emit('error', err); }); }); } this.destroyed = false; this.channels = {}; } module.exports = Connection; util.inherits(Connection, EventEmitter); /** * Current connection state. * * @type {String} * @api public */ Object.defineProperty(Connection.prototype, 'state', { enumerable: true, get: function () { var state; // Using 'destroyed' to be compatible with the driver. if (this.destroyed) { state = 'destroyed'; } else if (this.db) { state = this.db.serverConfig.isConnected() ? 'connected' : 'disconnected'; } else { state = 'connecting'; } return state; } }); /** * Creates or returns a channel with the passed name. * * @see Channel * @return {Channel} * @api public */ Connection.prototype.channel = function (name, options) { if (typeof name === 'object') { options = name; name = 'mubsub'; } if (!this.channels[name] || this.channels[name].closed) { this.channels[name] = new Channel(this, name, options); } return this.channels[name]; }; /** * Close connection. * * @param {Function} [callback] * @return {Connection} this * @api public */ Connection.prototype.close = function (callback) { this.destroyed = true; this.emit('close'); this.db.close(callback); return this; };
/* jshint node: true */ 'use strict'; var DeployPluginBase = require('ember-cli-deploy-plugin'); var S3Client = require('./lib/aws-s3'); var CodeDeployClient = require('./lib/aws-codedeploy'); var path = require('path'); var minmatch = require('minimatch'); var Promise = require('ember-cli/lib/ext/promise'); module.exports = { name: 'ember-cli-deploy-aws-codedeploy', createDeployPlugin: function(options) { var DeployPlugin = DeployPluginBase.extend({ name: options.name, defaultConfig: { filePattern: '**/*.{js,css,png,gif,ico,jpg,map,xml,txt,svg,swf,eot,ttf,woff,woff2,yml,html,htm}', basePackageName: this.project.pkg.name + '-' + this.project.pkg.version, archiveType: 'zip', archiveTempDirectory: 'tmp', distDir: function(context) { return context.distDir; }, distFiles: function(context) { return context.distFiles || []; }, manifestPath: function(context) { return context.manifestPath; // e.g. from ember-cli-deploy-manifest }, revisionKey: function(context) { var revisionData = context.revisionData; return revisionData.revisionKey + '-' + revisionData.timestamp; }, }, ensureConfigPropertySet: function(propertyName) { if (!this.propertyByString(this.pluginConfig, propertyName)) { var message = 'Missing required config: `' + propertyName + '`'; this.log(message, { color: 'red' }); throw new Error(message); } }, propertyByString: function(object, property) { var properties = property.replace(/\[(\w+)\]/g, '.$1'); properties = properties.replace(/^\./, ''); var a = properties.split('.'); for (var i = 0, n = a.length; i < n; ++i) { var k = a[i]; if (k in object) { object = object[k]; } else { return; } } return object; }, requiredConfig: ['accessKeyId', 'secretAccessKey', 'region', 'archiveType', 'awsDeploymentOptions.applicationName', 'awsDeploymentOptions.revision.revisionType'], prepare: function(context) { /** * We have two use cases here: * 1. User wants to use S3 and Code Deploy * 2. User does not want to use S3, only code deploy. */ this.awsCodeDeployServiceOptions = this.awsCodeDeployServiceOptions || {}; var awsDeploymentOptions = this.readConfig('awsDeploymentOptions'); if (awsDeploymentOptions.revision.revisionType === 'S3') { this.awsS3ServiceOptions = this.awsS3ServiceOptions || {}; if (!this.awsS3ServiceOptions['accessKeyId']) this.awsS3ServiceOptions['accessKeyId'] = this.readConfig('accessKeyId'); if (!this.awsS3ServiceOptions['secretAccessKey']) this.awsS3ServiceOptions['secretAccessKey'] = this.readConfig('secretAccessKey'); if (!this.awsS3ServiceOptions['region']) this.awsS3ServiceOptions['region'] = this.readConfig('region'); this._awsS3Client = new S3Client({ parentPlugin: this, awsS3ServiceOptions: this.awsS3ServiceOptions, distDir: this.readConfig('distDir'), revisionKey: this.readConfig('basePackageName') + '-' + this.readConfig('revisionKey'), manifestPath: this.readConfig('manifestPath'), archiveType: this.readConfig('archiveType'), archiveTempDirectory: this.readConfig('archiveTempDirectory'), }, this); } if (!this.awsCodeDeployServiceOptions['accessKeyId']) this.awsCodeDeployServiceOptions['accessKeyId'] = this.readConfig('accessKeyId'); if (!this.awsCodeDeployServiceOptions['secretAccessKey']) this.awsCodeDeployServiceOptions['secretAccessKey'] = this.readConfig('secretAccessKey'); if (!this.awsCodeDeployServiceOptions['region']) this.awsCodeDeployServiceOptions['region'] = this.readConfig('region'); if (!awsDeploymentOptions) awsDeploymentOptions = {}; if (!awsDeploymentOptions.applicationName) awsDeploymentOptions.applicationName = this.readConfig('basePackageName'); this._awsCodeDeployClient = new CodeDeployClient({ log: this.log, awsCodeDeployServiceOptions: this.awsCodeDeployServiceOptions, awsDeploymentOptions: awsDeploymentOptions }); }, upload: function(context) { var distributionFiles = this.readConfig('distFiles'); var filePattern = this.readConfig('filePattern'); var revisionType = this.readConfig('revisionType'); var awsDeploymentOptions = this.readConfig('awsDeploymentOptions'); var filesToUpload = distributionFiles.filter(minmatch.filter(filePattern, { matchBase: true })); this.log('Checking context', { color: 'yellow' }); var uploadPromise = (awsDeploymentOptions.revision.revisionType === 'S3') ? this._awsS3Client.upload(filesToUpload, this.readConfig('s3UploadOptions'), this.readConfig('manifestPath')) : new Promise().resolve(); return uploadPromise.then((result) => { return this._awsCodeDeployClient.createDeployment(result) }); } }); return new DeployPlugin(); } };
require(['common', 'jquery.metisMenu', 'layui', 'layers',"tools","ajaxurl", 'text!/assets/popup/del-news.html', 'text!/assets/popup/clear-news.html','text!/assets/popup/shield-news.html'], function (common, undefined, layui, layers,tool,ajaxurl,delNews, clearNews, shieldNews) { var main = { /** * [admin description] 获取用户信息 * @return {[type]} [description] */ admin:function(){ var userinfo = common.getUserInfo(); if(userinfo){ vm.userinfo = userinfo; } }, /** * 树形菜单 */ sideMenu: function () { Vue.nextTick(function () { $('#side-menu').metisMenu(); }) }, /** * 清空未读信息 */ DelNoread:function(type,sontype,callback){ tool.ajax({ url: ajaxurl.sms.delUnread, type: 'get', data:{ employee_id:vm.userinfo.id, type:type, sontype:sontype, }, success: function (result) { if (result.code == 1) { // 渲染到vue数据层 typeof callback === 'function' && callback.call(this); } } }); }, /** * 获取树形菜单数据 */ getNavData: function (type,sontype,callback) { tool.ajax({ url: ajaxurl.sms.big, type: 'get', data:{employee_id:vm.userinfo.id,}, success: function (result) { if (result.code == 1) { main.clickTypeCss(type); // 渲染到vue数据层 if(type !=null ){ vm.navData = result.data; main.getTypeData(type); main.getNewsData(type,sontype); // vm.allnewsNum = 888; for(var i=0,len=result.data.length;i<len;i++){ if(result.data[i].id == type){ if(result.data[i].noread != 0){ vm.allnewsNum = result.data[i].noread; }else{ vm.allnewsNum = ''; } } } typeof callback === 'function' && callback.call(this); }else{ vm.TypeId = result.data[0].id; main.DelNoread(result.data[0].id,'',function(){ main.getTypeData(result.data[0].id); main.getNewsData(result.data[0].id); vm.navData = result.data; // console.log(result.data[0].noread); }); vm.title = result.data[0].name; } } else { layers.toast(result.message); } } }); }, /** * 获取分类菜单数据 */ getTypeData: function (id) { tool.ajax({ url: ajaxurl.sms.small, type: 'get', data: {employee_id:vm.userinfo.id,type:id}, success: function (result) { if (result.code == 1) { // 渲染到vue数据层 main.clickSontypeCss(id); vm.TypeData = result.data; // main.getNewsData(id); } else { layers.toast(result.message); } } }); }, /** * 消息列表数据 */ getNewsData:function(id,sontype, callback){ layers.load(function (indexs) { vm.isLoadingIndex = indexs; }); tool.ajax({ url: ajaxurl.sms.List, type: 'get', data: { employee_id:vm.userinfo.id, type:id, sontype:sontype, page:vm.newsInfo.curpage, pagesize:vm.newsInfo.pagesize }, success: function (result) { if (result.code == 1) { // 渲染到vue数据层 vm.newsData = result.data; if(vm.newsData[0]){ vm.count=vm.newsData[0].count; }else{ vm.count=0; } main.followPage(); setTimeout(function(){ main.clickTypeCss(id); main.clickSontypeCss(sontype); }, 0); typeof callback === 'function' && callback.call(this); layers.closed(vm.isLoadingIndex); } else { layers.toast(result.message); } } }); /* 渲染到vue数据层 */ // vm.tableList = newsList; /* 实例化日期,表格 */ layui.use(['element', 'laypage', 'layer'], function(){ var $ = layui.jquery, laypage = layui.laypage, layer = layui.layer, element = layui.element; //Tab的切换功能,切换事件监听等,需要依赖element模块 /*分页器*/ laypage.render({ elem: 'demo8' ,count: 1000 ,layout: ['limit', 'prev', 'page', 'next'] }); //触发事件 var active = { tabAdd: function(){ //新增一个Tab项 element.tabAdd('demo', { title: '新选项'+ (Math.random()*1000|0) //用于演示 ,content: '内容'+ (Math.random()*1000|0) ,id: new Date().getTime() //实际使用一般是规定好的id,这里以时间戳模拟下 }) } ,tabDelete: function(othis){ //删除指定Tab项 element.tabDelete('demo', '44'); //删除:“商品管理” othis.addClass('layui-btn-disabled'); } ,tabChange: function(){ //切换到指定Tab项 element.tabChange('demo', '22'); //切换到:用户管理 } }; $('.site-demo-active').on('click', function(){ var othis = $(this), type = othis.data('type'); active[type] ? active[type].call(this, othis) : ''; }); //Hash地址的定位 var layid = location.hash.replace(/^#test=/, ''); element.tabChange('test', layid); element.on('tab(test)', function(elem){ location.hash = 'test='+ $(this).attr('lay-id'); }); }); }, /** * 清除分组下消息 */ delGroup:function(type,sontype,smsId){ tool.ajax({ url: ajaxurl.sms.delGroup, type: 'get', data:{ employee_id:vm.userinfo.id, type:type, sontype:sontype, sms_id:smsId, }, success: function (result) { if (result.code == 1) { layers.toast('消息已清理'); } else { layers.toast(result.message); } } }); }, /** * 删除消息询问框 */ delNews: function (type,sontype,smsId) { layers.confirm({ title: '提示', content: delNews, btn2: function(index, layero){ // btn 1 确定回调 main.delGroup(type,sontype,smsId); main.getNewsData(type,sontype); } }); }, /** * 清理消息询问框 */ clearNews: function (type,sontype) { layers.confirm({ title: '提示', content: clearNews, btn2: function(index, layero){ // btn 1 确定回调 main.delGroup(type,sontype); main.getNewsData(type,sontype); } }); }, /** 屏蔽系统消息 */ shieldNews: function () { layers.confirm({ title: '提示', content: shieldNews, btn2: function (index, layero) { // 确认的回调 } }); }, /** 大分组样式 */ clickTypeCss:function(id){ $('li[data-type="'+id+'"]').siblings().removeClass('active'); $('li[data-type="'+id+'"]').addClass('active'); // $(event.currentTarget).addClass('active'); }, /** 小分组样式 */ clickSontypeCss:function(id){ $('li[data-type="'+id+'"]').siblings().removeClass('sm-active'); $('li[data-type="'+id+'"]').addClass('sm-active'); }, /** 页面url获取到的收据加载 */ GainUrlData:function(){ // 获取路由参数id的值 var urls = tool.getUrlArgs(); if(urls.has){ vm.TypeId = urls.data.type; vm.SonTypeId = urls.data.sontype; // main.DelNoread(vm.TypeId,vm.SonTypeId); main.getNavData(vm.TypeId,vm.SonTypeId); main.getNewsData(vm.TypeId,vm.SonTypeId,function(){ main.clickTypeCss(vm.TypeId); main.clickSontypeCss(vm.SonTypeId); }) }else{ main.DelNoread(1,'',function(){ main.getNavData(); }) } }, /** 分页 */ followPage: function () { layui.use(['laypage'], function () { var laypage = layui.laypage; laypage.render({ elem: 'follow-page', count: vm.count //数据总数, ,limit: vm.newsInfo.pagesize //每页显示条数, ,curr: vm.newsInfo.curpage //当前页数 , ,jump: function (obj, first) { if (!first) { vm.newsInfo.curpage = obj.curr; main.getNewsData(vm.TypeId,vm.SonTypeId); } } }); }); }, }; /** * 实例化 ViewModel */ var vm = new Vue({ el: '#app', data: { list:'',// 侧栏树形菜单 navData:'',// 侧栏树形菜单 newsData:'', noMassage: '', TypeData:'', TypeId:'',//大分类ID SonTypeId:'',//小分类ID newsInfo:{pagesize:10,curpage:1},//初始化分页信息 urlType:'', urlsonType:'', count:'', allnewsNum:'', userinfo:'', title:'',//header 标题 }, methods: { clearNews: function () { main.clearNews(that); }, shieldNews: function () { main.shieldNews(that); }, /** * 点击事件 */ getType:function(id,tit){ vm.newsInfo.pagesize = 10; vm.newsInfo.curpage = 1; $('.site-page a').eq(0).siblings().removeClass('active') $('.site-page a').eq(0).addClass('active') main.clickSontypeCss(00); vm.TypeId = id; vm.SonTypeId =''; vm.title = tit; // main.getTypeData(id); main.DelNoread(id,'',function(){ main.getNavData(id); }); }, getSontype:function(id){ vm.newsInfo.pagesize = 10; vm.newsInfo.curpage = 1; $('.site-page a').eq(0).siblings().removeClass('active') $('.site-page a').eq(0).addClass('active') vm.SonTypeId = id; main.DelNoread(vm.TypeId,id,function(){ main.getNavData(vm.TypeId,id); }); // main.getNewsData(vm.TypeId,id); }, delOneNews:function(smsId){ main.delNews(vm.TypeId,vm.SonTypeId,smsId); }, clearallNews:function(){ if(vm.SonTypeId != ''){ main.delNews(vm.TypeId,vm.SonTypeId); }else{ main.delNews(vm.TypeId); } }, /** * 设置每页展示条数 */ onpageSize: function (event,i) { //设置每页展示条数 this.newsInfo.pagesize = i; this.newsInfo.curpage = 1; $(event.target).siblings().removeClass('active'); $(event.target).addClass('active'); main.getNewsData(vm.TypeId,vm.SonTypeId); }, } }); /** * 初始化 * @private */ var _init = function () { common.getTabLink(); main.GainUrlData(); main.admin(); }; _init(); });
import $ from 'jquery'; import ChromeExtensionMessageService from '../../../reuse/messageServiceDefinition'; /** * * @param {*} $scope * @param {*} $document * @param {*} $location * @param {ChromeExtensionMessageService} messageService * @param {*} analyticsService */ function MenuController($scope, $document, $location, messageService, analyticsService) { $scope.importOpml = function() { $('#opmlUploader').trigger('click'); }; $scope.togglePlaylistVisibility = togglePlaylistVisibility; $scope.exportOpml = exportOpml; // ng-change is not supported for input type='file' $document[0].getElementById('opmlUploader').addEventListener('change', fileNameChanged); function fileNameChanged(event) { var file = event.currentTarget.files[0]; // clear so that selecting the same file twice will call it again. // not really necessary in real world use cases. $document[0].getElementById('opmlUploader').value = ''; var reader = new FileReader; reader.onload = function(e) { var jqParsed = $(e.currentTarget.result); var podcasts = []; var rssFeeds = jqParsed.find('outline[type="rss"]'); rssFeeds.each(function(index, value) { var feedURL = $(value).attr('xmlUrl'); if(feedURL) { podcasts.push(feedURL); } }); if(podcasts.length) { $location.path('/Podcasts'); analyticsService.trackEvent('feed', 'add_by_opml_file', undefined, podcasts.length); messageService.for('podcastManager').sendMessage('addPodcasts', { podcasts: podcasts}); } }; reader.readAsText(file); } function togglePlaylistVisibility() { messageService.for('playlist').sendMessage('toggleVisibility'); } function exportOpml() { messageService.for('podcastManager').sendMessage('getOpml', null, response => { download(response); }); } function download(text) { var element = $document[0].createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); element.setAttribute('download', 'podStation.opml'); element.style.display = 'none'; $document[0].body.appendChild(element); element.click(); $document[0].body.removeChild(element); } } export default MenuController;
import * as actions from '../UserActions'; it('should setup loggingIn', () => { const action = actions.loggingIn(); const expected = { type: 'LOGGING_IN' }; expect(action).toEqual(expected); }); it('should setup loggedInSuccess', () => { const user = 'janesmith'; const action = actions.loggedInSuccess(user); const expected = { type: 'LOGGED_IN_SUCCESS', payload: user }; expect(action).toEqual(expected); }); it('should setup loggedInError', () => { const err = 'something went wrong'; const action = actions.loggedInError(err); const expected = { type: 'LOGGED_IN_ERROR', error: err }; expect(action).toEqual(expected); }); it('should setup logoutSuccess', () => { const action = actions.logoutSuccess(); const expected = { type: 'LOGGED_OUT_SUCCESS' }; expect(action).toEqual(expected); });
var page; var healthStore; var weightType; function pageLoaded(args) { page = args.object; weightType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass); healthStore = HKHealthStore.new(); requestPermissions(healthStore, [weightType], [weightType]); } exports.pageLoaded = pageLoaded; function getWeightButtonTap(args) { hideKeyboard(); getHealthKitValue(healthStore, weightType, function (weight) { alert("Your weight is " + weight.doubleValueForUnit(HKUnit.poundUnit()) + " pounds"); }); } exports.getWeightButtonTap = getWeightButtonTap; function setWeightButtonTap(args) { hideKeyboard(); var textField = page.getViewById("weightTextView"); var weight = parseFloat(textField.text); setHalthKitValue(healthStore, weightType, HKQuantity.quantityWithUnitDoubleValue(HKUnit.poundUnit(), weight)); } exports.setWeightButtonTap = setWeightButtonTap; function hideKeyboard() { var textField = page.getViewById("weightTextView"); textField.ios.resignFirstResponder(); } function requestPermissions(healthStore, writeTypes, readTypes) { var writeDataTypes = NSSet.setWithArray(writeTypes); var readDataTypes = NSSet.setWithArray(readTypes); healthStore.requestAuthorizationToShareTypesReadTypesCompletion(writeDataTypes, readDataTypes, function (success, error) { if (!success) { } }); } function getHealthKitValue(healthStore, quantityType, callback) { var endDateSortDescriptor = NSSortDescriptor.alloc().initWithKeyAscending(HKSampleSortIdentifierEndDate, false); var query = HKSampleQuery.alloc().initWithSampleTypePredicateLimitSortDescriptorsResultsHandler(quantityType, null, 1, [endDateSortDescriptor], function (query, results, error) { if (results) { var quantitySample = results.firstObject; if (quantitySample) { callback(quantitySample.quantity); } else { alert("Error!"); } } else { alert("Error!"); } }); healthStore.executeQuery(query); } function setHalthKitValue(healthStore, quantityType, quantity) { var now = NSDate.new(); var sample = HKQuantitySample.quantitySampleWithTypeQuantityStartDateEndDate(quantityType, quantity, now, now); healthStore.saveObjectWithCompletion(sample, function (success, error) { if (success) { alert("Done!"); } else { alert("Error!"); } }); }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @format */ 'use strict'; const visit = require('graphql').visit; import type { Argument, Condition, Directive, Fragment, FragmentSpread, InlineFragment, LinkedField, Literal, LocalArgumentDefinition, MatchField, MatchBranch, Request, Root, RootArgumentDefinition, ScalarField, SplitOperation, Variable, } from './GraphQLIR'; const NodeKeys = { Argument: ['value'], Condition: ['condition', 'selections'], Directive: ['args'], Fragment: ['argumentDefinitions', 'directives', 'selections'], FragmentSpread: ['args', 'directives'], InlineFragment: ['directives', 'selections'], LinkedField: ['args', 'directives', 'selections'], Literal: [], LocalArgumentDefinition: [], MatchField: ['args', 'directives', 'selections'], MatchBranch: ['selections'], Request: ['fragment', 'root'], Root: ['argumentDefinitions', 'directives', 'selections'], RootArgumentDefinition: [], ScalarField: ['args', 'directives'], SplitOperation: ['selections'], Variable: [], }; export type VisitNode = | Argument | Condition | Directive | Fragment | FragmentSpread | InlineFragment | LinkedField | Literal | LocalArgumentDefinition | MatchField | Request | Root | RootArgumentDefinition | ScalarField | SplitOperation | Variable; export type VisitFn<T: VisitNode> = ( node: T, // node we're visiting key?: any, // index/key to node from parent array/object parent?: ?(VisitNode | Array<VisitNode>), // Object immediately above node path?: Array<any>, // keys to get from root: [keyForChild, ..., keyForParent] ancestors?: Array<VisitNode | Array<VisitNode>>, // [root, child1, ..., grandparent] // Note: ancestors includes arrays which contain the visited node // These correspond to array indices in `path`. ) => any; export type NodeVisitorObject<T: VisitNode> = | {enter?: VisitFn<T>, leave?: VisitFn<T>} | VisitFn<T>; export type NodeVisitor = | NodeVisitorObject<VisitNode> | { Argument?: NodeVisitorObject<Argument>, Condition?: NodeVisitorObject<Condition>, Directive?: NodeVisitorObject<Directive>, Fragment?: NodeVisitorObject<Fragment>, FragmentSpread?: NodeVisitorObject<FragmentSpread>, InlineFragment?: NodeVisitorObject<InlineFragment>, LinkedField?: NodeVisitorObject<LinkedField>, MatchField?: NodeVisitorObject<MatchField>, MatchBranch?: NodeVisitorObject<MatchBranch>, Literal?: NodeVisitorObject<Literal>, LocalArgumentDefinition?: NodeVisitorObject<LocalArgumentDefinition>, Request?: NodeVisitorObject<Request>, Root?: NodeVisitorObject<Root>, RootArgumentDefinition?: NodeVisitorObject<RootArgumentDefinition>, ScalarField?: NodeVisitorObject<ScalarField>, Variable?: NodeVisitorObject<Variable>, }; function visitIR(root: VisitNode, visitor: NodeVisitor) { return (visit: $FlowFixMe)(root, visitor, NodeKeys); } module.exports = {visit: visitIR};
var ip = require('ip'); var azure = require('azure-storage'); var osenv = require('osenv'); var Guid = require('guid'); //console.log(process.env.AZURE_STORAGE_ACCOUNT); //console.log(process.env.AZURE_STORAGE_ACCESS_KEY); // Some things are not reliably in the env, and have a fallback command: var h = osenv.hostname(function (er, hostname) { h = hostname }); var localIpAddress = ip.address(); var tableSvc = azure.createTableService(); osenv.hostname(function (error, hostname) { if (!error) { var localIp = { PartitionKey: {'_':'localIp'}, RowKey: {'_': '' + Guid.create()}, ip: {'_': localIpAddress}, hostName: {'_': hostname} }; tableSvc.createTableIfNotExists('deviceip', function(error, result, response){ if(!error){ tableSvc.insertEntity('deviceip',localIp, function (error, result, response) { if(!error){ console.log('IP address: ' + JSON.stringify(localIp) + 'saved to Azure'); } else { console.log(error); } }); } else { console.log(error); } }); } else { console.log(error); } });
export const ic_format_paint_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M18 4V3c0-.55-.45-1-1-1H5c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V6h1v4H9v11c0 .55.45 1 1 1h2c.55 0 1-.45 1-1v-9h8V4h-3zm-2 2H6V4h10v2z"},"children":[]}]};
'use strict'; /** * @ngdoc function * @name gccdApp.controller:AboutCtrl * @description * # AboutCtrl * Controller of the itisforgirls */ angular.module('itisforgirls') .controller('AboutCtrl', function ($scope) { $scope.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ]; });
const Sequelize = require('sequelize'), connection = require('./sequelize.js'); const attributes = { id: { type: Sequelize.UUID, primaryKey: true, defaultValue: Sequelize.UUIDV4 }, username: { type: Sequelize.STRING, allowNull: false, unique: true, validate: { is: /^[a-z0-9\_\-]+$/i, len: [2,15] } }, email: { type: Sequelize.STRING, unique: true, validate: { isEmail: true } }, displayName: { type: Sequelize.STRING, allowNull: false, }, bio: { type: Sequelize.STRING }, location: { type: Sequelize.STRING }, avatar: { type: Sequelize.STRING }, password: { type: Sequelize.STRING }, title: { type: Sequelize.STRING }, salt: { type: Sequelize.STRING }, createdAt: { type: Sequelize.DATE, defaultValue: Sequelize.NOW } }; const options = { freezeTableName: true, toJSON: function () { var values = Object.assign({}, this.get()); // Killing unneded values for our http response. delete values.email; delete values.password; delete values.salt; delete values.createdAt; delete values.updatedAt; return values; } } const User = connection.define('users', attributes, options); module.exports = User;
var searchData= [ ['lib_2ehpp',['lib.hpp',['../lib_8hpp.html',1,'']]], ['lib_5f8hpp_2ejs',['lib_8hpp.js',['../lib__8hpp_8js.html',1,'']]] ];
// Generated by CoffeeScript 1.8.0 module.exports = (function(_this) { return function(stream, stdout, stderr) { var count, type; type = null; count = 0; return stream.on('readable', function() { var header, payload; while (true) { while (count > 0) { payload = stream.read(1); if (payload == null) { return; } count--; if (type === 2) { stderr.write(payload); } else { stdout.write(payload); } } header = stream.read(8); if (header == null) { return; } type = header.readUInt8(0); count = header.readUInt32BE(4); } }); }; })(this);
/** * Created by sam on 17/1/2. */ "use strict"; const mongoose = require('mongoose'); const SystemConfig = require('./config'); const { exceptionLogger: ExceptionLogger, dbMongoLogger : MongoLogger } = require('./logger'); const ProcessExitError = require('./error').ProcessExitError; const mongoConfig = SystemConfig.getSection('datasources/mongod'); exports.connect = function connect() { var port = mongoConfig.port; var connectArgs = [mongoConfig.host, mongoConfig.name || 'planer']; // port if (port) connectArgs.push(port); let user = mongoConfig.user; let pass = mongoConfig.pwd || mongoConfig.password; if (pass != null) { pass = pass.toString(); } if (user == null || pass == null) { MongoLogger.warn({ user: user, pass: pass }, 'try to connect mongo db without authentication, it is not safe enough and may cause commands execute failed! Make sure that this is expected behavior!') } // options connectArgs.push({ auth: true, user: user, pass: pass }); // callback connectArgs.push(function(err) { if (err) { let processExitError = new ProcessExitError({ cause: err }, 'process exit because of mongo connection failed'); ExceptionLogger.error(processExitError); process.exit(1); } }); // 配置有效性的校验交给mongoose 来完成 return mongoose.connect.apply(mongoose, connectArgs); };
~function () { /** * Create a new player. */ function Player(params) { params || (params = {}); for (var key in params) this[key] = params[key]; _createAnimation(this); _createMesh(this); _setThirdPersonCamera(this); this.score = 0; this.target = this.mesh.position.clone(); } Player.prototype.run = function () { this.anim.play("run"); } /** * Update the player at each frame. * @param delta The delta time between this frame and * the previous one. */ Player.prototype.update = function (delta) { this.anim.update(delta * 1000); if (THREE.Input.isKeyDown('leftArrow')) _moveLeft(this); if (THREE.Input.isKeyDown('rightArrow')) _moveRight(this); this.mesh.position.lerp(this.target, delta * 10); if (this.isInvinsible()) { this.invinsibleDelay -= delta; this.mesh.visible = ~~(this.invinsibleDelay * 10) % 2; } else this.mesh.visible = true; } /** * Check collision between the player and another entity. */ Player.prototype.hit = function (entity) { var d = entity.mesh.position.z + 35 - this.mesh.position.z; return d >= 0 && d <= 50 && entity.mesh.position.x === this.target.x; } /** * Return true if the player is in invisible mode. */ Player.prototype.isInvinsible = function () { return this.invinsibleDelay > 0; } /** * Increase player score. */ Player.prototype.increaseScore = function () { this.score++; } /** * Decrease player lifes. */ Player.prototype.decreaseLifes = function () { if (this.isInvinsible()) return ; this.lifes--; this.invinsibleDelay = 2; } /** * Translate the player to the left. */ var _moveLeft = function (self) { if (self.target.x === -50) return ; self.target.x -= 50; } /** * Translate the player to the right. */ var _moveRight = function (self) { if (self.target.x === 50) return ; self.target.x += 50; } /** * Create the player sprite animation. */ var _createAnimation = function (self) { var texture = new THREE.ImageUtils.loadTexture("resources/mario.png"); self.anim = new THREE.SpriteAnimation({ texture: texture, tilesHorizontal: 6, tilesVertical: 4, numberOfTiles: 24, delay: 42 }); self.anim.add("idle", {from: 22, to: 22}); self.anim.add("run", {from: 18, to: 23}); self.anim.play("idle"); } /** * Create the player mesh. */ var _createMesh = function (self) { var material = new THREE.MeshBasicMaterial({ map: self.anim.texture }); material.transparent = true; self.mesh = new THREE.Mesh( new THREE.PlaneGeometry(50, 50), material ); self.mesh.position.y += 25; self.mesh.position.z += 25; self.scene.add(self.mesh); } /** * Attach a third person camera to the player. */ var _setThirdPersonCamera = function (self) { self.controls = new THREE.ThirdPersonControls({ camera: self.camera, target: self.mesh, lerp: 0.05, offset: new THREE.Vector3(0, 90, 200), moveSpeed: 0, // on block les mouvements contraints: new THREE.Vector2(1, 1) // et les rotations }); self.camera.position.set(5000, 4000, 5000); } window.Player = Player; }();
"use strict"; /* exported deleteGroupOnClick */ function deleteGroupOnClick(event) { var name = ""; for(var i = 0; i < GROUPS.length; i++) { if(GROUPS[i].id === getAttribute(event, "id")) { name = GROUPS[i].name break; } } var aq = new ActionQueue([new Action(CONFIG.apiuri + "/group/" + encodeURIComponent(getAttribute(event, "id")), "DELETE")]); dialog("Opravdu si přejete smazat skupinu \"" + name + "\"?", "Ano", aq.closeDispatch, "Ne", function(){history.back();}); history.pushState({"sidePanel": "open"}, "title", "/admin/groups"); refreshLogin(); }
jQuery(document).ready( function (){ $('#ingresar').click( function () { var $usuario = $('input[name=usuario]'); var $pass = $('input[name=pass]'); //alert($usuario.val() + "-" + $pass.val()); //----// if ($usuario.val()=='') { $('#usuario').attr('required', true); document.getElementById("usuario").style.border="2px solid red"; document.getElementById("usuario").focus(); return false; } else { $('#usuario').attr('required', false); document.getElementById("usuario").style.border="2px solid green"; } //----// if ($pass.val()=='') { $("#pass").attr('undefined', true); document.getElementById("pass").style.border="2px solid red"; document.getElementById("pass").focus(); return false; } else { $("#pass").attr('required', false); document.getElementById("pass").style.border="2px solid green"; } //----// var data = "usuario=" + $usuario.val() + "&pass=" + $pass.val(); $.ajax( { type: "POST", url: "validar.php", data: data, dataType: "html", cache: false, success: function (data) { $('#tip').fadeIn(1000); $('#tip').fadeOut(4000); $('#tip').html(data); } } ); return false; } ); } );
describe('Bikini.BikiniStore', function() { var TEST = { data : { firstName: 'Max', sureName: 'Mustermann', age: 33 } }; it('creating bikini store', function() { assert.isString(serverUrl, 'Server url is defined.'); assert.isFunction(Bikini.BikiniStore, 'Bikini.BikiniStore is defined'); TEST.store = Bikini.BikiniStore.design({ useLocalStore: true, useSocketNotify: false }); assert.isObject(TEST.store, 'store successfully created.'); }); it('creating collection', function() { assert.isFunction(Bikini.Collection, 'Bikini.Collection is defined'); TEST.TestModel = Bikini.Model.extend({ idAttribute: '_id', entity: { name: 'test', fields: { _id: { type: Bikini.DATA.TYPE.STRING, required: YES, index: YES }, sureName: { name: 'USERNAME', type: Bikini.DATA.TYPE.STRING, required: YES, index: YES }, firstName: { type: Bikini.DATA.TYPE.STRING, length: 200 }, age: { type: Bikini.DATA.TYPE.INTEGER } } } }); assert.isFunction(TEST.TestModel, 'TestModel model successfully extended.'); TEST.url = serverUrl+'/bikini/test/'; TEST.TestsModelCollection = Bikini.Collection.extend({ model: TEST.TestModel, url: TEST.url, store: TEST.store, options: { sort: { sureName: 1 }, fields: { USERNAME: 1, sureName: 1, firstName: 1, age : 1 }, query: { age : { $gte : 25 } } } }); assert.isFunction(TEST.TestsModelCollection, 'Test collection successfully extended.'); TEST.Tests = TEST.TestsModelCollection.create(); assert.isObject(TEST.Tests, 'Test collection successfully created.'); assert.equal(TEST.Tests.store, TEST.store, 'Test collection has the correct store.'); var url = TEST.Tests.getUrl(); assert.ok(url !== TEST.url, 'The base url has been extended.'); assert.equal(url.indexOf(TEST.url), 0, 'the new url starts with the set url.'); assert.ok(url.indexOf('query=')>0, 'query is part of the url.'); assert.ok(url.indexOf('fields=')>0, 'fields is part of the url.'); assert.ok(url.indexOf('sort=')>0, 'sort is part of the url.'); // try to clean everything TEST.store.clear(TEST.Tests); }); it('create record', function(done) { TEST.Tests.create(TEST.data, { success: function(model) { assert.isObject(model, 'new record created successfully.'); TEST.id = model.id; assert.ok(TEST.id, 'new record has an id.'); done(); }, error: function() { assert.ok(false, 'new record created successfully.'); done(); } } ); }); it('read record', function() { var model = TEST.Tests.get(TEST.id); assert.ok(model, "record found"); assert.equal(model.get('firstName'), TEST.data.firstName, "found record has the correct 'firstname' value"); assert.equal(model.get('sureName'), TEST.data.sureName, "found record has the correct 'sureName' value"); assert.equal(model.get('age'), TEST.data.age, "found record has the correct 'age' value"); }); it('fetching data with new model', function(done) { TEST.TestModel2 = Bikini.Model.extend({ url : TEST.url, idAttribute: '_id', store: TEST.store, entity: { name: 'test' } }); var data = { _id: TEST.id }; var model = TEST.TestModel2.create(data); assert.isObject(model, "new model created"); assert.ok(_.isEqual(model.attributes, data), "new model holds correct data attributes"); model.fetch({ success: function() { assert.ok(true, 'model has been fetched.'); assert.equal(model.get('firstName'), TEST.data.firstName, "found record has the correct 'firstname' value"); assert.equal(model.get('USERNAME'), TEST.data.sureName, "found record has the correct 'USERNAME' value"); assert.equal(model.get('age'), TEST.data.age, "found record has the correct 'age' value"); done(); }, error: function(error) { assert.ok(false, 'model has been fetched.'); done(); } }) }); it('fetching collection', function(done) { TEST.Tests.reset(); assert.equal(TEST.Tests.length, 0, 'reset has cleared the collection.'); TEST.Tests.fetch({ success: function(collection) { assert.isObject(TEST.Tests.get(TEST.id), 'The model is still there'); done(); }, error: function() { assert.ok(false, 'Test collection fetched successfully.'); done(); } }); }); it('read record', function() { var model = TEST.Tests.get(TEST.id); assert.ok(model, "record found"); assert.equal(model.get('firstName'), TEST.data.firstName, "found record has the correct 'firstname' value"); assert.equal(model.get('sureName'), TEST.data.sureName, "found record has the correct 'sureName' value"); assert.equal(model.get('age'), TEST.data.age, "found record has the correct 'age' value"); }); it('delete record', function(done) { var model = TEST.Tests.get(TEST.id); assert.isObject(model, 'model found in collection'); assert.equal(model.id, TEST.id, 'model has the correct id'); model.destroy( { success: function(model) { assert.ok(true, 'record has been deleted.'); done(); }, error: function() { assert.ok(false, 'record has been deleted.'); done(); } }); }); it('cleanup records bikini', function(done) { if (TEST.Tests.length === 0) { done(); } else { var model, hasError = false, isDone = false; while ((model = TEST.Tests.first()) && !hasError) { model.destroy({ success: function() { if (TEST.Tests.length == 0 && !isDone) { isDone = true; assert.equal(TEST.Tests.length, 0, 'collection is empty'); done(); } }, error: function() { hasError = isDone = true; assert.ok(false, 'cleanup records bikini error'); done(); } }); } } }); });
(function () { 'use strict'; var url = $('.cart-item-selector').data('variant-action'), stockMessage = $("#stockMessage"), totalPrice = $('#totalPrice'), selectedSKUID = $('#selectedVariantID'); $('.js-variant-selector').change(function () { var id = $(this).val(); updateVariantSelection(id); }); function updateVariantSelection(variantId) { $.post(url, { variantID: variantId }, function (data) { stockMessage.text(data.stockMessage); totalPrice.text(data.totalPrice); selectedSKUID.val(variantId); }); } }());
var inherits = require('inherits') var Stream = require('stream') function Leveler(fn) { Stream.call(this) this.readable = this.writable = true this.points = 0 this.reached = Object.create(null) this.level = 0 this.fn = fn || function(x) { return Math.floor(Math.floor(25 + Math.sqrt(625 + 100 * x)) / 50) } this.on('levelup', this.levelup.bind(this)) } inherits(Leveler, Stream) module.exports = function(opts) { return new Leveler(opts) }; module.exports.Leveler = Leveler Leveler.prototype.write = function(points) { this.points += parseFloat(points) var level = this.fn(this.points) if (level !== false) this.levelup(level) } Leveler.prototype.end = function(points) { this.write(points || 0) } Leveler.prototype.levelup = function(level) { if (this.reached[level]) return false this.reached[level] = this.points this.level = level this.emit('data', level) }
/*! * jQuery JavaScript Library v1.10.2 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03T13:48Z */ (function(window, undefined) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<10 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.10.2", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function(selector, context) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init(selector, context, rootjQuery); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function(all, letter) { return letter.toUpperCase(); }, // The ready event handler completed = function(event) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if (document.addEventListener || event.type === "load" || document.readyState === "complete") { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if (document.addEventListener) { document.removeEventListener("DOMContentLoaded", completed, false); window.removeEventListener("load", completed, false); } else { document.detachEvent("onreadystatechange", completed); window.detachEvent("onload", completed); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function(selector, context, rootjQuery) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if (!selector) { return this; } // Handle HTML strings if (typeof selector === "string") { if (selector.charAt(0) === "<" && selector.charAt(selector.length - 1) === ">" && selector.length >= 3) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [null, selector, null]; } else { match = rquickExpr.exec(selector); } // Match html or make sure no context is specified for #id if (match && (match[1] || !context)) { // HANDLE: $(html) -> $(array) if (match[1]) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge(this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true)); // HANDLE: $(html, props) if (rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) { for (match in context) { // Properties of context are called as methods if possible if (jQuery.isFunction(this[match])) { this[match](context[match]); // ...and otherwise set as attributes } else { this.attr(match, context[match]); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById(match[2]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if (elem && elem.parentNode) { // Handle the case where IE and Opera return items // by name instead of ID if (elem.id !== match[2]) { return rootjQuery.find(selector); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if (!context || context.jquery) { return (context || rootjQuery).find(selector); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor(context).find(selector); } // HANDLE: $(DOMElement) } else if (selector.nodeType) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if (jQuery.isFunction(selector)) { return rootjQuery.ready(selector); } if (selector.selector !== undefined) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray(selector, this); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call(this); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function(num) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object (num < 0 ? this[this.length + num] : this[num]); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function(elems) { // Build a new jQuery matched element set var ret = jQuery.merge(this.constructor(), elems); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function(callback, args) { return jQuery.each(this, callback, args); }, ready: function(fn) { // Add the callback jQuery.ready.promise().done(fn); return this; }, slice: function() { return this.pushStack(core_slice.apply(this, arguments)); }, first: function() { return this.eq(0); }, last: function() { return this.eq(-1); }, eq: function(i) { var len = this.length, j = +i + (i < 0 ? len : 0); return this.pushStack(j >= 0 && j < len ? [this[j]] : []); }, map: function(callback) { return this.pushStack(jQuery.map(this, function(elem, i) { return callback.call(elem, i, elem); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if (typeof target === "boolean") { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if (typeof target !== "object" && !jQuery.isFunction(target)) { target = {}; } // extend jQuery itself if only one argument is passed if (length === i) { target = this; --i; } for (; i < length; i++) { // Only deal with non-null/undefined values if ((options = arguments[i]) != null) { // Extend the base object for (name in options) { src = target[name]; copy = options[name]; // Prevent never-ending loop if (target === copy) { continue; } // Recurse if we're merging plain objects or arrays if (deep && copy && (jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[name] = jQuery.extend(deep, clone, copy); // Don't bring in undefined values } else if (copy !== undefined) { target[name] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + (core_version + Math.random()).replace(/\D/g, ""), noConflict: function(deep) { if (window.$ === jQuery) { window.$ = _$; } if (deep && window.jQuery === jQuery) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function(hold) { if (hold) { jQuery.readyWait++; } else { jQuery.ready(true); } }, // Handle when the DOM is ready ready: function(wait) { // Abort if there are pending holds or we're already ready if (wait === true ? --jQuery.readyWait : jQuery.isReady) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if (!document.body) { return setTimeout(jQuery.ready); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if (wait !== true && --jQuery.readyWait > 0) { return; } // If there are functions bound, to execute readyList.resolveWith(document, [jQuery]); // Trigger any bound ready events if (jQuery.fn.trigger) { jQuery(document).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function(obj) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function(obj) { return jQuery.type(obj) === "array"; }, isWindow: function(obj) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function(obj) { return !isNaN(parseFloat(obj)) && isFinite(obj); }, type: function(obj) { if (obj == null) { return String(obj); } return typeof obj === "object" || typeof obj === "function" ? class2type[core_toString.call(obj)] || "object" : typeof obj; }, isPlainObject: function(obj) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if (!obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow(obj)) { return false; } try { // Not own constructor property must be Object if (obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) { return false; } } catch (e) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if (jQuery.support.ownLast) { for (key in obj) { return core_hasOwn.call(obj, key); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for (key in obj) {} return key === undefined || core_hasOwn.call(obj, key); }, isEmptyObject: function(obj) { var name; for (name in obj) { return false; } return true; }, error: function(msg) { throw new Error(msg); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function(data, context, keepScripts) { if (!data || typeof data !== "string") { return null; } if (typeof context === "boolean") { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec(data), scripts = !keepScripts && []; // Single tag if (parsed) { return [context.createElement(parsed[1])]; } parsed = jQuery.buildFragment([data], context, scripts); if (scripts) { jQuery(scripts).remove(); } return jQuery.merge([], parsed.childNodes); }, parseJSON: function(data) { // Attempt to parse using the native JSON parser first if (window.JSON && window.JSON.parse) { return window.JSON.parse(data); } if (data === null) { return data; } if (typeof data === "string") { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim(data); if (data) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if (rvalidchars.test(data.replace(rvalidescape, "@") .replace(rvalidtokens, "]") .replace(rvalidbraces, ""))) { return (new Function("return " + data))(); } } } jQuery.error("Invalid JSON: " + data); }, // Cross-browser xml parsing parseXML: function(data) { var xml, tmp; if (!data || typeof data !== "string") { return null; } try { if (window.DOMParser) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString(data, "text/xml"); } else { // IE xml = new ActiveXObject("Microsoft.XMLDOM"); xml.async = "false"; xml.loadXML(data); } } catch (e) { xml = undefined; } if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) { jQuery.error("Invalid XML: " + data); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function(data) { if (data && jQuery.trim(data)) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox (window.execScript || function(data) { window["eval"].call(window, data); })(data); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function(string) { return string.replace(rmsPrefix, "ms-").replace(rdashAlpha, fcamelCase); }, nodeName: function(elem, name) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function(obj, callback, args) { var value, i = 0, length = obj.length, isArray = isArraylike(obj); if (args) { if (isArray) { for (; i < length; i++) { value = callback.apply(obj[i], args); if (value === false) { break; } } } else { for (i in obj) { value = callback.apply(obj[i], args); if (value === false) { break; } } } // A special, fast, case for the most common use of each } else { if (isArray) { for (; i < length; i++) { value = callback.call(obj[i], i, obj[i]); if (value === false) { break; } } } else { for (i in obj) { value = callback.call(obj[i], i, obj[i]); if (value === false) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function(text) { return text == null ? "" : core_trim.call(text); } : // Otherwise use our own trimming functionality function(text) { return text == null ? "" : (text + "").replace(rtrim, ""); }, // results is for internal usage only makeArray: function(arr, results) { var ret = results || []; if (arr != null) { if (isArraylike(Object(arr))) { jQuery.merge(ret, typeof arr === "string" ? [arr] : arr); } else { core_push.call(ret, arr); } } return ret; }, inArray: function(elem, arr, i) { var len; if (arr) { if (core_indexOf) { return core_indexOf.call(arr, elem, i); } len = arr.length; i = i ? i < 0 ? Math.max(0, len + i) : i : 0; for (; i < len; i++) { // Skip accessing in sparse arrays if (i in arr && arr[i] === elem) { return i; } } } return -1; }, merge: function(first, second) { var l = second.length, i = first.length, j = 0; if (typeof l === "number") { for (; j < l; j++) { first[i++] = second[j]; } } else { while (second[j] !== undefined) { first[i++] = second[j++]; } } first.length = i; return first; }, grep: function(elems, callback, inv) { var retVal, ret = [], i = 0, length = elems.length; inv = !! inv; // Go through the array, only saving the items // that pass the validator function for (; i < length; i++) { retVal = !! callback(elems[i], i); if (inv !== retVal) { ret.push(elems[i]); } } return ret; }, // arg is for internal usage only map: function(elems, callback, arg) { var value, i = 0, length = elems.length, isArray = isArraylike(elems), ret = []; // Go through the array, translating each of the items to their if (isArray) { for (; i < length; i++) { value = callback(elems[i], i, arg); if (value != null) { ret[ret.length] = value; } } // Go through every key on the object, } else { for (i in elems) { value = callback(elems[i], i, arg); if (value != null) { ret[ret.length] = value; } } } // Flatten any nested arrays return core_concat.apply([], ret); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function(fn, context) { var args, proxy, tmp; if (typeof context === "string") { tmp = fn[context]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if (!jQuery.isFunction(fn)) { return undefined; } // Simulated bind args = core_slice.call(arguments, 2); proxy = function() { return fn.apply(context || this, args.concat(core_slice.call(arguments))); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function(elems, fn, key, value, chainable, emptyGet, raw) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if (jQuery.type(key) === "object") { chainable = true; for (i in key) { jQuery.access(elems, fn, i, key[i], true, emptyGet, raw); } // Sets one value } else if (value !== undefined) { chainable = true; if (!jQuery.isFunction(value)) { raw = true; } if (bulk) { // Bulk operations run against the entire set if (raw) { fn.call(elems, value); fn = null; // ...except when executing function values } else { bulk = fn; fn = function(elem, key, value) { return bulk.call(jQuery(elem), value); }; } } if (fn) { for (; i < length; i++) { fn(elems[i], key, raw ? value : value.call(elems[i], i, fn(elems[i], key))); } } } return chainable ? elems : // Gets bulk ? fn.call(elems) : length ? fn(elems[0], key) : emptyGet; }, now: function() { return (new Date()).getTime(); }, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function(elem, options, callback, args) { var ret, name, old = {}; // Remember the old values, and insert the new ones for (name in options) { old[name] = elem.style[name]; elem.style[name] = options[name]; } ret = callback.apply(elem, args || []); // Revert the old values for (name in options) { elem.style[name] = old[name]; } return ret; } }); jQuery.ready.promise = function(obj) { if (!readyList) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if (document.readyState === "complete") { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout(jQuery.ready); // Standards-based browsers support DOMContentLoaded } else if (document.addEventListener) { // Use the handy event callback document.addEventListener("DOMContentLoaded", completed, false); // A fallback to window.onload, that will always work window.addEventListener("load", completed, false); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent("onreadystatechange", completed); // A fallback to window.onload, that will always work window.attachEvent("onload", completed); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch (e) {} if (top && top.doScroll) { (function doScrollCheck() { if (!jQuery.isReady) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch (e) { return setTimeout(doScrollCheck, 50); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise(obj); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type["[object " + name + "]"] = name.toLowerCase(); }); function isArraylike(obj) { var length = obj.length, type = jQuery.type(obj); if (jQuery.isWindow(obj)) { return false; } if (obj.nodeType === 1 && length) { return true; } return type === "array" || type !== "function" && (length === 0 || typeof length === "number" && length > 0 && (length - 1) in obj); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.10.2 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03 */ (function(window, undefined) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function(a, b) { if (a === b) { hasDuplicate = true; return 0; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function(elem) { var i = 0, len = this.length; for (; i < len; i++) { if (this[i] === elem) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace("w", "w#"), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace(3, 8) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g"), rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"), rcombinators = new RegExp("^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*"), rsibling = new RegExp(whitespace + "*[+~]"), rattributeQuotes = new RegExp("=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g"), rpseudo = new RegExp(pseudos), ridentifier = new RegExp("^" + identifier + "$"), matchExpr = { "ID": new RegExp("^#(" + characterEncoding + ")"), "CLASS": new RegExp("^\\.(" + characterEncoding + ")"), "TAG": new RegExp("^(" + characterEncoding.replace("w", "w*") + ")"), "ATTR": new RegExp("^" + attributes), "PSEUDO": new RegExp("^" + pseudos), "CHILD": new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i"), "bool": new RegExp("^(?:" + booleans + ")$", "i"), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp("^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i") }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp("\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig"), funescape = function(_, escaped, escapedWhitespace) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode(high + 0x10000) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode(high >> 10 | 0xD800, high & 0x3FF | 0xDC00); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call(preferredDoc.childNodes)), preferredDoc.childNodes); // Support: Android<4.0 // Detect silently failing push.apply arr[preferredDoc.childNodes.length].nodeType; } catch (e) { push = { apply: arr.length ? // Leverage slice if possible function(target, els) { push_native.apply(target, slice.call(els)); } : // Support: IE<9 // Otherwise append directly function(target, els) { var j = target.length, i = 0; // Can't trust NodeList.length while ((target[j++] = els[i++])) {} target.length = j - 1; } }; } function Sizzle(selector, context, results, seed) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ((context ? context.ownerDocument || context : preferredDoc) !== document) { setDocument(context); } context = context || document; results = results || []; if (!selector || typeof selector !== "string") { return results; } if ((nodeType = context.nodeType) !== 1 && nodeType !== 9) { return []; } if (documentIsHTML && !seed) { // Shortcuts if ((match = rquickExpr.exec(selector))) { // Speed-up: Sizzle("#ID") if ((m = match[1])) { if (nodeType === 9) { elem = context.getElementById(m); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if (elem && elem.parentNode) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if (elem.id === m) { results.push(elem); return results; } } else { return results; } } else { // Context is not a document if (context.ownerDocument && (elem = context.ownerDocument.getElementById(m)) && contains(context, elem) && elem.id === m) { results.push(elem); return results; } } // Speed-up: Sizzle("TAG") } else if (match[2]) { push.apply(results, context.getElementsByTagName(selector)); return results; // Speed-up: Sizzle(".CLASS") } else if ((m = match[3]) && support.getElementsByClassName && context.getElementsByClassName) { push.apply(results, context.getElementsByClassName(m)); return results; } } // QSA path if (support.qsa && (!rbuggyQSA || !rbuggyQSA.test(selector))) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if (nodeType === 1 && context.nodeName.toLowerCase() !== "object") { groups = tokenize(selector); if ((old = context.getAttribute("id"))) { nid = old.replace(rescape, "\\$&"); } else { context.setAttribute("id", nid); } nid = "[id='" + nid + "'] "; i = groups.length; while (i--) { groups[i] = nid + toSelector(groups[i]); } newContext = rsibling.test(selector) && context.parentNode || context; newSelector = groups.join(","); } if (newSelector) { try { push.apply(results, newContext.querySelectorAll(newSelector)); return results; } catch (qsaError) {} finally { if (!old) { context.removeAttribute("id"); } } } } } // All others return select(selector.replace(rtrim, "$1"), context, results, seed); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache(key, value) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if (keys.push(key += " ") > Expr.cacheLength) { // Only keep the most recent entries delete cache[keys.shift()]; } return (cache[key] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction(fn) { fn[expando] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert(fn) { var div = document.createElement("div"); try { return !!fn(div); } catch (e) { return false; } finally { // Remove from its parent by default if (div.parentNode) { div.parentNode.removeChild(div); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle(attrs, handler) { var arr = attrs.split("|"), i = attrs.length; while (i--) { Expr.attrHandle[arr[i]] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck(a, b) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && (~b.sourceIndex || MAX_NEGATIVE) - (~a.sourceIndex || MAX_NEGATIVE); // Use IE sourceIndex if available on both nodes if (diff) { return diff; } // Check if b follows a if (cur) { while ((cur = cur.nextSibling)) { if (cur === b) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo(type) { return function(elem) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo(type) { return function(elem) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo(fn) { return markFunction(function(argument) { argument = +argument; return markFunction(function(seed, matches) { var j, matchIndexes = fn([], seed.length, argument), i = matchIndexes.length; // Match elements found at the specified indexes while (i--) { if (seed[(j = matchIndexes[i])]) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function(elem) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function(node) { var doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if (doc === document || doc.nodeType !== 9 || !doc.documentElement) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML(doc); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if (parent && parent.attachEvent && parent !== parent.top) { parent.attachEvent("onbeforeunload", function() { setDocument(); }); } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function(div) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function(div) { div.appendChild(doc.createComment("")); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function(div) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function(div) { docElem.appendChild(div).id = expando; return !doc.getElementsByName || !doc.getElementsByName(expando).length; }); // ID find and filter if (support.getById) { Expr.find["ID"] = function(id, context) { if (typeof context.getElementById !== strundefined && documentIsHTML) { var m = context.getElementById(id); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function(id) { var attrId = id.replace(runescape, funescape); return function(elem) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function(id) { var attrId = id.replace(runescape, funescape); return function(elem) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function(tag, context) { if (typeof context.getElementsByTagName !== strundefined) { return context.getElementsByTagName(tag); } } : function(tag, context) { var elem, tmp = [], i = 0, results = context.getElementsByTagName(tag); // Filter out possible comments if (tag === "*") { while ((elem = results[i++])) { if (elem.nodeType === 1) { tmp.push(elem); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function(className, context) { if (typeof context.getElementsByClassName !== strundefined && documentIsHTML) { return context.getElementsByClassName(className); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ((support.qsa = rnative.test(doc.querySelectorAll))) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function(div) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if (!div.querySelectorAll("[selected]").length) { rbuggyQSA.push("\\[" + whitespace + "*(?:value|" + booleans + ")"); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if (!div.querySelectorAll(":checked").length) { rbuggyQSA.push(":checked"); } }); assert(function(div) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute("type", "hidden"); div.appendChild(input).setAttribute("t", ""); if (div.querySelectorAll("[t^='']").length) { rbuggyQSA.push("[*^$]=" + whitespace + "*(?:''|\"\")"); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if (!div.querySelectorAll(":enabled").length) { rbuggyQSA.push(":enabled", ":disabled"); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ((support.matchesSelector = rnative.test((matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector)))) { assert(function(div) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call(div, "div"); // This should fail with an exception // Gecko does not error, returns false instead matches.call(div, "[s!='']:x"); rbuggyMatches.push("!=", pseudos); }); } rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join("|")); rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join("|")); /* Contains ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = rnative.test(docElem.contains) || docElem.compareDocumentPosition ? function(a, b) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !! (bup && bup.nodeType === 1 && ( adown.contains ? adown.contains(bup) : a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16)); } : function(a, b) { if (b) { while ((b = b.parentNode)) { if (b === a) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = docElem.compareDocumentPosition ? function(a, b) { // Flag for duplicate removal if (a === b) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition(b); if (compare) { // Disconnected nodes if (compare & 1 || (!support.sortDetached && b.compareDocumentPosition(a) === compare)) { // Choose the first element that is related to our preferred document if (a === doc || contains(preferredDoc, a)) { return -1; } if (b === doc || contains(preferredDoc, b)) { return 1; } // Maintain original order return sortInput ? (indexOf.call(sortInput, a) - indexOf.call(sortInput, b)) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function(a, b) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [a], bp = [b]; // Exit early if the nodes are identical if (a === b) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if (!aup || !bup) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? (indexOf.call(sortInput, a) - indexOf.call(sortInput, b)) : 0; // If the nodes are siblings, we can do a quick check } else if (aup === bup) { return siblingCheck(a, b); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ((cur = cur.parentNode)) { ap.unshift(cur); } cur = b; while ((cur = cur.parentNode)) { bp.unshift(cur); } // Walk down the tree looking for a discrepancy while (ap[i] === bp[i]) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck(ap[i], bp[i]) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function(expr, elements) { return Sizzle(expr, null, null, elements); }; Sizzle.matchesSelector = function(elem, expr) { // Set document vars if needed if ((elem.ownerDocument || elem) !== document) { setDocument(elem); } // Make sure that attribute selectors are quoted expr = expr.replace(rattributeQuotes, "='$1']"); if (support.matchesSelector && documentIsHTML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) { try { var ret = matches.call(elem, expr); // IE 9's matchesSelector returns false on disconnected nodes if (ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11) { return ret; } } catch (e) {} } return Sizzle(expr, document, null, [elem]).length > 0; }; Sizzle.contains = function(context, elem) { // Set document vars if needed if ((context.ownerDocument || context) !== document) { setDocument(context); } return contains(context, elem); }; Sizzle.attr = function(elem, name) { // Set document vars if needed if ((elem.ownerDocument || elem) !== document) { setDocument(elem); } var fn = Expr.attrHandle[name.toLowerCase()], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ? fn(elem, name, !documentIsHTML) : undefined; return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute(name) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function(msg) { throw new Error("Syntax error, unrecognized expression: " + msg); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function(results) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice(0); results.sort(sortOrder); if (hasDuplicate) { while ((elem = results[i++])) { if (elem === results[i]) { j = duplicates.push(i); } } while (j--) { results.splice(duplicates[j], 1); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function(elem) { var node, ret = "", i = 0, nodeType = elem.nodeType; if (!nodeType) { // If no nodeType, this is expected to be an array for (; (node = elem[i]); i++) { // Do not traverse comment nodes ret += getText(node); } } else if (nodeType === 1 || nodeType === 9 || nodeType === 11) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if (typeof elem.textContent === "string") { return elem.textContent; } else { // Traverse its children for (elem = elem.firstChild; elem; elem = elem.nextSibling) { ret += getText(elem); } } } else if (nodeType === 3 || nodeType === 4) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function(match) { match[1] = match[1].replace(runescape, funescape); // Move the given value to match[3] whether quoted or unquoted match[3] = (match[4] || match[5] || "").replace(runescape, funescape); if (match[2] === "~=") { match[3] = " " + match[3] + " "; } return match.slice(0, 4); }, "CHILD": function(match) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if (match[1].slice(0, 3) === "nth") { // nth-* requires argument if (!match[3]) { Sizzle.error(match[0]); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === "even" || match[3] === "odd")); match[5] = +((match[7] + match[8]) || match[3] === "odd"); // other types prohibit arguments } else if (match[3]) { Sizzle.error(match[0]); } return match; }, "PSEUDO": function(match) { var excess, unquoted = !match[5] && match[2]; if (matchExpr["CHILD"].test(match[0])) { return null; } // Accept quoted arguments as-is if (match[3] && match[4] !== undefined) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if (unquoted && rpseudo.test(unquoted) && // Get excess from tokenize (recursively) (excess = tokenize(unquoted, true)) && // advance to the next closing parenthesis (excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)) { // excess is a negative index match[0] = match[0].slice(0, excess); match[2] = unquoted.slice(0, excess); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice(0, 3); } }, filter: { "TAG": function(nodeNameSelector) { var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function(elem) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function(className) { var pattern = classCache[className + " "]; return pattern || (pattern = new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)")) && classCache(className, function(elem) { return pattern.test(typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || ""); }); }, "ATTR": function(name, operator, check) { return function(elem) { var result = Sizzle.attr(elem, name); if (result == null) { return operator === "!="; } if (!operator) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf(check) === 0 : operator === "*=" ? check && result.indexOf(check) > -1 : operator === "$=" ? check && result.slice(-check.length) === check : operator === "~=" ? (" " + result + " ").indexOf(check) > -1 : operator === "|=" ? result === check || result.slice(0, check.length + 1) === check + "-" : false; }; }, "CHILD": function(type, what, argument, first, last) { var simple = type.slice(0, 3) !== "nth", forward = type.slice(-4) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function(elem) { return !!elem.parentNode; } : function(elem, context, xml) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if (parent) { // :(first|last|only)-(child|of-type) if (simple) { while (dir) { node = elem; while ((node = node[dir])) { if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [forward ? parent.firstChild : parent.lastChild]; // non-xml :nth-child(...) stores cache data on `parent` if (forward && useCache) { // Seek `elem` from a previously-cached index outerCache = parent[expando] || (parent[expando] = {}); cache = outerCache[type] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[nodeIndex]; while ((node = ++nodeIndex && node && node[dir] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop())) { // When found, cache indexes on `parent` and break if (node.nodeType === 1 && ++diff && node === elem) { outerCache[type] = [dirruns, nodeIndex, diff]; break; } } // Use previously-cached element index if available } else if (useCache && (cache = (elem[expando] || (elem[expando] = {}))[type]) && cache[0] === dirruns) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ((node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop())) { if ((ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) && ++diff) { // Cache the index of each encountered element if (useCache) { (node[expando] || (node[expando] = {}))[type] = [dirruns, diff]; } if (node === elem) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || (diff % first === 0 && diff / first >= 0); } }; }, "PSEUDO": function(pseudo, argument) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error("unsupported pseudo: " + pseudo); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if (fn[expando]) { return fn(argument); } // But maintain support for old signatures if (fn.length > 1) { args = [pseudo, pseudo, "", argument]; return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function(seed, matches) { var idx, matched = fn(seed, argument), i = matched.length; while (i--) { idx = indexOf.call(seed, matched[i]); seed[idx] = !(matches[idx] = matched[i]); } }) : function(elem) { return fn(elem, 0, args); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function(selector) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile(selector.replace(rtrim, "$1")); return matcher[expando] ? markFunction(function(seed, matches, context, xml) { var elem, unmatched = matcher(seed, null, xml, []), i = seed.length; // Match elements unmatched by `matcher` while (i--) { if ((elem = unmatched[i])) { seed[i] = !(matches[i] = elem); } } }) : function(elem, context, xml) { input[0] = elem; matcher(input, null, xml, results); return !results.pop(); }; }), "has": markFunction(function(selector) { return function(elem) { return Sizzle(selector, elem).length > 0; }; }), "contains": markFunction(function(text) { return function(elem) { return (elem.textContent || elem.innerText || getText(elem)).indexOf(text) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction(function(lang) { // lang value must be a valid identifier if (!ridentifier.test(lang || "")) { Sizzle.error("unsupported lang: " + lang); } lang = lang.replace(runescape, funescape).toLowerCase(); return function(elem) { var elemLang; do { if ((elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang"))) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf(lang + "-") === 0; } } while ((elem = elem.parentNode) && elem.nodeType === 1); return false; }; }), // Miscellaneous "target": function(elem) { var hash = window.location && window.location.hash; return hash && hash.slice(1) === elem.id; }, "root": function(elem) { return elem === docElem; }, "focus": function(elem) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !! (elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function(elem) { return elem.disabled === false; }, "disabled": function(elem) { return elem.disabled === true; }, "checked": function(elem) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !! elem.checked) || (nodeName === "option" && !! elem.selected); }, "selected": function(elem) { // Accessing this property makes selected-by-default // options in Safari work properly if (elem.parentNode) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function(elem) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for (elem = elem.firstChild; elem; elem = elem.nextSibling) { if (elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4) { return false; } } return true; }, "parent": function(elem) { return !Expr.pseudos["empty"](elem); }, // Element/input types "header": function(elem) { return rheader.test(elem.nodeName); }, "input": function(elem) { return rinputs.test(elem.nodeName); }, "button": function(elem) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function(elem) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ((attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type); }, // Position-in-collection "first": createPositionalPseudo(function() { return [0]; }), "last": createPositionalPseudo(function(matchIndexes, length) { return [length - 1]; }), "eq": createPositionalPseudo(function(matchIndexes, length, argument) { return [argument < 0 ? argument + length : argument]; }), "even": createPositionalPseudo(function(matchIndexes, length) { var i = 0; for (; i < length; i += 2) { matchIndexes.push(i); } return matchIndexes; }), "odd": createPositionalPseudo(function(matchIndexes, length) { var i = 1; for (; i < length; i += 2) { matchIndexes.push(i); } return matchIndexes; }), "lt": createPositionalPseudo(function(matchIndexes, length, argument) { var i = argument < 0 ? argument + length : argument; for (; --i >= 0;) { matchIndexes.push(i); } return matchIndexes; }), "gt": createPositionalPseudo(function(matchIndexes, length, argument) { var i = argument < 0 ? argument + length : argument; for (; ++i < length;) { matchIndexes.push(i); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for (i in { radio: true, checkbox: true, file: true, password: true, image: true }) { Expr.pseudos[i] = createInputPseudo(i); } for (i in { submit: true, reset: true }) { Expr.pseudos[i] = createButtonPseudo(i); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize(selector, parseOnly) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[selector + " "]; if (cached) { return parseOnly ? 0 : cached.slice(0); } soFar = selector; groups = []; preFilters = Expr.preFilter; while (soFar) { // Comma and first run if (!matched || (match = rcomma.exec(soFar))) { if (match) { // Don't consume trailing commas as valid soFar = soFar.slice(match[0].length) || soFar; } groups.push(tokens = []); } matched = false; // Combinators if ((match = rcombinators.exec(soFar))) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace(rtrim, " ") }); soFar = soFar.slice(matched.length); } // Filters for (type in Expr.filter) { if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match)))) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice(matched.length); } } if (!matched) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : // Cache the tokens tokenCache(selector, groups).slice(0); } function toSelector(tokens) { var i = 0, len = tokens.length, selector = ""; for (; i < len; i++) { selector += tokens[i].value; } return selector; } function addCombinator(matcher, combinator, base) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function(elem, context, xml) { while ((elem = elem[dir])) { if (elem.nodeType === 1 || checkNonElements) { return matcher(elem, context, xml); } } } : // Check against all ancestor/preceding elements function(elem, context, xml) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if (xml) { while ((elem = elem[dir])) { if (elem.nodeType === 1 || checkNonElements) { if (matcher(elem, context, xml)) { return true; } } } } else { while ((elem = elem[dir])) { if (elem.nodeType === 1 || checkNonElements) { outerCache = elem[expando] || (elem[expando] = {}); if ((cache = outerCache[dir]) && cache[0] === dirkey) { if ((data = cache[1]) === true || data === cachedruns) { return data === true; } } else { cache = outerCache[dir] = [dirkey]; cache[1] = matcher(elem, context, xml) || cachedruns; if (cache[1] === true) { return true; } } } } } }; } function elementMatcher(matchers) { return matchers.length > 1 ? function(elem, context, xml) { var i = matchers.length; while (i--) { if (!matchers[i](elem, context, xml)) { return false; } } return true; } : matchers[0]; } function condense(unmatched, map, filter, context, xml) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for (; i < len; i++) { if ((elem = unmatched[i])) { if (!filter || filter(elem, context, xml)) { newUnmatched.push(elem); if (mapped) { map.push(i); } } } } return newUnmatched; } function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) { if (postFilter && !postFilter[expando]) { postFilter = setMatcher(postFilter); } if (postFinder && !postFinder[expando]) { postFinder = setMatcher(postFinder, postSelector); } return markFunction(function(seed, results, context, xml) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts(selector || "*", context.nodeType ? [context] : context, []), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || (seed ? preFilter : preexisting || postFilter) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if (matcher) { matcher(matcherIn, matcherOut, context, xml); } // Apply postFilter if (postFilter) { temp = condense(matcherOut, postMap); postFilter(temp, [], context, xml); // Un-match failing elements by moving them back to matcherIn i = temp.length; while (i--) { if ((elem = temp[i])) { matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem); } } } if (seed) { if (postFinder || preFilter) { if (postFinder) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while (i--) { if ((elem = matcherOut[i])) { // Restore matcherIn since elem is not yet a final match temp.push((matcherIn[i] = elem)); } } postFinder(null, (matcherOut = []), temp, xml); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while (i--) { if ((elem = matcherOut[i]) && (temp = postFinder ? indexOf.call(seed, elem) : preMap[i]) > -1) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut); if (postFinder) { postFinder(null, results, matcherOut, xml); } else { push.apply(results, matcherOut); } } }); } function matcherFromTokens(tokens) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[tokens[0].type], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator(function(elem) { return elem === checkContext; }, implicitRelative, true), matchAnyContext = addCombinator(function(elem) { return indexOf.call(checkContext, elem) > -1; }, implicitRelative, true), matchers = [function(elem, context, xml) { return (!leadingRelative && (xml || context !== outermostContext)) || ( (checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml)); }]; for (; i < len; i++) { if ((matcher = Expr.relative[tokens[i].type])) { matchers = [addCombinator(elementMatcher(matchers), matcher)]; } else { matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches); // Return special upon seeing a positional matcher if (matcher[expando]) { // Find the next relative operator (if any) for proper handling j = ++i; for (; j < len; j++) { if (Expr.relative[tokens[j].type]) { break; } } return setMatcher( i > 1 && elementMatcher(matchers), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice(0, i - 1).concat({ value: tokens[i - 2].type === " " ? "*" : "" })).replace(rtrim, "$1"), matcher, i < j && matcherFromTokens(tokens.slice(i, j)), j < len && matcherFromTokens((tokens = tokens.slice(j))), j < len && toSelector(tokens)); } matchers.push(matcher); } } return elementMatcher(matchers); } function matcherFromGroupMatchers(elementMatchers, setMatchers) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function(seed, context, xml, results, expandContext) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]("*", expandContext && context.parentNode || context), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if (outermost) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for (; (elem = elems[i]) != null; i++) { if (byElement && elem) { j = 0; while ((matcher = elementMatchers[j++])) { if (matcher(elem, context, xml)) { results.push(elem); break; } } if (outermost) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if (bySet) { // They will have gone through all possible matchers if ((elem = !matcher && elem)) { matchedCount--; } // Lengthen the array for every element, matched or not if (seed) { unmatched.push(elem); } } } // Apply set filters to unmatched elements matchedCount += i; if (bySet && i !== matchedCount) { j = 0; while ((matcher = setMatchers[j++])) { matcher(unmatched, setMatched, context, xml); } if (seed) { // Reintegrate element matches to eliminate the need for sorting if (matchedCount > 0) { while (i--) { if (!(unmatched[i] || setMatched[i])) { setMatched[i] = pop.call(results); } } } // Discard index placeholder values to get only actual matches setMatched = condense(setMatched); } // Add matches to results push.apply(results, setMatched); // Seedless set matches succeeding multiple successful matchers stipulate sorting if (outermost && !seed && setMatched.length > 0 && (matchedCount + setMatchers.length) > 1) { Sizzle.uniqueSort(results); } } // Override manipulation of globals by nested matchers if (outermost) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction(superMatcher) : superMatcher; } compile = Sizzle.compile = function(selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[selector + " "]; if (!cached) { // Generate a function of recursive functions that can be used to check each element if (!group) { group = tokenize(selector); } i = group.length; while (i--) { cached = matcherFromTokens(group[i]); if (cached[expando]) { setMatchers.push(cached); } else { elementMatchers.push(cached); } } // Cache the compiled function cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers)); } return cached; }; function multipleContexts(selector, contexts, results) { var i = 0, len = contexts.length; for (; i < len; i++) { Sizzle(selector, contexts[i], results); } return results; } function select(selector, context, results, seed) { var i, tokens, token, type, find, match = tokenize(selector); if (!seed) { // Try to minimize operations if there is only one group if (match.length === 1) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice(0); if (tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) { context = (Expr.find["ID"](token.matches[0].replace(runescape, funescape), context) || [])[0]; if (!context) { return results; } selector = selector.slice(tokens.shift().value.length); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test(selector) ? 0 : tokens.length; while (i--) { token = tokens[i]; // Abort if we hit a combinator if (Expr.relative[(type = token.type)]) { break; } if ((find = Expr.find[type])) { // Search, expanding context for leading sibling combinators if ((seed = find( token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && context.parentNode || context))) { // If seed is empty or no tokens remain, we can return early tokens.splice(i, 1); selector = seed.length && toSelector(tokens); if (!selector) { push.apply(results, seed); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile(selector, match)( seed, context, !documentIsHTML, results, rsibling.test(selector)); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort(sortOrder).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function(div1) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition(document.createElement("div")) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if (!assert(function(div) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#"; })) { addHandle("type|href|height|width", function(elem, name, isXML) { if (!isXML) { return elem.getAttribute(name, name.toLowerCase() === "type" ? 1 : 2); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if (!support.attributes || !assert(function(div) { div.innerHTML = "<input/>"; div.firstChild.setAttribute("value", ""); return div.firstChild.getAttribute("value") === ""; })) { addHandle("value", function(elem, name, isXML) { if (!isXML && elem.nodeName.toLowerCase() === "input") { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if (!assert(function(div) { return div.getAttribute("disabled") == null; })) { addHandle(booleans, function(elem, name, isXML) { var val; if (!isXML) { return (val = elem.getAttributeNode(name)) && val.specified ? val.value : elem[name] === true ? name.toLowerCase() : null; } }); } jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(window); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions(options) { var object = optionsCache[options] = {}; jQuery.each(options.match(core_rnotwhite) || [], function(_, flag) { object[flag] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function(options) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? (optionsCache[options] || createOptions(options)) : jQuery.extend({}, options); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function(data) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for (; list && firingIndex < firingLength; firingIndex++) { if (list[firingIndex].apply(data[0], data[1]) === false && options.stopOnFalse) { memory = false; // To prevent further calls using add break; } } firing = false; if (list) { if (stack) { if (stack.length) { fire(stack.shift()); } } else if (memory) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if (list) { // First, we save the current length var start = list.length; (function add(args) { jQuery.each(args, function(_, arg) { var type = jQuery.type(arg); if (type === "function") { if (!options.unique || !self.has(arg)) { list.push(arg); } } else if (arg && arg.length && type !== "string") { // Inspect recursively add(arg); } }); })(arguments); // Do we need to add the callbacks to the // current firing batch? if (firing) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if (memory) { firingStart = start; fire(memory); } } return this; }, // Remove a callback from the list remove: function() { if (list) { jQuery.each(arguments, function(_, arg) { var index; while ((index = jQuery.inArray(arg, list, index)) > -1) { list.splice(index, 1); // Handle firing indexes if (firing) { if (index <= firingLength) { firingLength--; } if (index <= firingIndex) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function(fn) { return fn ? jQuery.inArray(fn, list) > -1 : !! (list && list.length); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if (!memory) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function(context, args) { if (list && (!fired || stack)) { args = args || []; args = [context, args.slice ? args.slice() : args]; if (firing) { stack.push(args); } else { fire(args); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith(this, arguments); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function(func) { var tuples = [ // action, add listener, listener list, final state ["resolve", "done", jQuery.Callbacks("once memory"), "resolved"], ["reject", "fail", jQuery.Callbacks("once memory"), "rejected"], ["notify", "progress", jQuery.Callbacks("memory")] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done(arguments).fail(arguments); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function(newDefer) { jQuery.each(tuples, function(i, tuple) { var action = tuple[0], fn = jQuery.isFunction(fns[i]) && fns[i]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[tuple[1]](function() { var returned = fn && fn.apply(this, arguments); if (returned && jQuery.isFunction(returned.promise)) { returned.promise() .done(newDefer.resolve) .fail(newDefer.reject) .progress(newDefer.notify); } else { newDefer[action + "With"](this === promise ? newDefer.promise() : this, fn ? [returned] : arguments); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function(obj) { return obj != null ? jQuery.extend(obj, promise) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each(tuples, function(i, tuple) { var list = tuple[2], stateString = tuple[3]; // promise[ done | fail | progress ] = list.add promise[tuple[1]] = list.add; // Handle state if (stateString) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[i ^ 1][2].disable, tuples[2][2].lock); } // deferred[ resolve | reject | notify ] deferred[tuple[0]] = function() { deferred[tuple[0] + "With"](this === deferred ? promise : this, arguments); return this; }; deferred[tuple[0] + "With"] = list.fireWith; }); // Make the deferred a promise promise.promise(deferred); // Call given func if any if (func) { func.call(deferred, deferred); } // All done! return deferred; }, // Deferred helper when: function(subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call(arguments), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || (subordinate && jQuery.isFunction(subordinate.promise)) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function(i, contexts, values) { return function(value) { contexts[i] = this; values[i] = arguments.length > 1 ? core_slice.call(arguments) : value; if (values === progressValues) { deferred.notifyWith(contexts, values); } else if (!(--remaining)) { deferred.resolveWith(contexts, values); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if (length > 1) { progressValues = new Array(length); progressContexts = new Array(length); resolveContexts = new Array(length); for (; i < length; i++) { if (resolveValues[i] && jQuery.isFunction(resolveValues[i].promise)) { resolveValues[i].promise() .done(updateFunc(i, resolveContexts, resolveValues)) .fail(deferred.reject) .progress(updateFunc(i, progressContexts, progressValues)); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if (!remaining) { deferred.resolveWith(resolveContexts, resolveValues); } return deferred.promise(); } }); jQuery.support = (function(support) { var all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute("className", "t"); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Finish early in limited (non-browser) environments all = div.getElementsByTagName("*") || []; a = div.getElementsByTagName("a")[0]; if (!a || !a.style || !all.length) { return support; } // First batch of tests select = document.createElement("select"); opt = select.appendChild(document.createElement("option")); input = div.getElementsByTagName("input")[0]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName("tbody").length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !! div.getElementsByTagName("link").length; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test(a.getAttribute("style")); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.hrefNormalized = a.getAttribute("href") === "/a"; // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 support.opacity = /^0.5/.test(a.style.opacity); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !! a.style.cssFloat; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !! input.value; // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !! document.createElement("form").enctype; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement("nav").cloneNode(true).outerHTML !== "<:nav></:nav>"; // Will be defined later support.inlineBlockNeedsLayout = false; support.shrinkWrapBlocks = false; support.pixelPosition = false; support.deleteExpando = true; support.noCloneEvent = true; support.reliableMarginRight = true; support.boxSizingReliable = true; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode(true).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch (e) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute("value", ""); support.input = input.getAttribute("value") === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute("type", "radio"); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute("checked", "t"); input.setAttribute("name", "t"); fragment = document.createDocumentFragment(); fragment.appendChild(input); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if (div.attachEvent) { div.attachEvent("onclick", function() { support.noCloneEvent = false; }); div.cloneNode(true).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) for (i in { submit: true, change: true, focusin: true }) { div.setAttribute(eventName = "on" + i, "t"); support[i + "Bubbles"] = eventName in window || div.attributes[eventName].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode(true).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: IE<9 // Iteration over object's inherited properties before its own. for (i in jQuery(support)) { break; } support.ownLast = i !== "0"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if (!body) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild(container).appendChild(div); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[0].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = (tds[0].offsetHeight === 0); tds[0].style.display = ""; tds[1].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && (tds[0].offsetHeight === 0); // Check box-sizing and margin behavior. div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap(body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if (window.getComputedStyle) { support.pixelPosition = (window.getComputedStyle(div, null) || {}).top !== "1%"; support.boxSizingReliable = (window.getComputedStyle(div, null) || { width: "4px" }).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild(document.createElement("div")); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat((window.getComputedStyle(marginDiv, null) || {}).marginRight); } if (typeof div.style.zoom !== core_strundefined) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = (div.offsetWidth === 3); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = (div.offsetWidth !== 3); if (support.inlineBlockNeedsLayout) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild(container); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })({}); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData(elem, name, data, pvt /* Internal Use Only */ ) { if (!jQuery.acceptData(elem)) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[internalKey] : elem[internalKey] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ((!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string") { return; } if (!id) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if (isNode) { id = elem[internalKey] = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if (!cache[id]) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[id] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if (typeof name === "object" || typeof name === "function") { if (pvt) { cache[id] = jQuery.extend(cache[id], name); } else { cache[id].data = jQuery.extend(cache[id].data, name); } } thisCache = cache[id]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if (!pvt) { if (!thisCache.data) { thisCache.data = {}; } thisCache = thisCache.data; } if (data !== undefined) { thisCache[jQuery.camelCase(name)] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if (typeof name === "string") { // First Try to find as-is property data ret = thisCache[name]; // Test for null|undefined property data if (ret == null) { // Try to find the camelCased property ret = thisCache[jQuery.camelCase(name)]; } } else { ret = thisCache; } return ret; } function internalRemoveData(elem, name, pvt) { if (!jQuery.acceptData(elem)) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[jQuery.expando] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if (!cache[id]) { return; } if (name) { thisCache = pvt ? cache[id] : cache[id].data; if (thisCache) { // Support array or space separated string names for data keys if (!jQuery.isArray(name)) { // try the string as a key before any manipulation if (name in thisCache) { name = [name]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase(name); if (name in thisCache) { name = [name]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat(jQuery.map(name, jQuery.camelCase)); } i = name.length; while (i--) { delete thisCache[name[i]]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if (pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache)) { return; } } } // See jQuery.data for more information if (!pvt) { delete cache[id].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if (!isEmptyDataObject(cache[id])) { return; } } // Destroy the cache if (isNode) { jQuery.cleanData([elem], true); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if (jQuery.support.deleteExpando || cache != cache.window) { /* jshint eqeqeq: true */ delete cache[id]; // When all else fails, null } else { cache[id] = null; } } jQuery.extend({ cache: {}, // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "applet": true, "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function(elem) { elem = elem.nodeType ? jQuery.cache[elem[jQuery.expando]] : elem[jQuery.expando]; return !!elem && !isEmptyDataObject(elem); }, data: function(elem, name, data) { return internalData(elem, name, data); }, removeData: function(elem, name) { return internalRemoveData(elem, name); }, // For internal use only. _data: function(elem, name, data) { return internalData(elem, name, data, true); }, _removeData: function(elem, name) { return internalRemoveData(elem, name, true); }, // A method for determining if a DOM node can handle the data expando acceptData: function(elem) { // Do not set data on non-element because it will not be cleared (#8335). if (elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9) { return false; } var noData = elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function(key, value) { var attrs, name, data = null, i = 0, elem = this[0]; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if (key === undefined) { if (this.length) { data = jQuery.data(elem); if (elem.nodeType === 1 && !jQuery._data(elem, "parsedAttrs")) { attrs = elem.attributes; for (; i < attrs.length; i++) { name = attrs[i].name; if (name.indexOf("data-") === 0) { name = jQuery.camelCase(name.slice(5)); dataAttr(elem, name, data[name]); } } jQuery._data(elem, "parsedAttrs", true); } } return data; } // Sets multiple values if (typeof key === "object") { return this.each(function() { jQuery.data(this, key); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data(this, key, value); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr(elem, key, jQuery.data(elem, key)) : null; }, removeData: function(key) { return this.each(function() { jQuery.removeData(this, key); }); } }); function dataAttr(elem, key, data) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if (data === undefined && elem.nodeType === 1) { var name = "data-" + key.replace(rmultiDash, "-$1").toLowerCase(); data = elem.getAttribute(name); if (typeof data === "string") { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string + data + "" === data ? +data : rbrace.test(data) ? jQuery.parseJSON(data) : data; } catch (e) {} // Make sure we set the data so it isn't changed later jQuery.data(elem, key, data); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject(obj) { var name; for (name in obj) { // if the public data object is empty, the private is still empty if (name === "data" && jQuery.isEmptyObject(obj[name])) { continue; } if (name !== "toJSON") { return false; } } return true; } jQuery.extend({ queue: function(elem, type, data) { var queue; if (elem) { type = (type || "fx") + "queue"; queue = jQuery._data(elem, type); // Speed up dequeue by getting out quickly if this is just a lookup if (data) { if (!queue || jQuery.isArray(data)) { queue = jQuery._data(elem, type, jQuery.makeArray(data)); } else { queue.push(data); } } return queue || []; } }, dequeue: function(elem, type) { type = type || "fx"; var queue = jQuery.queue(elem, type), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks(elem, type), next = function() { jQuery.dequeue(elem, type); }; // If the fx queue is dequeued, always remove the progress sentinel if (fn === "inprogress") { fn = queue.shift(); startLength--; } if (fn) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if (type === "fx") { queue.unshift("inprogress"); } // clear up the last queue stop function delete hooks.stop; fn.call(elem, next, hooks); } if (!startLength && hooks) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function(elem, type) { var key = type + "queueHooks"; return jQuery._data(elem, key) || jQuery._data(elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData(elem, type + "queue"); jQuery._removeData(elem, key); }) }); } }); jQuery.fn.extend({ queue: function(type, data) { var setter = 2; if (typeof type !== "string") { data = type; type = "fx"; setter--; } if (arguments.length < setter) { return jQuery.queue(this[0], type); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue(this, type, data); // ensure a hooks for this queue jQuery._queueHooks(this, type); if (type === "fx" && queue[0] !== "inprogress") { jQuery.dequeue(this, type); } }); }, dequeue: function(type) { return this.each(function() { jQuery.dequeue(this, type); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function(time, type) { time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; type = type || "fx"; return this.queue(type, function(next, hooks) { var timeout = setTimeout(next, time); hooks.stop = function() { clearTimeout(timeout); }; }); }, clearQueue: function(type) { return this.queue(type || "fx", []); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function(type, obj) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if (!(--count)) { defer.resolveWith(elements, [elements]); } }; if (typeof type !== "string") { obj = type; type = undefined; } type = type || "fx"; while (i--) { tmp = jQuery._data(elements[i], type + "queueHooks"); if (tmp && tmp.empty) { count++; tmp.empty.add(resolve); } } resolve(); return defer.promise(obj); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function(name, value) { return jQuery.access(this, jQuery.attr, name, value, arguments.length > 1); }, removeAttr: function(name) { return this.each(function() { jQuery.removeAttr(this, name); }); }, prop: function(name, value) { return jQuery.access(this, jQuery.prop, name, value, arguments.length > 1); }, removeProp: function(name) { name = jQuery.propFix[name] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[name] = undefined; delete this[name]; } catch (e) {} }); }, addClass: function(value) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if (jQuery.isFunction(value)) { return this.each(function(j) { jQuery(this).addClass(value.call(this, j, this.className)); }); } if (proceed) { // The disjunction here is for better compressibility (see removeClass) classes = (value || "").match(core_rnotwhite) || []; for (; i < len; i++) { elem = this[i]; cur = elem.nodeType === 1 && (elem.className ? (" " + elem.className + " ").replace(rclass, " ") : " "); if (cur) { j = 0; while ((clazz = classes[j++])) { if (cur.indexOf(" " + clazz + " ") < 0) { cur += clazz + " "; } } elem.className = jQuery.trim(cur); } } } return this; }, removeClass: function(value) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if (jQuery.isFunction(value)) { return this.each(function(j) { jQuery(this).removeClass(value.call(this, j, this.className)); }); } if (proceed) { classes = (value || "").match(core_rnotwhite) || []; for (; i < len; i++) { elem = this[i]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && (elem.className ? (" " + elem.className + " ").replace(rclass, " ") : ""); if (cur) { j = 0; while ((clazz = classes[j++])) { // Remove *all* instances while (cur.indexOf(" " + clazz + " ") >= 0) { cur = cur.replace(" " + clazz + " ", " "); } } elem.className = value ? jQuery.trim(cur) : ""; } } } return this; }, toggleClass: function(value, stateVal) { var type = typeof value; if (typeof stateVal === "boolean" && type === "string") { return stateVal ? this.addClass(value) : this.removeClass(value); } if (jQuery.isFunction(value)) { return this.each(function(i) { jQuery(this).toggleClass(value.call(this, i, this.className, stateVal), stateVal); }); } return this.each(function() { if (type === "string") { // toggle individual class names var className, i = 0, self = jQuery(this), classNames = value.match(core_rnotwhite) || []; while ((className = classNames[i++])) { // check each className given, space separated list if (self.hasClass(className)) { self.removeClass(className); } else { self.addClass(className); } } // Toggle whole class name } else if (type === core_strundefined || type === "boolean") { if (this.className) { // store className if set jQuery._data(this, "__className__", this.className); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data(this, "__className__") || ""; } }); }, hasClass: function(selector) { var className = " " + selector + " ", i = 0, l = this.length; for (; i < l; i++) { if (this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf(className) >= 0) { return true; } } return false; }, val: function(value) { var ret, hooks, isFunction, elem = this[0]; if (!arguments.length) { if (elem) { hooks = jQuery.valHooks[elem.type] || jQuery.valHooks[elem.nodeName.toLowerCase()]; if (hooks && "get" in hooks && (ret = hooks.get(elem, "value")) !== undefined) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction(value); return this.each(function(i) { var val; if (this.nodeType !== 1) { return; } if (isFunction) { val = value.call(this, i, jQuery(this).val()); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if (val == null) { val = ""; } else if (typeof val === "number") { val += ""; } else if (jQuery.isArray(val)) { val = jQuery.map(val, function(value) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[this.type] || jQuery.valHooks[this.nodeName.toLowerCase()]; // If set returns undefined, fall back to normal setting if (!hooks || !("set" in hooks) || hooks.set(this, val, "value") === undefined) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function(elem) { // Use proper attribute retrieval(#6932, #12072) var val = jQuery.find.attr(elem, "value"); return val != null ? val : elem.text; } }, select: { get: function(elem) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for (; i < max; i++) { option = options[i]; // oldIE doesn't update selected after form reset (#2551) if ((option.selected || i === index) && // Don't return options that are disabled or in a disabled optgroup (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName(option.parentNode, "optgroup"))) { // Get the specific value for the option value = jQuery(option).val(); // We don't need an array for one selects if (one) { return value; } // Multi-Selects return an array values.push(value); } } return values; }, set: function(elem, value) { var optionSet, option, options = elem.options, values = jQuery.makeArray(value), i = options.length; while (i--) { option = options[i]; if ((option.selected = jQuery.inArray(jQuery(option).val(), values) >= 0)) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if (!optionSet) { elem.selectedIndex = -1; } return values; } } }, attr: function(elem, name, value) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if (!elem || nType === 3 || nType === 8 || nType === 2) { return; } // Fallback to prop when attributes are not supported if (typeof elem.getAttribute === core_strundefined) { return jQuery.prop(elem, name, value); } // All attributes are lowercase // Grab necessary hook if one is defined if (nType !== 1 || !jQuery.isXMLDoc(elem)) { name = name.toLowerCase(); hooks = jQuery.attrHooks[name] || (jQuery.expr.match.bool.test(name) ? boolHook : nodeHook); } if (value !== undefined) { if (value === null) { jQuery.removeAttr(elem, name); } else if (hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined) { return ret; } else { elem.setAttribute(name, value + ""); return value; } } else if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) { return ret; } else { ret = jQuery.find.attr(elem, name); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function(elem, value) { var name, propName, i = 0, attrNames = value && value.match(core_rnotwhite); if (attrNames && elem.nodeType === 1) { while ((name = attrNames[i++])) { propName = jQuery.propFix[name] || name; // Boolean attributes get special treatment (#10870) if (jQuery.expr.match.bool.test(name)) { // Set corresponding property to false if (getSetInput && getSetAttribute || !ruseDefault.test(name)) { elem[propName] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[jQuery.camelCase("default-" + name)] = elem[propName] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr(elem, name, ""); } elem.removeAttribute(getSetAttribute ? name : propName); } } }, attrHooks: { type: { set: function(elem, value) { if (!jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input")) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute("type", value); if (val) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function(elem, name, value) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if (!elem || nType === 3 || nType === 8 || nType === 2) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc(elem); if (notxml) { // Fix name and attach hooks name = jQuery.propFix[name] || name; hooks = jQuery.propHooks[name]; } if (value !== undefined) { return hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined ? ret : (elem[name] = value); } else { return hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null ? ret : elem[name]; } }, propHooks: { tabIndex: { get: function(elem) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr(elem, "tabindex"); return tabindex ? parseInt(tabindex, 10) : rfocusable.test(elem.nodeName) || rclickable.test(elem.nodeName) && elem.href ? 0 : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function(elem, value, name) { if (value === false) { // Remove boolean attributes when set to false jQuery.removeAttr(elem, name); } else if (getSetInput && getSetAttribute || !ruseDefault.test(name)) { // IE<8 needs the *property* name elem.setAttribute(!getSetAttribute && jQuery.propFix[name] || name, name); // Use defaultChecked and defaultSelected for oldIE } else { elem[jQuery.camelCase("default-" + name)] = elem[name] = true; } return name; } }; jQuery.each(jQuery.expr.match.bool.source.match(/\w+/g), function(i, name) { var getter = jQuery.expr.attrHandle[name] || jQuery.find.attr; jQuery.expr.attrHandle[name] = getSetInput && getSetAttribute || !ruseDefault.test(name) ? function(elem, name, isXML) { var fn = jQuery.expr.attrHandle[name], ret = isXML ? undefined : /* jshint eqeqeq: false */ (jQuery.expr.attrHandle[name] = undefined) != getter(elem, name, isXML) ? name.toLowerCase() : null; jQuery.expr.attrHandle[name] = fn; return ret; } : function(elem, name, isXML) { return isXML ? undefined : elem[jQuery.camelCase("default-" + name)] ? name.toLowerCase() : null; }; }); // fix oldIE attroperties if (!getSetInput || !getSetAttribute) { jQuery.attrHooks.value = { set: function(elem, value, name) { if (jQuery.nodeName(elem, "input")) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set(elem, value, name); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if (!getSetAttribute) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function(elem, value, name) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode(name); if (!ret) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute(name))); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute(name) ? value : undefined; } }; jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords = // Some attributes are constructed with empty-string values when not defined function(elem, name, isXML) { var ret; return isXML ? undefined : (ret = elem.getAttributeNode(name)) && ret.value !== "" ? ret.value : null; }; jQuery.valHooks.button = { get: function(elem, name) { var ret = elem.getAttributeNode(name); return ret && ret.specified ? ret.value : undefined; }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function(elem, value, name) { nodeHook.set(elem, value === "" ? false : value, name); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each(["width", "height"], function(i, name) { jQuery.attrHooks[name] = { set: function(elem, value) { if (value === "") { elem.setAttribute(name, "auto"); return value; } } }; }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if (!jQuery.support.hrefNormalized) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each(["href", "src"], function(i, name) { jQuery.propHooks[name] = { get: function(elem) { return elem.getAttribute(name, 4); } }; }); } if (!jQuery.support.style) { jQuery.attrHooks.style = { get: function(elem) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function(elem, value) { return (elem.style.cssText = value + ""); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if (!jQuery.support.optSelected) { jQuery.propHooks.selected = { get: function(elem) { var parent = elem.parentNode; if (parent) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if (parent.parentNode) { parent.parentNode.selectedIndex; } } return null; } }; } jQuery.each(["tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable"], function() { jQuery.propFix[this.toLowerCase()] = this; }); // IE6/7 call enctype encoding if (!jQuery.support.enctype) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter jQuery.each(["radio", "checkbox"], function() { jQuery.valHooks[this] = { set: function(elem, value) { if (jQuery.isArray(value)) { return (elem.checked = jQuery.inArray(jQuery(elem).val(), value) >= 0); } } }; if (!jQuery.support.checkOn) { jQuery.valHooks[this].get = function(elem) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch (err) {} } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function(elem, types, handler, data, selector) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data(elem); // Don't attach events to noData or text/comment nodes (but allow plain objects) if (!elemData) { return; } // Caller can pass in an object of custom data in lieu of the handler if (handler.handler) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if (!handler.guid) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if (!(events = elemData.events)) { events = elemData.events = {}; } if (!(eventHandle = elemData.handle)) { eventHandle = elemData.handle = function(e) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply(eventHandle.elem, arguments) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = (types || "").match(core_rnotwhite) || [""]; t = types.length; while (t--) { tmp = rtypenamespace.exec(types[t]) || []; type = origType = tmp[1]; namespaces = (tmp[2] || "").split(".").sort(); // There *must* be a type, no attaching namespace-only handlers if (!type) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[type] || {}; // If selector defined, determine special event api type, otherwise given type type = (selector ? special.delegateType : special.bindType) || type; // Update special based on newly reset type special = jQuery.event.special[type] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test(selector), namespace: namespaces.join(".") }, handleObjIn); // Init the event handler queue if we're the first if (!(handlers = events[type])) { handlers = events[type] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if (!special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false) { // Bind the global event handler to the element if (elem.addEventListener) { elem.addEventListener(type, eventHandle, false); } else if (elem.attachEvent) { elem.attachEvent("on" + type, eventHandle); } } } if (special.add) { special.add.call(elem, handleObj); if (!handleObj.handler.guid) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if (selector) { handlers.splice(handlers.delegateCount++, 0, handleObj); } else { handlers.push(handleObj); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[type] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function(elem, types, handler, selector, mappedTypes) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData(elem) && jQuery._data(elem); if (!elemData || !(events = elemData.events)) { return; } // Once for each type.namespace in types; type may be omitted types = (types || "").match(core_rnotwhite) || [""]; t = types.length; while (t--) { tmp = rtypenamespace.exec(types[t]) || []; type = origType = tmp[1]; namespaces = (tmp[2] || "").split(".").sort(); // Unbind all events (on this namespace, if provided) for the element if (!type) { for (type in events) { jQuery.event.remove(elem, type + types[t], handler, selector, true); } continue; } special = jQuery.event.special[type] || {}; type = (selector ? special.delegateType : special.bindType) || type; handlers = events[type] || []; tmp = tmp[2] && new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)"); // Remove matching events origCount = j = handlers.length; while (j--) { handleObj = handlers[j]; if ((mappedTypes || origType === handleObj.origType) && (!handler || handler.guid === handleObj.guid) && (!tmp || tmp.test(handleObj.namespace)) && (!selector || selector === handleObj.selector || selector === "**" && handleObj.selector)) { handlers.splice(j, 1); if (handleObj.selector) { handlers.delegateCount--; } if (special.remove) { special.remove.call(elem, handleObj); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if (origCount && !handlers.length) { if (!special.teardown || special.teardown.call(elem, namespaces, elemData.handle) === false) { jQuery.removeEvent(elem, type, elemData.handle); } delete events[type]; } } // Remove the expando if it's no longer used if (jQuery.isEmptyObject(events)) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData(elem, "events"); } }, trigger: function(event, data, elem, onlyHandlers) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [elem || document], type = core_hasOwn.call(event, "type") ? event.type : event, namespaces = core_hasOwn.call(event, "namespace") ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if (elem.nodeType === 3 || elem.nodeType === 8) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if (rfocusMorph.test(type + jQuery.event.triggered)) { return; } if (type.indexOf(".") >= 0) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[jQuery.expando] ? event : new jQuery.Event(type, typeof event === "object" && event); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; // Clean up the event in case it is being reused event.result = undefined; if (!event.target) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [event] : jQuery.makeArray(data, [event]); // Allow special events to draw outside the lines special = jQuery.event.special[type] || {}; if (!onlyHandlers && special.trigger && special.trigger.apply(elem, data) === false) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if (!onlyHandlers && !special.noBubble && !jQuery.isWindow(elem)) { bubbleType = special.delegateType || type; if (!rfocusMorph.test(bubbleType + type)) { cur = cur.parentNode; } for (; cur; cur = cur.parentNode) { eventPath.push(cur); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if (tmp === (elem.ownerDocument || document)) { eventPath.push(tmp.defaultView || tmp.parentWindow || window); } } // Fire handlers on the event path i = 0; while ((cur = eventPath[i++]) && !event.isPropagationStopped()) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = (jQuery._data(cur, "events") || {})[event.type] && jQuery._data(cur, "handle"); if (handle) { handle.apply(cur, data); } // Native handler handle = ontype && cur[ontype]; if (handle && jQuery.acceptData(cur) && handle.apply && handle.apply(cur, data) === false) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if (!onlyHandlers && !event.isDefaultPrevented()) { if ((!special._default || special._default.apply(eventPath.pop(), data) === false) && jQuery.acceptData(elem)) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if (ontype && elem[type] && !jQuery.isWindow(elem)) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ontype]; if (tmp) { elem[ontype] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[type](); } catch (e) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if (tmp) { elem[ontype] = tmp; } } } } return event.result; }, dispatch: function(event) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix(event); var i, ret, handleObj, matched, j, handlerQueue = [], args = core_slice.call(arguments), handlers = (jQuery._data(this, "events") || {})[event.type] || [], special = jQuery.event.special[event.type] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if (special.preDispatch && special.preDispatch.call(this, event) === false) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call(this, event, handlers); // Run delegates first; they may want to stop propagation beneath us i = 0; while ((matched = handlerQueue[i++]) && !event.isPropagationStopped()) { event.currentTarget = matched.elem; j = 0; while ((handleObj = matched.handlers[j++]) && !event.isImmediatePropagationStopped()) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if (!event.namespace_re || event.namespace_re.test(handleObj.namespace)) { event.handleObj = handleObj; event.data = handleObj.data; ret = ((jQuery.event.special[handleObj.origType] || {}).handle || handleObj.handler) .apply(matched.elem, args); if (ret !== undefined) { if ((event.result = ret) === false) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if (special.postDispatch) { special.postDispatch.call(this, event); } return event.result; }, handlers: function(event, handlers) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if (delegateCount && cur.nodeType && (!event.button || event.type !== "click")) { /* jshint eqeqeq: false */ for (; cur != this; cur = cur.parentNode || this) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if (cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click")) { matches = []; for (i = 0; i < delegateCount; i++) { handleObj = handlers[i]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if (matches[sel] === undefined) { matches[sel] = handleObj.needsContext ? jQuery(sel, this).index(cur) >= 0 : jQuery.find(sel, this, null, [cur]).length; } if (matches[sel]) { matches.push(handleObj); } } if (matches.length) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if (delegateCount < handlers.length) { handlerQueue.push({ elem: this, handlers: handlers.slice(delegateCount) }); } return handlerQueue; }, fix: function(event) { if (event[jQuery.expando]) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[type]; if (!fixHook) { this.fixHooks[type] = fixHook = rmouseEvent.test(type) ? this.mouseHooks : rkeyEvent.test(type) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat(fixHook.props) : this.props; event = new jQuery.Event(originalEvent); i = copy.length; while (i--) { prop = copy[i]; event[prop] = originalEvent[prop]; } // Support: IE<9 // Fix target property (#1925) if (!event.target) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if (event.target.nodeType === 3) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !! event.metaKey; return fixHook.filter ? fixHook.filter(event, originalEvent) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function(event, original) { // Add which for key events if (event.which == null) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function(event, original) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if (event.pageX == null && original.clientX != null) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = original.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Add relatedTarget, if necessary if (!event.relatedTarget && fromElement) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if (!event.which && button !== undefined) { event.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0))); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if (this !== safeActiveElement() && this.focus) { try { this.focus(); return false; } catch (e) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if (this === safeActiveElement() && this.blur) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if (jQuery.nodeName(this, "input") && this.type === "checkbox" && this.click) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function(event) { return jQuery.nodeName(event.target, "a"); } }, beforeunload: { postDispatch: function(event) { // Even when returnValue equals to undefined Firefox will still show alert if (event.result !== undefined) { event.originalEvent.returnValue = event.result; } } } }, simulate: function(type, elem, event, bubble) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} }); if (bubble) { jQuery.event.trigger(e, null, elem); } else { jQuery.event.dispatch.call(elem, e); } if (e.isDefaultPrevented()) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function(elem, type, handle) { if (elem.removeEventListener) { elem.removeEventListener(type, handle, false); } } : function(elem, type, handle) { var name = "on" + type; if (elem.detachEvent) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if (typeof elem[name] === core_strundefined) { elem[name] = null; } elem.detachEvent(name, handle); } }; jQuery.Event = function(src, props) { // Allow instantiation without the 'new' keyword if (!(this instanceof jQuery.Event)) { return new jQuery.Event(src, props); } // Event object if (src && src.type) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if (props) { jQuery.extend(this, props); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[jQuery.expando] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if (!e) { return; } // If preventDefault exists, run it on the original event if (e.preventDefault) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if (!e) { return; } // If stopPropagation exists, run it on the original event if (e.stopPropagation) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function(orig, fix) { jQuery.event.special[orig] = { delegateType: fix, bindType: fix, handle: function(event) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if (!related || (related !== target && !jQuery.contains(target, related))) { event.type = handleObj.origType; ret = handleObj.handler.apply(this, arguments); event.type = fix; } return ret; } }; }); // IE submit delegation if (!jQuery.support.submitBubbles) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if (jQuery.nodeName(this, "form")) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add(this, "click._submit keypress._submit", function(e) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName(elem, "input") || jQuery.nodeName(elem, "button") ? elem.form : undefined; if (form && !jQuery._data(form, "submitBubbles")) { jQuery.event.add(form, "submit._submit", function(event) { event._submit_bubble = true; }); jQuery._data(form, "submitBubbles", true); } }); // return undefined since we don't need an event listener }, postDispatch: function(event) { // If form was submitted by the user, bubble the event up the tree if (event._submit_bubble) { delete event._submit_bubble; if (this.parentNode && !event.isTrigger) { jQuery.event.simulate("submit", this.parentNode, event, true); } } }, teardown: function() { // Only need this for delegated form submit events if (jQuery.nodeName(this, "form")) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove(this, "._submit"); } }; } // IE change delegation and checkbox/radio fix if (!jQuery.support.changeBubbles) { jQuery.event.special.change = { setup: function() { if (rformElems.test(this.nodeName)) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if (this.type === "checkbox" || this.type === "radio") { jQuery.event.add(this, "propertychange._change", function(event) { if (event.originalEvent.propertyName === "checked") { this._just_changed = true; } }); jQuery.event.add(this, "click._change", function(event) { if (this._just_changed && !event.isTrigger) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate("change", this, event, true); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add(this, "beforeactivate._change", function(e) { var elem = e.target; if (rformElems.test(elem.nodeName) && !jQuery._data(elem, "changeBubbles")) { jQuery.event.add(elem, "change._change", function(event) { if (this.parentNode && !event.isSimulated && !event.isTrigger) { jQuery.event.simulate("change", this.parentNode, event, true); } }); jQuery._data(elem, "changeBubbles", true); } }); }, handle: function(event) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if (this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox")) { return event.handleObj.handler.apply(this, arguments); } }, teardown: function() { jQuery.event.remove(this, "._change"); return !rformElems.test(this.nodeName); } }; } // Create "bubbling" focus and blur events if (!jQuery.support.focusinBubbles) { jQuery.each({ focus: "focusin", blur: "focusout" }, function(orig, fix) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function(event) { jQuery.event.simulate(fix, event.target, jQuery.event.fix(event), true); }; jQuery.event.special[fix] = { setup: function() { if (attaches++ === 0) { document.addEventListener(orig, handler, true); } }, teardown: function() { if (--attaches === 0) { document.removeEventListener(orig, handler, true); } } }; }); } jQuery.fn.extend({ on: function(types, selector, data, fn, /*INTERNAL*/ one) { var type, origFn; // Types can be a map of types/handlers if (typeof types === "object") { // ( types-Object, selector, data ) if (typeof selector !== "string") { // ( types-Object, data ) data = data || selector; selector = undefined; } for (type in types) { this.on(type, selector, data, types[type], one); } return this; } if (data == null && fn == null) { // ( types, fn ) fn = selector; data = selector = undefined; } else if (fn == null) { if (typeof selector === "string") { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if (fn === false) { fn = returnFalse; } else if (!fn) { return this; } if (one === 1) { origFn = fn; fn = function(event) { // Can use an empty set, since event contains the info jQuery().off(event); return origFn.apply(this, arguments); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || (origFn.guid = jQuery.guid++); } return this.each(function() { jQuery.event.add(this, types, fn, data, selector); }); }, one: function(types, selector, data, fn) { return this.on(types, selector, data, fn, 1); }, off: function(types, selector, fn) { var handleObj, type; if (types && types.preventDefault && types.handleObj) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery(types.delegateTarget).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler); return this; } if (typeof types === "object") { // ( types-object [, selector] ) for (type in types) { this.off(type, selector, types[type]); } return this; } if (selector === false || typeof selector === "function") { // ( types [, fn] ) fn = selector; selector = undefined; } if (fn === false) { fn = returnFalse; } return this.each(function() { jQuery.event.remove(this, types, fn, selector); }); }, trigger: function(type, data) { return this.each(function() { jQuery.event.trigger(type, data, this); }); }, triggerHandler: function(type, data) { var elem = this[0]; if (elem) { return jQuery.event.trigger(type, data, elem, true); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function(selector) { var i, ret = [], self = this, len = self.length; if (typeof selector !== "string") { return this.pushStack(jQuery(selector).filter(function() { for (i = 0; i < len; i++) { if (jQuery.contains(self[i], this)) { return true; } } })); } for (i = 0; i < len; i++) { jQuery.find(selector, self[i], ret); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack(len > 1 ? jQuery.unique(ret) : ret); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function(target) { var i, targets = jQuery(target, this), len = targets.length; return this.filter(function() { for (i = 0; i < len; i++) { if (jQuery.contains(this, targets[i])) { return true; } } }); }, not: function(selector) { return this.pushStack(winnow(this, selector || [], true)); }, filter: function(selector) { return this.pushStack(winnow(this, selector || [], false)); }, is: function(selector) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test(selector) ? jQuery(selector) : selector || [], false).length; }, closest: function(selectors, context) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test(selectors) || typeof selectors !== "string" ? jQuery(selectors, context || this.context) : 0; for (; i < l; i++) { for (cur = this[i]; cur && cur !== context; cur = cur.parentNode) { // Always skip document fragments if (cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors))) { cur = ret.push(cur); break; } } } return this.pushStack(ret.length > 1 ? jQuery.unique(ret) : ret); }, // Determine the position of an element within // the matched set of elements index: function(elem) { // No argument, return index in parent if (!elem) { return (this[0] && this[0].parentNode) ? this.first().prevAll().length : -1; } // index in selector if (typeof elem === "string") { return jQuery.inArray(this[0], jQuery(elem)); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this); }, add: function(selector, context) { var set = typeof selector === "string" ? jQuery(selector, context) : jQuery.makeArray(selector && selector.nodeType ? [selector] : selector), all = jQuery.merge(this.get(), set); return this.pushStack(jQuery.unique(all)); }, addBack: function(selector) { return this.add(selector == null ? this.prevObject : this.prevObject.filter(selector)); } }); function sibling(cur, dir) { do { cur = cur[dir]; } while (cur && cur.nodeType !== 1); return cur; } jQuery.each({ parent: function(elem) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function(elem) { return jQuery.dir(elem, "parentNode"); }, parentsUntil: function(elem, i, until) { return jQuery.dir(elem, "parentNode", until); }, next: function(elem) { return sibling(elem, "nextSibling"); }, prev: function(elem) { return sibling(elem, "previousSibling"); }, nextAll: function(elem) { return jQuery.dir(elem, "nextSibling"); }, prevAll: function(elem) { return jQuery.dir(elem, "previousSibling"); }, nextUntil: function(elem, i, until) { return jQuery.dir(elem, "nextSibling", until); }, prevUntil: function(elem, i, until) { return jQuery.dir(elem, "previousSibling", until); }, siblings: function(elem) { return jQuery.sibling((elem.parentNode || {}).firstChild, elem); }, children: function(elem) { return jQuery.sibling(elem.firstChild); }, contents: function(elem) { return jQuery.nodeName(elem, "iframe") ? elem.contentDocument || elem.contentWindow.document : jQuery.merge([], elem.childNodes); } }, function(name, fn) { jQuery.fn[name] = function(until, selector) { var ret = jQuery.map(this, fn, until); if (name.slice(-5) !== "Until") { selector = until; } if (selector && typeof selector === "string") { ret = jQuery.filter(selector, ret); } if (this.length > 1) { // Remove duplicates if (!guaranteedUnique[name]) { ret = jQuery.unique(ret); } // Reverse order for parents* and prev-derivatives if (rparentsprev.test(name)) { ret = ret.reverse(); } } return this.pushStack(ret); }; }); jQuery.extend({ filter: function(expr, elems, not) { var elem = elems[0]; if (not) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector(elem, expr) ? [elem] : [] : jQuery.find.matches(expr, jQuery.grep(elems, function(elem) { return elem.nodeType === 1; })); }, dir: function(elem, dir, until) { var matched = [], cur = elem[dir]; while (cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery(cur).is(until))) { if (cur.nodeType === 1) { matched.push(cur); } cur = cur[dir]; } return matched; }, sibling: function(n, elem) { var r = []; for (; n; n = n.nextSibling) { if (n.nodeType === 1 && n !== elem) { r.push(n); } } return r; } }); // Implement the identical functionality for filter and not function winnow(elements, qualifier, not) { if (jQuery.isFunction(qualifier)) { return jQuery.grep(elements, function(elem, i) { /* jshint -W018 */ return !!qualifier.call(elem, i, elem) !== not; }); } if (qualifier.nodeType) { return jQuery.grep(elements, function(elem) { return (elem === qualifier) !== not; }); } if (typeof qualifier === "string") { if (isSimple.test(qualifier)) { return jQuery.filter(qualifier, elements, not); } qualifier = jQuery.filter(qualifier, elements); } return jQuery.grep(elements, function(elem) { return (jQuery.inArray(elem, qualifier) >= 0) !== not; }); } function createSafeFragment(document) { var list = nodeNames.split("|"), safeFrag = document.createDocumentFragment(); if (safeFrag.createElement) { while (list.length) { safeFrag.createElement( list.pop()); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [1, "<select multiple='multiple'>", "</select>"], legend: [1, "<fieldset>", "</fieldset>"], area: [1, "<map>", "</map>"], param: [1, "<object>", "</object>"], thead: [1, "<table>", "</table>"], tr: [2, "<table><tbody>", "</tbody></table>"], col: [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"], td: [3, "<table><tbody><tr>", "</tr></tbody></table>"], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [0, "", ""] : [1, "X<div>", "</div>"] }, safeFragment = createSafeFragment(document), fragmentDiv = safeFragment.appendChild(document.createElement("div")); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function(value) { return jQuery.access(this, function(value) { return value === undefined ? jQuery.text(this) : this.empty().append((this[0] && this[0].ownerDocument || document).createTextNode(value)); }, null, value, arguments.length); }, append: function() { return this.domManip(arguments, function(elem) { if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) { var target = manipulationTarget(this, elem); target.appendChild(elem); } }); }, prepend: function() { return this.domManip(arguments, function(elem) { if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) { var target = manipulationTarget(this, elem); target.insertBefore(elem, target.firstChild); } }); }, before: function() { return this.domManip(arguments, function(elem) { if (this.parentNode) { this.parentNode.insertBefore(elem, this); } }); }, after: function() { return this.domManip(arguments, function(elem) { if (this.parentNode) { this.parentNode.insertBefore(elem, this.nextSibling); } }); }, // keepData is for internal use only--do not document remove: function(selector, keepData) { var elem, elems = selector ? jQuery.filter(selector, this) : this, i = 0; for (; (elem = elems[i]) != null; i++) { if (!keepData && elem.nodeType === 1) { jQuery.cleanData(getAll(elem)); } if (elem.parentNode) { if (keepData && jQuery.contains(elem.ownerDocument, elem)) { setGlobalEval(getAll(elem, "script")); } elem.parentNode.removeChild(elem); } } return this; }, empty: function() { var elem, i = 0; for (; (elem = this[i]) != null; i++) { // Remove element nodes and prevent memory leaks if (elem.nodeType === 1) { jQuery.cleanData(getAll(elem, false)); } // Remove any remaining nodes while (elem.firstChild) { elem.removeChild(elem.firstChild); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if (elem.options && jQuery.nodeName(elem, "select")) { elem.options.length = 0; } } return this; }, clone: function(dataAndEvents, deepDataAndEvents) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone(this, dataAndEvents, deepDataAndEvents); }); }, html: function(value) { return jQuery.access(this, function(value) { var elem = this[0] || {}, i = 0, l = this.length; if (value === undefined) { return elem.nodeType === 1 ? elem.innerHTML.replace(rinlinejQuery, "") : undefined; } // See if we can take a shortcut and just use innerHTML if (typeof value === "string" && !rnoInnerhtml.test(value) && (jQuery.support.htmlSerialize || !rnoshimcache.test(value)) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test(value)) && !wrapMap[(rtagName.exec(value) || ["", ""])[1].toLowerCase()]) { value = value.replace(rxhtmlTag, "<$1></$2>"); try { for (; i < l; i++) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if (elem.nodeType === 1) { jQuery.cleanData(getAll(elem, false)); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch (e) {} } if (elem) { this.empty().append(value); } }, null, value, arguments.length); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map(this, function(elem) { return [elem.nextSibling, elem.parentNode]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip(arguments, function(elem) { var next = args[i++], parent = args[i++]; if (parent) { // Don't use the snapshot next if it has moved (#13810) if (next && next.parentNode !== parent) { next = this.nextSibling; } jQuery(this).remove(); parent.insertBefore(elem, next); } // Allow new content to include elements from the context set }, true); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function(selector) { return this.remove(selector, true); }, domManip: function(args, callback, allowIntersection) { // Flatten any nested arrays args = core_concat.apply([], args); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction(value); // We can't cloneNode fragments that contain checked, in WebKit if (isFunction || !(l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test(value))) { return this.each(function(index) { var self = set.eq(index); if (isFunction) { args[0] = value.call(this, index, self.html()); } self.domManip(args, callback, allowIntersection); }); } if (l) { fragment = jQuery.buildFragment(args, this[0].ownerDocument, false, !allowIntersection && this); first = fragment.firstChild; if (fragment.childNodes.length === 1) { fragment = first; } if (first) { scripts = jQuery.map(getAll(fragment, "script"), disableScript); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for (; i < l; i++) { node = fragment; if (i !== iNoClone) { node = jQuery.clone(node, true, true); // Keep references to cloned scripts for later restoration if (hasScripts) { jQuery.merge(scripts, getAll(node, "script")); } } callback.call(this[i], node, i); } if (hasScripts) { doc = scripts[scripts.length - 1].ownerDocument; // Reenable scripts jQuery.map(scripts, restoreScript); // Evaluate executable scripts on first document insertion for (i = 0; i < hasScripts; i++) { node = scripts[i]; if (rscriptType.test(node.type || "") && !jQuery._data(node, "globalEval") && jQuery.contains(doc, node)) { if (node.src) { // Hope ajax is available... jQuery._evalUrl(node.src); } else { jQuery.globalEval((node.text || node.textContent || node.innerHTML || "").replace(rcleanScript, "")); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget(elem, content) { return jQuery.nodeName(elem, "table") && jQuery.nodeName(content.nodeType === 1 ? content : content.firstChild, "tr") ? elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody")) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript(elem) { elem.type = (jQuery.find.attr(elem, "type") !== null) + "/" + elem.type; return elem; } function restoreScript(elem) { var match = rscriptTypeMasked.exec(elem.type); if (match) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval(elems, refElements) { var elem, i = 0; for (; (elem = elems[i]) != null; i++) { jQuery._data(elem, "globalEval", !refElements || jQuery._data(refElements[i], "globalEval")); } } function cloneCopyEvent(src, dest) { if (dest.nodeType !== 1 || !jQuery.hasData(src)) { return; } var type, i, l, oldData = jQuery._data(src), curData = jQuery._data(dest, oldData), events = oldData.events; if (events) { delete curData.handle; curData.events = {}; for (type in events) { for (i = 0, l = events[type].length; i < l; i++) { jQuery.event.add(dest, type, events[type][i]); } } } // make the cloned public data object a copy from the original if (curData.data) { curData.data = jQuery.extend({}, curData.data); } } function fixCloneNodeIssues(src, dest) { var nodeName, e, data; // We do not need to do anything for non-Elements if (dest.nodeType !== 1) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if (!jQuery.support.noCloneEvent && dest[jQuery.expando]) { data = jQuery._data(dest); for (e in data.events) { jQuery.removeEvent(dest, e, data.handle); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute(jQuery.expando); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if (nodeName === "script" && dest.text !== src.text) { disableScript(dest).text = src.text; restoreScript(dest); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if (nodeName === "object") { if (dest.parentNode) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if (jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML))) { dest.innerHTML = src.innerHTML; } } else if (nodeName === "input" && manipulation_rcheckableType.test(src.type)) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if (dest.value !== src.value) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if (nodeName === "option") { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if (nodeName === "input" || nodeName === "textarea") { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function(name, original) { jQuery.fn[name] = function(selector) { var elems, i = 0, ret = [], insert = jQuery(selector), last = insert.length - 1; for (; i <= last; i++) { elems = i === last ? this : this.clone(true); jQuery(insert[i])[original](elems); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply(ret, elems.get()); } return this.pushStack(ret); }; }); function getAll(context, tag) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName(tag || "*") : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll(tag || "*") : undefined; if (!found) { for (found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++) { if (!tag || jQuery.nodeName(elem, tag)) { found.push(elem); } else { jQuery.merge(found, getAll(elem, tag)); } } } return tag === undefined || tag && jQuery.nodeName(context, tag) ? jQuery.merge([context], found) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked(elem) { if (manipulation_rcheckableType.test(elem.type)) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function(elem, dataAndEvents, deepDataAndEvents) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains(elem.ownerDocument, elem); if (jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test("<" + elem.nodeName + ">")) { clone = elem.cloneNode(true); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild(clone = fragmentDiv.firstChild); } if ((!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem)) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll(clone); srcElements = getAll(elem); // Fix all IE cloning issues for (i = 0; (node = srcElements[i]) != null; ++i) { // Ensure that the destination node is not null; Fixes #9587 if (destElements[i]) { fixCloneNodeIssues(node, destElements[i]); } } } // Copy the events from the original to the clone if (dataAndEvents) { if (deepDataAndEvents) { srcElements = srcElements || getAll(elem); destElements = destElements || getAll(clone); for (i = 0; (node = srcElements[i]) != null; i++) { cloneCopyEvent(node, destElements[i]); } } else { cloneCopyEvent(elem, clone); } } // Preserve script evaluation history destElements = getAll(clone, "script"); if (destElements.length > 0) { setGlobalEval(destElements, !inPage && getAll(elem, "script")); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function(elems, context, scripts, selection) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment(context), nodes = [], i = 0; for (; i < l; i++) { elem = elems[i]; if (elem || elem === 0) { // Add nodes directly if (jQuery.type(elem) === "object") { jQuery.merge(nodes, elem.nodeType ? [elem] : elem); // Convert non-html into a text node } else if (!rhtml.test(elem)) { nodes.push(context.createTextNode(elem)); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild(context.createElement("div")); // Deserialize a standard representation tag = (rtagName.exec(elem) || ["", ""])[1].toLowerCase(); wrap = wrapMap[tag] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace(rxhtmlTag, "<$1></$2>") + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while (j--) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if (!jQuery.support.leadingWhitespace && rleadingWhitespace.test(elem)) { nodes.push(context.createTextNode(rleadingWhitespace.exec(elem)[0])); } // Remove IE's autoinserted <tbody> from table fragments if (!jQuery.support.tbody) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test(elem) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test(elem) ? tmp : 0; j = elem && elem.childNodes.length; while (j--) { if (jQuery.nodeName((tbody = elem.childNodes[j]), "tbody") && !tbody.childNodes.length) { elem.removeChild(tbody); } } } jQuery.merge(nodes, tmp.childNodes); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while (tmp.firstChild) { tmp.removeChild(tmp.firstChild); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if (tmp) { safe.removeChild(tmp); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if (!jQuery.support.appendChecked) { jQuery.grep(getAll(nodes, "input"), fixDefaultChecked); } i = 0; while ((elem = nodes[i++])) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if (selection && jQuery.inArray(elem, selection) !== -1) { continue; } contains = jQuery.contains(elem.ownerDocument, elem); // Append to fragment tmp = getAll(safe.appendChild(elem), "script"); // Preserve script evaluation history if (contains) { setGlobalEval(tmp); } // Capture executables if (scripts) { j = 0; while ((elem = tmp[j++])) { if (rscriptType.test(elem.type || "")) { scripts.push(elem); } } } } tmp = null; return safe; }, cleanData: function(elems, /* internal */ acceptData) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for (; (elem = elems[i]) != null; i++) { if (acceptData || jQuery.acceptData(elem)) { id = elem[internalKey]; data = id && cache[id]; if (data) { if (data.events) { for (type in data.events) { if (special[type]) { jQuery.event.remove(elem, type); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent(elem, type, data.handle); } } } // Remove cache only if it was not already removed by jQuery.event.remove if (cache[id]) { delete cache[id]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if (deleteExpando) { delete elem[internalKey]; } else if (typeof elem.removeAttribute !== core_strundefined) { elem.removeAttribute(internalKey); } else { elem[internalKey] = null; } core_deletedIds.push(id); } } } } }, _evalUrl: function(url) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); jQuery.fn.extend({ wrapAll: function(html) { if (jQuery.isFunction(html)) { return this.each(function(i) { jQuery(this).wrapAll(html.call(this, i)); }); } if (this[0]) { // The elements to wrap the target around var wrap = jQuery(html, this[0].ownerDocument).eq(0).clone(true); if (this[0].parentNode) { wrap.insertBefore(this[0]); } wrap.map(function() { var elem = this; while (elem.firstChild && elem.firstChild.nodeType === 1) { elem = elem.firstChild; } return elem; }).append(this); } return this; }, wrapInner: function(html) { if (jQuery.isFunction(html)) { return this.each(function(i) { jQuery(this).wrapInner(html.call(this, i)); }); } return this.each(function() { var self = jQuery(this), contents = self.contents(); if (contents.length) { contents.wrapAll(html); } else { self.append(html); } }); }, wrap: function(html) { var isFunction = jQuery.isFunction(html); return this.each(function(i) { jQuery(this).wrapAll(isFunction ? html.call(this, i) : html); }); }, unwrap: function() { return this.parent().each(function() { if (!jQuery.nodeName(this, "body")) { jQuery(this).replaceWith(this.childNodes); } }).end(); } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp("^(" + core_pnum + ")(.*)$", "i"), rnumnonpx = new RegExp("^(" + core_pnum + ")(?!px)[a-z%]+$", "i"), rrelNum = new RegExp("^([+-])=(" + core_pnum + ")", "i"), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = ["Top", "Right", "Bottom", "Left"], cssPrefixes = ["Webkit", "O", "Moz", "ms"]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName(style, name) { // shortcut for names that are not vendor prefixed if (name in style) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while (i--) { name = cssPrefixes[i] + capName; if (name in style) { return name; } } return origName; } function isHidden(elem, el) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css(elem, "display") === "none" || !jQuery.contains(elem.ownerDocument, elem); } function showHide(elements, show) { var display, elem, hidden, values = [], index = 0, length = elements.length; for (; index < length; index++) { elem = elements[index]; if (!elem.style) { continue; } values[index] = jQuery._data(elem, "olddisplay"); display = elem.style.display; if (show) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if (!values[index] && display === "none") { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if (elem.style.display === "" && isHidden(elem)) { values[index] = jQuery._data(elem, "olddisplay", css_defaultDisplay(elem.nodeName)); } } else { if (!values[index]) { hidden = isHidden(elem); if (display && display !== "none" || !hidden) { jQuery._data(elem, "olddisplay", hidden ? display : jQuery.css(elem, "display")); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for (index = 0; index < length; index++) { elem = elements[index]; if (!elem.style) { continue; } if (!show || elem.style.display === "none" || elem.style.display === "") { elem.style.display = show ? values[index] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function(name, value) { return jQuery.access(this, function(elem, name, value) { var len, styles, map = {}, i = 0; if (jQuery.isArray(name)) { styles = getStyles(elem); len = name.length; for (; i < len; i++) { map[name[i]] = jQuery.css(elem, name[i], false, styles); } return map; } return value !== undefined ? jQuery.style(elem, name, value) : jQuery.css(elem, name); }, name, value, arguments.length > 1); }, show: function() { return showHide(this, true); }, hide: function() { return showHide(this); }, toggle: function(state) { if (typeof state === "boolean") { return state ? this.show() : this.hide(); } return this.each(function() { if (isHidden(this)) { jQuery(this).show(); } else { jQuery(this).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function(elem, computed) { if (computed) { // We should always get a number back from opacity var ret = curCSS(elem, "opacity"); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function(elem, name, value, extra) { // Don't set styles on text and comment nodes if (!elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase(name), style = elem.style; name = jQuery.cssProps[origName] || (jQuery.cssProps[origName] = vendorPropName(style, origName)); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[name] || jQuery.cssHooks[origName]; // Check if we're setting a value if (value !== undefined) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if (type === "string" && (ret = rrelNum.exec(value))) { value = (ret[1] + 1) * ret[2] + parseFloat(jQuery.css(elem, name)); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if (value == null || type === "number" && isNaN(value)) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if (type === "number" && !jQuery.cssNumber[origName]) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if (!jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0) { style[name] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if (!hooks || !("set" in hooks) || (value = hooks.set(elem, value, extra)) !== undefined) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[name] = value; } catch (e) {} } } else { // If a hook was provided get the non-computed value from there if (hooks && "get" in hooks && (ret = hooks.get(elem, false, extra)) !== undefined) { return ret; } // Otherwise just get the value from the style object return style[name]; } }, css: function(elem, name, extra, styles) { var num, val, hooks, origName = jQuery.camelCase(name); // Make sure that we're working with the right name name = jQuery.cssProps[origName] || (jQuery.cssProps[origName] = vendorPropName(elem.style, origName)); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[name] || jQuery.cssHooks[origName]; // If a hook was provided get the computed value from there if (hooks && "get" in hooks) { val = hooks.get(elem, true, extra); } // Otherwise, if a way to get the computed value exists, use that if (val === undefined) { val = curCSS(elem, name, styles); } //convert "normal" to computed value if (val === "normal" && name in cssNormalTransform) { val = cssNormalTransform[name]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if (extra === "" || extra) { num = parseFloat(val); return extra === true || jQuery.isNumeric(num) ? num || 0 : val; } return val; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if (window.getComputedStyle) { getStyles = function(elem) { return window.getComputedStyle(elem, null); }; curCSS = function(elem, name, _computed) { var width, minWidth, maxWidth, computed = _computed || getStyles(elem), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue(name) || computed[name] : undefined, style = elem.style; if (computed) { if (ret === "" && !jQuery.contains(elem.ownerDocument, elem)) { ret = jQuery.style(elem, name); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if (rnumnonpx.test(ret) && rmargin.test(name)) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if (document.documentElement.currentStyle) { getStyles = function(elem) { return elem.currentStyle; }; curCSS = function(elem, name, _computed) { var left, rs, rsLeft, computed = _computed || getStyles(elem), ret = computed ? computed[name] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if (ret == null && style && style[name]) { ret = style[name]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if (rnumnonpx.test(ret) && !rposition.test(name)) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if (rsLeft) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if (rsLeft) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber(elem, value, subtract) { var matches = rnumsplit.exec(value); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max(0, matches[1] - (subtract || 0)) + (matches[2] || "px") : value; } function augmentWidthOrHeight(elem, name, extra, isBorderBox, styles) { var i = extra === (isBorderBox ? "border" : "content") ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for (; i < 4; i += 2) { // both box models exclude margin, so add it if we want it if (extra === "margin") { val += jQuery.css(elem, extra + cssExpand[i], true, styles); } if (isBorderBox) { // border-box includes padding, so remove it if we want content if (extra === "content") { val -= jQuery.css(elem, "padding" + cssExpand[i], true, styles); } // at this point, extra isn't border nor margin, so remove border if (extra !== "margin") { val -= jQuery.css(elem, "border" + cssExpand[i] + "Width", true, styles); } } else { // at this point, extra isn't content, so add padding val += jQuery.css(elem, "padding" + cssExpand[i], true, styles); // at this point, extra isn't content nor padding, so add border if (extra !== "padding") { val += jQuery.css(elem, "border" + cssExpand[i] + "Width", true, styles); } } } return val; } function getWidthOrHeight(elem, name, extra) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles(elem), isBorderBox = jQuery.support.boxSizing && jQuery.css(elem, "boxSizing", false, styles) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if (val <= 0 || val == null) { // Fall back to computed then uncomputed css if necessary val = curCSS(elem, name, styles); if (val < 0 || val == null) { val = elem.style[name]; } // Computed unit is not pixels. Stop here and return. if (rnumnonpx.test(val)) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && (jQuery.support.boxSizingReliable || val === elem.style[name]); // Normalize "", auto, and prepare for extra val = parseFloat(val) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return (val + augmentWidthOrHeight( elem, name, extra || (isBorderBox ? "border" : "content"), valueIsBorderBox, styles)) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay(nodeName) { var doc = document, display = elemdisplay[nodeName]; if (!display) { display = actualDisplay(nodeName, doc); // If the simple way fails, read from inside an iframe if (display === "none" || !display) { // Use the already-created iframe if possible iframe = (iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css("cssText", "display:block !important")).appendTo(doc.documentElement); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = (iframe[0].contentWindow || iframe[0].contentDocument).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay(nodeName, doc); iframe.detach(); } // Store the correct default display elemdisplay[nodeName] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay(name, doc) { var elem = jQuery(doc.createElement(name)).appendTo(doc.body), display = jQuery.css(elem[0], "display"); elem.remove(); return display; } jQuery.each(["height", "width"], function(i, name) { jQuery.cssHooks[name] = { get: function(elem, computed, extra) { if (computed) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test(jQuery.css(elem, "display")) ? jQuery.swap(elem, cssShow, function() { return getWidthOrHeight(elem, name, extra); }) : getWidthOrHeight(elem, name, extra); } }, set: function(elem, value, extra) { var styles = extra && getStyles(elem); return setPositiveNumber(elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css(elem, "boxSizing", false, styles) === "border-box", styles) : 0); } }; }); if (!jQuery.support.opacity) { jQuery.cssHooks.opacity = { get: function(elem, computed) { // IE uses filters for opacity return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ? (0.01 * parseFloat(RegExp.$1)) + "" : computed ? "1" : ""; }, set: function(elem, value) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric(value) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ((value >= 1 || value === "") && jQuery.trim(filter.replace(ralpha, "")) === "" && style.removeAttribute) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute("filter"); // if there is no filter style applied in a css rule or unset inline opacity, we are done if (value === "" || currentStyle && !currentStyle.filter) { return; } } // otherwise, set new filter values style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if (!jQuery.support.reliableMarginRight) { jQuery.cssHooks.marginRight = { get: function(elem, computed) { if (computed) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap(elem, { "display": "inline-block" }, curCSS, [elem, "marginRight"]); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if (!jQuery.support.pixelPosition && jQuery.fn.position) { jQuery.each(["top", "left"], function(i, prop) { jQuery.cssHooks[prop] = { get: function(elem, computed) { if (computed) { computed = curCSS(elem, prop); // if curCSS returns percentage, fallback to offset return rnumnonpx.test(computed) ? jQuery(elem).position()[prop] + "px" : computed; } } }; }); } }); if (jQuery.expr && jQuery.expr.filters) { jQuery.expr.filters.hidden = function(elem) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css(elem, "display")) === "none"); }; jQuery.expr.filters.visible = function(elem) { return !jQuery.expr.filters.hidden(elem); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function(prefix, suffix) { jQuery.cssHooks[prefix + suffix] = { expand: function(value) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [value]; for (; i < 4; i++) { expanded[prefix + cssExpand[i] + suffix] = parts[i] || parts[i - 2] || parts[0]; } return expanded; } }; if (!rmargin.test(prefix)) { jQuery.cssHooks[prefix + suffix].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param(this.serializeArray()); }, serializeArray: function() { return this.map(function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop(this, "elements"); return elements ? jQuery.makeArray(elements) : this; }) .filter(function() { var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery(this).is(":disabled") && rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) && (this.checked || !manipulation_rcheckableType.test(type)); }) .map(function(i, elem) { var val = jQuery(this).val(); return val == null ? null : jQuery.isArray(val) ? jQuery.map(val, function(val) { return { name: elem.name, value: val.replace(rCRLF, "\r\n") }; }) : { name: elem.name, value: val.replace(rCRLF, "\r\n") }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function(a, traditional) { var prefix, s = [], add = function(key, value) { // If value is a function, invoke it and return its value value = jQuery.isFunction(value) ? value() : (value == null ? "" : value); s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if (traditional === undefined) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if (jQuery.isArray(a) || (a.jquery && !jQuery.isPlainObject(a))) { // Serialize the form elements jQuery.each(a, function() { add(this.name, this.value); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for (prefix in a) { buildParams(prefix, a[prefix], traditional, add); } } // Return the resulting serialization return s.join("&").replace(r20, "+"); }; function buildParams(prefix, obj, traditional, add) { var name; if (jQuery.isArray(obj)) { // Serialize array item. jQuery.each(obj, function(i, v) { if (traditional || rbracket.test(prefix)) { // Treat each array item as a scalar. add(prefix, v); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams(prefix + "[" + (typeof v === "object" ? i : "") + "]", v, traditional, add); } }); } else if (!traditional && jQuery.type(obj) === "object") { // Serialize object item. for (name in obj) { buildParams(prefix + "[" + name + "]", obj[name], traditional, add); } } else { // Serialize scalar item. add(prefix, obj); } } jQuery.each(("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function(i, name) { // Handle event binding jQuery.fn[name] = function(data, fn) { return arguments.length > 0 ? this.on(name, null, data, fn) : this.trigger(name); }; }); jQuery.fn.extend({ hover: function(fnOver, fnOut) { return this.mouseenter(fnOver).mouseleave(fnOut || fnOver); }, bind: function(types, data, fn) { return this.on(types, null, data, fn); }, unbind: function(types, fn) { return this.off(types, null, fn); }, delegate: function(selector, types, data, fn) { return this.on(types, selector, data, fn); }, undelegate: function(selector, types, fn) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off(selector, "**") : this.off(types, selector || "**", fn); } }); var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch (e) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement("a"); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports(structure) { // dataTypeExpression is optional and defaults to "*" return function(dataTypeExpression, func) { if (typeof dataTypeExpression !== "string") { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match(core_rnotwhite) || []; if (jQuery.isFunction(func)) { // For each dataType in the dataTypeExpression while ((dataType = dataTypes[i++])) { // Prepend if requested if (dataType[0] === "+") { dataType = dataType.slice(1) || "*"; (structure[dataType] = structure[dataType] || []).unshift(func); // Otherwise append } else { (structure[dataType] = structure[dataType] || []).push(func); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR) { var inspected = {}, seekingTransport = (structure === transports); function inspect(dataType) { var selected; inspected[dataType] = true; jQuery.each(structure[dataType] || [], function(_, prefilterOrFactory) { var dataTypeOrTransport = prefilterOrFactory(options, originalOptions, jqXHR); if (typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[dataTypeOrTransport]) { options.dataTypes.unshift(dataTypeOrTransport); inspect(dataTypeOrTransport); return false; } else if (seekingTransport) { return !(selected = dataTypeOrTransport); } }); return selected; } return inspect(options.dataTypes[0]) || !inspected["*"] && inspect("*"); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend(target, src) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for (key in src) { if (src[key] !== undefined) { (flatOptions[key] ? target : (deep || (deep = {})))[key] = src[key]; } } if (deep) { jQuery.extend(true, target, deep); } return target; } jQuery.fn.load = function(url, params, callback) { if (typeof url !== "string" && _load) { return _load.apply(this, arguments); } var selector, response, type, self = this, off = url.indexOf(" "); if (off >= 0) { selector = url.slice(off, url.length); url = url.slice(0, off); } // If it's a function if (jQuery.isFunction(params)) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if (params && typeof params === "object") { type = "POST"; } // If we have elements to modify, make the request if (self.length > 0) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function(responseText) { // Save response for use in complete callback response = arguments; self.html(selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) : // Otherwise use the full result responseText); }).complete(callback && function(jqXHR, status) { self.each(callback, response || [jqXHR.responseText, status, jqXHR]); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], function(i, type) { jQuery.fn[type] = function(fn) { return this.on(type, fn); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test(ajaxLocParts[1]), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function(target, settings) { return settings ? // Building a settings object ajaxExtend(ajaxExtend(target, jQuery.ajaxSettings), settings) : // Extending ajaxSettings ajaxExtend(jQuery.ajaxSettings, target); }, ajaxPrefilter: addToPrefiltersOrTransports(prefilters), ajaxTransport: addToPrefiltersOrTransports(transports), // Main method ajax: function(url, options) { // If url is an object, simulate pre-1.5 signature if (typeof url === "object") { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup({}, options), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && (callbackContext.nodeType || callbackContext.jquery) ? jQuery(callbackContext) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function(key) { var match; if (state === 2) { if (!responseHeaders) { responseHeaders = {}; while ((match = rheaders.exec(responseHeadersString))) { responseHeaders[match[1].toLowerCase()] = match[2]; } } match = responseHeaders[key.toLowerCase()]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function(name, value) { var lname = name.toLowerCase(); if (!state) { name = requestHeadersNames[lname] = requestHeadersNames[lname] || name; requestHeaders[name] = value; } return this; }, // Overrides response content-type header overrideMimeType: function(type) { if (!state) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function(map) { var code; if (map) { if (state < 2) { for (code in map) { // Lazy-add the new callback in a way that preserves old ones statusCode[code] = [statusCode[code], map[code]]; } } else { // Execute the appropriate callbacks jqXHR.always(map[jqXHR.status]); } } return this; }, // Cancel the request abort: function(statusText) { var finalText = statusText || strAbort; if (transport) { transport.abort(finalText); } done(0, finalText); return this; } }; // Attach deferreds deferred.promise(jqXHR).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ((url || s.url || ajaxLocation) + "").replace(rhash, "").replace(rprotocol, ajaxLocParts[1] + "//"); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim(s.dataType || "*").toLowerCase().match(core_rnotwhite) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if (s.crossDomain == null) { parts = rurl.exec(s.url.toLowerCase()); s.crossDomain = !! (parts && (parts[1] !== ajaxLocParts[1] || parts[2] !== ajaxLocParts[2] || (parts[3] || (parts[1] === "http:" ? "80" : "443")) !== (ajaxLocParts[3] || (ajaxLocParts[1] === "http:" ? "80" : "443")))); } // Convert data if not already a string if (s.data && s.processData && typeof s.data !== "string") { s.data = jQuery.param(s.data, s.traditional); } // Apply prefilters inspectPrefiltersOrTransports(prefilters, s, options, jqXHR); // If request was aborted inside a prefilter, stop there if (state === 2) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if (fireGlobals && jQuery.active++ === 0) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test(s.type); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if (!s.hasContent) { // If data is available, append data to url if (s.data) { cacheURL = (s.url += (ajax_rquery.test(cacheURL) ? "&" : "?") + s.data); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if (s.cache === false) { s.url = rts.test(cacheURL) ? // If there is already a '_' parameter, set its value cacheURL.replace(rts, "$1_=" + ajax_nonce++) : // Otherwise add one to the end cacheURL + (ajax_rquery.test(cacheURL) ? "&" : "?") + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if (s.ifModified) { if (jQuery.lastModified[cacheURL]) { jqXHR.setRequestHeader("If-Modified-Since", jQuery.lastModified[cacheURL]); } if (jQuery.etag[cacheURL]) { jqXHR.setRequestHeader("If-None-Match", jQuery.etag[cacheURL]); } } // Set the correct header, if data is being sent if (s.data && s.hasContent && s.contentType !== false || options.contentType) { jqXHR.setRequestHeader("Content-Type", s.contentType); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader("Accept", s.dataTypes[0] && s.accepts[s.dataTypes[0]] ? s.accepts[s.dataTypes[0]] + (s.dataTypes[0] !== "*" ? ", " + allTypes + "; q=0.01" : "") : s.accepts["*"]); // Check for headers option for (i in s.headers) { jqXHR.setRequestHeader(i, s.headers[i]); } // Allow custom headers/mimetypes and early abort if (s.beforeSend && (s.beforeSend.call(callbackContext, jqXHR, s) === false || state === 2)) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for (i in { success: 1, error: 1, complete: 1 }) { jqXHR[i](s[i]); } // Get transport transport = inspectPrefiltersOrTransports(transports, s, options, jqXHR); // If no transport, we auto-abort if (!transport) { done(-1, "No Transport"); } else { jqXHR.readyState = 1; // Send global event if (fireGlobals) { globalEventContext.trigger("ajaxSend", [jqXHR, s]); } // Timeout if (s.async && s.timeout > 0) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout); } try { state = 1; transport.send(requestHeaders, done); } catch (e) { // Propagate exception as error if not done if (state < 2) { done(-1, e); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done(status, nativeStatusText, responses, headers) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if (state === 2) { return; } // State is "done" now state = 2; // Clear timeout if it exists if (timeoutTimer) { clearTimeout(timeoutTimer); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if (responses) { response = ajaxHandleResponses(s, jqXHR, responses); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert(s, response, jqXHR, isSuccess); // If successful, handle type chaining if (isSuccess) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if (s.ifModified) { modified = jqXHR.getResponseHeader("Last-Modified"); if (modified) { jQuery.lastModified[cacheURL] = modified; } modified = jqXHR.getResponseHeader("etag"); if (modified) { jQuery.etag[cacheURL] = modified; } } // if no content if (status === 204 || s.type === "HEAD") { statusText = "nocontent"; // if not modified } else if (status === 304) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if (status || !statusText) { statusText = "error"; if (status < 0) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = (nativeStatusText || statusText) + ""; // Success/Error if (isSuccess) { deferred.resolveWith(callbackContext, [success, statusText, jqXHR]); } else { deferred.rejectWith(callbackContext, [jqXHR, statusText, error]); } // Status-dependent callbacks jqXHR.statusCode(statusCode); statusCode = undefined; if (fireGlobals) { globalEventContext.trigger(isSuccess ? "ajaxSuccess" : "ajaxError", [jqXHR, s, isSuccess ? success : error]); } // Complete completeDeferred.fireWith(callbackContext, [jqXHR, statusText]); if (fireGlobals) { globalEventContext.trigger("ajaxComplete", [jqXHR, s]); // Handle the global AJAX counter if (!(--jQuery.active)) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function(url, data, callback) { return jQuery.get(url, data, callback, "json"); }, getScript: function(url, callback) { return jQuery.get(url, undefined, callback, "script"); } }); jQuery.each(["get", "post"], function(i, method) { jQuery[method] = function(url, data, callback, type) { // shift arguments if data argument was omitted if (jQuery.isFunction(data)) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses(s, jqXHR, responses) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while (dataTypes[0] === "*") { dataTypes.shift(); if (ct === undefined) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if (ct) { for (type in contents) { if (contents[type] && contents[type].test(ct)) { dataTypes.unshift(type); break; } } } // Check to see if we have a response for the expected dataType if (dataTypes[0] in responses) { finalDataType = dataTypes[0]; } else { // Try convertible dataTypes for (type in responses) { if (!dataTypes[0] || s.converters[type + " " + dataTypes[0]]) { finalDataType = type; break; } if (!firstDataType) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if (finalDataType) { if (finalDataType !== dataTypes[0]) { dataTypes.unshift(finalDataType); } return responses[finalDataType]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert(s, response, jqXHR, isSuccess) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if (dataTypes[1]) { for (conv in s.converters) { converters[conv.toLowerCase()] = s.converters[conv]; } } current = dataTypes.shift(); // Convert to each sequential dataType while (current) { if (s.responseFields[current]) { jqXHR[s.responseFields[current]] = response; } // Apply the dataFilter if provided if (!prev && isSuccess && s.dataFilter) { response = s.dataFilter(response, s.dataType); } prev = current; current = dataTypes.shift(); if (current) { // There's only work to do if current dataType is non-auto if (current === "*") { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if (prev !== "*" && prev !== current) { // Seek a direct converter conv = converters[prev + " " + current] || converters["* " + current]; // If none found, seek a pair if (!conv) { for (conv2 in converters) { // If conv2 outputs current tmp = conv2.split(" "); if (tmp[1] === current) { // If prev can be converted to accepted input conv = converters[prev + " " + tmp[0]] || converters["* " + tmp[0]]; if (conv) { // Condense equivalence converters if (conv === true) { conv = converters[conv2]; // Otherwise, insert the intermediate dataType } else if (converters[conv2] !== true) { current = tmp[0]; dataTypes.unshift(tmp[1]); } break; } } } } // Apply converter (if not an equivalence) if (conv !== true) { // Unless errors are allowed to bubble, catch and return them if (conv && s["throws"]) { response = conv(response); } else { try { response = conv(response); } catch (e) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function(text) { jQuery.globalEval(text); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter("script", function(s) { if (s.cache === undefined) { s.cache = false; } if (s.crossDomain) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport("script", function(s) { // This transport only deals with cross domain requests if (s.crossDomain) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function(_, callback) { script = document.createElement("script"); script.async = true; if (s.scriptCharset) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function(_, isAbort) { if (isAbort || !script.readyState || /loaded|complete/.test(script.readyState)) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if (script.parentNode) { script.parentNode.removeChild(script); } // Dereference the script script = null; // Callback if not abort if (!isAbort) { callback(200, "success"); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore(script, head.firstChild); }, abort: function() { if (script) { script.onload(undefined, true); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || (jQuery.expando + "_" + (ajax_nonce++)); this[callback] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter("json jsonp", function(s, originalSettings, jqXHR) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && (rjsonp.test(s.url) ? "url" : typeof s.data === "string" && !(s.contentType || "").indexOf("application/x-www-form-urlencoded") && rjsonp.test(s.data) && "data"); // Handle iff the expected data type is "jsonp" or we have a parameter to set if (jsonProp || s.dataTypes[0] === "jsonp") { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction(s.jsonpCallback) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if (jsonProp) { s[jsonProp] = s[jsonProp].replace(rjsonp, "$1" + callbackName); } else if (s.jsonp !== false) { s.url += (ajax_rquery.test(s.url) ? "&" : "?") + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if (!responseContainer) { jQuery.error(callbackName + " was not called"); } return responseContainer[0]; }; // force json dataType s.dataTypes[0] = "json"; // Install callback overwritten = window[callbackName]; window[callbackName] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[callbackName] = overwritten; // Save back as free if (s[callbackName]) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push(callbackName); } // Call if it was a function and we have a response if (responseContainer && jQuery.isFunction(overwritten)) { overwritten(responseContainer[0]); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for (key in xhrCallbacks) { xhrCallbacks[key](undefined, true); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch (e) {} } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !! xhrSupported && ("withCredentials" in xhrSupported); xhrSupported = jQuery.support.ajax = !! xhrSupported; // Create transport if the browser can provide an xhr if (xhrSupported) { jQuery.ajaxTransport(function(s) { // Cross domain only allowed if supported through XMLHttpRequest if (!s.crossDomain || jQuery.support.cors) { var callback; return { send: function(headers, complete) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if (s.username) { xhr.open(s.type, s.url, s.async, s.username, s.password); } else { xhr.open(s.type, s.url, s.async); } // Apply custom fields if provided if (s.xhrFields) { for (i in s.xhrFields) { xhr[i] = s.xhrFields[i]; } } // Override mime type if needed if (s.mimeType && xhr.overrideMimeType) { xhr.overrideMimeType(s.mimeType); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if (!s.crossDomain && !headers["X-Requested-With"]) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for (i in headers) { xhr.setRequestHeader(i, headers[i]); } } catch (err) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send((s.hasContent && s.data) || null); // Listener callback = function(_, isAbort) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if (callback && (isAbort || xhr.readyState === 4)) { // Only called once callback = undefined; // Do not keep as active anymore if (handle) { xhr.onreadystatechange = jQuery.noop; if (xhrOnUnloadAbort) { delete xhrCallbacks[handle]; } } // If it's an abort if (isAbort) { // Abort it manually if needed if (xhr.readyState !== 4) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if (typeof xhr.responseText === "string") { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch (e) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if (!status && s.isLocal && !s.crossDomain) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if (status === 1223) { status = 204; } } } } catch (firefoxAccessException) { if (!isAbort) { complete(-1, firefoxAccessException); } } // Call complete if needed if (responses) { complete(status, statusText, responses, responseHeaders); } }; if (!s.async) { // if we're in sync mode we fire the callback callback(); } else if (xhr.readyState === 4) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout(callback); } else { handle = ++xhrId; if (xhrOnUnloadAbort) { // Create the active xhrs callbacks list if needed // and attach the unload handler if (!xhrCallbacks) { xhrCallbacks = {}; jQuery(window).unload(xhrOnUnloadAbort); } // Add to list of active xhrs callbacks xhrCallbacks[handle] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if (callback) { callback(undefined, true); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp("^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i"), rrun = /queueHooks$/, animationPrefilters = [defaultPrefilter], tweeners = { "*": [function(prop, value) { var tween = this.createTween(prop, value), target = tween.cur(), parts = rfxnum.exec(value), unit = parts && parts[3] || (jQuery.cssNumber[prop] ? "" : "px"), // Starting value computation is required for potential unit mismatches start = (jQuery.cssNumber[prop] || unit !== "px" && +target) && rfxnum.exec(jQuery.css(tween.elem, prop)), scale = 1, maxIterations = 20; if (start && start[3] !== unit) { // Trust units reported by jQuery.css unit = unit || start[3]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style(tween.elem, prop, start + unit); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while (scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations); } // Update tween properties if (parts) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + (parts[1] + 1) * parts[2] : +parts[2]; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return (fxNow = jQuery.now()); } function createTween(value, prop, animation) { var tween, collection = (tweeners[prop] || []).concat(tweeners["*"]), index = 0, length = collection.length; for (; index < length; index++) { if ((tween = collection[index].call(animation, prop, value))) { // we're done with this property return tween; } } } function Animation(elem, properties, options) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always(function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if (stopped) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max(0, animation.startTime + animation.duration - currentTime), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for (; index < length; index++) { animation.tweens[index].run(percent); } deferred.notifyWith(elem, [animation, percent, remaining]); if (percent < 1 && length) { return remaining; } else { deferred.resolveWith(elem, [animation]); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend({}, properties), opts: jQuery.extend(true, { specialEasing: {} }, options), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function(prop, end) { var tween = jQuery.Tween(elem, animation.opts, prop, end, animation.opts.specialEasing[prop] || animation.opts.easing); animation.tweens.push(tween); return tween; }, stop: function(gotoEnd) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if (stopped) { return this; } stopped = true; for (; index < length; index++) { animation.tweens[index].run(1); } // resolve when we played the last frame // otherwise, reject if (gotoEnd) { deferred.resolveWith(elem, [animation, gotoEnd]); } else { deferred.rejectWith(elem, [animation, gotoEnd]); } return this; } }), props = animation.props; propFilter(props, animation.opts.specialEasing); for (; index < length; index++) { result = animationPrefilters[index].call(animation, elem, props, animation.opts); if (result) { return result; } } jQuery.map(props, createTween, animation); if (jQuery.isFunction(animation.opts.start)) { animation.opts.start.call(elem, animation); } jQuery.fx.timer( jQuery.extend(tick, { elem: elem, anim: animation, queue: animation.opts.queue })); // attach callbacks from options return animation.progress(animation.opts.progress) .done(animation.opts.done, animation.opts.complete) .fail(animation.opts.fail) .always(animation.opts.always); } function propFilter(props, specialEasing) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for (index in props) { name = jQuery.camelCase(index); easing = specialEasing[name]; value = props[index]; if (jQuery.isArray(value)) { easing = value[1]; value = props[index] = value[0]; } if (index !== name) { props[name] = value; delete props[index]; } hooks = jQuery.cssHooks[name]; if (hooks && "expand" in hooks) { value = hooks.expand(value); delete props[name]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for (index in value) { if (!(index in props)) { props[index] = value[index]; specialEasing[index] = easing; } } } else { specialEasing[name] = easing; } } } jQuery.Animation = jQuery.extend(Animation, { tweener: function(props, callback) { if (jQuery.isFunction(props)) { callback = props; props = ["*"]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for (; index < length; index++) { prop = props[index]; tweeners[prop] = tweeners[prop] || []; tweeners[prop].unshift(callback); } }, prefilter: function(callback, prepend) { if (prepend) { animationPrefilters.unshift(callback); } else { animationPrefilters.push(callback); } } }); function defaultPrefilter(elem, props, opts) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden(elem), dataShow = jQuery._data(elem, "fxshow"); // handle queue: false promises if (!opts.queue) { hooks = jQuery._queueHooks(elem, "fx"); if (hooks.unqueued == null) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if (!hooks.unqueued) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if (!jQuery.queue(elem, "fx").length) { hooks.empty.fire(); } }); }); } // height/width overflow pass if (elem.nodeType === 1 && ("height" in props || "width" in props)) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [style.overflow, style.overflowX, style.overflowY]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if (jQuery.css(elem, "display") === "inline" && jQuery.css(elem, "float") === "none") { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if (!jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay(elem.nodeName) === "inline") { style.display = "inline-block"; } else { style.zoom = 1; } } } if (opts.overflow) { style.overflow = "hidden"; if (!jQuery.support.shrinkWrapBlocks) { anim.always(function() { style.overflow = opts.overflow[0]; style.overflowX = opts.overflow[1]; style.overflowY = opts.overflow[2]; }); } } // show/hide pass for (prop in props) { value = props[prop]; if (rfxtypes.exec(value)) { delete props[prop]; toggle = toggle || value === "toggle"; if (value === (hidden ? "hide" : "show")) { continue; } orig[prop] = dataShow && dataShow[prop] || jQuery.style(elem, prop); } } if (!jQuery.isEmptyObject(orig)) { if (dataShow) { if ("hidden" in dataShow) { hidden = dataShow.hidden; } } else { dataShow = jQuery._data(elem, "fxshow", {}); } // store state if its toggle - enables .stop().toggle() to "reverse" if (toggle) { dataShow.hidden = !hidden; } if (hidden) { jQuery(elem).show(); } else { anim.done(function() { jQuery(elem).hide(); }); } anim.done(function() { var prop; jQuery._removeData(elem, "fxshow"); for (prop in orig) { jQuery.style(elem, prop, orig[prop]); } }); for (prop in orig) { tween = createTween(hidden ? dataShow[prop] : 0, prop, anim); if (!(prop in dataShow)) { dataShow[prop] = tween.start; if (hidden) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween(elem, options, prop, end, easing) { return new Tween.prototype.init(elem, options, prop, end, easing); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function(elem, options, prop, end, easing, unit) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || (jQuery.cssNumber[prop] ? "" : "px"); }, cur: function() { var hooks = Tween.propHooks[this.prop]; return hooks && hooks.get ? hooks.get(this) : Tween.propHooks._default.get(this); }, run: function(percent) { var eased, hooks = Tween.propHooks[this.prop]; if (this.options.duration) { this.pos = eased = jQuery.easing[this.easing]( percent, this.options.duration * percent, 0, 1, this.options.duration); } else { this.pos = eased = percent; } this.now = (this.end - this.start) * eased + this.start; if (this.options.step) { this.options.step.call(this.elem, this.now, this); } if (hooks && hooks.set) { hooks.set(this); } else { Tween.propHooks._default.set(this); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function(tween) { var result; if (tween.elem[tween.prop] != null && (!tween.elem.style || tween.elem.style[tween.prop] == null)) { return tween.elem[tween.prop]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css(tween.elem, tween.prop, ""); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function(tween) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if (jQuery.fx.step[tween.prop]) { jQuery.fx.step[tween.prop](tween); } else if (tween.elem.style && (tween.elem.style[jQuery.cssProps[tween.prop]] != null || jQuery.cssHooks[tween.prop])) { jQuery.style(tween.elem, tween.prop, tween.now + tween.unit); } else { tween.elem[tween.prop] = tween.now; } } } }; // Support: IE <=9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function(tween) { if (tween.elem.nodeType && tween.elem.parentNode) { tween.elem[tween.prop] = tween.now; } } }; jQuery.each(["toggle", "show", "hide"], function(i, name) { var cssFn = jQuery.fn[name]; jQuery.fn[name] = function(speed, easing, callback) { return speed == null || typeof speed === "boolean" ? cssFn.apply(this, arguments) : this.animate(genFx(name, true), speed, easing, callback); }; }); jQuery.fn.extend({ fadeTo: function(speed, to, easing, callback) { // show any hidden elements after setting opacity to 0 return this.filter(isHidden).css("opacity", 0).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback); }, animate: function(prop, speed, easing, callback) { var empty = jQuery.isEmptyObject(prop), optall = jQuery.speed(speed, easing, callback), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation(this, jQuery.extend({}, prop), optall); // Empty animations, or finishing resolves immediately if (empty || jQuery._data(this, "finish")) { anim.stop(true); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each(doAnimation) : this.queue(optall.queue, doAnimation); }, stop: function(type, clearQueue, gotoEnd) { var stopQueue = function(hooks) { var stop = hooks.stop; delete hooks.stop; stop(gotoEnd); }; if (typeof type !== "string") { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if (clearQueue && type !== false) { this.queue(type || "fx", []); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data(this); if (index) { if (data[index] && data[index].stop) { stopQueue(data[index]); } } else { for (index in data) { if (data[index] && data[index].stop && rrun.test(index)) { stopQueue(data[index]); } } } for (index = timers.length; index--;) { if (timers[index].elem === this && (type == null || timers[index].queue === type)) { timers[index].anim.stop(gotoEnd); dequeue = false; timers.splice(index, 1); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if (dequeue || !gotoEnd) { jQuery.dequeue(this, type); } }); }, finish: function(type) { if (type !== false) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data(this), queue = data[type + "queue"], hooks = data[type + "queueHooks"], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue(this, type, []); if (hooks && hooks.stop) { hooks.stop.call(this, true); } // look for any active animations, and finish them for (index = timers.length; index--;) { if (timers[index].elem === this && timers[index].queue === type) { timers[index].anim.stop(true); timers.splice(index, 1); } } // look for any animations in the old queue and finish them for (index = 0; index < length; index++) { if (queue[index] && queue[index].finish) { queue[index].finish.call(this); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx(type, includeWidth) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for (; i < 4; i += 2 - includeWidth) { which = cssExpand[i]; attrs["margin" + which] = attrs["padding" + which] = type; } if (includeWidth) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function(name, props) { jQuery.fn[name] = function(speed, easing, callback) { return this.animate(props, speed, easing, callback); }; }); jQuery.speed = function(speed, easing, fn) { var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : { complete: fn || !fn && easing || jQuery.isFunction(speed) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction(easing) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if (opt.queue == null || opt.queue === true) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if (jQuery.isFunction(opt.old)) { opt.old.call(this); } if (opt.queue) { jQuery.dequeue(this, opt.queue); } }; return opt; }; jQuery.easing = { linear: function(p) { return p; }, swing: function(p) { return 0.5 - Math.cos(p * Math.PI) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for (; i < timers.length; i++) { timer = timers[i]; // Checks the timer has not already been removed if (!timer() && timers[i] === timer) { timers.splice(i--, 1); } } if (!timers.length) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function(timer) { if (timer() && jQuery.timers.push(timer)) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if (!timerId) { timerId = setInterval(jQuery.fx.tick, jQuery.fx.interval); } }; jQuery.fx.stop = function() { clearInterval(timerId); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if (jQuery.expr && jQuery.expr.filters) { jQuery.expr.filters.animated = function(elem) { return jQuery.grep(jQuery.timers, function(fn) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function(options) { if (arguments.length) { return options === undefined ? this : this.each(function(i) { jQuery.offset.setOffset(this, options, i); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[0], doc = elem && elem.ownerDocument; if (!doc) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if (!jQuery.contains(docElem, elem)) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if (typeof elem.getBoundingClientRect !== core_strundefined) { box = elem.getBoundingClientRect(); } win = getWindow(doc); return { top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0), left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0) }; }; jQuery.offset = { setOffset: function(elem, options, i) { var position = jQuery.css(elem, "position"); // set position first, in-case top/left are set even on static elem if (position === "static") { elem.style.position = "relative"; } var curElem = jQuery(elem), curOffset = curElem.offset(), curCSSTop = jQuery.css(elem, "top"), curCSSLeft = jQuery.css(elem, "left"), calculatePosition = (position === "absolute" || position === "fixed") && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if (calculatePosition) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat(curCSSTop) || 0; curLeft = parseFloat(curCSSLeft) || 0; } if (jQuery.isFunction(options)) { options = options.call(elem, i, curOffset); } if (options.top != null) { props.top = (options.top - curOffset.top) + curTop; } if (options.left != null) { props.left = (options.left - curOffset.left) + curLeft; } if ("using" in options) { options.using.call(elem, props); } else { curElem.css(props); } } }; jQuery.fn.extend({ position: function() { if (!this[0]) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[0]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if (jQuery.css(elem, "position") === "fixed") { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if (!jQuery.nodeName(offsetParent[0], "html")) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css(offsetParent[0], "borderTopWidth", true); parentOffset.left += jQuery.css(offsetParent[0], "borderLeftWidth", true); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css(elem, "marginTop", true), left: offset.left - parentOffset.left - jQuery.css(elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while (offsetParent && (!jQuery.nodeName(offsetParent, "html") && jQuery.css(offsetParent, "position") === "static")) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each({ scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function(method, prop) { var top = /Y/.test(prop); jQuery.fn[method] = function(val) { return jQuery.access(this, function(elem, method, val) { var win = getWindow(elem); if (val === undefined) { return win ? (prop in win) ? win[prop] : win.document.documentElement[method] : elem[method]; } if (win) { win.scrollTo(!top ? val : jQuery(win).scrollLeft(), top ? val : jQuery(win).scrollTop()); } else { elem[method] = val; } }, method, val, arguments.length, null); }; }); function getWindow(elem) { return jQuery.isWindow(elem) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each({ Height: "height", Width: "width" }, function(name, type) { jQuery.each({ padding: "inner" + name, content: type, "": "outer" + name }, function(defaultExtra, funcName) { // margin is only for outerHeight, outerWidth jQuery.fn[funcName] = function(margin, value) { var chainable = arguments.length && (defaultExtra || typeof margin !== "boolean"), extra = defaultExtra || (margin === true || value === true ? "margin" : "border"); return jQuery.access(this, function(elem, type, value) { var doc; if (jQuery.isWindow(elem)) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement["client" + name]; } // Get document width or height if (elem.nodeType === 9) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body["scroll" + name], doc["scroll" + name], elem.body["offset" + name], doc["offset" + name], doc["client" + name]); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css(elem, type, extra) : // Set width or height on the element jQuery.style(elem, type, value, extra); }, type, chainable ? margin : undefined, chainable, null); }; }); }); // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if (typeof module === "object" && module && typeof module.exports === "object") { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Otherwise expose jQuery to the global object as usual window.jQuery = window.$ = jQuery; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if (typeof define === "function" && define.amd) { define("jquery", [], function() { return jQuery; }); } } })(window);
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><circle cx="16.5" cy="2.38" r="2" /><path d="M24 11.88v-4.7l-5.05-2.14c-.97-.41-2.09-.06-2.65.84l-1 1.6c-.67 1.18-1.91 2.06-3.41 2.32l.06.06c.69.69 1.52 1.07 2.46 1.17.8-.42 1.52-.98 2.09-1.64l.6 3-1.16 1.1-.94.89v7.5h2v-6l2.1-2 1.8 8H23l-2.18-11-.62-3.1 1.8.7v3.4h2zM10.29 8.09c.22.15.47.24.72.29.13.02.25.04.38.04s.26-.01.38-.04c.13-.02.25-.06.37-.11.24-.1.47-.24.66-.44.49-.49.67-1.17.55-1.8-.07-.37-.25-.74-.55-1.03-.19-.19-.42-.34-.66-.44-.12-.05-.24-.09-.37-.11s-.25-.04-.38-.04c-.12 0-.23.01-.35.03-.14.02-.28.06-.41.11-.23.11-.46.26-.65.45-.3.29-.48.66-.55 1.03-.12.63.06 1.31.55 1.8.09.1.2.18.31.26z" /><path d="M11.24 10.56l-2-2c-.1-.1-.2-.18-.31-.26-.22-.14-.47-.24-.72-.28-.13-.03-.25-.04-.38-.04-.51 0-1.02.2-1.41.59l-3.34 3.34c-.41.41-.62.98-.58 1.54 0 .18.04.37.11.55l1.07 2.95-3.63 3.63L1.46 22l4.24-4.24v-2.22L7 16.75v5.13h2v-6l-2.12-2.12 2.36-2.36.71.71c1.29 1.26 2.97 2.04 5.03 2.04l-.14-2.07c-1.5-.02-2.7-.62-3.6-1.52z" /></React.Fragment> , 'SportsKabaddiTwoTone');
const router = require('express').Router() const { users } = require('./users') const { todos } = require('./todos') router.use('/', users) router.use('/', todos) module.exports = { routes : router }
// All symbols in the Supplemental Arrows-B block as per Unicode v5.0.0: [ '\u2900', '\u2901', '\u2902', '\u2903', '\u2904', '\u2905', '\u2906', '\u2907', '\u2908', '\u2909', '\u290A', '\u290B', '\u290C', '\u290D', '\u290E', '\u290F', '\u2910', '\u2911', '\u2912', '\u2913', '\u2914', '\u2915', '\u2916', '\u2917', '\u2918', '\u2919', '\u291A', '\u291B', '\u291C', '\u291D', '\u291E', '\u291F', '\u2920', '\u2921', '\u2922', '\u2923', '\u2924', '\u2925', '\u2926', '\u2927', '\u2928', '\u2929', '\u292A', '\u292B', '\u292C', '\u292D', '\u292E', '\u292F', '\u2930', '\u2931', '\u2932', '\u2933', '\u2934', '\u2935', '\u2936', '\u2937', '\u2938', '\u2939', '\u293A', '\u293B', '\u293C', '\u293D', '\u293E', '\u293F', '\u2940', '\u2941', '\u2942', '\u2943', '\u2944', '\u2945', '\u2946', '\u2947', '\u2948', '\u2949', '\u294A', '\u294B', '\u294C', '\u294D', '\u294E', '\u294F', '\u2950', '\u2951', '\u2952', '\u2953', '\u2954', '\u2955', '\u2956', '\u2957', '\u2958', '\u2959', '\u295A', '\u295B', '\u295C', '\u295D', '\u295E', '\u295F', '\u2960', '\u2961', '\u2962', '\u2963', '\u2964', '\u2965', '\u2966', '\u2967', '\u2968', '\u2969', '\u296A', '\u296B', '\u296C', '\u296D', '\u296E', '\u296F', '\u2970', '\u2971', '\u2972', '\u2973', '\u2974', '\u2975', '\u2976', '\u2977', '\u2978', '\u2979', '\u297A', '\u297B', '\u297C', '\u297D', '\u297E', '\u297F' ];
import React, {Component, PropTypes} from 'react'; import moment from 'moment'; import theme from '../../Item/components/FieldsView.scss'; const tripHelps = { auto: 'Автомобиль', plane: 'Самолет', train: 'Поезд' }; export default class TripFields extends Component { static propTypes = { fields: PropTypes.object.isRequired }; render() { const {fields} = this.props; const startDate = moment(fields.startDate); const endDate = moment(fields.endDate); return ( <div className={theme.fields}> <h5>Основные сведения</h5> <table className={theme.table}> <tbody> <tr> <td className={theme.key}>Тип поездки:</td> <td className={theme.value}> <pre>{fields.tripType === 'trip' ? 'Командировка' : 'Служебная поездка'}</pre> </td> </tr> <tr> <td className={theme.key}>Период:</td> <td className={theme.value}> <pre>{startDate.format('DD.MM.YYYY')} - {endDate.format('DD.MM.YYYY')}</pre> </td> </tr> <tr> <td className={theme.key}>Сотрудники:</td> <td className={theme.value}> <pre> {Object.keys(fields.forUsers).map((key) => { return <span key={key}>{fields.forUsers[key].title}</span>; })} </pre> </td> </tr> <tr> <td className={theme.key}>Цель поездки:</td> <td className={theme.value}> <pre>{fields.target}</pre> </td> </tr> </tbody> </table> <h5>Местоназначение</h5> <table className={theme.table}> <tbody> <tr> <td className={theme.key}>Страна, город:</td> <td className={theme.value}><pre>{fields.country} {fields.city}</pre></td> </tr> <tr> <td className={theme.key}>Организация:</td> <td className={theme.value}><pre>{fields.company}</pre></td> </tr> <tr> <td className={theme.key}>Проезд туда:</td> <td className={theme.value}><pre>{tripHelps[fields.tripTo]}</pre></td> </tr> <tr> <td className={theme.key}>Проезд обратно:</td> <td className={theme.value}><pre>{tripHelps[fields.tripBack]}</pre></td> </tr> <tr> <td className={theme.key}>Другие расходы:</td> <td className={theme.value}><pre>{fields.otherExpenses}</pre></td> </tr> </tbody> </table> </div> ); } }
import React, { Component } from "react"; class PageHeader extends Component { render() { return ( <div> Page Header </div> ); } } export default PageHeader;
// Code borrowed from: // https://github.com/DockYard/ember-one-way-controls/blob/v2.0.0/addon/-private/dynamic-attribute-bindings.js import Mixin from '@ember/object/mixin'; export default Mixin.create({ attributeBindings: [], NON_ATTRIBUTE_BOUND_PROPS: ['class', 'classNames'], concatenatedProperties: ['NON_ATTRIBUTE_BOUND_PROPS'], _isKeyBoundToAttribute(key) { return ( this.NON_ATTRIBUTE_BOUND_PROPS.indexOf(key) === -1 && this.attributeBindings .indexOf(key) === -1 ); }, init() { this._super(...arguments); const newAttributeBindings = Object .keys(this.attrs) .filter(key => this._isKeyBoundToAttribute(key)); const attributeBindings = this.attributeBindings.concat(newAttributeBindings); this.setProperties({attributeBindings}); } });
var autoprefixer = require('autoprefixer'); var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); var InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); var WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin'); var getClientEnvironment = require('./env'); var paths = require('./paths'); // Webpack uses `publicPath` to determine where the app is being served from. // In development, we always serve from the root. This makes config easier. var publicPath = '/'; // `publicUrl` is just like `publicPath`, but we will provide it to our app // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript. // Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz. var publicUrl = ''; // Get environment variables to inject into our app. var env = getClientEnvironment(publicUrl); // This is the development configuration. // It is focused on developer experience and fast rebuilds. // The production configuration is different and lives in a separate file. module.exports = { // You may want 'eval' instead if you prefer to see the compiled output in DevTools. // See the discussion in https://github.com/facebookincubator/create-react-app/issues/343. devtool: 'cheap-module-source-map', // These are the "entry points" to our application. // This means they will be the "root" imports that are included in JS bundle. // The first two entry points enable "hot" CSS and auto-refreshes for JS. entry: [ // Include an alternative client for WebpackDevServer. A client's job is to // connect to WebpackDevServer by a socket and get notified about changes. // When you save a file, the client will either apply hot updates (in case // of CSS changes), or refresh the page (in case of JS changes). When you // make a syntax error, this client will display a syntax error overlay. // Note: instead of the default WebpackDevServer client, we use a custom one // to bring better experience for Create React App users. You can replace // the line below with these two lines if you prefer the stock client: // require.resolve('webpack-dev-server/client') + '?/', // require.resolve('webpack/hot/dev-server'), require.resolve('react-dev-utils/webpackHotDevClient'), // We ship a few polyfills by default: require.resolve('./polyfills'), // Finally, this is your app's code: paths.appIndexJs // We include the app code last so that if there is a runtime error during // initialization, it doesn't blow up the WebpackDevServer client, and // changing JS code would still trigger a refresh. ], output: { // Next line is not used in dev but WebpackDevServer crashes without it: path: paths.appBuild, // Add /* filename */ comments to generated require()s in the output. pathinfo: true, // This does not produce a real file. It's just the virtual path that is // served by WebpackDevServer in development. This is the JS bundle // containing code from all our entry points, and the Webpack runtime. filename: 'static/js/bundle.js', // This is the URL that app is served from. We use "/" in development. publicPath: publicPath }, resolve: { // This allows you to set a fallback for where Webpack should look for modules. // We read `NODE_PATH` environment variable in `paths.js` and pass paths here. // We use `fallback` instead of `root` because we want `node_modules` to "win" // if there any conflicts. This matches Node resolution mechanism. // https://github.com/facebookincubator/create-react-app/issues/253 fallback: paths.nodePaths, // These are the reasonable defaults supported by the Node ecosystem. // We also include JSX as a common component filename extension to support // some tools, although we do not recommend using it, see: // https://github.com/facebookincubator/create-react-app/issues/290 extensions: ['.js', '.json', '.jsx', ''], alias: { // Support React Native Web // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ 'react-native': 'react-native-web' } }, module: { // First, run the linter. // It's important to do this before Babel processes the JS. preLoaders: [ { test: /\.(js|jsx)$/, loader: 'eslint', include: paths.appSrc, } ], loaders: [ // Default loader: load all assets that are not handled // by other loaders with the url loader. // Note: This list needs to be updated with every change of extensions // the other loaders match. // E.g., when adding a loader for a new supported file extension, // we need to add the supported extension to this loader too. // Add one new line in `exclude` for each loader. // // "file" loader makes sure those assets get served by WebpackDevServer. // When you `import` an asset, you get its (virtual) filename. // In production, they would get copied to the `build` folder. // "url" loader works like "file" loader except that it embeds assets // smaller than specified limit in bytes as data URLs to avoid requests. // A missing `test` is equivalent to a match. { exclude: [ /\.html$/, /\.(js|jsx)$/, /\.(css|scss)$/, /\.json$/, /\.svg$/ ], loader: 'url', query: { limit: 10000, name: 'static/media/[name].[hash:8].[ext]' } }, // Process JS with Babel. { test: /\.(js|jsx)$/, include: paths.appSrc, loader: 'babel', query: { // This is a feature of `babel-loader` for webpack (not Babel itself). // It enables caching results in ./node_modules/.cache/babel-loader/ // directory for faster rebuilds. cacheDirectory: true } }, { test: /\.scss$/, include: paths.appSrc, loaders: ["style", "css", "sass"] }, // "postcss" loader applies autoprefixer to our CSS. // "css" loader resolves paths in CSS and adds assets as dependencies. // "style" loader turns CSS into JS modules that inject <style> tags. // In production, we use a plugin to extract that CSS to a file, but // in development "style" loader enables hot editing of CSS. { test: /\.css$/, loader: 'style!css?importLoaders=1!postcss' }, // JSON is not enabled by default in Webpack but both Node and Browserify // allow it implicitly so we also enable it. { test: /\.json$/, loader: 'json' }, // "file" loader for svg { test: /\.svg$/, loader: 'file', query: { name: 'static/media/[name].[hash:8].[ext]' } } ] }, // We use PostCSS for autoprefixing only. postcss: function() { return [ autoprefixer({ browsers: [ '>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9', // React doesn't support IE8 anyway ] }), ]; }, plugins: [ new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" }), // Makes the public URL available as %PUBLIC_URL% in index.html, e.g.: // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> // In development, this will be an empty string. new InterpolateHtmlPlugin({ PUBLIC_URL: publicUrl }), // Generates an `index.html` file with the <script> injected. new HtmlWebpackPlugin({ inject: true, template: paths.appHtml, }), // Makes some environment variables available to the JS code, for example: // if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`. new webpack.DefinePlugin(env), // This is necessary to emit hot updates (currently CSS only): new webpack.HotModuleReplacementPlugin(), // Watcher doesn't work well if you mistype casing in a path so we use // a plugin that prints an error when you attempt to do this. // See https://github.com/facebookincubator/create-react-app/issues/240 new CaseSensitivePathsPlugin(), // If you require a missing module and then `npm install` it, you still have // to restart the development server for Webpack to discover it. This plugin // makes the discovery automatic so you don't have to restart. // See https://github.com/facebookincubator/create-react-app/issues/186 new WatchMissingNodeModulesPlugin(paths.appNodeModules) ], // Some libraries import Node modules but don't use them in the browser. // Tell Webpack to provide empty mocks for them so importing them works. node: { fs: 'empty', net: 'empty', tls: 'empty' } };
angular .module('sectorWeb.ctrl.reports', []) .controller('reportsCtrl', [ '$scope', '$location', 'reportsService', '$routeParams', function ($scope, $location, reportsService, $routeParams) { $scope.list = []; $scope.searchText = $routeParams.param ? $routeParams.param: ""; $scope.refresh = function () { $scope.list = []; reportsService.list() .then(function successCallback(response) { $scope.list = response.data; }); }; $scope.search = function () { if ($scope.searchText.length >= 3) { $scope.go("/reports/" + $scope.searchText); } } $scope.refresh(); }]);
var pins={}; module.exports={ setup:function(pin, direction, callback){ pins[pin]={value:0, direction:direction}; callback(null); }, read:function(pin, callback){ callback(null, pins[pin].value); }, write:function(pin, value, callback){ pins[pin].value=value; callback(null); } }
(function() { $(function() { $.getHash = function(url) { if (url) { return url.substring(url.indexOf("#") + 1); } else { return window.location.hash; } }; /* ```javascript unless Modernizr.input.placeholder $("input").each -> $(this).placeholder() unless $(this).attr("placeholder") is "" ``` */ $.fn.placeholder = function() { var emptyMe, fullMe; $(this).data("placeholder", $(this).attr("placeholder")); $(this).val(jQuery(this).attr("placeholder")); emptyMe = function() { $(this).data("placeholder", $(this).val()); return $(this).val(""); }; fullMe = function() { if ($(this).val() === "") { return $(this).val($(this).data("placeholder")); } }; $(this).on("focus", emptyMe); $(this).on("blur", fullMe); return $(this); }; $.fn.hoverSrc = function(on_, off_) { var hoverIn, hoverOut, suffixeOff, suffixeOn; suffixeOn = (on_ ? on_ : "-hover"); suffixeOff = (off_ ? off_ : "-off"); hoverIn = function() { var srcName; if (!$(this).hasClass("active")) { srcName = $(this).attr("src"); srcName = srcName.replace(suffixeOff, suffixeOn); return $(this).attr({ src: srcName }); } }; hoverOut = function() { var srcName; if (!$(this).hasClass("active")) { srcName = $(this).attr("src"); srcName = srcName.replace(suffixeOn, suffixeOff); return $(this).attr({ src: srcName }); } }; $(this).each(function() { $(this).bind("focus mouseenter", hoverIn); $(this).bind("blur mouseleave", hoverOut); return (new Image()).src = $(this).attr("src").replace("-off", "-hover"); }); return $(this); }; $.fn.fixToTop = function(gap, steps) { var $that, fix, free, offSet, origin, originOffSet, step, stepsClasses; $that = $(this); origin = (gap ? $that[0].offsetTop + gap : $that[0].offsetTop); originOffSet = parseFloat($that.next().css("marginTop")); offSet = parseFloat($that.height()) + parseFloat($that.next().css("marginTop")); /* If steps option is found, listen to scroll to set classes for each step ```JavaScript steps: "className": offsetValue ``` */ if (steps) { stepsClasses = ""; for (step in steps) { stepsClasses += ' ' + step; } $(window).scroll(function() { var _results; _results = []; for (step in steps) { if ($that.css("visibility") !== "hidden" && $(window).scrollTop() > steps[step]) { _results.push($that.removeClass(stepsClasses).addClass(step)); } else { _results.push(void 0); } } return _results; }); } $(window).scroll(function() { if ($that.css("visibility") !== "hidden" && $(window).scrollTop() > origin) { return fix(); } else { return free(); } }); fix = function() { if (!$that.hasClass("fixed")) { offSet = parseFloat($that.height()) + parseFloat($that.next().css("marginTop")); $that.addClass("fixed"); return $that.next().css("marginTop", offSet + "px"); } }; free = function() { $that.removeClass("fixed"); return $that.next().css("marginTop", originOffSet + "px"); }; return $(this); }; $.fn.pulldown = function() { var $buttons, $items, $list; $list = $(this); $items = $list.children(); $buttons = $items.find("> *:first-child"); $items.addClass("close"); $buttons.addClass("pulldownButton"); $buttons.unbind(" click"); $buttons.bind("click", function(e) { return e.preventDefault(); }); $items.children().not($buttons).addClass("pulldownContent"); $items.data("state", 0); $items.on("click", function(e) { var $item; e.preventDefault(); $item = $(this); if ($item.data("state")) { return $item.data("state", 0).addClass("close"); } else { $item.data("state", 1).removeClass("close"); return $items.not($item).data("state", 0).addClass("close"); } }); $list.data("pulldown", 1); return $(this); }; $.fn.backToTop = function(gap) { var $that; $that = $(this); gap = (gap ? gap : 0); $(this).off("click"); $(this).on("click", function(e) { e.preventDefault(); return $("html").scrollTo(0, { duration: 800 }); }); $(this).off("backToTop.scroll"); $(this).on("backToTop.scroll", function() { if ($(window).scrollTop() >= gap) { return $that.fadeIn(); } else { return $that.fadeOut(); } }); if (!$(this).data("backToTop")) { $(window).scroll(function() { return $that.trigger("backToTop.scroll"); }); } $(this).data("backToTop", 1); return $(this); }; return $.fn.smoothAnchors = function(offsetTop, screenOffset) { var $anchors, anchorsOffsets, anchorsOffsetsLength, lastExecution, timeWindow; $anchors = $(this).find("a[href*=\"#c\"]"); anchorsOffsets = []; offsetTop = (offsetTop ? offsetTop : 50); screenOffset = (screenOffset ? screenOffset : $(window).height() / 6); $anchors.each(function() { return anchorsOffsets.push($("#" + $.getHash($(this).attr("href"))).offset().top); }); anchorsOffsetsLength = anchorsOffsets.length; $anchors.unbind("click"); $anchors.click(function(e) { e.preventDefault(); return $("html").scrollTo($("#" + $.getHash($(this).attr("href"))), { offset: { top: -offsetTop }, duration: 800 }); }); timeWindow = 500; lastExecution = new Date((new Date()).getTime()); $(window).scroll(function(e) { var i, j, scrollTop; if ((lastExecution.getTime() + timeWindow) <= (new Date()).getTime()) { scrollTop = $(window).scrollTop() + offsetTop + screenOffset; $anchors.removeClass("active"); i = 0; while (i < anchorsOffsetsLength) { j = i + 1; if (scrollTop >= anchorsOffsets[i] && !anchorsOffsets[j]) { $anchors.not($anchors[i]).removeClass("active"); $($anchors[i]).addClass("active"); lastExecution = new Date((new Date()).getTime()); return; } else if (scrollTop >= anchorsOffsets[i] && scrollTop < anchorsOffsets[j]) { $anchors.not($anchors[i]).removeClass("active"); $($anchors[i]).addClass("active"); lastExecution = new Date((new Date()).getTime()); return; } i++; } } }); return $(this); }; }); }).call(this); //# sourceMappingURL=base.js.map
'use strict'; /** * @ngdoc function * @name anyandgoApp.controller:MemosNewCtrl * @description * # MemosNewCtrl * Controller of the anyandgoApp */ angular.module('anyandgoApp') .controller('MemosNewCtrl', function ($scope, $routeParams, PeopleService, $interval) { if(typeof chatInterval !== 'undefined') { //Cancel it $interval.cancel(chatInterval); } var CKupdate = function(){ var instance; for(instance in CKEDITOR.instances) { CKEDITOR.instances[instance].updateElement(); } CKEDITOR.instances[instance].setData(''); } $scope.usersto = {}; var configS2 = { placeholder: "Destinatarios...", ajax: { url : '/services/search/people/tags', dataType: 'json', quietMillis: 250, data: function (term, page) { return { keyword: term }; }, results: function (data, page) { console.log(data); return { results: data }; }, cache: true }, tags:[], //minimumInputLength: 3, id: function(data){ return data._id; }, dropdownCssClass: "bigdrop", initSelection: function(element, callback) { //console.log(element, callback); callback(data); }, formatSelection: function(data) { return data.name; }, formatResult: function(data) { var markup = '<div class="row-fluid">'; markup += data.name + " - " + data.email; markup += '</div>'; return markup; } }; var usuario = $('#usuarios'); usuario.select2(configS2); usuario.on('select2-selecting', function(e) { //console.log(e); }); // https://github.com/lemonde/angular-ckeditor //$('#message').wysihtml5(); // Editor options. $scope.options = { language: 'en', allowedContent: true, entities: false }; // Called when the editor is completely ready. $scope.onReady = function () { // ... }; $scope.sendMemo = function (e) { e.preventDefault(); e.stopPropagation(); // You cannot use double binding with hidden field. // http://stackoverflow.com/questions/18446359/angularjs-does-not-send-hidden-field-value PeopleService.sendMemo($('#usuarios').val(), $scope.memocontent).then(function(r){ // console.log(r.data); // Clear the form CKupdate(); $('#usuarios').select2('data',null); }); }; });
var Type = require("@kaoscript/runtime").Type; module.exports = function() { var __ks_Foobar = {}; __ks_Foobar.__ks_func_foobar_0 = function() { }; __ks_Foobar._im_foobar = function(that) { var args = Array.prototype.slice.call(arguments, 1, arguments.length); if(args.length === 0) { return __ks_Foobar.__ks_func_foobar_0.apply(that); } throw new SyntaxError("Wrong number of arguments"); }; function foo(x) { if(arguments.length < 1) { throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 1)"); } if(x === void 0 || x === null) { throw new TypeError("'x' is not nullable"); } else if(!Type.isBoolean(x)) { throw new TypeError("'x' is not of type 'Boolean'"); } let y = null; y = bar(); if(y !== null) { __ks_Foobar._im_foobar(y); } } function bar() { } };
const compose = require('koa-compose') const helmet = require('koa-helmet') const cors = require('kcors') const compress = require('koa-compress') const bodyParser = require('koa-bodyparser') const handleErrors = require('./errors') const middlewares = () => compose([ handleErrors(), // handle thrown or uncaught exceptions anywhere down the line helmet(), // reset HTTP headers (e.g. remove x-powered-by) cors(), // allow cross-origin compress({}), // HTTP compression bodyParser() // parse request body into ctx.request.body ]) module.exports = middlewares
'use strict'; const commonTags = require('common-tags'); const prepareFilenameToContentMap = require('../lib/prepare_filename_to_content_map'); describe('prepareFilenameToContentMap()', () => { it('should return a map with file name to file contents', () => { const filepaths = ['./path1/slide1.md', './path2/slide2.md']; const fileToContents = { './path1/slide1.md': 'Slide 1 contents', './path2/slide2.md': 'Slide 2 contents' }; function read(path) { return fileToContents[path]; } const result = prepareFilenameToContentMap(filepaths, read); expect(result.get('slide1')).not.toBeUndefined(); expect(result.get('slide2')).not.toBeUndefined(); }); it('should keep the given path in case slideResolutionFullPath is given as option', () => { const filepaths = ['./path1/slide1.md', './path2/slide2.md']; const fileToContents = { './path1/slide1.md': 'Slide 1 contents', './path2/slide2.md': 'Slide 2 contents' }; const options = { slideResolutionFullPath: true }; function read(path) { return fileToContents[path]; } const result = prepareFilenameToContentMap(filepaths, read, options); expect(result.get('./path1/slide1')).not.toBeUndefined(); expect(result.get('./path2/slide2')).not.toBeUndefined(); }); it('should return an object with a data and an attribute property as contents', () => { const filepaths = ['./path1/slide1.md', './path2/slide2.md']; const fileToContents = { './path1/slide1.md': 'Slide 1 contents', './path2/slide2.md': 'Slide 2 contents' }; function read(path) { return fileToContents[path]; } const result = prepareFilenameToContentMap(filepaths, read); // We have no sections, front matter or options.layoutAttributes -> data only has a section with content expect(result.get('slide1').data).toEqual({filename: 'slide1', sections: {content: 'Slide 1 contents'}}); // We have no front matter -> empty attributes expect(result.get('slide1').attributes).toEqual({}); expect(result.get('slide2').data).toEqual({filename: 'slide2', sections: {content: 'Slide 2 contents'}}); expect(result.get('slide2').attributes).toEqual({}); }); it('should contain front matter attributes in the data and attributes properties', () => { const filepaths = ['./path1/slide1.md', './path2/slide2.md']; const slide1Contents = commonTags.stripIndents`--- title: Slide 1 --- Contents of slide 1`; const slide2Contents = commonTags.stripIndents`--- title: Slide 2 --- Contents of slide 2`; const fileToContents = { './path1/slide1.md': slide1Contents, './path2/slide2.md': slide2Contents }; function read(path) { return fileToContents[path]; } const result = prepareFilenameToContentMap(filepaths, read); expect(result.get('slide1').data.title).toEqual('Slide 1'); expect(result.get('slide1').attributes).toEqual({title: 'Slide 1'}); expect(result.get('slide2').data.title).toEqual('Slide 2'); expect(result.get('slide2').attributes).toEqual({title: 'Slide 2'}); }); it('should override attributes in options.layoutAttributes which have the same name as attributes in the front matter (only in the data property)', () => { const filepaths = ['./path1/slide1.md', './path2/slide2.md']; const slide1Contents = commonTags.stripIndents`--- slideTitle: Slide 1 --- Contents of slide 1`; const slide2Contents = commonTags.stripIndents`--- title: Slide 2 --- Contents of slide 2`; const fileToContents = { './path1/slide1.md': slide1Contents, './path2/slide2.md': slide2Contents }; const options = { layoutAttributes: { title: 'Title for all slides' } }; function read(path) { return fileToContents[path]; } const result = prepareFilenameToContentMap(filepaths, read, options); expect(result.get('slide1').data.title).toEqual('Title for all slides'); expect(result.get('slide1').data.slideTitle).toEqual('Slide 1'); expect(result.get('slide1').attributes).toEqual({slideTitle: 'Slide 1'}); expect(result.get('slide2').data.title).toEqual('Slide 2'); expect(result.get('slide2').attributes).toEqual({title: 'Slide 2'}); }); it('should have a sections property in the data with all slide sections', () => { const filepaths = ['./path1/slide1.md']; const slide1Contents = commonTags.stripIndents`--- title: Slide 1 --- ---section1--- Contents of slide 1 section 1 ---section2--- Contents of slide 1 section 2 `; const fileToContents = { './path1/slide1.md': slide1Contents }; function read(path) { return fileToContents[path]; } const result = prepareFilenameToContentMap(filepaths, read); expect(result.get('slide1').data.sections.section1).toBe('\nContents of slide 1 section 1\n\n'); expect(result.get('slide1').data.sections.section2).toBe('\nContents of slide 1 section 2'); }); });
import CharacterNav from './CharacterNav' export default CharacterNav
module.exports = { invokeCallback: function (callback, error, result) { return (this.isFunction(callback)) ? callback(error, result) : null; }, isFunction: function (f) { return f && typeof f === 'function'; } };
/*global chart $*/ var requestsAll; var colorPattern = ['#003d66', '#4d004d', '#00ccff']; $(document).ready(function() { var max; var dates = ['x']; var theDate = new Date(); for (var i = 0; i < 7; i++) { theDate = new Date(new Date().setDate(new Date().getDate()-i)); dates.push( theDate.getFullYear()+'-'+(theDate.getMonth()+1)+'-'+theDate.getDate()); } requestsAll = c3.generate({ bindto: '#requests-all', size: { height: 250 }, data: { x: 'x', columns: [ dates, ['total', 0, 0, 0, 0, 0, 0, 0, 0], ['wishlist', 0, 0, 0, 0, 0, 0, 0, 0], ['requests', 0, 0, 0, 0, 0, 0, 0, 0] ], type: 'bar', names: { total: 'Total', requests: 'Requests', wishlist: 'Wishlists' } }, axis: { x: { type: 'timeseries', tick: { format: '%b %e' } }, y: { show: true } }, color: { pattern: colorPattern }, legend: { show: true } }); }); var updateCharts = function(data) { requestsAll.load({ json: data, keys: { value: ['x', 'total', 'wishlist', 'requests'] } }); }; var loadChart = function(){ var current_url_data = window.location.pathname.split('/'); var id = current_url_data[2]; var startDate = $('#start-date').val(); var endDate = $('#end-date').val(); var url = '/teachers/' + id + '/retrieve_charts_data'; $.ajax({ type: 'get', url: url, data: {}, success: function(data) { placeCorrectCharts(data); } }); }; var placeCorrectCharts = function(data) { updateCharts(data.result); max = data.max; }
/*! * js-file-browser * Copyright(c) 2011 Biotechnology Computing Facility, University of Arizona. See included LICENSE.txt file. * * With components from: Ext JS Library 3.3.1 * Copyright(c) 2006-2010 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ /*! * Ext JS Library 3.3.1 * Copyright(c) 2006-2010 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ /* This file is automaticly generated by create_language_js.py */ // some data used in the examples Ext.namespace('Ext.exampledata'); // TODO: complete and sort the list Ext.exampledata.languages = [ ['af', 'Afrikaans', 'ISO-8859-2'], ['bg', 'Bulgarian', 'utf-8'], ['ca', 'Catalonian', 'ascii'], ['hr', 'Croatian', 'utf-8'], ['cs', 'Czech', 'utf-8'], ['da', 'Danish', 'utf-8'], ['nl', 'Dutch', 'ascii'], ['en', 'English', 'ascii'], ['en_UK', 'English (UK)', 'ascii'], ['fa', 'Farsi (Persian)', 'utf-8'], ['fr_CA', 'France (Canadian)', 'UTF-8'], ['fr', 'France (France)', 'UTF-8'], ['de', 'German', 'utf-8'], ['el_GR', 'Greek', 'utf-8'], ['gr', 'Greek (Old Version)', 'utf-8'], ['he', 'Hebrew', 'windows-1255'], ['hu', 'Hungarian', 'utf-8'], ['id', 'Indonesian', 'ascii'], ['it', 'Italian', 'ascii'], ['ja', 'Japanese', 'utf-8'], ['ko', 'Korean', 'utf-8'], ['lv', 'Latvian', 'utf-8'], ['lt', 'Lithuanian', 'utf-8'], ['mk', 'Macedonia', 'utf-8'], ['no', 'Norwegian', 'utf-8'], ['pl', 'Polish', 'utf-8'], ['pt_BR', 'Portuguese/Brazil', 'ascii'], ['ro', 'Romanian', 'utf-8'], ['ru', 'Russian', 'UTF-8'], ['sr_RS', 'Serbian Cyrillic', 'UTF-8'], ['sr', 'Serbian Latin', 'utf-8'], ['zh_CN', 'Simplified Chinese', 'utf-8'], ['sk', 'Slovak', 'utf-8'], ['sl', 'Slovenian', 'utf-8'], ['es', 'Spanish/Latin American', 'utf-8'], ['sv_SE', 'Swedish', 'utf-8'], ['th', 'Thailand', 'utf-8'], ['zh_TW', 'Traditional Chinese', 'UTF-8'], ['tr', 'Turkish', 'utf-8'], ['ukr', 'Ukrainian', 'UTF-8'], ['vn', 'Vietnamese', 'UTF-8'] ];
var group__freemaster__demo = [ [ "FreeMASTER Demo Introduction", "group__freemaster__demo__introduction.html", "group__freemaster__demo__introduction" ], [ "FreeMASTER Demo User's Guide", "group__freemaster__demo__user__guide.html", "group__freemaster__demo__user__guide" ] ];
var wru = require('wru'); var collection = []; var functions = require('./..'); var setBit = functions.setBit; var resetBit = functions.resetBit; var isSetBit = functions.isSetBit; var toggleBit = functions.toggleBit; var result; collection[collection.length] = function() { var bitMask = 5; // 1 + 0 + 4 wru.assert("setBit test 1", setBit(bitMask, 2) === 7); wru.assert("setBit test 2", setBit(bitMask, 4) === 5); }; collection[collection.length] = function() { var bitMask = 5; // 1 + 0 + 4 wru.assert("resetBit test 1", resetBit(bitMask, 2) === 5); wru.assert("resetBit test 2", resetBit(bitMask, 4) === 1); }; collection[collection.length] = function() { var bitMask = 5; // 1 + 0 + 4 wru.assert("isSetBit test 1", isSetBit(bitMask, 2) === false); wru.assert("isSetBit test 2", isSetBit(bitMask, 4) === true); }; collection[collection.length] = function() { var bitMask = 5; // 1 + 0 + 4 wru.assert("toggleBit test 1", toggleBit(bitMask, 2) == 7); wru.assert("toggleBit test 2", toggleBit(bitMask, 4) == 1); }; wru.test(collection);
const squads = (state = [], action) => { return state; } export default squads;
PageModule.controller('PageFormController', function PageFormController($scope, $http, $q) { /** * * @type {String} */ var rootUrl = ''; /** * * @returns {void} */ $scope.generateSlug = function() { var pageHeader = $('#Page_header').val(); $http({ method: 'GET', url: rootUrl + '/generateSlug?header=' + pageHeader, }).success(function(data) { $('#Page_route').val(data); }); }; /** * * @returns {void} */ $scope.generateKeywords = function() { console.log('asdasdasd'); var pageContent = $('#Page_content').val(); $http({ method: 'POST', url: rootUrl + '/generateKeywords', data: $.param({content: pageContent}), headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } }).success(function(data) { $('#Page_meta_keywords').val(data); }); }; /** * * @returns {void} */ $scope.generateDescription = function() { console.log('asdasdasd'); var pageContent = $('#Page_description').val(); $('#Page_meta_description').val(pageContent); }; /** * * @returns {void} */ $scope.generateTitle = function() { var pageContent = $('#Page_header').val(); $('#Page_meta_title').val(pageContent); }; /** * * @param {String} url * @returns {void} */ $scope.init = function(url) { rootUrl = url; }; });
import 'babel-polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import {Router, Route, browserHistory} from 'react-router'; import injectTapEventPlugin from 'react-tap-event-plugin'; import {Main} from './app/main'; import './index.less'; // Needed for onTouchTap // http://stackoverflow.com/a/34015469/988941 injectTapEventPlugin(); ReactDOM.render( <Router history={browserHistory}> <Route path="/" component={Main}/> </Router>, document.getElementById('root') );
(function() { if (!window.JHVH) window.JHVH = {}; // need to keep for keeping calculating svg path to fit all sizes var ORIGIN_WIDTH = 559; var ORIGIN_HEIGHT = 100; var RATIO_W = ORIGIN_WIDTH / ORIGIN_HEIGHT; var RATIO_H = ORIGIN_HEIGHT / ORIGIN_WIDTH; var TEMP_WIDTH = ORIGIN_WIDTH; var TEMP_HEIGHT = TEMP_WIDTH * RATIO_H; var SCALEX = ORIGIN_WIDTH / TEMP_WIDTH; var SCALEY = ORIGIN_HEIGHT / TEMP_HEIGHT; var ON_COLOR = '#39b54a'; var RED_COLOR = '#830303'; var OFF_COLOR = '#120d09'; var paths = { topLine: { offsetX: 0, offsetY: 0, color: ON_COLOR, path: 'M23.000,26.000 C23.000,26.000 23.000,28.000 23.000,28.000 C23.000,28.000 248.000,28.000 248.000,28.000 C248.000,28.000 248.000,26.000 248.000,26.000 C248.000,26.000 23.000,26.000 23.000,26.000 Z' }, bottomLine: { offsetX: 0, offsetY: 0, color: ON_COLOR, path: 'M65.000,31.000 C65.000,31.000 207.000,31.000 207.000,31.000 C207.000,31.000 202.000,38.000 202.000,38.000 C202.000,38.000 71.000,38.000 71.000,38.000 C71.000,38.000 65.000,31.000 65.000,31.000 Z' }, tempIcon: { offsetX: 0, offsetY: 0, color: ON_COLOR, path: 'M264.557,0.966 C264.557,0.966 264.525,0.000 265.656,0.000 C266.788,0.000 266.756,0.828 266.756,0.828 C266.756,0.828 266.756,2.761 266.756,2.761 C266.756,2.761 271.153,2.761 271.153,2.761 C271.153,2.761 271.153,4.418 271.153,4.418 C271.153,4.418 266.756,4.418 266.756,4.418 C266.756,4.418 266.756,5.799 266.756,5.799 C266.756,5.799 271.153,5.799 271.153,5.799 C271.153,5.799 271.153,7.456 271.153,7.456 C271.153,7.456 266.756,7.456 266.756,7.456 C266.756,7.456 266.756,8.837 266.756,8.837 C266.756,8.837 271.153,8.837 271.153,8.837 C271.153,8.837 271.153,10.493 271.153,10.493 C271.153,10.493 267.443,10.493 267.443,10.493 C267.443,10.493 267.443,13.945 267.443,13.945 C267.443,13.945 266.399,14.619 265.794,14.083 C265.316,13.842 264.557,13.669 264.557,13.669 C264.557,13.669 264.557,0.966 264.557,0.966 Z' }, tempIconWater: { offsetX: 0, offsetY: 0, color: ON_COLOR, path: 'M258.237,14.866 C258.237,14.866 258.507,14.636 259.093,14.636 C260.108,14.636 260.395,15.357 261.417,15.357 C262.438,15.357 262.960,14.636 263.878,14.636 C264.796,14.636 265.571,15.341 266.309,15.341 C267.048,15.341 267.604,14.774 268.648,14.774 C269.692,14.774 270.485,15.341 271.217,15.341 C272.231,15.341 272.388,14.620 273.281,14.620 C274.175,14.620 274.137,15.004 274.137,15.004 C274.137,15.004 274.137,16.507 274.137,16.507 C274.137,16.507 273.904,16.154 273.281,16.154 C272.565,16.154 272.357,16.998 271.095,16.998 C269.832,16.998 269.629,16.139 268.618,16.139 C267.608,16.139 267.244,16.998 266.309,16.998 C265.219,16.998 264.747,16.154 263.970,16.154 C263.068,16.154 262.499,16.983 261.524,16.983 C260.549,16.983 259.995,16.124 259.215,16.124 C258.435,16.124 258.237,16.507 258.237,16.507 C258.237,16.507 258.237,14.866 258.237,14.866 Z' }, tempIconWaterSplashLeft: { offsetX: 0, offsetY: 0, color: ON_COLOR, path: 'M257.000,12.012 C257.000,12.012 257.984,11.460 259.198,11.460 C260.758,11.460 261.695,12.288 262.634,12.288 C263.247,12.195 263.595,12.288 263.595,12.288 C263.595,12.288 263.595,13.669 263.595,13.669 C263.595,13.669 263.592,13.796 262.771,13.807 C261.771,13.807 260.317,12.979 259.336,12.979 C258.354,12.979 257.000,13.531 257.000,13.531 C257.000,13.531 257.000,12.012 257.000,12.012 Z' }, tempIconWaterSplashRight: { offsetX: 0, offsetY: 0, color: ON_COLOR, path: 'M275.000,12.012 C275.000,12.012 274.016,11.460 272.802,11.460 C271.242,11.460 270.305,12.288 269.366,12.288 C268.753,12.195 268.405,12.288 268.405,12.288 C268.405,12.288 268.405,13.669 268.405,13.669 C268.405,13.669 268.408,13.796 269.229,13.807 C270.229,13.807 271.683,12.979 272.664,12.979 C273.646,12.979 275.000,13.531 275.000,13.531 C275.000,13.531 275.000,12.012 275.000,12.012 Z' }, oneH: { offsetX: 0, offsetY: 0, color: ON_COLOR, path: 'M261.000,26.000 C261.000,26.000 261.000,39.000 261.000,39.000 C261.000,39.000 264.000,39.000 264.000,39.000 C264.000,39.000 264.000,26.000 264.000,26.000 C264.000,26.000 261.000,26.000 261.000,26.000 Z' }, twoH: { offsetX: 0, offsetY: 0, color: ON_COLOR, path: 'M270.000,26.000 C270.000,26.000 270.000,39.000 270.000,39.000 C270.000,39.000 273.000,39.000 273.000,39.000 C273.000,39.000 273.000,26.000 273.000,26.000 C273.000,26.000 270.000,26.000 270.000,26.000 Z' }, threeH: { offsetX: 0, offsetY: 0, color: ON_COLOR, path: 'M265.000,32.000 C265.000,32.000 265.000,34.000 265.000,34.000 C265.000,34.000 269.000,34.000 269.000,34.000 C269.000,34.000 269.000,32.000 269.000,32.000 C269.000,32.000 265.000,32.000 265.000,32.000 Z' }, oneC: { offsetX: 0, offsetY: 0, color: ON_COLOR, path: 'M0.000,26.000 C0.000,26.000 0.000,39.000 0.000,39.000 C0.000,39.000 3.000,39.000 3.000,39.000 C3.000,39.000 3.000,26.000 3.000,26.000 C3.000,26.000 0.000,26.000 0.000,26.000 Z' }, twoC: { offsetX: 0, offsetY: 0, color: ON_COLOR, path: 'M4.000,26.000 C4.000,26.000 4.000,28.000 4.000,28.000 C4.000,28.000 12.000,28.000 12.000,28.000 C12.000,28.000 12.000,26.000 12.000,26.000 C12.000,26.000 4.000,26.000 4.000,26.000 Z' }, threeC: { offsetX: 0, offsetY: 0, color: ON_COLOR, path: 'M4.000,37.000 C4.000,37.000 4.000,39.000 4.000,39.000 C4.000,39.000 12.000,39.000 12.000,39.000 C12.000,39.000 12.000,37.000 12.000,37.000 C12.000,37.000 4.000,37.000 4.000,37.000 Z' } }; var parts = [ paths.topLine, paths.bottomLine, paths.tempIcon, paths.tempIconWater, paths.tempIconWaterSplashLeft, paths.tempIconWaterSplashRight, paths.oneH, paths.twoH, paths.threeH, paths.oneC, paths.twoC, paths.threeC ]; var TempLine = function (elID) { // Element setup this.canvas = document.createElement('canvas'); this.ctx = this.canvas.getContext('2d'); this.canvas.width = TEMP_WIDTH; this.canvas.height = TEMP_HEIGHT; document.getElementById(elID).appendChild(this.canvas); // resize/rescale SVG paths and convert them to cavas shapes convertPaths.apply(this, [paths]); // draws the converted paths draw.call(this); } TempLine.prototype.x = function (x) { //this.canvas.style.marginLeft = x + 'px'; this._x = x; } TempLine.prototype.y = function (y) { //this.canvas.style.marginTop = y + 'px'; this._y = y; } // for when multiple frameworks are all being drawn to a single context. // NOTE: Should end up as default, since managing multiple canvases doesnt make sense. TempLine.prototype.drawToContext = function (ctx) { convertPaths.apply(this, [paths]); for (var i = 0, l = parts.length; i < l; i++) { ctx.fillStyle = parts[i].color; ctx.fill(parts[i].p2D); } } function draw () { var p, newPath; this.ctx.clearRect(0, 0, TEMP_WIDTH, TEMP_HEIGHT); // segments to on state for (var i = 0, l = parts.length; i < l; i++) { this.ctx.fillStyle = parts[i].color; // reuse the converted paths this.ctx.fill(parts[i].p2D); } } // dynamic changes svg paths based on container dimensions function updateSVGPath (path, offsetX, offsetY) { var p = path; var a = p.split(' '); var b; var x, y, xy, firstChar; var newPath = ''; for (var i = 0, l = a.length; i < l; i++) { // separate points b = a[i].split(','); // last index will only be Z if (b[0] !== 'Z') { // first character might be a letter, which means an instruction besides line-to x = b[0]; // hold on to this to be added back after coords get updated firstChar = x.charAt(0); // get rid of the letter, so that string can be converted to a number // NOTE: Will need to add something less specific, since there are more key letters than M and C if (firstChar === 'M' || firstChar === 'C') { x = x.substr(1, x.length); } else { x = Number(x); firstChar = null; } // Y will never have a letter y = Number(b[1]); // apply offset and scale to each coordinate xy = updateCoords(x, y, offsetX, offsetY); // reattach first character and conver back to string if (firstChar) { xy[0] = firstChar + String(xy[0]); } else { xy[0] = String(xy[0]); } xy[1] = String(xy[1]); // set proper format and append to updated path string newPath += xy[0] + ',' + xy[1] + ' '; } else { newPath += 'Z'; } } return newPath; } // should only convert paths on init and resize function convertPaths (source) { var adjustedPath; for (var i = 0; i < parts.length; i++) { adjustedPath = updateSVGPath(parts[i].path, this._x, this._y); parts[i].p2D = new Path2D(adjustedPath); } } // adds offset and scale to original svg path function updateCoords (x, y, offsetX, offsetY) { // offset from 0,0 in parent x = offsetX + (x * SCALEX); y = offsetY + (y * SCALEY); return [x,y]; } function update () { convertPaths.apply(this, [paths]); } TempLine.prototype.resize = function () { convertPaths.apply(this, [paths]); } if (!window.JHVH) window.JHVH = {}; window.JHVH.TempLine = TempLine; })();
/* * Kendo UI v2014.2.1008 (http://www.telerik.com/kendo-ui) * Copyright 2014 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["ca-ES"] = { name: "ca-ES", numberFormat: { pattern: ["-n"], decimals: 2, ",": ".", ".": ",", groupSize: [3], percent: { pattern: ["-n %","n %"], decimals: 2, ",": ".", ".": ",", groupSize: [3], symbol: "%" }, currency: { pattern: ["-n $","n $"], decimals: 2, ",": ".", ".": ",", groupSize: [3], symbol: "€" } }, calendars: { standard: { days: { names: ["diumenge","dilluns","dimarts","dimecres","dijous","divendres","dissabte"], namesAbbr: ["dg.","dl.","dt.","dc.","dj.","dv.","ds."], namesShort: ["dg","dl","dt","dc","dj","dv","ds"] }, months: { names: ["gener","febrer","març","abril","maig","juny","juliol","agost","setembre","octubre","novembre","desembre",""], namesAbbr: ["gen","feb","març","abr","maig","juny","jul","ag","set","oct","nov","des",""] }, AM: [""], PM: [""], patterns: { d: "dd/MM/yyyy", D: "dddd, d' / 'MMMM' / 'yyyy", F: "dddd, d' / 'MMMM' / 'yyyy HH:mm:ss", g: "dd/MM/yyyy HH:mm", G: "dd/MM/yyyy HH:mm:ss", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "HH:mm", T: "HH:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM' / 'yyyy", Y: "MMMM' / 'yyyy" }, "/": "/", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
var expect = require("chai").expect , comment = require("../app/service/comment"); /* * Mocks */ var socket = { request: { user: { logged_in: true, id: 1 } } }; describe("app/service/comment", function () { describe('#post()', function () { it('if user is logged out then socket should emit an error', function (done) { socket.request.user.logged_in = false; socket.emit = function (key, data) { expect(key).to.equal('comment/post/error'); done(); }; comment.post(socket, { thread_id: 1, replyTo: 0 }); }); }); describe('#like()', function () { it('if user is logged out then socket should emit an error', function (done) { socket.request.user.logged_in = false; socket.emit = function (key, data) { expect(key).to.equal('comment/like/error'); done(); }; comment.like(socket, {comment_id: 1}); }); it('if comment doesn\'t exist then socket should emit an error', function (done) { socket.request.user.logged_in = true; socket.emit = function (key, data) { expect(key).to.equal('comment/like/error'); done(); }; comment.like(socket, {comment_id: 100000000}); }); }); });
/*global describe:false,expect:false,rIt:false*/ describe("utils", function() { "use strict"; describe("format", function() { rIt("should format single param", ["utils"], function(utils) { expect(utils.format("The Winner is %", "John Doe")) .toEqual("The Winner is John Doe"); }); rIt("should format multiple params", ["utils"], function(utils) { expect(utils.format("% should %", "You", "hack!")) .toEqual("You should hack!"); }); rIt("allows escaping of params", ["utils"], function(utils) { expect(utils.format("% get %\\% on the %!", "You", "5", "price")) .toEqual("You get 5% on the price!"); }); }); describe("assert", function() { rIt("should not throw errors when successful", ["config", "utils"], function(config, utils) { config.enableAssertions = true; utils.assert(true, "Some message"); }); rIt("should throw errors", ["config", "utils"], function(config, utils) { config.enableAssertions = true; try { utils.assert(false, "The error is: %", "Unknown"); throw new Error("This should fail!"); } catch (e) { expect(e.message).toEqual("Assertion error: The error is: Unknown"); } }); rIt("should not throw errors when deactivated", ["config", "utils"], function(config, utils) { config.enableAssertions = false; try { utils.assert(false, "Some message"); } finally { config.enableAssertions = true; } }); }); describe("assertFunction", function() { rIt("should identify functions", ["config", "utils"], function(config, utils) { config.enableAssertions = true; utils.assertFunction(describe, "This is a valid function"); }); rIt("should fail for != function", ["config", "utils"], function(config, utils) { config.enableAssertions = true; try { utils.assert(false, "I need a %", "callback"); throw new Error("This should fail!"); } catch (e) { expect(e.message).toEqual("Assertion error: I need a callback"); } }); }); describe("onlyAllowInUnitTest", function() { var functionCalled = false; var testFn = function() { functionCalled = true; }; rIt("should fail for mode != unit test", ["config", "utils"], function(config, utils) { functionCalled = false; config.unitTestMode = false; var wrappedFn = utils.onlyAllowInUnitTest(testFn); try { wrappedFn(); } catch (e) { // the assertion error is the right one in this case expect(e.message.indexOf("Assertion error")).not.toEqual(-1); } expect(functionCalled).toBe(false); }); rIt("should work in unit test mode", ["config", "utils"], function(config, utils) { functionCalled = false; config.unitTestMode = true; var wrappedFn = utils.onlyAllowInUnitTest(testFn); wrappedFn(); expect(functionCalled).toBe(true); }); }); });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _linglog = require('linglog'); var _linglog2 = _interopRequireDefault(_linglog); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = (0, _linglog2.default)('gulp-insert-md', { timeFormat: 'HH:mm:ss' }); module.exports = exports['default'];
import {createCustomOsc} from './oscillator' export function createChorus(ctx: Object) { const merger = ctx.createChannelMerger(2) const input = ctx.createGain() const output = ctx.createGain() const feedbackL = ctx.createGain() const feedbackR = ctx.createGain() const delayL = ctx.createDelay() const delayR = ctx.createDelay() const lfoLGain = ctx.createGain() const lfoRGain = ctx.createGain() const lfoL = createCustomOsc(ctx) const lfoR = createCustomOsc(ctx) input.connect(output) input.connect(delayL) input.connect(delayR) lfoL.connect(lfoLGain) lfoL.start(0) lfoR.connect(lfoRGain) lfoR.start(0) lfoRGain.connect(delayR.delayTime) lfoLGain.connect(delayL.delayTime) lfoLGain.connect(lfoR.frequency) delayL.connect(feedbackL) delayR.connect(feedbackR) feedbackL.connect(delayL) feedbackR.connect(delayR) feedbackL.connect(merger, 0, 0) feedbackR.connect(merger, 0, 1) merger.connect(output) const setters = { frequency(value) { lfoL.frequency.value = value lfoR.frequency.value = value }, feedback(value) { feedbackL.gain.value = value feedbackR.gain.value = value } } return { __setters: setters, input, connect(node) { output.connect(node) }, init(patch) { lfoL.init({ frequency: patch.frequency, type: patch.type, phase: 180 }) lfoR.init({ frequency: patch.frequency, type: patch.type, phase: 0 }) // TODO: Add public access to chorus depth here input.gain.value = 0.6934 lfoLGain.gain.value = 0.002 lfoRGain.gain.value = 0.002 feedbackL.gain.value = patch.feedback feedbackR.gain.value = patch.feedback }, set(key, val) { setters[key](val) } } }
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2018 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ var Class = require('../utils/Class'); var CONST = require('./const'); var GetValue = require('../utils/object/GetValue'); var NOOP = require('../utils/NOOP'); var Scene = require('./Scene'); var Systems = require('./Systems'); /** * @classdesc * The Scene Manager. * * The Scene Manager is a Game level system, responsible for creating, processing and updating all of the * Scenes in a Game instance. * * * @class SceneManager * @memberOf Phaser.Scenes * @constructor * @since 3.0.0 * * @param {Phaser.Game} game - The Phaser.Game instance this Scene Manager belongs to. * @param {object} sceneConfig - Scene specific configuration settings. */ var SceneManager = new Class({ initialize: function SceneManager (game, sceneConfig) { /** * The Game that this SceneManager belongs to. * * @name Phaser.Scenes.SceneManager#game * @type {Phaser.Game} * @since 3.0.0 */ this.game = game; /** * An object that maps the keys to the scene so we can quickly get a scene from a key without iteration. * * @name Phaser.Scenes.SceneManager#keys * @type {object} * @since 3.0.0 */ this.keys = {}; /** * The array in which all of the scenes are kept. * * @name Phaser.Scenes.SceneManager#scenes * @type {array} * @since 3.0.0 */ this.scenes = []; /** * Scenes pending to be added are stored in here until the manager has time to add it. * * @name Phaser.Scenes.SceneManager#_pending * @type {array} * @private * @since 3.0.0 */ this._pending = []; /** * An array of scenes waiting to be started once the game has booted. * * @name Phaser.Scenes.SceneManager#_start * @type {array} * @private * @since 3.0.0 */ this._start = []; /** * An operations queue, because we don't manipulate the scenes array during processing. * * @name Phaser.Scenes.SceneManager#_queue * @type {array} * @private * @since 3.0.0 */ this._queue = []; /** * Boot time data to merge. * * @name Phaser.Scenes.SceneManager#_data * @type {object} * @private * @since 3.4.0 */ this._data = {}; /** * Is the Scene Manager actively processing the Scenes list? * * @name Phaser.Scenes.SceneManager#isProcessing * @type {boolean} * @default false * @readOnly * @since 3.0.0 */ this.isProcessing = false; /** * Has the Scene Manager properly started? * * @name Phaser.Scenes.SceneManager#isBooted * @type {boolean} * @default false * @readOnly * @since 3.4.0 */ this.isBooted = false; /** * Do any of the Cameras in any of the Scenes require a custom viewport? * If not we can skip scissor tests. * * @name Phaser.Scenes.SceneManager#customViewports * @type {number} * @default 0 * @since 3.12.0 */ this.customViewports = 0; if (sceneConfig) { if (!Array.isArray(sceneConfig)) { sceneConfig = [ sceneConfig ]; } for (var i = 0; i < sceneConfig.length; i++) { // The i === 0 part just autostarts the first Scene given (unless it says otherwise in its config) this._pending.push({ key: 'default', scene: sceneConfig[i], autoStart: (i === 0), data: {} }); } } game.events.once('ready', this.bootQueue, this); }, /** * Internal first-time Scene boot handler. * * @method Phaser.Scenes.SceneManager#bootQueue * @private * @since 3.2.0 */ bootQueue: function () { if (this.isBooted) { return; } var i; var entry; var key; var sceneConfig; for (i = 0; i < this._pending.length; i++) { entry = this._pending[i]; key = entry.key; sceneConfig = entry.scene; var newScene; if (sceneConfig instanceof Scene) { newScene = this.createSceneFromInstance(key, sceneConfig); } else if (typeof sceneConfig === 'object') { newScene = this.createSceneFromObject(key, sceneConfig); } else if (typeof sceneConfig === 'function') { newScene = this.createSceneFromFunction(key, sceneConfig); } // Replace key in case the scene changed it key = newScene.sys.settings.key; this.keys[key] = newScene; this.scenes.push(newScene); // Any data to inject? if (this._data[key]) { newScene.sys.settings.data = this._data[key].data; if (this._data[key].autoStart) { entry.autoStart = true; } } if (entry.autoStart || newScene.sys.settings.active) { this._start.push(key); } } // Clear the pending lists this._pending.length = 0; this._data = {}; this.isBooted = true; // _start might have been populated by the above for (i = 0; i < this._start.length; i++) { entry = this._start[i]; this.start(entry); } this._start.length = 0; }, /** * Process the Scene operations queue. * * @method Phaser.Scenes.SceneManager#processQueue * @since 3.0.0 */ processQueue: function () { var pendingLength = this._pending.length; var queueLength = this._queue.length; if (pendingLength === 0 && queueLength === 0) { return; } var i; var entry; if (pendingLength) { for (i = 0; i < pendingLength; i++) { entry = this._pending[i]; this.add(entry.key, entry.scene, entry.autoStart, entry.data); } // _start might have been populated by this.add for (i = 0; i < this._start.length; i++) { entry = this._start[i]; this.start(entry); } // Clear the pending lists this._start.length = 0; this._pending.length = 0; return; } for (i = 0; i < this._queue.length; i++) { entry = this._queue[i]; this[entry.op](entry.keyA, entry.keyB); } this._queue.length = 0; }, /** * Adds a new Scene into the SceneManager. * You must give each Scene a unique key by which you'll identify it. * * The `sceneConfig` can be: * * * A `Phaser.Scene` object, or an object that extends it. * * A plain JavaScript object * * A JavaScript ES6 Class that extends `Phaser.Scene` * * A JavaScript ES5 prototype based Class * * A JavaScript function * * If a function is given then a new Scene will be created by calling it. * * @method Phaser.Scenes.SceneManager#add * @since 3.0.0 * * @param {string} key - A unique key used to reference the Scene, i.e. `MainMenu` or `Level1`. * @param {(Phaser.Scene|Phaser.Scenes.Settings.Config|function)} sceneConfig - The config for the Scene * @param {boolean} [autoStart=false] - If `true` the Scene will be started immediately after being added. * @param {object} [data] - Optional data object. This will be set as Scene.settings.data and passed to `Scene.init`. * * @return {?Phaser.Scene} The added Scene, if it was added immediately, otherwise `null`. */ add: function (key, sceneConfig, autoStart, data) { if (autoStart === undefined) { autoStart = false; } if (data === undefined) { data = {}; } // If processing or not booted then put scene into a holding pattern if (this.isProcessing || !this.isBooted) { this._pending.push({ key: key, scene: sceneConfig, autoStart: autoStart, data: data }); if (!this.isBooted) { this._data[key] = { data: data }; } return null; } key = this.getKey(key, sceneConfig); var newScene; if (sceneConfig instanceof Scene) { newScene = this.createSceneFromInstance(key, sceneConfig); } else if (typeof sceneConfig === 'object') { sceneConfig.key = key; newScene = this.createSceneFromObject(key, sceneConfig); } else if (typeof sceneConfig === 'function') { newScene = this.createSceneFromFunction(key, sceneConfig); } // Any data to inject? newScene.sys.settings.data = data; // Replace key in case the scene changed it key = newScene.sys.settings.key; this.keys[key] = newScene; this.scenes.push(newScene); if (autoStart || newScene.sys.settings.active) { if (this._pending.length) { this._start.push(key); } else { this.start(key); } } return newScene; }, /** * Removes a Scene from the SceneManager. * * The Scene is removed from the local scenes array, it's key is cleared from the keys * cache and Scene.Systems.destroy is then called on it. * * If the SceneManager is processing the Scenes when this method is called it will * queue the operation for the next update sequence. * * @method Phaser.Scenes.SceneManager#remove * @since 3.2.0 * * @param {(string|Phaser.Scene)} scene - The Scene to be removed. * * @return {Phaser.Scenes.SceneManager} This SceneManager. */ remove: function (key) { if (this.isProcessing) { this._queue.push({ op: 'remove', keyA: key, keyB: null }); } else { var sceneToRemove = this.getScene(key); if (!sceneToRemove || sceneToRemove.sys.isTransitioning()) { return this; } var index = this.scenes.indexOf(sceneToRemove); var sceneKey = sceneToRemove.sys.settings.key; if (index > -1) { delete this.keys[sceneKey]; this.scenes.splice(index, 1); if (this._start.indexOf(sceneKey) > -1) { index = this._start.indexOf(sceneKey); this._start.splice(index, 1); } sceneToRemove.sys.destroy(); } } return this; }, /** * Boot the given Scene. * * @method Phaser.Scenes.SceneManager#bootScene * @private * @since 3.0.0 * * @param {Phaser.Scene} scene - The Scene to boot. */ bootScene: function (scene) { var sys = scene.sys; var settings = sys.settings; if (scene.init) { scene.init.call(scene, settings.data); settings.status = CONST.INIT; if (settings.isTransition) { sys.events.emit('transitioninit', settings.transitionFrom, settings.transitionDuration); } } var loader; if (sys.load) { loader = sys.load; loader.reset(); } if (loader && scene.preload) { scene.preload.call(scene); // Is the loader empty? if (loader.list.size === 0) { this.create(scene); } else { settings.status = CONST.LOADING; // Start the loader going as we have something in the queue loader.once('complete', this.loadComplete, this); loader.start(); } } else { // No preload? Then there was nothing to load either this.create(scene); } }, /** * Handles load completion for a Scene's Loader. * * Starts the Scene that the Loader belongs to. * * @method Phaser.Scenes.SceneManager#loadComplete * @private * @since 3.0.0 * * @param {Phaser.Loader.LoaderPlugin} loader - The loader that has completed loading. */ loadComplete: function (loader) { var scene = loader.scene; // Try to unlock HTML5 sounds every time any loader completes if (this.game.sound.onBlurPausedSounds) { this.game.sound.unlock(); } this.create(scene); }, /** * Handle payload completion for a Scene. * * @method Phaser.Scenes.SceneManager#payloadComplete * @private * @since 3.0.0 * * @param {Phaser.Loader.LoaderPlugin} loader - The loader that has completed loading its Scene's payload. */ payloadComplete: function (loader) { this.bootScene(loader.scene); }, /** * Updates the Scenes. * * @method Phaser.Scenes.SceneManager#update * @since 3.0.0 * * @param {number} time - Time elapsed. * @param {number} delta - Delta time from the last update. */ update: function (time, delta) { this.processQueue(); this.isProcessing = true; // Loop through the active scenes in reverse order for (var i = this.scenes.length - 1; i >= 0; i--) { var sys = this.scenes[i].sys; if (sys.settings.status > CONST.START && sys.settings.status <= CONST.RUNNING) { sys.step(time, delta); } } }, /** * Informs the Scenes of the Game being resized. * * @method Phaser.Scenes.SceneManager#resize * @since 3.2.0 * * @param {number} width - The new width of the game. * @param {number} height - The new height of the game. */ resize: function (width, height) { // Loop through the scenes in forward order for (var i = 0; i < this.scenes.length; i++) { var sys = this.scenes[i].sys; sys.resize(width, height); } }, /** * Renders the Scenes. * * @method Phaser.Scenes.SceneManager#render * @since 3.0.0 * * @param {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)} renderer - The renderer to use. */ render: function (renderer) { // Loop through the scenes in forward order for (var i = 0; i < this.scenes.length; i++) { var sys = this.scenes[i].sys; if (sys.settings.visible && sys.settings.status >= CONST.LOADING && sys.settings.status < CONST.SLEEPING) { sys.render(renderer); } } this.isProcessing = false; }, /** * Calls the given Scene's {@link Phaser.Scene#create} method and updates its status. * * @method Phaser.Scenes.SceneManager#create * @private * @since 3.0.0 * * @param {Phaser.Scene} scene - The Scene to create. */ create: function (scene) { var sys = scene.sys; var settings = sys.settings; if (scene.create) { settings.status = CONST.CREATING; scene.create.call(scene, settings.data); if (settings.isTransition) { sys.events.emit('transitionstart', settings.transitionFrom, settings.transitionDuration); } } // If the Scene has an update function we'll set it now, otherwise it'll remain as NOOP if (scene.update) { sys.sceneUpdate = scene.update; } settings.status = CONST.RUNNING; }, /** * Creates and initializes a Scene from a function. * * @method Phaser.Scenes.SceneManager#createSceneFromFunction * @private * @since 3.0.0 * * @param {string} key - The key of the Scene. * @param {function} scene - The function to create the Scene from. * * @return {Phaser.Scene} The created Scene. */ createSceneFromFunction: function (key, scene) { var newScene = new scene(); if (newScene instanceof Scene) { var configKey = newScene.sys.settings.key; if (configKey !== '') { key = configKey; } if (this.keys.hasOwnProperty(key)) { throw new Error('Cannot add a Scene with duplicate key: ' + key); } return this.createSceneFromInstance(key, newScene); } else { newScene.sys = new Systems(newScene); newScene.sys.settings.key = key; newScene.sys.init(this.game); return newScene; } }, /** * Creates and initializes a Scene instance. * * @method Phaser.Scenes.SceneManager#createSceneFromInstance * @private * @since 3.0.0 * * @param {string} key - The key of the Scene. * @param {Phaser.Scene} newScene - The Scene instance. * * @return {Phaser.Scene} The created Scene. */ createSceneFromInstance: function (key, newScene) { var configKey = newScene.sys.settings.key; if (configKey !== '') { key = configKey; } else { newScene.sys.settings.key = key; } newScene.sys.init(this.game); return newScene; }, /** * Creates and initializes a Scene from an Object definition. * * @method Phaser.Scenes.SceneManager#createSceneFromObject * @private * @since 3.0.0 * * @param {string} key - The key of the Scene. * @param {(string|Phaser.Scenes.Settings.Config)} sceneConfig - The Scene config. * * @return {Phaser.Scene} The created Scene. */ createSceneFromObject: function (key, sceneConfig) { var newScene = new Scene(sceneConfig); var configKey = newScene.sys.settings.key; if (configKey !== '') { key = configKey; } else { newScene.sys.settings.key = key; } newScene.sys.init(this.game); // Extract callbacks var defaults = [ 'init', 'preload', 'create', 'update', 'render' ]; for (var i = 0; i < defaults.length; i++) { var sceneCallback = GetValue(sceneConfig, defaults[i], null); if (sceneCallback) { newScene[defaults[i]] = sceneCallback; } } // Now let's move across any other functions or properties that may exist in the extend object: /* scene: { preload: preload, create: create, extend: { hello: 1, test: 'atari', addImage: addImage } } */ if (sceneConfig.hasOwnProperty('extend')) { for (var propertyKey in sceneConfig.extend) { var value = sceneConfig.extend[propertyKey]; if (propertyKey === 'data' && newScene.hasOwnProperty('data') && typeof value === 'object') { // Populate the DataManager newScene.data.merge(value); } else if (propertyKey !== 'sys') { newScene[propertyKey] = value; } } } return newScene; }, /** * Retrieves the key of a Scene from a Scene config. * * @method Phaser.Scenes.SceneManager#getKey * @private * @since 3.0.0 * * @param {string} key - The key to check in the Scene config. * @param {(Phaser.Scene|Phaser.Scenes.Settings.Config|function)} sceneConfig - The Scene config. * * @return {string} The Scene key. */ getKey: function (key, sceneConfig) { if (!key) { key = 'default'; } if (typeof sceneConfig === 'function') { return key; } else if (sceneConfig instanceof Scene) { key = sceneConfig.sys.settings.key; } else if (typeof sceneConfig === 'object' && sceneConfig.hasOwnProperty('key')) { key = sceneConfig.key; } // By this point it's either 'default' or extracted from the Scene if (this.keys.hasOwnProperty(key)) { throw new Error('Cannot add a Scene with duplicate key: ' + key); } else { return key; } }, /** * Retrieves a Scene. * * @method Phaser.Scenes.SceneManager#getScene * @since 3.0.0 * * @param {string|Phaser.Scene} key - The Scene to retrieve. * * @return {?Phaser.Scene} The Scene. */ getScene: function (key) { if (typeof key === 'string') { if (this.keys[key]) { return this.keys[key]; } } else { for (var i = 0; i < this.scenes.length; i++) { if (key === this.scenes[i]) { return key; } } } return null; }, /** * Determines whether a Scene is active. * * @method Phaser.Scenes.SceneManager#isActive * @since 3.0.0 * * @param {string} key - The Scene to check. * * @return {boolean} Whether the Scene is active. */ isActive: function (key) { var scene = this.getScene(key); if (scene) { return scene.sys.isActive(); } return null; }, /** * Determines whether a Scene is visible. * * @method Phaser.Scenes.SceneManager#isVisible * @since 3.0.0 * * @param {string} key - The Scene to check. * * @return {boolean} Whether the Scene is visible. */ isVisible: function (key) { var scene = this.getScene(key); if (scene) { return scene.sys.isVisible(); } return null; }, /** * Determines whether a Scene is sleeping. * * @method Phaser.Scenes.SceneManager#isSleeping * @since 3.0.0 * * @param {string} key - The Scene to check. * * @return {boolean} Whether the Scene is sleeping. */ isSleeping: function (key) { var scene = this.getScene(key); if (scene) { return scene.sys.isSleeping(); } return null; }, /** * Pauses the given Scene. * * @method Phaser.Scenes.SceneManager#pause * @since 3.0.0 * * @param {string} key - The Scene to pause. * @param {object} [data] - An optional data object that will be passed to the Scene and emitted by its pause event. * * @return {Phaser.Scenes.SceneManager} This SceneManager. */ pause: function (key, data) { var scene = this.getScene(key); if (scene) { scene.sys.pause(data); } return this; }, /** * Resumes the given Scene. * * @method Phaser.Scenes.SceneManager#resume * @since 3.0.0 * * @param {string} key - The Scene to resume. * @param {object} [data] - An optional data object that will be passed to the Scene and emitted by its resume event. * * @return {Phaser.Scenes.SceneManager} This SceneManager. */ resume: function (key, data) { var scene = this.getScene(key); if (scene) { scene.sys.resume(data); } return this; }, /** * Puts the given Scene to sleep. * * @method Phaser.Scenes.SceneManager#sleep * @since 3.0.0 * * @param {string} key - The Scene to put to sleep. * @param {object} [data] - An optional data object that will be passed to the Scene and emitted by its sleep event. * * @return {Phaser.Scenes.SceneManager} This SceneManager. */ sleep: function (key, data) { var scene = this.getScene(key); if (scene && !scene.sys.isTransitioning()) { scene.sys.sleep(data); } return this; }, /** * Awakens the given Scene. * * @method Phaser.Scenes.SceneManager#wake * @since 3.0.0 * * @param {string} key - The Scene to wake up. * @param {object} [data] - An optional data object that will be passed to the Scene and emitted by its wake event. * * @return {Phaser.Scenes.SceneManager} This SceneManager. */ wake: function (key, data) { var scene = this.getScene(key); if (scene) { scene.sys.wake(data); } return this; }, /** * Runs the given Scene, but does not change the state of this Scene. * * If the given Scene is paused, it will resume it. If sleeping, it will wake it. * If not running at all, it will be started. * * Use this if you wish to open a modal Scene by calling `pause` on the current * Scene, then `run` on the modal Scene. * * @method Phaser.Scenes.SceneManager#run * @since 3.10.0 * * @param {string} key - The Scene to run. * @param {object} [data] - A data object that will be passed to the Scene on start, wake, or resume. * * @return {Phaser.Scenes.SceneManager} This Scene Manager. */ run: function (key, data) { var scene = this.getScene(key); if (!scene) { for (var i = 0; i < this._pending.length; i++) { if (this._pending[i].key === key) { this.queueOp('start', key, data); break; } } return this; } if (scene.sys.isSleeping()) { // Sleeping? scene.sys.wake(data); } else if (scene.sys.isBooted && !scene.sys.isActive()) { // Paused? scene.sys.resume(data); } else { // Not actually running? this.start(key, data); } }, /** * Starts the given Scene. * * @method Phaser.Scenes.SceneManager#start * @since 3.0.0 * * @param {string} key - The Scene to start. * @param {object} [data] - Optional data object to pass to Scene.Settings and Scene.init. * * @return {Phaser.Scenes.SceneManager} This SceneManager. */ start: function (key, data) { // If the Scene Manager is not running, then put the Scene into a holding pattern if (!this.isBooted) { this._data[key] = { autoStart: true, data: data }; return this; } var scene = this.getScene(key); if (scene) { scene.sys.start(data); var loader; if (scene.sys.load) { loader = scene.sys.load; } // Files payload? if (loader && scene.sys.settings.hasOwnProperty('pack')) { loader.reset(); if (loader.addPack({ payload: scene.sys.settings.pack })) { scene.sys.settings.status = CONST.LOADING; loader.once('complete', this.payloadComplete, this); loader.start(); return this; } } this.bootScene(scene); } return this; }, /** * Stops the given Scene. * * @method Phaser.Scenes.SceneManager#stop * @since 3.0.0 * * @param {string} key - The Scene to stop. * * @return {Phaser.Scenes.SceneManager} This SceneManager. */ stop: function (key) { var scene = this.getScene(key); if (scene && !scene.sys.isTransitioning()) { scene.sys.shutdown(); } return this; }, /** * Sleeps one one Scene and starts the other. * * @method Phaser.Scenes.SceneManager#switch * @since 3.0.0 * * @param {string} from - The Scene to sleep. * @param {string} to - The Scene to start. * * @return {Phaser.Scenes.SceneManager} This SceneManager. */ switch: function (from, to) { var sceneA = this.getScene(from); var sceneB = this.getScene(to); if (sceneA && sceneB && sceneA !== sceneB) { this.sleep(from); if (this.isSleeping(to)) { this.wake(to); } else { this.start(to); } } return this; }, /** * Retrieves a Scene by numeric index. * * @method Phaser.Scenes.SceneManager#getAt * @since 3.0.0 * * @param {integer} index - The index of the Scene to retrieve. * * @return {(Phaser.Scene|undefined)} The Scene. */ getAt: function (index) { return this.scenes[index]; }, /** * Retrieves the numeric index of a Scene. * * @method Phaser.Scenes.SceneManager#getIndex * @since 3.0.0 * * @param {(string|Phaser.Scene)} key - The key of the Scene. * * @return {integer} The index of the Scene. */ getIndex: function (key) { var scene = this.getScene(key); return this.scenes.indexOf(scene); }, /** * Brings a Scene to the top of the Scenes list. * * This means it will render above all other Scenes. * * @method Phaser.Scenes.SceneManager#bringToTop * @since 3.0.0 * * @param {(string|Phaser.Scene)} key - The Scene to move. * * @return {Phaser.Scenes.SceneManager} This SceneManager. */ bringToTop: function (key) { if (this.isProcessing) { this._queue.push({ op: 'bringToTop', keyA: key, keyB: null }); } else { var index = this.getIndex(key); if (index !== -1 && index < this.scenes.length) { var scene = this.getScene(key); this.scenes.splice(index, 1); this.scenes.push(scene); } } return this; }, /** * Sends a Scene to the back of the Scenes list. * * This means it will render below all other Scenes. * * @method Phaser.Scenes.SceneManager#sendToBack * @since 3.0.0 * * @param {(string|Phaser.Scene)} key - The Scene to move. * * @return {Phaser.Scenes.SceneManager} This SceneManager. */ sendToBack: function (key) { if (this.isProcessing) { this._queue.push({ op: 'sendToBack', keyA: key, keyB: null }); } else { var index = this.getIndex(key); if (index !== -1 && index > 0) { var scene = this.getScene(key); this.scenes.splice(index, 1); this.scenes.unshift(scene); } } return this; }, /** * Moves a Scene down one position in the Scenes list. * * @method Phaser.Scenes.SceneManager#moveDown * @since 3.0.0 * * @param {(string|Phaser.Scene)} key - The Scene to move. * * @return {Phaser.Scenes.SceneManager} This SceneManager. */ moveDown: function (key) { if (this.isProcessing) { this._queue.push({ op: 'moveDown', keyA: key, keyB: null }); } else { var indexA = this.getIndex(key); if (indexA > 0) { var indexB = indexA - 1; var sceneA = this.getScene(key); var sceneB = this.getAt(indexB); this.scenes[indexA] = sceneB; this.scenes[indexB] = sceneA; } } return this; }, /** * Moves a Scene up one position in the Scenes list. * * @method Phaser.Scenes.SceneManager#moveUp * @since 3.0.0 * * @param {(string|Phaser.Scene)} key - The Scene to move. * * @return {Phaser.Scenes.SceneManager} This SceneManager. */ moveUp: function (key) { if (this.isProcessing) { this._queue.push({ op: 'moveUp', keyA: key, keyB: null }); } else { var indexA = this.getIndex(key); if (indexA < this.scenes.length - 1) { var indexB = indexA + 1; var sceneA = this.getScene(key); var sceneB = this.getAt(indexB); this.scenes[indexA] = sceneB; this.scenes[indexB] = sceneA; } } return this; }, /** * Moves a Scene so it is immediately above another Scene in the Scenes list. * * This means it will render over the top of the other Scene. * * @method Phaser.Scenes.SceneManager#moveAbove * @since 3.2.0 * * @param {(string|Phaser.Scene)} keyA - The Scene that Scene B will be moved above. * @param {(string|Phaser.Scene)} keyB - The Scene to be moved. * * @return {Phaser.Scenes.SceneManager} This SceneManager. */ moveAbove: function (keyA, keyB) { if (keyA === keyB) { return this; } if (this.isProcessing) { this._queue.push({ op: 'moveAbove', keyA: keyA, keyB: keyB }); } else { var indexA = this.getIndex(keyA); var indexB = this.getIndex(keyB); if (indexA !== -1 && indexB !== -1) { var tempScene = this.getAt(indexB); // Remove this.scenes.splice(indexB, 1); // Add in new location this.scenes.splice(indexA + 1, 0, tempScene); } } return this; }, /** * Moves a Scene so it is immediately below another Scene in the Scenes list. * * This means it will render behind the other Scene. * * @method Phaser.Scenes.SceneManager#moveBelow * @since 3.2.0 * * @param {(string|Phaser.Scene)} keyA - The Scene that Scene B will be moved above. * @param {(string|Phaser.Scene)} keyB - The Scene to be moved. * * @return {Phaser.Scenes.SceneManager} This SceneManager. */ moveBelow: function (keyA, keyB) { if (keyA === keyB) { return this; } if (this.isProcessing) { this._queue.push({ op: 'moveBelow', keyA: keyA, keyB: keyB }); } else { var indexA = this.getIndex(keyA); var indexB = this.getIndex(keyB); if (indexA !== -1 && indexB !== -1) { var tempScene = this.getAt(indexB); // Remove this.scenes.splice(indexB, 1); if (indexA === 0) { this.scenes.unshift(tempScene); } else { // Add in new location this.scenes.splice(indexA, 0, tempScene); } } } return this; }, /** * Queue a Scene operation for the next update. * * @method Phaser.Scenes.SceneManager#queueOp * @private * @since 3.0.0 * * @param {string} op - The operation to perform. * @param {(string|Phaser.Scene)} keyA - Scene A. * @param {(string|Phaser.Scene)} [keyB] - Scene B. * * @return {Phaser.Scenes.SceneManager} This SceneManager. */ queueOp: function (op, keyA, keyB) { this._queue.push({ op: op, keyA: keyA, keyB: keyB }); return this; }, /** * Swaps the positions of two Scenes in the Scenes list. * * @method Phaser.Scenes.SceneManager#swapPosition * @since 3.0.0 * * @param {(string|Phaser.Scene)} keyA - The first Scene to swap. * @param {(string|Phaser.Scene)} keyB - The second Scene to swap. * * @return {Phaser.Scenes.SceneManager} This SceneManager. */ swapPosition: function (keyA, keyB) { if (keyA === keyB) { return this; } if (this.isProcessing) { this._queue.push({ op: 'swapPosition', keyA: keyA, keyB: keyB }); } else { var indexA = this.getIndex(keyA); var indexB = this.getIndex(keyB); if (indexA !== indexB && indexA !== -1 && indexB !== -1) { var tempScene = this.getAt(indexA); this.scenes[indexA] = this.scenes[indexB]; this.scenes[indexB] = tempScene; } } return this; }, /** * Dumps debug information about each Scene to the developer console. * * @method Phaser.Scenes.SceneManager#dump * @since 3.2.0 */ dump: function () { var out = []; var map = [ 'pending', 'init', 'start', 'loading', 'creating', 'running', 'paused', 'sleeping', 'shutdown', 'destroyed' ]; for (var i = 0; i < this.scenes.length; i++) { var sys = this.scenes[i].sys; var key = (sys.settings.visible && (sys.settings.status === CONST.RUNNING || sys.settings.status === CONST.PAUSED)) ? '[*] ' : '[-] '; key += sys.settings.key + ' (' + map[sys.settings.status] + ')'; out.push(key); } console.log(out.join('\n')); }, /** * Destroy the SceneManager and all of its Scene's systems. * * @method Phaser.Scenes.SceneManager#destroy * @since 3.0.0 */ destroy: function () { for (var i = 0; i < this.scenes.length; i++) { var sys = this.scenes[i].sys; sys.destroy(); } this.update = NOOP; this.scenes = []; this._pending = []; this._start = []; this._queue = []; this.game = null; } }); module.exports = SceneManager;
/**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * ClassManager.js * * * * hprose ClassManager for HTML5. * * * * LastModified: Nov 18, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ (function (hprose, global) { 'use strict'; var WeakMap = global.WeakMap; var classCache = Object.create(null); var aliasCache = new WeakMap(); function register(cls, alias) { aliasCache.set(cls, alias); classCache[alias] = cls; } function getClassAlias(cls) { return aliasCache.get(cls); } function getClass(alias) { return classCache[alias]; } hprose.ClassManager = Object.create(null, { register: { value: register }, getClassAlias: { value: getClassAlias }, getClass: { value: getClass } }); hprose.register = register; register(Object, 'Object'); })(hprose, hprose.global);
/* * The MIT License (MIT) * Copyright (c) 2016 SK PLANET. 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. */ /*! * \RecentWordPluginLocalStorageAddOn.js * \Addon source for RecentWordPlugin.js * \copyright Copyright (c) 2016, SK PLANET. All Rights Reserved. * \license This project is released under the MIT License. * \contributor Jisu Youn (jisu.youn@gmail.com) * \warning dont'use this source in other library source. */ class RecentWordPluginLocalStorageAddOn { constructor(sKey, nMaxList) { this.sKey = sKey; this.nMaxList = nMaxList; } saveKeyword(sKeyword) { if (this.validStorage()) return; let aLegacy = this.getKeywords(); //to Array if (aLegacy === null) aLegacy = []; else aLegacy = JSON.parse(aLegacy); //save data let nIndex = aLegacy.indexOf(sKeyword); if ( nIndex > -1) { if(nIndex === (aLegacy.length-1)) return; aLegacy.splice(nIndex, 1); } aLegacy.unshift(sKeyword); if (aLegacy.length >= this.nMaxList) aLegacy.length = this.nMaxList; localStorage.setItem(this.sKey, JSON.stringify(aLegacy)); } getKeywords(){ if (this.validStorage()) return; let sResult = localStorage.getItem(this.sKey); return sResult; } removeKeywords() { if (this.validStorage()) return; return localStorage.removeItem(this.sKey); } validStorage() { if ( typeof(Storage) === "undefined") return; } }
"use strict"; module.exports = { entry: { playground: "./playground/index.js" }, output: { filename: "[name].js", path: __dirname + "/static/" }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader", options: { presets: ["env", "react"] } } ] }, externals: { clipboard: "ClipboardJS", codemirror: "CodeMirror", react: "React", "react-dom": "ReactDOM" } };
(function (global, factory) { if (typeof define === "function" && define.amd) { define(['exports', '../node_modules/skatejs/lib/index'], factory); } else if (typeof exports !== "undefined") { factory(exports, require('../node_modules/skatejs/lib/index')); } else { var mod = { exports: {} }; factory(mod.exports, global.index); global.properties = mod.exports; } })(this, function (exports, _index) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.string = exports.number = exports.boolean = exports.array = undefined; var _index2 = _interopRequireDefault(_index); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var props = _index2.default.properties; var array = props.array; var boolean = props.boolean; var number = props.number; var string = props.string; exports.default = props; exports.array = array; exports.boolean = boolean; exports.number = number; exports.string = string; });
jQuery(document).ready(function(){ /** * add a category */ jQuery("#submitCategory").on("click", function(){ var category_name = jQuery("#category_name").attr("value"); if(!category_name) { alert("category input filde is empty please enter a category name"); return false; } jQuery.ajax({ url:phpToJsPath.ajaxurl, type:"POST", data:{ action:"add_category", category_name: category_name }, success:function(response){ location.reload(); jQuery("#message").show(); }, error:function(err) { location.reload(); jQuery("#errMessage").show(); } }); }); /** * delete a category */ jQuery(".delete-category").on("click", function(){ var confitMessage = confirm("would you like deleted this category ?"); if(!confitMessage) return false; var category_id = jQuery(this).attr("data-id"); jQuery.ajax({ url:phpToJsPath.ajaxurl, type:"POST", data:{ action:"delete_category", category_id:category_id }, success:function(response){ location.reload(); console.log(response); }, error:function(err){ location.reload(); console.log(err); } }); }); /** * update a category */ jQuery(".update-category").on("click",function(){ var category_id = jQuery(this).attr("data-id"); var category_name = prompt("please add a new name for category and click on OK for update category name !!"); if(category_name == "" || category_name==null) { return false; } jQuery.ajax({ url:phpToJsPath.ajaxurl, type:"POST", data:{ action:"update_category", category_id:category_id, category_name:category_name }, success:function(response){ location.reload(); console.log(response); }, error:function(err){ location.reload(); console.log(err); } }); }); /** * add a slide */ jQuery("#uploadSlide").on("click", function(){ var selectFile = jQuery("input[name=slide_image]"); var imageToUpload = selectFile[0].files[0]; var slide_caption = jQuery("#slide_caption").val(); var slide_alt_description = jQuery("#slide_alt_description").val(); var category_id = jQuery("#category_id").val(); var slide_status = jQuery("#slide_status").is(':checked'); var slide_time = jQuery("#slide_time").val(); var slide_update = jQuery("#slide_update").val(); var slide_width = jQuery("#slide_width").val(); var slide_height = jQuery("#slide_height").val(); var slide_description = jQuery("#slide_description").val(); if(imageToUpload == "" || imageToUpload == null) { alert("please select a file and submit file to upload !"); return false; } if(category_id == "" || category_id == null) { alert("please choose a category and submit file to upload !"); return false; } if(slide_time == "" || slide_time == null) { alert("please reload this upload form !"); return false; } var formData = new FormData(); formData.append("action", "image_upload"); formData.append("image_slide", imageToUpload); formData.append("slide_caption", slide_caption); formData.append("slide_alt_description", slide_alt_description); formData.append("category_id", category_id); formData.append("slide_status", slide_status); formData.append("slide_time", slide_time); formData.append("slide_update", slide_update); formData.append("slide_width", slide_width); formData.append("slide_height", slide_height); formData.append("slide_description", slide_description); jQuery("#loading").fadeIn(); jQuery.ajax({ url:phpToJsPath.ajaxurl, type:"POST", processData:false, contentType:false, data:formData, success : function(response){ jQuery("#messageSuccessAddSlide").fadeIn(); jQuery("#loading").fadeOut(); jQuery("#slide_caption").val(""); jQuery("#slide_alt_description").val(""); jQuery("#category_id").val(""); jQuery("#slide_update").val(""); jQuery("#slide_width").val(""); jQuery("#slide_height").val(""); jQuery("#slide_description").val(""); console.log(response); }, error : function(err){ jQuery("#messageSuccessAddSlide").fadeIn(); console.log(err); } }); }); // php delete slide jQuery(".delete-slide").on("click", function(){ // ask a question for delete slide var askQuestion = confirm("Are you sure remove this is slide ?"); if(!askQuestion) { return false; } var slide_id = jQuery(this).attr("data-id"); jQuery.ajax({ url:phpToJsPath.ajaxurl, type:"POST", data:{ action:"delete_slide", id:slide_id, }, success:function(res){ console.log(res); location.reload(); jQuery("") }, error:function(err){ console.log(err); } }); }); /** * jqury ui update form init */ jQuery( function() { var dialog, form, updateSlideId; var slide_id = jQuery("#upload-slide_id"); var slide_caption = jQuery("#update-slide-caption"); var slide_description = jQuery("#update-slide-description"); var slide_alt_tag = jQuery("#update-slide-alt-tag"); var slide_category = jQuery("#update-slide-category"); var slide_status = jQuery("#update-slide-status"); var slide_time = jQuery("#upload-slide-time"); var slide_update = jQuery("#upload-slide_update"); var slide_width = jQuery("#update-slide-width"); var slide_height = jQuery("#update-slide-height"); function updateTips( t ) { tips .text( t ) .addClass( "ui-state-highlight" ); setTimeout(function() { tips.removeClass( "ui-state-highlight", 1500 ); }, 500 ); } function updateSlide() { var valid = true; var checkBoxIsChecked = slide_status.is(':checked'); jQuery.ajax({ url:phpToJsPath.ajaxurl, type:"POST", data:{ action:"update_form_submit", slide_id:slide_id.val(), slide_alt_tag:slide_alt_tag.val(), slide_caption:slide_caption.val(), slide_category:slide_category.val(), slide_status:checkBoxIsChecked, slide_time:slide_time.val(), slide_update:slide_update.val(), slide_width:slide_width.val(), slide_height:slide_height.val(), slide_description:slide_description.val() }, success:function(res){ location.reload(); console.log(res); }, error:function(err){ location.reload(); console.log(err); } }); console.log("click on update information"); } dialog = jQuery( "#dialog-form" ).dialog({ autoOpen: false, height: 400, width: 350, title: 'Update slide information', modal: true, buttons: { "Update informaion": updateSlide, Cancel: function() { dialog.dialog( "close" ); } }, close: function() { form[ 0 ].reset(); } }); form = dialog.find( "form" ).on( "submit", function( event ) { console.log("you click on submit"); }); jQuery( ".update-slide" ).on( "click", function() { updateSlideId = jQuery(this).attr("data-id"); jQuery.ajax({ url:phpToJsPath.ajaxurl, type:"Post", data:{ action:"get_Slide_Info_By_Id", slideId:updateSlideId }, success:function(res){ var dataRes = jQuery.parseJSON(res); slide_id.val(updateSlideId); slide_caption.val(dataRes[0].kiki_slide_header); slide_description.val(dataRes[0].kiki_slide_content); slide_alt_tag.val(dataRes[0].kiki_slide_img_alt); slide_status.val(dataRes[0].kiki_slide_status); slide_time.val(dataRes[0].kiki_slide_date); slide_update.val(Date.now()); slide_category.val(dataRes[0].kiki_slide_category_id); slide_width.val(dataRes[0].kiki_slide_width); slide_height.val(dataRes[0].kiki_slide_height); // check checkbox is checked if(dataRes[0].kiki_slide_status == "1") { jQuery("#update-slide-status").attr('checked', true); } else { jQuery("#update-slide-status").removeAttr('checked'); } }, error:function(err){ console.log(err); } }); dialog.dialog( "open" ); }); } ); });
/* tags: basic <p>This example shows how you can implement a simple Minecraft renderer in regl.</p> */ const canvas = document.body.appendChild(document.createElement('canvas')) const fit = require('canvas-fit') const regl = require('../regl')(canvas) const mat4 = require('gl-mat4') const camera = require('canvas-orbit-camera')(canvas) window.addEventListener('resize', fit(canvas), false) // configure intial camera view. camera.rotate([0.0, 0.0], [0.0, -0.4]) camera.zoom(15.0) // all the positions of a single block. var blockPosition = [ // side faces [[-0.5, +0.5, +0.5], [+0.5, +0.5, +0.5], [+0.5, -0.5, +0.5], [-0.5, -0.5, +0.5]], // positive z face. [[+0.5, +0.5, +0.5], [+0.5, +0.5, -0.5], [+0.5, -0.5, -0.5], [+0.5, -0.5, +0.5]], // positive x face [[+0.5, +0.5, -0.5], [-0.5, +0.5, -0.5], [-0.5, -0.5, -0.5], [+0.5, -0.5, -0.5]], // negative z face [[-0.5, +0.5, -0.5], [-0.5, +0.5, +0.5], [-0.5, -0.5, +0.5], [-0.5, -0.5, -0.5]], // negative x face. // top faces [[-0.5, +0.5, -0.5], [+0.5, +0.5, -0.5], [+0.5, +0.5, +0.5], [-0.5, +0.5, +0.5]] ] // all the uvs of a single block. var blockUv = [ // side faces [[0.0, 0.5], [0.5, 0.5], [0.5, 1.0], [0.0, 1.0]], [[0.0, 0.5], [0.5, 0.5], [0.5, 1.0], [0.0, 1.0]], [[0.0, 0.5], [0.5, 0.5], [0.5, 1.0], [0.0, 1.0]], [[0.0, 0.5], [0.5, 0.5], [0.5, 1.0], [0.0, 1.0]], // top [[0.0, 0.0], [0.5, 0.0], [0.5, 0.5], [0.0, 0.5]] ] // all the normals of a single block. var blockNormal = [ // side faces [[0.0, 0.0, +1.0], [0.0, 0.0, +1.0], [0.0, 0.0, +1.0], [0.0, 0.0, +1.0]], [[+1.0, 0.0, 0.0], [+1.0, 0.0, 0.0], [+1.0, 0.0, 0.0], [+1.0, 0.0, 0.0]], [[0.0, 0.0, -1.0], [0.0, 0.0, -1.0], [0.0, 0.0, -1.0], [0.0, 0.0, -1.0]], [[-1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [-1.0, 0.0, 0.0]], // top [[0.0, +1.0, 0.0], [0.0, +1.0, 0.0], [0.0, +1.0, 0.0], [0.0, +1.0, 0.0]] ] // the terrain is just described by some sine functions. var evalHeight = (x, z) => { var freq = 30.0 return Math.round( 2.0 * Math.sin(freq * 1.0 * 3.14 * x) * Math.sin(freq * 2.0 * 3.14 * z) + 3.0 * Math.cos(freq * 4.0 * 3.14 * x + 2.1) * Math.sin(freq * 5.0 * 3.14 * z + 0.9) + 1.0 * Math.cos(freq * 8.0 * 3.14 * x + 43.43) * Math.cos(freq * 3.0 * 3.14 * z + 34.3)) } // these contains all the geometry of the world. // you can add blocks to these arrays by calling addBlock() var uv = [] var elements = [] var position = [] var normal = [] var addBlock = (x, y, z) => { var index = position.length for (var i = 0; i < 5; i++) { if (i === 0 && y <= evalHeight(x, z + 1)) { // positive z face continue // not visible, skip } if (i === 1 && y <= evalHeight(x + 1, z)) { // positive x face continue // not visible, skip } if (i === 2 && y <= evalHeight(x, z - 1)) { // negative z face continue // not visible, skip } if (i === 3 && y <= evalHeight(x - 1, z)) { // negative x face continue // not visible, skip } var j // add positions. for (j = 0; j < blockPosition[i].length; j++) { var p = blockPosition[i][j] position.push([p[0] + x, p[1] + y, p[2] + z]) } // add normals. for (j = 0; j < blockNormal[i].length; j++) { var n = blockNormal[i][j] normal.push([n[0], n[1], n[2]]) } // add uvs. for (j = 0; j < blockUv[i].length; j++) { var a = blockUv[i][j] uv.push([a[0], a[1]]) } // add quad face. elements.push([2 + index, 1 + index, 0 + index]) elements.push([2 + index, 0 + index, 3 + index]) index += 4 // next quad. } } const S = 40 // world size. // create world: for (var x = -S; x <= S; x++) { for (var z = -S; z <= S; z++) { var y = evalHeight(x, z) addBlock(x, y, z) } } // now the world has been created. Now create the draw call. const drawWorld = regl({ cull: { enable: true, face: 'back' }, context: { view: () => camera.view() }, frag: ` precision mediump float; varying vec2 vUv; varying vec3 vNormal; uniform sampler2D atlas; void main () { vec3 lightDir = normalize(vec3(0.4, 0.9, 0.3)); vec3 tex = texture2D(atlas, vUv).rgb; vec3 ambient = 0.3 * tex; vec3 diffuse = 0.7 * tex * clamp( dot(vNormal, lightDir ), 0.0, 1.0 ); gl_FragColor = vec4(ambient + diffuse, 1.0); }`, vert: ` precision mediump float; attribute vec3 position, normal; attribute vec2 uv; varying vec2 vUv; varying vec3 vNormal; uniform mat4 projection, view; void main() { vUv = uv; vNormal = normal; gl_Position = projection * view * vec4(position, 1); }`, uniforms: { view: regl.context('view'), projection: ({viewportWidth, viewportHeight}) => mat4.perspective([], Math.PI / 4, viewportWidth / viewportHeight, 0.01, 1000), atlas: regl.prop('atlas') }, attributes: { position: regl.prop('position'), uv: regl.prop('uv'), normal: regl.prop('normal') }, elements: regl.prop('elements') }) require('resl')({ manifest: { atlas: { type: 'image', src: 'assets/atlas.png', parser: (data) => regl.texture({ mag: 'nearest', mipmap: true, min: 'linear mipmap linear', data: data }) } }, onDone: ({ atlas }) => { regl.frame(() => { drawWorld({position, elements, uv, normal, atlas}) camera.tick() }) } })
module.exports = { output: { library: 'RadioGroup', libraryTarget: 'umd' }, externals: [ { react: { root: 'React', commonjs2: 'react', commonjs: 'react', amd: 'react' } } ], module: { loaders: [ {test: /\.jsx?$/, exclude: /build|node_modules/, loader: 'babel-loader'}, ] }, resolve: { extensions: ['.js', '.jsx'] } };
export const RouteAuth = { REQUIRED: 2, DISABLED: 0, OPTIONAL: 1, };
// Entry point for the notebook bundle containing custom model definitions. // // Setup notebook base URL // // Some static assets may be required by the custom widget javascript. The base // url for the notebook is not known at build time and is therefore computed // dynamically. __webpack_public_path__ = document.querySelector('body').getAttribute('data-base-url') + 'nbextensions/jupyter-canvas/'; // Export widget models and views, and the npm package version number. module.exports = require('./jupyter-canvas.js'); module.exports['version'] = require('../package.json').version;
"use strict"; module.exports = { home: require("./home") };
describe('inventory routes', () => { var expect = chai.expect; describe('state', () => { var view = 'inventory/inventory.html'; beforeEach(function () { angular.mock.module('app.inventory'); bard.inject(this, '$rootScope', '$state', '$templateCache'); $templateCache.put(view, ''); }); bard.verifyNoOutstandingHttpRequests(); it('should map state inventory to url /inventory ', () => { console.log("inventory should map state inventory to url"); expect($state.href('inventory', {})).to.equal('/inventory'); }); it('should map /inventory route to inventory View template', () => { console.log("inventory should map /inventory route to inventory View template"); expect($state.get('inventory').views['@'].templateUrl).to.equal(view); }); it('should work with $state.go', () => { console.log("inventory should work with $state.go"); $state.go('inventory'); $rootScope.$apply(); expect($state.is('inventory')); }); it('should have title "inventory" ', () => { console.log('inventory should have title "inventory"'); $state.go('inventory'); $rootScope.$apply(); expect($state.current.data.pageTitle).to.equal('Inventory'); }); }); });
export default class ChatService { constructor(webSocketService, $q, $rootScope) { this.channelName = 'chat'; this.webSocketService = webSocketService; this.$q = $q; } enterChat(){ var deferred = this.$q.defer(); if(this.webSocketService.isConnected()){ this.webSocketService.enterRoom(this.channelName, (data) => { deferred.resolve(data); }); } return deferred.promise; } leaveChat(){ this.webSocketService.leaveRoom(this.channelName, () => { this.webSocketService.socket.off('chat new message'); this.webSocketService.socket.off('chat user joined'); this.webSocketService.socket.off('chat user left'); }); } sendMessage(message){ var deferred = this.$q.defer(); this.webSocketService.socket.emit('chat message', message, (resp) => { deferred.resolve(resp); }); return deferred.promise; } listenNewMessage(cb){ this.webSocketService.listen('chat new message', cb); } listenUserJoin(cb){ this.webSocketService.listen('chat user joined', cb); } listenUserLeave(cb){ this.webSocketService.listen('chat user left', cb); } } ChatService.$inject = ['webSocketService', '$q', '$rootScope'];
var initSort = function() { $("#sortable").sortable({ containment: "document", items: "> div", handle: ".handle", tolerance: "pointer", cursor: "move", opacity: 0.8, revert: 300, delay: 150, placeholder: "movable-placeholder", start: function(e, ui) { ui.placeholder.height(ui.helper.outerHeight()); } }); $(".sortable-content-children").sortable({ items: "> div", tolerance: "pointer", containment: "parent" }); } var initDrag = function () { $(".sortable-content-children").sortable({ items: "> div", tolerance: "pointer", containment: "parent" }); } $(document).on('click', '.viewRoutine', function() { var routineId = $(this).children('input').val(); $("#routines").hide(); $("#viewRoutine").html('<div id="pageload">' + '<div class="showbox">' + '<div class="loader">' + '<svg class="circular" viewBox="25 25 50 50">' + '<circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10"/>' + '</svg>' + '</div>' + '<p class="loader-text">Getting routine...</p>' + '</div>' + '</div>').show(); $.ajax({ url: '/routines/' + routineId, headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, method: 'GET', success: function(data) { $("#viewRoutine").html(data['data']).show(); $("#sortable").sortable({ handle: '.handle', cursor: 'move', cancel: '' }).disableSelection(); $('.selectpicker').selectpicker({}); initSort(); }, error: function() { $("#viewRoutine").hide(); $("#routines").show(); } }) }); $(document).on('click', '.routine-back', function() { $("#viewRoutine").empty().hide(); $("#routines").show(); $(".ps-container").scrollTop(0); $(".ps-container").perfectScrollbar('update'); }); $(document).on('click', '.deleteSharedRoutine', function() { var routineId = $(this).attr('id'); var name = $("#routine-" + routineId).find('.routine-name').html().trim(); swal({ title: 'Are you sure?', text: name + " will be removed from this list.", type: 'warning', showCancelButton: true, confirmButtonClass: 'btn btn-danger', cancelButtonClass: 'btn btn-primary', confirmButtonText: 'Yes, delete it!', buttonsStyling: false }).then(function () { swal({ title: 'Deleted!', text: 'The routine has been deleted.', type: 'success', confirmButtonClass: 'btn btn-primary', buttonsStyling: false }).done(); deleteRoutine(routineId); }).done(); }); /* Functions for deleting a routing */ $(document).on('click', '.deleteRoutine', function() { var routineId = $(this).attr('id'); var name = $("#routine-" + routineId).find('.routine-name').html().trim(); swal({ title: 'Are you sure?', text: name + " will be removed from your routines. However all connected workouts will not be deleted. You could also set the routine as inactive.", type: 'warning', showCancelButton: true, confirmButtonClass: 'btn btn-danger', cancelButtonClass: 'btn btn-primary', confirmButtonText: 'Yes, delete it!', buttonsStyling: false }).then(function () { swal({ title: 'Deleted!', text: 'Your routine has been deleted.', type: 'success', confirmButtonClass: 'btn btn-primary', buttonsStyling: false }).done(); deleteRoutine(routineId); }).done(); }); var deleteRoutine = function(routineId) { $.ajax({ url: '/routines/' + routineId + '/delete', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, method: 'GET', success: function(data) { $("#routine-" + routineId).fadeOut(); $("tr.child").fadeOut(); } }); } /* Functions for removing/adding exerciserows */ $(document).on('click', '#addMore', function() { var currentExerciseNr = parseInt($("#exerciseNr").val()); var exerciseNr = currentExerciseNr + 1; var formData = '<div class="thisExercise">' + '<input class="exerciseOrder" type="hidden" name="exercises[' + exerciseNr + '][order_nr]" value="">' + '<div class="card m-t-10 m-b-10">' + '<div class="card-body">' + '<div class="sortable-content">' + '<div class="clearfix">' + '<div class="btn-sm btn-primary sort-icon handle float-left">' + '<span class="fal fa-arrows-v"></span> Drag to sort' + '</div>' + '<button type="button" class="deleteExercise btn btn-sm btn-danger float-right m-x-0"><span class="fal fa-trash"></span></button>' + '</div>' + '<div class="row">' + '<div class="col-xs-12 col-sm-6">' + '<div class="form-group m-t-10 label-floating">' + '<label class="bmd-label-floating" for="exercise_name">Excersice name</label>' + '<input type="text" class="required form-control exercise_name" id="exercise_name" name="exercises[' + exerciseNr + '][exercise_name]">' + '</div>' + '</div>' + '<div class="col-xs-12 col-sm-6">' + '<div class="form-group">' + '<select id="muscle_group" class="selectpicker" name="exercises[' + exerciseNr + '][muscle_group]" data-style="select-with-transition" title="Choose a muscle group" data-size="8">' + '<option selected disabled>Select a muscle group</option>' + '<option value="back">Back</option>' + '<option value="biceps">Biceps</option>' + '<option value="triceps">Triceps</option>' + '<option value="forearms">Forearms</option>' + '<option value="abs">Abs</option>' + '<option value="shoulders">Shoulders</option>' + '<option value="legs">Legs</option>' + '<option value="chest">Chest</option>' + '</select>' + '</div>' + '</div>' + '</div>' + '<div class="row">' + '<div class="col-xs-12 col-sm-4">' + '<div class="form-group m-t-10 label-floating">' + '<label class="bmd-label-floating" for="goal_weight">Weight goal</label>' + '<input type="number" step="any" class="required form-control" id="goal_weight" name="exercises[' + exerciseNr + '][goal_weight]">' + '</div>' + '</div>' + '<div class="col-xs-6 col-sm-4">' + '<div class="form-group m-t-10 label-floating">' + '<label class="bmd-label-floating" for="goal_sets">Sets goal</label>' + '<input type="number" class="required form-control" id="goal_sets" name="exercises[' + exerciseNr + '][goal_sets]">' + '</div>' + '</div>' + '<div class="col-xs-6 col-sm-4">' + '<div class="form-group m-t-10 label-floating">' + '<label class="bmd-label-floating" for="goal_reps">Reps goal</label>' + '<input type="number" class="required form-control" id="goal_reps" name="exercises[' + exerciseNr + '][goal_reps]">' + '</div>' + '</div>' + '</div>' + '<div class="row">' + '<div class="col-md-8 col-xs-6">' + '<div class="form-group label-floating">' + '<label class="bmd-label-floating" for="media">Media</label>' + '<input type="text" class="form-control" id="media" name="exercises[' + exerciseNr + '][media]">' + '<i class="material-icons material-icons-sm pointer is-tooltip" ' + 'onclick="logit.initModal(\'\', \'Here you can add any URL that you like. Maybe to a YouTube video showing how the exercise is done?\', false)">' + 'help' + '</i>' + '</div>' + '</div>' + '<div class="col-md-4 col-xs-6">' + '<div class="form-check mt-4">' + '<label class="form-check-label">' + '<input class="form-check-input" type="checkbox" name="exercises[' + exerciseNr + '][is_warmup]">' + 'Warmup set' + '<span class="form-check-sign">' + '<span class="check"></span>' + '</span>' + '</label>' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>'; $("#exerciseNr").val(exerciseNr); $("#sortable").append(formData); $('.selectpicker').selectpicker({}); }); $(document).on('click', '#addSuperset', function() { var currentSupersetNr = parseInt($("#supersetNr").val()); var supersetNr = currentSupersetNr + 1; var formData = '<div class="thisExercise">' + '<input class="exerciseOrder" type="hidden" name="supersets[' + supersetNr + '][order_nr]" value="">' + '<div class="card card-transparent m-t-10 m-b-10">' + '<div class="card-body">' + '<div class="sortable-content">' + '<div class="clearfix">' + '<div class="btn-sm btn-primary sort-icon handle float-left">' + '<span class="fal fa-arrows-v"></span>' + ' Drag to sort' + '</div>' + '<button type="button" class="deleteExercise btn btn-sm btn-danger float-right m-x-0"><span class="fal fa-trash"></span></button>' + '</div>' + '<div class="form-group label-floating">' + '<label class="bmd-label-floating" for="exercise_name">Superset Name</label>' + '<input type="text" class="required form-control exercise_name" id="exercise_name" name="supersets[' + supersetNr + '][superset_name]">' + '</div>' + '</div>' + '<div class="sortable-content-children">' + '</div>' + '<input type="hidden" class="thisSupersetNr" value="' + supersetNr + '">' + '<button id="addMore-superset" type="button" class="btn btn-primary">Add another exercise</button>' + '</div>' + '</div>' + '</div>'; $("#supersetNr").val(supersetNr); $("#sortable").append(formData); $('.selectpicker').selectpicker({}); initSort(); }); $(document).on('click', '#addMore-superset', function() { var currentsupersetNr = parseInt($(this).parent().find('.thisSupersetNr').val()); var supersetNr = currentsupersetNr; var currentExerciseNr = parseInt($("#exerciseNr").val()); var exerciseNr = currentExerciseNr + 1; var formData = '<div class="thisExercise">' + '<div class="card m-t-10 m-b-10">' + '<div class="card-body">' + '<div class="sortable-content">' + '<div class="clearfix">' + '<div class="btn-sm btn-primary sort-icon handle float-left">' + '<span class="fal fa-arrows-v"></span>' + ' Drag to sort' + '</div>' + '<button type="button" class="deleteExercise btn btn-sm btn-danger float-right m-x-0"><span class="fal fa-trash"></span></button>' + '</div>' + '<div class="row">' + '<div class="col-xs-12 col-sm-6">' + '<div class="form-group label-floating">' + '<label class="bmd-label-floating" for="exercise_name">Excersice name</label>' + '<input type="text" class="required form-control exercise_name" id="exercise_name" name="supersets[' + supersetNr + '][' + exerciseNr + '][exercise_name]">' + '</div>' + '</div>' + '<div class="col-xs-12 col-sm-6">' + '<div class="form-group">' + '<select id="muscle_group" name="supersets[' + supersetNr + '][' + exerciseNr + '][muscle_group]" class="selectpicker" data-style="select-with-transition" title="Choose a muscle group" data-size="8">' + '<option selected disabled>Select a muscle group</option>' + '<option value="back">Back</option>' + '<option value="biceps">Biceps</option>' + '<option value="triceps">Triceps</option>' + '<option value="forearms">Forearms</option>' + '<option value="abs">Abs</option>' + '<option value="shoulders">Shoulders</option>' + '<option value="legs">Legs</option>' + '<option value="chest">Chest</option>' + '</select>' + '</div>' + '</div>' + '</div>' + '<div class="row">' + '<div class="col-md-4">' + '<div class="form-group label-floating">' + '<label class="bmd-label-floating" for="goal_weight">Weight goal</label>' + '<input type="number" step="any" class="required form-control" id="goal_weight" name="supersets[' + supersetNr + '][' + exerciseNr + '][goal_weight]">' + '</div>' + '</div>' + '<div class="col-sm-6 col-xs-6 col-md-4">' + '<div class="form-group label-floating">' + '<label class="bmd-label-floating" for="goal_sets">Sets goal</label>' + '<input type="number" class="required form-control" id="goal_sets" name="supersets[' + supersetNr + '][' + exerciseNr + '][goal_sets]">' + '</div>' + '</div>' + '<div class="col-sm-6 col-xs-6 col-md-4">' + '<div class="form-group label-floating">' + '<label class="bmd-label-floating" for="goal_reps">Reps goal</label>' + '<input type="number" class="required form-control" id="goal_reps" name="supersets[' + supersetNr + '][' + exerciseNr + '][goal_reps]">' + '</div>' + '</div>' + '</div>' + '<div class="row">' + '<div class="col-md-8 col-xs-6">' + '<div class="form-group label-floating">' + '<label class="bmd-label-floating" for="media">Media</label>' + '<input type="text" class="form-control" id="media" name="supersets[' + supersetNr + '][' + exerciseNr + '][media]">' + '<i class="material-icons material-icons-sm pointer is-tooltip" ' + 'onclick="logit.initModal(\'\', \'Here you can add any URL that you like. Maybe to a YouTube video showing how the exercise is done?\', false)">' + 'help' + '</i>' + '</div>' + '</div>' + '<div class="col-md-4 col-xs-6">' + '<div class="form-check mt-4">' + '<label class="form-check-label">' + '<input class="form-check-input" type="checkbox" name="supersets[' + supersetNr + '][' + exerciseNr + '][is_warmup]">' + 'Warmup set' + '<span class="form-check-sign">' + '<span class="check"></span>' + '</span>' + '</label>' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>'; $("#supersetNr").val(supersetNr); $("#exerciseNr").val(exerciseNr); $(this).parent().find(".sortable-content-children").append(formData); $('.selectpicker').selectpicker({}); initDrag(); }); $(document).on('click', '.deleteExercise', function() { $(this).closest('.thisExercise').fadeOut(function() { $(this).empty(); }); }); $(document).on('click', '#addRoutine', function() { var ok = true $(".required").each(function() { if ($(this).val() == "" || $(this).val() == null) { $(this).closest(".form-group").addClass("has-danger").find(".bmd-label-floating").removeClass("hidden") ok = false } else { $(this).closest(".form-group").removeClass("has-danger").find(".bmd-label-floating").addClass("hidden") } }); $(".btn-group.bootstrap-select").each(function() { if ($(this).find('button').attr('title') == "Select a muscle group") { $(this).closest(".form-group").addClass("has-danger").find(".bmd-label-floating").removeClass("hidden") ok = false } else { $(this).closest(".form-group").removeClass("has-danger").find(".bmd-label-floating").addClass("hidden") } }); var names = []; var dupes = []; var namesOk = false; $(".exercise_name").each(function() { names.push($(this).val()) }); names.sort() for (var i = 0; i < names.length - 1; i++) { if (names[i + 1] == names[i]) { dupes.push(names[i]); namesOk = true; ok = false; } } if (namesOk) { $("#alert-field").html('<div class="alert alert-danger">' + '<strong>Whops!</strong> Some of your exercises shares the same name (' + dupes[0] + '). This might cause issues. Append something to your duplicate exercisenames and try again.' + '</div>') } else { $("#alert-field").empty(); } // Gives each element proper ording $(".exerciseOrder").each(function(key) { $(this).val(key); }) if (ok) { $(this).html('<span class="fal fa-spin fa-circle-notch"></span> Saving changes ...'); } return ok }); $(document).on('click', '#changeStatus', function() { var routineId = $("#routineId").val(); var status = $("#status").val(); $.ajax({ url: '/routines/' + routineId + '/edit/status/', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, method: 'POST', data: { 'routineId': routineId, 'status': status, }, success: function(data) { if (data.success) { location.reload(); } else { $("#changeStatus").removeClass("btn-default").addClass("btn-danger").text("Refresh page and try again!") } }, error: function() { $("#changeStatus").removeClass("btn-default").addClass("btn-danger").text("Refresh page and try again!") } }) }); $(document).ready(function() { $('#datatables').DataTable({ "pagingType": "full_numbers", "lengthMenu": [ [10, 25, 50, -1], [10, 25, 50, "All"] ], responsive: true, language: { search: "_INPUT_", searchPlaceholder: "Search records", } }); var table = $('#datatables').DataTable(); initSort(); });
'use strict'; angular.module('yeoMeanApp') .controller('ContactCtrl', function ($rootScope, $scope) { $rootScope.metaTitle = "Contact | Brian Mitchell"; $rootScope.metaDescription = "Where to find Brian Mitchell"; $rootScope.metaType = "website"; $rootScope.metaImage = "/assets/images/BM-Logo-Large.png"; });
// Importing from `.json.js` a workaround for a bug in web browsers' "native" // ES6 importing system which is uncapable of importing "*.json" files. // https://github.com/catamphetamine/libphonenumber-js/issues/239 import metadata from '../metadata.mobile.json.js' export default metadata export function withMetadata(func, _arguments) { var args = Array.prototype.slice.call(_arguments) args.push(metadata) return func.apply(this, args) }
import{C as e}from"./component-f7c3c04e.js";import"./index-5013a1cd.js";export default class extends e{static get params(){return{component:"debugger",props:["target"]}}}
/** * Smokescreen Player - A Flash player written in JavaScript * http://smokescreen.us/ * * Copyright 2011, Chris Smoak * Released under the MIT License. * http://www.opensource.org/licenses/mit-license.php */ define(function(require, exports, module) { var ext = require('lib/ext') var env = require('lib/env') var DisplayObject = require('player/display_object').DisplayObject var Element = require('dom/element').Element var Namespace = require('dom/namespace').Namespace var as2_MovieClip = require('as2/movie_clip').MovieClip var DisplayList = require('player/display_list').DisplayList var MovieClip = function(def, loader, parent, renderer) { this.def = def this.loader = loader this.parent = parent this.renderer = renderer DisplayObject.call(this) this.timeline = def.timeline this.playhead = null this.onEnterFrameCallback = ext.bind(this.onEnterFrame, this) this.displayList = new DisplayList() this.$isTimelineControlled = !!this.timeline this.renderer.setMovieClip(this) } ext.inherits(MovieClip, DisplayObject) ext.add(MovieClip.prototype, { getPlayhead: function() { return this.playhead }, getFrameCount: function() { return this.timeline ? this.timeline.getFrameCount() : 1 }, // TODO: implement when we have async loading frameReady : function(frame) { return true }, enterFrame: function() { // update playhead var lastPlayhead = this.playhead if (lastPlayhead === null) { // first frame this.playing = (this.getFrameCount() > 1) this.playhead = 0 } else { // after first frame if (this.playing) { this.playhead += 1 if (this.playhead >= this.getFrameCount()) { this.playhead = 0 } } } this.$processFrameChange(lastPlayhead, true) }, $processFrameChange: function(lastPlayhead, enterFrame) { var toAdd = null if (this.playhead !== lastPlayhead) { if (this.timeline) { // update timeline entries var changes = this.timeline.getChangedSpans(lastPlayhead, this.playhead) var toRemove = changes.toRemove toAdd = changes.toAdd var toUpdate = changes.toUpdate // children are removed var removeLength = toRemove.length for (var i = 0; i < removeLength; i++) { var entry = toRemove[i] this.removeChildAtDepth(entry.getDepth()) } // children are updated var updateLength = toUpdate.length for (var i = 0; i < updateLength; i++) { var entry = toUpdate[i] this.$updateChild(entry) } } } // update all existing children var displayObjects = this.displayList.getDisplayObjects() for (var depth in displayObjects) { if (displayObjects.hasOwnProperty(depth)) { if (displayObjects[depth].enterFrame) { displayObjects[depth].enterFrame() } } } // queue up onEnterFrame if this is not the first time we're called if (enterFrame && lastPlayhead !== null) { this.loader.addAction(this.onEnterFrameCallback) } // queue up frame script if we've changed frames if (this.playhead !== lastPlayhead) { var callback = ext.bind(this.frameAction, this, [this.playhead]) this.loader.addAction(callback) } // new children are inited if (toAdd) { var addLength = toAdd.length for (var i = 0; i < addLength; i++) { var entry = toAdd[i] var obj = this.loader.createDisplayObject(entry.getInstance().tag, this) // TODO: limit when we need to update here this.$updateChild(entry) //obj.spanid = entry.getInstance().id } } }, $updateChild: function(entry) { var obj = this.displayList.getAtDepth(entry.getDepth()) if (obj && obj.isTimelineControlled()) { obj.timelineUpdate(entry.tag) } }, removeChildAtDepth: function(depth) { var obj = this.displayList.removeAtDepth(depth) if (obj) { this.renderer.removeChild(obj) this.childChangedName(obj, obj.getName(), null) } }, insertChild: function(obj, depth) { var displayList = this.displayList // if we have an existing object at this depth, move it var existing = displayList.getAtDepth(depth) if (existing) { var newDepth = displayList.getNextHighestDepth() existing.setDepth(newDepth) displayList.removeAtDepth(depth) displayList.setAtDepth(existing, newDepth) } // add the new object obj.setDepth(depth) displayList.setAtDepth(obj, depth) this.renderer.addChild(obj) this.childChangedName(obj, null, obj.getName()) }, frameAction: function(frame) { if (!this.timeline) { return } var tags = this.timeline.getFrame(frame).tags for (var i = 0; i < tags.length; i++) { var tag = tags[i] // TODO: cleanup following // button children's tags don't have headers if (!tag.header) { continue } //var t = fljs.swf.TagTypes switch (tag.header.TagType) { case 12://t.DoAction: this.loader.doAction(this, tag) break case 9://t.SetBackgroundColor: // TODO break case 15://t.StartSound: case 19://t.SoundStreamBlock: case 18://t.SoundStreamHead: case 45://t.SoundStreamHead2: break default: // [nop] } } }, onEnterFrame: function() { // TODO: rename _as2Object if (this._as2Object && this._as2Object.onEnterFrame) { this._as2Object.onEnterFrame() } }, play: function() { this.playing = true }, stop: function() { this.playing = false }, gotoAndPlay: function(frame) { this.playing = true this.$gotoFrame(frame) }, gotoAndStop: function(frame) { this.playing = false this.$gotoFrame(frame) }, $gotoFrame: function(frame) { // are we specifying a frame by label? if (typeof frame == 'string') { if (this.timeline) { frame = this.timeline.getFrameNumberForLabel(frame) } } // or by frame number? else { // we're 0-based, as2 is 1-based frame -= 1 } if (frame === null || frame < 0) { frame = 0 } if (frame >= this.getFrameCount()) { frame = this.getFrameCount() - 1 } var lastPlayhead = this.playhead this.playhead = frame this.$processFrameChange(lastPlayhead, false) }, as2Object : function() { if (!this._as2Object) { var mc = this._as2Object = new as2_MovieClip() mc.__dispObj = this var objs = this.displayList.getDisplayObjects() for (var depth in objs) { if (objs.hasOwnProperty(depth)) { var obj = objs[depth] var name = obj.getName() if (name) { mc[name] = obj.as2Object() } } } if (this.getName()) { mc[this.getName()] = mc } } return this._as2Object }, childChangedName: function(child, oldName, newName) { if (!oldName && !newName) { return } var mc = this._as2Object if (mc) { var target = child.as2Object() if (oldName && mc[oldName] === target) { delete mc[oldName] } if (newName) { mc[newName] = target } } }, /** * DisplayObject override */ calcBbox : function() { var bbox var objs = this.displayList.getDisplayObjects() for (var depth in objs) { if (objs.hasOwnProperty(depth)) { var obj = objs[depth] var objBbox = obj.placeBbox() if (!bbox) { bbox = objBbox.slice(0) } else { bbox = [ bbox[0] < objBbox[0] ? bbox[0] : objBbox[0], bbox[1] < objBbox[1] ? bbox[1] : objBbox[1], bbox[2] > objBbox[2] ? bbox[2] : objBbox[2], bbox[3] > objBbox[3] ? bbox[3] : objBbox[3] ] } } } if (!bbox) { bbox = [0, 0, 0, 0] } return bbox } }) exports.MovieClip = MovieClip })
version https://git-lfs.github.com/spec/v1 oid sha256:ba917294e0f245eed27f8fcafe6ff796ed9b6f99a4025eb0271300e09e1c464d size 1209
import { reducerFactory } from 'retax'; import { userTheme, adminTheme } from 'themes'; import { SET_ADMIN_THEME, SET_USER_THEME, } from 'constants/actions'; export default reducerFactory( userTheme, { [SET_ADMIN_THEME]() { return adminTheme; }, [SET_USER_THEME]() { return userTheme; }, } );
import { expect } from 'chai'; import HttpSmartError from 'http-smart-error'; import { RSError } from '../src'; import RSBaseError from '../src/error/base'; describe('RSError', () => { it('checks the error classes', () => { const classes = [ 'InvalidInputType', 'InvalidArgumentType', 'InvalidParameterType', 'MissingParameter', 'MissingApiKey', 'InvalidApiKey', 'MissingAccessToken', 'InvalidAccessToken', 'Timeout', 'NotFound', ]; expect(RSError).to.have.all.keys(classes); for (const cls of classes) { if (cls === 'InvalidInputType') { continue; } expect(new RSError[cls]()).to.be.an.instanceOf(RSBaseError); expect(new RSError[cls]()).to.be.an.instanceOf(HttpSmartError); } }); it('checks the default error', () => { const e = new RSError(); expect(e).to.be.an.instanceOf(HttpSmartError); expect(e).to.have.all.keys(['statusCode', 'code', 'message']); expect(e.statusCode).to.be.equal(500); expect(e.message).to.be.equal('Internal Server Error'); expect(e.code).to.be.equal('ERR_INTERNAL_SERVER_ERROR'); expect(e.getDescription()).to.be.equal(null); const f = RSError.toErrorField(); expect(f).to.have.all.keys(['code', 'description']); expect(f.code).to.be.equal(e.code); expect(f.description).to.be.equal(e.getDescription()); }); it('checks the default error with message and payload', () => { const e = new RSError('Test error', { test: 'test' }); expect(e).to.be.an.instanceOf(HttpSmartError); expect(e).to.have.all.keys(['statusCode', 'code', 'message', 'test']); expect(e.statusCode).to.be.equal(500); expect(e.message).to.be.equal('Test error'); expect(e.code).to.be.equal('ERR_INTERNAL_SERVER_ERROR'); expect(e.getDescription()).to.be.equal(null); expect(e.test).to.be.equal('test'); const f = RSError.toErrorField(); expect(f).to.have.all.keys(['code', 'description']); expect(f.code).to.be.equal(e.code); expect(f.description).to.be.equal(e.getDescription()); }); it('checks the subclass of the RSError', () => { class BadRequestError extends RSError { _getStatusCode() { return HttpSmartError.BAD_REQUEST; } } const e = new BadRequestError(); expect(e).to.be.an.instanceOf(HttpSmartError); expect(e).to.be.an.instanceOf(RSError); expect(e).to.have.all.keys(['statusCode', 'code', 'message']); expect(e.statusCode).to.be.equal(HttpSmartError.BAD_REQUEST); expect(e.message).to.be.equal('Bad Request'); expect(e.code).to.be.equal('ERR_BAD_REQUEST'); expect(e.getDescription()).to.be.equal(null); const f = BadRequestError.toErrorField(); expect(f).to.have.all.keys(['code', 'description']); expect(f.code).to.be.equal(e.code); expect(f.description).to.be.equal(e.getDescription()); }); it('checks the subclass of the RSError with custom message and code', () => { class BadRequestError extends RSError { getDescription() { return 'Returned if something went wrong.'; } _getStatusCode() { return HttpSmartError.BAD_REQUEST; } _getMessage() { return 'Custom message error'; } _getCode() { return 'wrong_request'; } } const e = new BadRequestError(); expect(e).to.be.an.instanceOf(HttpSmartError); expect(e).to.be.an.instanceOf(RSError); expect(e).to.have.all.keys(['statusCode', 'code', 'message']); expect(e.statusCode).to.be.equal(HttpSmartError.BAD_REQUEST); expect(e.message).to.be.equal('Custom message error'); expect(e.code).to.be.equal('ERR_WRONG_REQUEST'); expect(e.getDescription()).to.be.equal('Returned if something went wrong.'); const f = BadRequestError.toErrorField(); expect(f).to.have.all.keys(['code', 'description']); expect(f.code).to.be.equal(e.code); expect(f.description).to.be.equal(e.getDescription()); }); });
/** * Selfbits API V2 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: 2.0.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=Organization.js.map
define(function (require) { var fs = require('fs'), when = require('when'); return Constructor; function Constructor(debugLogger, filePath) { var self = this; self.diff = function diff(otherFile) { var deferred = when.defer(); fs.stat(filePath, function (err, stats) { // debugLogger.log('stats'); var diffResult = !!err || stats.size != parseInt(otherFile.size); // debugLogger.log(diffResult); deferred.resolve(diffResult); }); return deferred.promise; }; } });
var path = require('path') var fs = require('fs') var argv = require('optimist').argv; var express = require('express') var webpack = require('webpack') var config = require('../config') var opn = require('opn') var proxyMiddleware = require('http-proxy-middleware') var webpackConfig = process.env.NODE_ENV === 'testing' ? require('./webpack.prod.conf') : require('./webpack.dev.conf') // default port where dev server listens for incoming traffic var port = process.env.PORT || config.dev.port // Define HTTP proxies to your custom API backend // https://github.com/chimurai/http-proxy-middleware var proxyTable = config.dev.proxyTable var app = express() var compiler = webpack(webpackConfig) var devMiddleware = require('webpack-dev-middleware')(compiler, { publicPath: webpackConfig.output.publicPath, stats: { colors: true, chunks: false } }) var hotMiddleware = require('webpack-hot-middleware')(compiler) // force page reload when html-webpack-plugin template changes compiler.plugin('compilation', function (compilation) { compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) { hotMiddleware.publish({ action: 'reload' }) cb() }) }) // proxy api requests // Object.keys(proxyTable).forEach(function (context) { // var options = proxyTable[context] // if (typeof options === 'string') { // options = { target: options } // } // app.use(proxyMiddleware(context, options)) // }); // mock/proxy api requests var mockDir = path.resolve(__dirname, '../mock'); (function setMock(mockDir) { fs.readdirSync(mockDir).forEach(function (file) { var filePath = path.resolve(mockDir, file); var mock; if (fs.statSync(filePath).isDirectory()) { setMock(filePath); } else { mock = require(filePath); app.use(mock.api, argv.proxy ? proxyMiddleware({target: 'http://' + argv.proxy}) : mock.response); } }); })(mockDir);; // handle fallback for HTML5 history API app.use(require('connect-history-api-fallback')({ index: '/index.html' })) // serve webpack bundle output app.use(devMiddleware) // enable hot-reload and state-preserving // compilation error display app.use(hotMiddleware) // serve pure static assets var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory) app.use(staticPath, express.static('./static')) module.exports = app.listen(port, function (err) { if (err) { console.log(err) return } var uri = 'http://localhost:' + port console.log('Dev server listening at ' + uri + '\n') // opn(uri) })