code stringlengths 2 1.05M |
|---|
(function(JST) {
var TablarCrudRecentAdded;
TablarCrudRecentAdded = (function() {
function TablarCrudRecentAdded() {}
TablarCrudRecentAdded.prototype.parseData = function(args) {
return args;
};
TablarCrudRecentAdded.prototype.render = function(obj) {
var $root;
if (obj == null) {
obj = {};
}
return $root = $("#" + obj.elemHash);
};
return TablarCrudRecentAdded;
})();
return assignTmpl(JST.tablar.crud, 'recentadded', 'tablar.crud.recentadded', new TablarCrudRecentAdded);
})(this.JST);
|
import Vue from 'vue';
import component from '~/jobs/components/empty_state.vue';
import mountComponent from '../../helpers/vue_mount_component_helper';
describe('Empty State', () => {
const Component = Vue.extend(component);
let vm;
const props = {
illustrationPath: 'illustrations/pending_job_empty.svg',
illustrationSizeClass: 'svg-430',
title: 'This job has not started yet',
playable: false,
variablesSettingsUrl: '',
};
const content = 'This job is in pending state and is waiting to be picked by a runner';
afterEach(() => {
vm.$destroy();
});
describe('renders image and title', () => {
beforeEach(() => {
vm = mountComponent(Component, {
...props,
content,
});
});
it('renders img with provided path and size', () => {
expect(vm.$el.querySelector('img').getAttribute('src')).toEqual(props.illustrationPath);
expect(vm.$el.querySelector('.svg-content').classList).toContain(props.illustrationSizeClass);
});
it('renders provided title', () => {
expect(vm.$el.querySelector('.js-job-empty-state-title').textContent.trim()).toEqual(
props.title,
);
});
});
describe('with content', () => {
it('renders content', () => {
vm = mountComponent(Component, {
...props,
content,
});
expect(vm.$el.querySelector('.js-job-empty-state-content').textContent.trim()).toEqual(
content,
);
});
});
describe('without content', () => {
it('does not render content', () => {
vm = mountComponent(Component, {
...props,
});
expect(vm.$el.querySelector('.js-job-empty-state-content')).toBeNull();
});
});
describe('with action', () => {
it('renders action', () => {
vm = mountComponent(Component, {
...props,
content,
action: {
path: 'runner',
button_title: 'Check runner',
method: 'post',
},
});
expect(vm.$el.querySelector('.js-job-empty-state-action').getAttribute('href')).toEqual(
'runner',
);
});
});
describe('without action', () => {
it('does not render action', () => {
vm = mountComponent(Component, {
...props,
content,
action: null,
});
expect(vm.$el.querySelector('.js-job-empty-state-action')).toBeNull();
});
});
describe('without playbale action', () => {
it('does not render manual variables form', () => {
vm = mountComponent(Component, {
...props,
content,
});
expect(vm.$el.querySelector('.js-manual-vars-form')).toBeNull();
});
});
describe('with playbale action and not scheduled job', () => {
beforeEach(() => {
vm = mountComponent(Component, {
...props,
content,
playable: true,
scheduled: false,
action: {
path: 'runner',
button_title: 'Check runner',
method: 'post',
},
});
});
it('renders manual variables form', () => {
expect(vm.$el.querySelector('.js-manual-vars-form')).not.toBeNull();
});
it('does not render the empty state action', () => {
expect(vm.$el.querySelector('.js-job-empty-state-action')).toBeNull();
});
});
describe('with playbale action and scheduled job', () => {
it('does not render manual variables form', () => {
vm = mountComponent(Component, {
...props,
content,
});
expect(vm.$el.querySelector('.js-manual-vars-form')).toBeNull();
});
});
});
|
var jayson = require('jayson');
var client = jayson.client.http({
port: 3000
});
var post='چندتا دختر و پسر با شخصیت میخوام بیان تو گروهم اگه کسی هست بگه لینک بدم.. چرا کسی نمیاد ؟؟ یعنی همه گروه دارن؟'
client.request('post', [post], function(err, error, result) {
if(err) throw err;
console.log(result);
});
|
Clazz.declarePackage ("JU");
Clazz.load (["J.api.JmolAudioPlayer"], "JU.JmolAudio", ["JU.Logger"], function () {
c$ = Clazz.decorateAsClass (function () {
this.params = null;
this.myClip = null;
this.fileName = null;
this.vwr = null;
this.id = null;
this.autoClose = false;
Clazz.instantialize (this, arguments);
}, JU, "JmolAudio", null, [J.api.JmolAudioPlayer]);
Clazz.makeConstructor (c$,
function () {
});
Clazz.defineMethod (c$, "playAudio",
function (vwr, htParams) {
try {
this.id = htParams.get ("id");
if (this.id == null || this.id.length == 0) {
this.autoClose = true;
htParams.put ("id", this.id = "audio" + ++JU.JmolAudio.idCount);
}this.vwr = vwr;
this.params = htParams;
this.params.put ("audioPlayer", this);
this.fileName = htParams.get ("audioFile");
vwr.sm.registerAudio (this.id, htParams);
{
Jmol._playAudio(vwr.html5Applet, htParams);
}if (this.myClip == null) return;
if (htParams.containsKey ("action")) this.action (htParams.get ("action"));
else if (htParams.containsKey ("loop")) {
this.action ("loop");
} else {
this.autoClose = true;
this.action ("start");
}} catch (e) {
if (Clazz.exceptionOf (e, Exception)) {
JU.Logger.info ("File " + this.fileName + " could not be opened as an audio file");
} else {
throw e;
}
}
}, "JV.Viewer,java.util.Map");
Clazz.overrideMethod (c$, "update",
function (le) {
}, "javax.sound.sampled.LineEvent");
Clazz.defineMethod (c$, "processUpdate",
function (type) {
JU.Logger.info ("audio id " + this.id + " " + this.fileName + " " + type);
if (type === "open" || type === "Open") {
this.params.put ("status", "open");
} else if (type === "play" || type === "Start") {
this.params.put ("status", "play");
} else if (type === "pause" || type === "Stop") {
this.params.put ("status", "pause");
if (this.autoClose) {
this.myClip.close ();
}} else if (type === "ended" || type === "Close") {
this.params.put ("status", "ended");
} else {
this.params.put ("status", type);
}this.vwr.sm.notifyAudioStatus (this.params);
}, "~S");
Clazz.overrideMethod (c$, "action",
function (action) {
if (this.myClip == null) {
if (action === "kill") return;
this.params.put ("status", "ended");
this.vwr.sm.notifyAudioStatus (this.params);
return;
}try {
if ("start".equals (action)) {
this.myClip.setMicrosecondPosition (0);
this.myClip.loop (0);
this.myClip.start ();
} else if ("loop".equals (action)) {
this.myClip.setMicrosecondPosition (0);
this.myClip.loop (10);
this.myClip.start ();
} else if ("pause".equals (action)) {
if (this.myClip != null) this.myClip.stop ();
} else if ("play".equals (action)) {
this.myClip.stop ();
this.myClip.start ();
} else if ("close".equals (action)) {
this.myClip.close ();
}} catch (t) {
}
}, "~S");
Clazz.defineStatics (c$,
"MAX_LOOP", 10,
"idCount", 0);
});
|
'use strict';
let Session = require('../models/Session');
let sessionService = require('../services/sessionService');
let fileService = require('../services/fileService');
let path = require('path');
let express = require('express');
let router = express.Router();
let status = require('http-status');
let config = null;
function initialize(conf) {
config = conf;
}
/**
* Get all sessions.
*/
router.get('/sessions', (request, response) => {
sessionService.getSessions()
.then((sessions) => {
response.json(sessions);
})
.catch((err) => {
return response.status(status.INTERNAL_SERVER_ERROR).json({ error: err });
});
});
/**
* Get a session by id.
*/
router.get('/sessions/:id', (request, response) => {
let sessionId = request.params.id;
if (isNaN(sessionId) === true) {
return response.status(status.PRECONDITION_FAILED).json({ error: 'No session id given' });
}
sessionService.getSessionById(sessionId)
.then((session) => {
if (session === undefined) {
response.status(status.NOT_FOUND).json({ error: `Session with id ${sessionId} not found` });
} else {
response.json(session);
}
})
.catch((error) => {
return response.status(status.INTERNAL_SERVER_ERROR).json({ error: error });
});
});
/**
* Create a session.
*/
router.put('/sessions', (request, response) => {
let session = request.body;
if (session === undefined || session === null || Object.keys(session).length === 0) {
return response.status(status.PRECONDITION_FAILED).json({ error: 'No body given.'});
}
// create session
let sessionModel = new Session(session);
sessionService.createSession(sessionModel)
.then((sessionId) => {
if (sessionModel.files === null || sessionModel.files === undefined || sessionModel.files.length === 0) {
return response.status(status.CREATED).json({ id: sessionId });
}
// create session files
sessionService.createSessionFiles(sessionId, sessionModel.files)
.then(() => {
// start converting
console.log('Starting convert process');
fileService.startConvertProcess(sessionModel.files)
.then(() => {
return response.status(status.CREATED).json({ id: sessionId });
})
.catch((error) => {
return response.status(status.INTERNAL_SERVER_ERROR).json({ error: error });
});
})
.catch((error) => {
console.log(error.stack);
return response.status(status.INTERNAL_SERVER_ERROR).json({ error: error });
})
})
.catch((error) => {
return response.status(status.INTERNAL_SERVER_ERROR).json({ error: error });
})
});
module.exports = {
initialize, router
} |
const path = require('path');
const _ = require('lodash');
const chokidar = require('chokidar');
const bs = require('browser-sync').create();
const logger = require('connect-logger');
const historyApiFallback = require('connect-history-api-fallback');
const config = require('../config');
const cache = require ('../utils/cache');
const make = require('./make');
const requireDir = require('require-dir');
const plugins = requireDir('../plugins', {camelcase: true});
module.exports = serve;
function serve() {
if (process.env.task !== 'build') {
const srcDirResolved = path.resolve(config.srcDir);
const aboveSrcPaths = _(cache.get('files'))
.keys()
.concat(_.map(cache.get('deps'), 'srcResolved'))
.filter(srcResolved => !srcResolved.startsWith(srcDirResolved))
.uniq()
.value();
const watchOpts = {
ignoreInitial: true
};
chokidar.watch([srcDirResolved, ...aboveSrcPaths], watchOpts).on('all', (event, changedPath) => {
if (event !== 'change') {
return make().then(() => bs.reload());
}
const file = cache.get('files', changedPath);
const consumers = [];
const assets = [];
const reloadTargets = [];
var shouldMake = false;
var shouldMakeAll = false;
if (_.includes(['asset', 'import', 'wrapper'], file.role)) {
const deps = _(cache.get('deps'))
.filter({srcResolved: changedPath})
.map(dep => cache.get('files', dep.consumer))
.uniq()
.value();
consumers.push(...deps);
}
if (file.role === 'asset') {
assets.push(file);
const assetConsumers = _.filter(consumers, {role: 'asset'});
assets.push(...assetConsumers);
reloadTargets.push(file.destResolved);
reloadTargets.push(..._.map(assetConsumers, 'destResolved'));
shouldMake = true;
} else if (file.role === 'import') {
const assetConsumers = _.filter(consumers, {role: 'asset'});
assets.push(...assetConsumers);
reloadTargets.push(..._.map(assetConsumers, 'destResolved'));
shouldMake = true;
} else if (file.role === 'data') {
shouldMakeAll = true;
} else if (file.role === 'template') {
plugins.static(file);
} else if (file.role === 'wrapper') {
const templates = _.filter(consumers, {role: 'template'});
templates.forEach(plugins.static);
} else if (_.includes(['partial', 'lambda'], file.role)) {
const opts = {
shouldGetPartials: file.role === 'partial',
shouldGetLambdas: file.role === 'lambda'
};
const templates = _.filter(cache.get('files'), {role: 'template'});
templates.forEach(template => plugins.static(template, opts));
} else {
shouldMakeAll = true;
}
if (shouldMakeAll) {
make().then(() => bs.reload());
} else if (shouldMake) {
make({assets, targeted: true}).then(() => bs.reload(reloadTargets));
} else {
bs.reload();
}
});
}
const bsMiddleware = [logger()];
if (config.spaRouting) {
bsMiddleware.push(historyApiFallback());
}
const bsOpts = {
server: {
baseDir: config.destDir,
serveStaticOptions: {
extensions: ['html']
}
},
middleware: bsMiddleware,
snippetOptions: {
rule: {
match: /$/,
fn: function (snippet) {
return snippet;
}
}
},
notify: false,
ghostMode: false
};
bs.init(bsOpts);
}
|
"use strict";
module.exports = {
'constructors': {
'Date': function(opts) {
return new Date(opts);
}
},
'methods': {
'Point': function(Point, types) {
Point.prototype.toString = function() {
return '[object Point('+ this.x + ',' + this.y + ')]';
};
},
'PointCollection': function(PointCollection, types) {
PointCollection.prototype.push = function(point) {
/* ... */
};
}
}
};
|
exports.index = function (req, res) {
res.render('home', {
title: 'Home'
});
};
|
// For authoring Nightwatch tests, see
// http://nightwatchjs.org/guide#usage
module.exports = {
'default e2e tests': function (browser) {
// automatically uses dev Server port from /config.index.js
// default: http://localhost:8080
// see nightwatch.conf.js
const devServer = browser.globals.devServerURL
browser
.url(devServer)
.waitForElementVisible('#sedientos', 5000)
.assert.elementPresent('.vue-map')
// Google maps is loaded
.assert.elementPresent('gm-style')
// We should be able to count markers when using customized html
.end()
}
}
|
// jme.auth.flat_file_sha512-crypt.js
var sha512 = require('sha512crypt-node');
exports.register = function () {
var plugin = this;
plugin.inherits('auth/auth_base');
var load_config = function () {
plugin.cfg = plugin.config.get('jme.mailbox_accounts', 'json') || {};
};
load_config();
};
exports.hook_capabilities = function (next, connection) {
var plugin = this;
// don't allow AUTH unless private IP or encrypted
if (!connection.using_tls) {
connection.logdebug(plugin, "Auth disabled for insecure public connection");
return next();
}
var methods = ['PLAIN', 'LOGIN'];
connection.capabilities.push('AUTH ' + methods.join(' '));
connection.notes.allowed_auth_methods = methods;
next();
};
exports.retrieveUser = function (connection, user, cb) {
var plugin = this;
var username = user.split('@')[0];
var domain = user.split('@')[1] || '';
connection.loginfo(plugin, "Checking password for " + user);
if (plugin.cfg.accounts[domain]) {
if (plugin.cfg.accounts[domain][username]) {
return cb(plugin.cfg.accounts[domain][username].password);
}
}
return cb(null);
};
exports.validateHash = function(hash, password) {
// Need to add support for round specification here
var salt = hash.match(/^\$6\$(.*)\$/)[1];
var validHash = sha512.b64_sha512crypt(password, salt);
if (validHash === hash) return true;
return false;
};
exports.check_plain_passwd = function (connection, user, password, cb) {
var instance = this;
this.retrieveUser(connection, user, function (hash) {
if (hash === null) {
return cb(false);
}
var validHash = instance.validateHash(hash, password);
return cb(validHash);
});
};
|
var sequelize = require('sequelize');
function timediff(start, end, name, unit){
return [sequelize.fn('TIMESTAMPDIFF', sequelize.literal(unit), sequelize.col(start), sequelize.col(end)), name];
}
function final_time(datetime, name, unit, value, format){
return [sequelize.fn('DATE_FORMAT', sequelize.fn('DATE_ADD', sequelize.col(datetime), sequelize.literal('INTERVAL '+value+' '+unit+'')), format), name];
}
function epg_progress(start, end, name){
var time_passed = sequelize.fn('TIMESTAMPDIFF', sequelize.literal('SECOND'), sequelize.col(start), sequelize.literal('NOW()'));
var duration = sequelize.fn('TIMESTAMPDIFF', sequelize.literal('SECOND'), sequelize.col(start), sequelize.col(end));
return [time_passed, name];
}
function epg_progressi(start, end, name){
return [sequelize.fn('IF', sequelize.col(start), sequelize.literal('NOW()'), sequelize.literal('start>now'), sequelize.literal('start<now')), name];
}
function add_constant(value, name){
return [sequelize.literal("'"+value+"'"), name];
}
function to_upper(value, name){
return [sequelize.fn('upper', Sequelize.col('title')), name];
}
exports.timediff = timediff;
exports.final_time = final_time;
exports.epg_progress = epg_progress;
exports.add_constant = add_constant;
exports.to_upper = to_upper;
exports.epg_progressi = epg_progressi; |
import React from 'react';
import { IndexLink, Link } from 'react-router';
import './Header.scss';
export const Header = () => (
<div className='header'>
</div>
);
export default Header;
|
import Bot from './Bot';
import LoggerFactory from './Logger';
import TwitchWebhookHandler from './TwitchWebhookHandler';
import ConfigManager from './ConfigManager';
import CommandConfig from './config/CommandConfig';
const logger = LoggerFactory.getLogger();
let bot;
let twitch;
let saved = false;
function twitchEnabled() {
if (process.argv) {
for (const value of process.argv) {
if (/^(--twitch-notifications|-t)/.test(value)) {
return true;
}
}
}
}
function onExit() {
if (!saved) {
if (bot.memesUpdated) {
ConfigManager.saveMemes(bot.commands.meme);
logger.log('info', 'saved Memes');
}
if (bot.commandsUpdated) {
delete bot.commands.meme;
CommandConfig.commands = bot.commands;
ConfigManager.saveCommands(CommandConfig);
}
ConfigManager.saveGuildSettings(bot.guildSettings);
logger.log('info', 'Saved guild settings');
ConfigManager.saveGuildLevels(bot.guildLevels);
logger.log('info', 'Saved guild levels');
if (twitch) {
twitch.unsubFromAll();
}
saved = true;
}
process.exit(0);
}
process.on('SIGINT', onExit);
process.on('SIGTERM', onExit);
process.on('exit', onExit);
bot = new Bot();
if (twitchEnabled()) {
twitch = new TwitchWebhookHandler(bot);
}
|
"use strict";
var rulebook = require('../../domain/gameroom/rulebook'),
rulebookRepository = require('../repository/rulebook'),
RULEBOOK_ID = 'gnostica';
exports.schema = rulebookRepository.schemaName;
exports.up = function(db) {
var gnostica = rulebook.createRulebook(RULEBOOK_ID, 'Gnostica');
gnostica.description = 'A muti-player strategy game where players compete for influence over a magical landscape of tarot cards.';
gnostica.participants = {
min: 2,
max: 6
};
var repo = rulebookRepository.open(db);
return repo.save(gnostica);
};
exports.down = function(db) {
var repo = rulebookRepository.open(db);
return repo.removeById(RULEBOOK_ID);
};
|
/**
* Created by QingWang on 2014/8/6.
*/
var mysql = require('mysql');
var JsonResult = require('./JsonResult');
var chance = require('chance');
var fs = require('fs');
function Utility () {
}
/*
* function parser(obj)
* [Array] obj : this is a dictionary contains orderby,query,pagination or null
*
* This is function is parser the dictionary to sql where condition and return it.
*
*/
Utility.prototype.parser = function (obj, alias) {
var params = obj.params;
if (!params || params == 'undefined') {
params = {
orderby: null,
query: null,
pagination: null
};
}
//表的别名
var d = '';
if (alias) {
d = alias + '.';
}
var orderBy = params.orderby;//排序
var query = params.query;//查询参数
var pagination = params.pagination;//分页参数
//sql where condition
var condition = " WHERE 1=1 ";
if (query) {
for (var item in query) {
condition += " and " + d + item + "=" + mysql.escape(query[item]);
}
}
//order by
var orderColumnCount = 0;
var order = " ";
if (orderBy) {
order = " order by ";
for (var item in orderBy) {
orderColumnCount++;
order += (item + " " + orderBy[item] + ",");
}
if (orderColumnCount == 0) {
order = "";
}
else {
order = order.substring(0, order.length - 1);//移除最后一个逗号
}
}
// pagination
var limit = " ";
if (pagination) {
limit = " limit " + parseInt(pagination.pagesize) * parseInt(pagination.pageindex) + "," + pagination.pagesize;
}
return {condition: condition, order: order, limit: limit};
};
Utility.prototype.parserQueryLike = function (obj, alias, isLike, includeField, tenant) {
var params = obj.params;
if (!params || params == 'undefined') {
params = {
orderby: null,
query: null,
pagination: null
};
}
//表的别名
var d = '';
if (alias != '') {
d = alias + '.';
}
var orderBy = params.orderby;//排序
var query = params.query;//查询参数
var pagination = params.pagination;//分页参数
//sql where condition
var condition = " WHERE 1=1 ";
if (query) {
for (var item in query) {
if (isLike && this.contains(includeField, item)) {
condition += " and (lower(" + d + item + ") like '%" + query[item].toLowerCase() + "%')";
} else {
condition += " and lower(" + d + item + ")=" + mysql.escape(query[item].toLowerCase());
}
}
}
if (tenant) {
condition += " and " + d + "tenant=" + tenant;
}
//order by
var orderColumnCount = 0;
var order = " ";
if (orderBy) {
order = " order by ";
for (var item in orderBy) {
orderColumnCount++;
order += (item + " " + orderBy[item] + ",");
}
if (orderColumnCount == 0) {
order = "";
}
else {
order = order.substring(0, order.length - 1);//移除最后一个逗号
}
}
// pagination
var limit = " ";
if (pagination) {
limit = " limit " + parseInt(pagination.pagesize) * parseInt(pagination.pageindex) + "," + pagination.pagesize;
}
return {condition: condition, order: order, limit: limit};
};
/*
* function combineParams(params,isAddId)
* [Array] params : this is a dictionary contains request paramters.
* [boolean] isAddId: this is a boolean type, whether or not create guid.
* [Array] exceptArray:this is a except parameters array.
*
* This is function is combin the insert sql parameters and return it.
*
*/
Utility.prototype.combineParams = function (params, isAddId, exceptArray) {
var keys = '',
values = '';
if (isAddId) {
params.id = this.NewGuid();
}
for (var item in params) {
if (this.contains(exceptArray, item)) {
continue;
}
keys += item + ',';
values += mysql.escape(params[item]) + ",";
}
return {keys: keys, values: values};
};
/*
* function combineDeleteQuery(parameter,dbtable)
* [Array] parameter : this is a dictionary contains request paramters.
* [String] dbtable: this is a database table.
*
* This is function is combin the delete sql parameters and return it.
*
*/
Utility.prototype.combineDeleteQuery = function (parameter, dbtable) {
var condition = '',
result = false,
deleteQuery = '';
if (parameter.id != '') {
condition = ' WHERE id=' + mysql.escape(parameter.id);
deleteQuery = 'DELETE FROM ' + dbtable + condition;
result = true;
} else {
deleteQuery = "输入的参数id为空,不能进行删除操作!";
}
return {result: result, query: deleteQuery};
};
/*
* function combineUpdateParam(parameter,exceptArray)
* [Array] parameter : this is a dictionary contains request paramters.
* [Array] exceptArray: this is a except parameters array.
*
* This is function is combin the update sql parameters condition and return it.
*
*/
Utility.prototype.combineUpdateParam = function (parameter, exceptArray) {
var condition = ' SET ',
result = false;
for (var item in parameter) {
result = true;
if (this.contains(exceptArray, item)) {
continue;
}
condition += item + "=" + mysql.escape(parameter[item]) + ",";
}
if (!result) {
condition = "更新的参数为空,所以不能进行更新!";
}
return {result: result, condition: condition};
};
/*
* function jsonResult(err,data,cnt)
* [Error] err : error message.
* [Array] data: the data from the database.
* [int] cnt: the pagination totalcount.
*
* This is function return the json object.
*
*/
Utility.prototype.jsonResult = function (err, data, cnt) {
var jsonResult = new JsonResult();
jsonResult.Result = true;
jsonResult.Message = '';
jsonResult.Data = data;
if (cnt) {
jsonResult.TotalCount = cnt;
}
if (err) {
jsonResult.Result = false;
jsonResult.Message = err;
jsonResult.Data = '';
}
return jsonResult;
};
/*
* function contains(arr,item)
* [Array] arr : Array.
* [string] item : item.
*
* This is function Array extention.
*
*/
Utility.prototype.contains = function (arr, item) {
return RegExp(item).test(arr);
};
Utility.prototype.NewGuid = function () {
return new chance().guid();
};
Utility.prototype.isValidData = function (data) {
return data !== undefined && data !== "" && data !== null;
};
Utility.prototype.Group = 0;
Utility.prototype.User = 1;
Utility.prototype.ResetPassword = "123456";
Utility.prototype.ParamToJson = function (tpParam) {
if (tpParam) {
var paramsObj = typeof(tpParam) == "object" ? tpParam : JSON.parse(tpParam);
return paramsObj;
}
return tpParam;
};
Utility.prototype.JsonToParamString = function (tpParam) {
if (tpParam) {
var paramsStr = typeof(tpParam) == "string" ? tpParam : JSON.stringify(tpParam);
return paramsStr;
}
return tpParam;
};
Utility.prototype.ParamsParse = function (tpParam) {
var params = this.ParamToJson(tpParam);
if (!params || params == 'undefined') {
params = {
orderby: null,
query: null,
pagination: null
};
}
if (!params.orderby) {
params.orderby = {};
}
if (!params.query) {
params.query = {};
}
if (!params.pagination) {
params.pagination = {};
}
return params;
};
Utility.prototype.GetLastAppFile = function (path, versionCode, domainUrl, callback) {
fs.readdir(path, function (err, files) {
if (err) {
console.log('error:\n' + err);
return callback(err, {success: false, apkurl: ''});
}
var success = false;
var returnVersion = versionCode.replace(/\./g, '');
var returnFile = '';
files.forEach(function (file) {
var res = file.match(/app_(\d+\.(\d+\.)+\d+).apk/); //没有使用g选项
var version = res[1].replace(/\./g, '');
if (parseInt(version) > parseInt(returnVersion)) {
returnVersion = version;
returnFile = domainUrl + "/android/" + file;
success = true;
}
});
callback(err, {success: success, apkurl: returnFile});
});
};
module.exports = new Utility();
|
$(document).ready(function() {
var form = $("form")[0];
var submitButton = $("#submit-button");
var resetButton = $("#reset-button");
submitButton.click(function() {
// The serialize method requires that input elements have name attributes
var data = $(form).serialize();
// Post using xml http request...
// Prevent the page from submitting
return false;
});
resetButton.click(function() {
// Reset the form to default values
form.reset();
// Prevent the page from submitting
return false;
});
form.onsubmit = function() {
// Only runs when submitting via button click, not programatically
console.log("Submitting...");
};
});
|
'use strict';
angular.module('myApp.Settings', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/Settings', {
templateUrl: 'Settings/Settings.html',
controller: 'SettingsCtrl'
});
}])
.controller('SettingsCtrl', [function() {
}]); |
/**
* @module app.infobar.projectionselectorDirective
*/
/**
* @fileoverview This file provides a "projectionselector" directive
* This directive is used to insert an Projection Selector and
* Coordinate Display into the HTML page.
* Example:
*
* <app-projectionselector app-projectionselector-map="::mainCtrl.map" >
* </app-projectionselector>
*
* Note the use of the one-time binding operator (::) in the map expression.
* One-time binding is used because we know the map is not going to change
* during the lifetime of the application.
*
*/
import appModule from '../module.js';
/**
* @return {angular.Directive} The Directive Object Definition.
* @param {string} appProjectionselectorTemplateUrl The template url.
* @ngInject
*/
const exports = function(appProjectionselectorTemplateUrl) {
return {
restrict: 'E',
scope: {
'map': '=appProjectionselectorMap'
},
controller: 'AppProjectionselectorController',
controllerAs: 'ctrl',
bindToController: true,
templateUrl: appProjectionselectorTemplateUrl
};
};
appModule.directive('appProjectionselector', exports);
export default exports;
|
(function () {
'use strict';
angular
.module('curriculums')
.controller('CurriculumsController', CurriculumsController);
CurriculumsController.$inject = ['$scope', 'Notification', 'CurriculumsService', 'Authentication', '$http', '$window', 'FonctionsService', 'EtablissementsService'];
function CurriculumsController($scope, Notification, CurriculumsService, Authentication, $http, $window, FonctionsService, EtablissementsService) {
var vm = this;
vm.downloadPdf = downloadPdf;
vm.user = Authentication.user;
vm.fonctions = FonctionsService.query();
vm.etablissements = EtablissementsService.query();
vm.cv = CurriculumsService.get({
curriculumId: Authentication.user.cv
});
vm.validateCV = validateCV;
function validateCV() {
$http.get('/api/validateCV').success(function() {
console.log('ok');
});
}
function downloadPdf(user) {
$http.get('/api/curriculums/pdf/' + cv._id)
.then(function(response) {
var path = response.data;
path = path.slice(1);
$window.open (path, '_blank');
});
}
}
}());
|
// two way binding textarea value
var san = require('../../../dist/san.ssr');
var MyComponent = san.defineComponent({
template: '<div><span title="{{name}}">{{name}}</span> <textarea value="{=name=}"></textarea></div>'
});
exports = module.exports = MyComponent;
|
module.exports = {
transform: {},
moduleNameMapper: {
'<rootDir>': '<rootDir>'
}
}
|
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { Pages, navList } from './components/pages';
import MainPage from './components/mainpage';
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';
// Current Issues: Sending props to sub-components with Router
const [
Page1,
Page2,
Page3,
Page4,
Page5,
Page6,
Page7,
Page8,
Page9,
Page10,
] = Pages;
class App extends Component {
constructor(props) {
super(props);
this.state = { value: null };
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({ value: e.target.value });
console.log(this.state.value);
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Test App</h2>
</div>
<Router>
<div>
<div>
<ul className="nav">
<li>
<Link to="/">Start</Link>
</li>
{navList}
</ul>
</div>
<Switch>
<Route exact path="/" component={MainPage} />
<Route path="/q1" component={Page1} />
<Route path="/q2" component={Page2} />
<Route path="/q3" component={Page3} />
<Route path="/q4" component={Page4} />
<Route path="/q5" component={Page5} />
<Route path="/q6" component={Page6} />
<Route path="/q7" component={Page7} />
<Route path="/q8" component={Page8} />
<Route path="/q9" component={Page9} />
<Route path="/q10" component={Page10} />
<Route
render={function() {
return <h1>Error: Nothing Found</h1>;
}}
/>
</Switch>
</div>
</Router>
</div>
);
}
}
export default App;
|
import svelte from "rollup-plugin-svelte";
import commonjs from "@rollup/plugin-commonjs";
import resolve from "@rollup/plugin-node-resolve";
import replace from "@rollup/plugin-replace";
import livereload from "rollup-plugin-livereload";
import { terser } from "rollup-plugin-terser";
const production = !process.env.ROLLUP_WATCH;
function serve() {
let server;
function toExit() {
if (server) server.kill(0);
}
return {
writeBundle() {
if (server) return;
server = require("child_process").spawn("npm", ["run", "start", "--", "--dev"], {
stdio: ["ignore", "inherit", "inherit"],
shell: true
});
process.on("SIGTERM", toExit);
process.on("exit", toExit);
}
};
}
export default [{
input: "src/app/main.js",
output: {
sourcemap: true,
format: "iife",
name: "app",
file: "dist/app-script.js"
},
plugins: [
svelte({
compilerOptions: {
// enable run-time checks when not in production
dev: !production
}
}),
// If you have external dependencies installed from
// npm, you"ll most likely need these plugins. In
// some cases you"ll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ["svelte"]
}),
commonjs(),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload("dist"),
// If we"re building for production (npm run build
// instead of npm run dev), minify
production && terser()
],
watch: {
clearScreen: false
}
}, {
input: "src/entry.js",
output: {
format: "iife",
name: "entry",
file: "dist/entry-script.js"
},
plugins: [
production && terser()
],
}, {
input: "src/sw.js",
output: {
format: "iife",
name: "sw",
file: "service-worker.js"
},
plugins: [
resolve(),
replace({
"process.env.NODE_ENV": production ? "'production'" : "''",
}),
production && terser()
],
}];
|
export { default } from 'ember-fhir/models/process-request'; |
var XhrIo = {
get: function () {
}
}; |
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(90);
module.exports = __webpack_require__(90);
/***/ }),
/***/ 90:
/***/ (function(module, exports) {
(function( window, undefined ) {
kendo.cultures["en"] = {
name: "en",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
name: "",
abbr: "",
pattern: ["($n)","$n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "$"
}
},
calendars: {
standard: {
days: {
names: ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],
namesAbbr: ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],
namesShort: ["Su","Mo","Tu","We","Th","Fr","Sa"]
},
months: {
names: ["January","February","March","April","May","June","July","August","September","October","November","December"],
namesAbbr: ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
},
AM: ["AM","am","AM"],
PM: ["PM","pm","PM"],
patterns: {
d: "M/d/yyyy",
D: "dddd, MMMM d, yyyy",
F: "dddd, MMMM d, yyyy h:mm:ss tt",
g: "M/d/yyyy h:mm tt",
G: "M/d/yyyy h:mm:ss tt",
m: "MMMM d",
M: "MMMM d",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "h:mm tt",
T: "h:mm:ss tt",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": "/",
":": ":",
firstDay: 0
}
}
}
})(this);
/***/ })
/******/ }); |
import React, { Component } from 'react'
import Button from './component/Button'
import HLine from './component/HLine'
import H1 from './component/H1'
import H1Sub from './component/H1Sub'
import Callout from './component/Callout'
import Mission from "./component/Mission";
import colors from './colors'
import css from './styles.css'
import s from './svg/hline.svg'
import style from './component/Button'
const styles = {
button: {
flex: '0 1 23%',
// marginLeft: '24px',
}
}
class App extends Component {
render() {
return <div className='flex-column' style={{padding: '0px 42px', color: colors.dark}}>
<div className='flex-row' style={{
margin: '26px 0px 22px'}}>
<Callout style={{marginRight: '24px'}} />
<div className='flex-row' style={{flex: '1', justifyContent: 'space-between'}}>
<Button text='MAP' img='' style={styles.button} />
<Button text='QUEST' img='' style={styles.button} />
<Button text='ITEM' img='' style={styles.button} />
<Button text='WEAPON' img='' style={styles.button} />
</div>
</div>
<HLine style={{margin: '0px -42px'}} />
<div className='flex-row' style={{margin: '10px 0px 36px', alignItems: 'baseline'}}>
<H1 text='MAP' />
</div>
<div className='flex-row'>
<div className='flex-column' style={{flex: 3, justifyContent: 'space-between', marginRight: '66px'}}>
<div className='flex-row' style={{height: '200px'}}>
<Callout style={{marginRight: '24px'}} />
<div className='flex-column' style={{flex: 1, justifyContent: 'space-between'}}>
<Button type='small' text='快速保存' img='' />
<Button type='small' text='地图阅览模式' img='' />
<Button type='small' text='地图图示一览' img='' />
</div>
</div>
<Mission area='森林地带' name='飞弹的补给作战' summary='支援沉默都市的飞弹补给作战' />
</div>
<img style={{flex: 7, height: '600px', border: `1px solid ${colors.gray}`}} src='' alt='' />
</div>
<HLine style={{margin: '32px -42px'}} />
</div>
}
componentWillMount() {
document.body.style.backgroundColor = colors.light
}
}
export default App |
/**
* Phoenix Channels JavaScript client
*
* ## Socket Connection
*
* A single connection is established to the server and
* channels are multiplexed over the connection.
* Connect to the server using the `Socket` class:
*
* ```javascript
* let socket = new Socket("/socket", {params: {userToken: "123"}})
* socket.connect()
* ```
*
* The `Socket` constructor takes the mount point of the socket,
* the authentication params, as well as options that can be found in
* the Socket docs, such as configuring the `LongPoll` transport, and
* heartbeat.
*
* ## Channels
*
* Channels are isolated, concurrent processes on the server that
* subscribe to topics and broker events between the client and server.
* To join a channel, you must provide the topic, and channel params for
* authorization. Here's an example chat room example where `"new_msg"`
* events are listened for, messages are pushed to the server, and
* the channel is joined with ok/error/timeout matches:
*
* ```javascript
* let channel = socket.channel("room:123", {token: roomToken})
* channel.on("new_msg", msg => console.log("Got message", msg) )
* $input.onEnter( e => {
* channel.push("new_msg", {body: e.target.val}, 10000)
* .receive("ok", (msg) => console.log("created message", msg) )
* .receive("error", (reasons) => console.log("create failed", reasons) )
* .receive("timeout", () => console.log("Networking issue...") )
* })
*
* channel.join()
* .receive("ok", ({messages}) => console.log("catching up", messages) )
* .receive("error", ({reason}) => console.log("failed join", reason) )
* .receive("timeout", () => console.log("Networking issue. Still waiting..."))
*```
*
* ## Joining
*
* Creating a channel with `socket.channel(topic, params)`, binds the params to
* `channel.params`, which are sent up on `channel.join()`.
* Subsequent rejoins will send up the modified params for
* updating authorization params, or passing up last_message_id information.
* Successful joins receive an "ok" status, while unsuccessful joins
* receive "error".
*
* ## Duplicate Join Subscriptions
*
* While the client may join any number of topics on any number of channels,
* the client may only hold a single subscription for each unique topic at any
* given time. When attempting to create a duplicate subscription,
* the server will close the existing channel, log a warning, and
* spawn a new channel for the topic. The client will have their
* `channel.onClose` callbacks fired for the existing channel, and the new
* channel join will have its receive hooks processed as normal.
*
* ## Pushing Messages
*
* From the previous example, we can see that pushing messages to the server
* can be done with `channel.push(eventName, payload)` and we can optionally
* receive responses from the push. Additionally, we can use
* `receive("timeout", callback)` to abort waiting for our other `receive` hooks
* and take action after some period of waiting. The default timeout is 10000ms.
*
*
* ## Socket Hooks
*
* Lifecycle events of the multiplexed connection can be hooked into via
* `socket.onError()` and `socket.onClose()` events, ie:
*
* ```javascript
* socket.onError( () => console.log("there was an error with the connection!") )
* socket.onClose( () => console.log("the connection dropped") )
* ```
*
*
* ## Channel Hooks
*
* For each joined channel, you can bind to `onError` and `onClose` events
* to monitor the channel lifecycle, ie:
*
* ```javascript
* channel.onError( () => console.log("there was an error!") )
* channel.onClose( () => console.log("the channel has gone away gracefully") )
* ```
*
* ### onError hooks
*
* `onError` hooks are invoked if the socket connection drops, or the channel
* crashes on the server. In either case, a channel rejoin is attempted
* automatically in an exponential backoff manner.
*
* ### onClose hooks
*
* `onClose` hooks are invoked only in two cases. 1) the channel explicitly
* closed on the server, or 2). The client explicitly closed, by calling
* `channel.leave()`
*
*
* ## Presence
*
* The `Presence` object provides features for syncing presence information
* from the server with the client and handling presences joining and leaving.
*
* ### Syncing state from the server
*
* To sync presence state from the server, first instantiate an object and
* pass your channel in to track lifecycle events:
*
* ```javascript
* let channel = socket.channel("some:topic")
* let presence = new Presence(channel)
* ```
*
* Next, use the `presence.onSync` callback to react to state changes
* from the server. For example, to render the list of users every time
* the list changes, you could write:
*
* ```javascript
* presence.onSync(() => {
* myRenderUsersFunction(presence.list())
* })
* ```
*
* ### Listing Presences
*
* `presence.list` is used to return a list of presence information
* based on the local state of metadata. By default, all presence
* metadata is returned, but a `listBy` function can be supplied to
* allow the client to select which metadata to use for a given presence.
* For example, you may have a user online from different devices with
* a metadata status of "online", but they have set themselves to "away"
* on another device. In this case, the app may choose to use the "away"
* status for what appears on the UI. The example below defines a `listBy`
* function which prioritizes the first metadata which was registered for
* each user. This could be the first tab they opened, or the first device
* they came online from:
*
* ```javascript
* let listBy = (id, {metas: [first, ...rest]}) => {
* first.count = rest.length + 1 // count of this user's presences
* first.id = id
* return first
* }
* let onlineUsers = presence.list(listBy)
* ```
*
* ### Handling individual presence join and leave events
*
* The `presence.onJoin` and `presence.onLeave` callbacks can be used to
* react to individual presences joining and leaving the app. For example:
*
* ```javascript
* let presence = new Presence(channel)
*
* // detect if user has joined for the 1st time or from another tab/device
* presence.onJoin((id, current, newPres) => {
* if(!current){
* console.log("user has entered for the first time", newPres)
* } else {
* console.log("user additional presence", newPres)
* }
* })
*
* // detect if user has left from all tabs/devices, or is still present
* presence.onLeave((id, current, leftPres) => {
* if(current.metas.length === 0){
* console.log("user has left from all devices", leftPres)
* } else {
* console.log("user left from a device", leftPres)
* }
* })
* // receive presence data from server
* presence.onSync(() => {
* displayUsers(presence.list())
* })
* ```
* @module phoenix
*/
const globalSelf = typeof self !== "undefined" ? self : null
const globalWindow = typeof window !== "undefined" ? window : null
const global = globalSelf || globalWindow || this
const VSN = "2.0.0"
const SOCKET_STATES = {connecting: 0, open: 1, closing: 2, closed: 3}
const DEFAULT_TIMEOUT = 10000
const WS_CLOSE_NORMAL = 1000
const CHANNEL_STATES = {
closed: "closed",
errored: "errored",
joined: "joined",
joining: "joining",
leaving: "leaving",
}
const CHANNEL_EVENTS = {
close: "phx_close",
error: "phx_error",
join: "phx_join",
reply: "phx_reply",
leave: "phx_leave"
}
const CHANNEL_LIFECYCLE_EVENTS = [
CHANNEL_EVENTS.close,
CHANNEL_EVENTS.error,
CHANNEL_EVENTS.join,
CHANNEL_EVENTS.reply,
CHANNEL_EVENTS.leave
]
const TRANSPORTS = {
longpoll: "longpoll",
websocket: "websocket"
}
// wraps value in closure or returns closure
let closure = (value) => {
if(typeof value === "function"){
return value
} else {
let closure = function(){ return value }
return closure
}
}
/**
* Initializes the Push
* @param {Channel} channel - The Channel
* @param {string} event - The event, for example `"phx_join"`
* @param {Object} payload - The payload, for example `{user_id: 123}`
* @param {number} timeout - The push timeout in milliseconds
*/
class Push {
constructor(channel, event, payload, timeout){
this.channel = channel
this.event = event
this.payload = payload || function(){ return {} }
this.receivedResp = null
this.timeout = timeout
this.timeoutTimer = null
this.recHooks = []
this.sent = false
}
/**
*
* @param {number} timeout
*/
resend(timeout){
this.timeout = timeout
this.reset()
this.send()
}
/**
*
*/
send(){ if(this.hasReceived("timeout")){ return }
this.startTimeout()
this.sent = true
this.channel.socket.push({
topic: this.channel.topic,
event: this.event,
payload: this.payload(),
ref: this.ref,
join_ref: this.channel.joinRef()
})
}
/**
*
* @param {*} status
* @param {*} callback
*/
receive(status, callback){
if(this.hasReceived(status)){
callback(this.receivedResp.response)
}
this.recHooks.push({status, callback})
return this
}
/**
* @private
*/
reset(){
this.cancelRefEvent()
this.ref = null
this.refEvent = null
this.receivedResp = null
this.sent = false
}
/**
* @private
*/
matchReceive({status, response, ref}){
this.recHooks.filter( h => h.status === status )
.forEach( h => h.callback(response) )
}
/**
* @private
*/
cancelRefEvent(){ if(!this.refEvent){ return }
this.channel.off(this.refEvent)
}
/**
* @private
*/
cancelTimeout(){
clearTimeout(this.timeoutTimer)
this.timeoutTimer = null
}
/**
* @private
*/
startTimeout(){ if(this.timeoutTimer){ this.cancelTimeout() }
this.ref = this.channel.socket.makeRef()
this.refEvent = this.channel.replyEventName(this.ref)
this.channel.on(this.refEvent, payload => {
this.cancelRefEvent()
this.cancelTimeout()
this.receivedResp = payload
this.matchReceive(payload)
})
this.timeoutTimer = setTimeout(() => {
this.trigger("timeout", {})
}, this.timeout)
}
/**
* @private
*/
hasReceived(status){
return this.receivedResp && this.receivedResp.status === status
}
/**
* @private
*/
trigger(status, response){
this.channel.trigger(this.refEvent, {status, response})
}
}
/**
*
* @param {string} topic
* @param {(Object|function)} params
* @param {Socket} socket
*/
export class Channel {
constructor(topic, params, socket) {
this.state = CHANNEL_STATES.closed
this.topic = topic
this.params = closure(params || {})
this.socket = socket
this.bindings = []
this.bindingRef = 0
this.timeout = this.socket.timeout
this.joinedOnce = false
this.joinPush = new Push(this, CHANNEL_EVENTS.join, this.params, this.timeout)
this.pushBuffer = []
this.rejoinTimer = new Timer(() => {
if(this.socket.isConnected()){ this.rejoin() }
}, this.socket.rejoinAfterMs)
this.socket.onError(() => this.rejoinTimer.reset())
this.socket.onOpen(() => {
this.rejoinTimer.reset()
if(this.isErrored()){ this.rejoin() }
})
this.joinPush.receive("ok", () => {
this.state = CHANNEL_STATES.joined
this.rejoinTimer.reset()
this.pushBuffer.forEach( pushEvent => pushEvent.send() )
this.pushBuffer = []
})
this.joinPush.receive("error", () => {
this.state = CHANNEL_STATES.errored
if(this.socket.isConnected()){ this.rejoinTimer.scheduleTimeout() }
})
this.onClose(() => {
this.rejoinTimer.reset()
if(this.socket.hasLogger()) this.socket.log("channel", `close ${this.topic} ${this.joinRef()}`)
this.state = CHANNEL_STATES.closed
this.socket.remove(this)
})
this.onError(reason => {
if(this.socket.hasLogger()) this.socket.log("channel", `error ${this.topic}`, reason)
if(this.isJoining()){ this.joinPush.reset() }
this.state = CHANNEL_STATES.errored
if(this.socket.isConnected()){ this.rejoinTimer.scheduleTimeout() }
})
this.joinPush.receive("timeout", () => {
if(this.socket.hasLogger()) this.socket.log("channel", `timeout ${this.topic} (${this.joinRef()})`, this.joinPush.timeout)
let leavePush = new Push(this, CHANNEL_EVENTS.leave, closure({}), this.timeout)
leavePush.send()
this.state = CHANNEL_STATES.errored
this.joinPush.reset()
if(this.socket.isConnected()){ this.rejoinTimer.scheduleTimeout() }
})
this.on(CHANNEL_EVENTS.reply, (payload, ref) => {
this.trigger(this.replyEventName(ref), payload)
})
}
/**
* Join the channel
* @param {integer} timeout
* @returns {Push}
*/
join(timeout = this.timeout){
if(this.joinedOnce){
throw new Error(`tried to join multiple times. 'join' can only be called a single time per channel instance`)
} else {
this.timeout = timeout
this.joinedOnce = true
this.rejoin()
return this.joinPush
}
}
/**
* Hook into channel close
* @param {Function} callback
*/
onClose(callback){
this.on(CHANNEL_EVENTS.close, callback)
}
/**
* Hook into channel errors
* @param {Function} callback
*/
onError(callback){
return this.on(CHANNEL_EVENTS.error, reason => callback(reason))
}
/**
* Subscribes on channel events
*
* Subscription returns a ref counter, which can be used later to
* unsubscribe the exact event listener
*
* @example
* const ref1 = channel.on("event", do_stuff)
* const ref2 = channel.on("event", do_other_stuff)
* channel.off("event", ref1)
* // Since unsubscription, do_stuff won't fire,
* // while do_other_stuff will keep firing on the "event"
*
* @param {string} event
* @param {Function} callback
* @returns {integer} ref
*/
on(event, callback){
let ref = this.bindingRef++
this.bindings.push({event, ref, callback})
return ref
}
/**
* @param {string} event
* @param {integer} ref
*/
off(event, ref){
this.bindings = this.bindings.filter((bind) => {
return !(bind.event === event && (typeof ref === "undefined" || ref === bind.ref))
})
}
/**
* @private
*/
canPush(){ return this.socket.isConnected() && this.isJoined() }
/**
* @param {string} event
* @param {Object} payload
* @param {number} [timeout]
* @returns {Push}
*/
push(event, payload, timeout = this.timeout){
if(!this.joinedOnce){
throw new Error(`tried to push '${event}' to '${this.topic}' before joining. Use channel.join() before pushing events`)
}
let pushEvent = new Push(this, event, function(){ return payload }, timeout)
if(this.canPush()){
pushEvent.send()
} else {
pushEvent.startTimeout()
this.pushBuffer.push(pushEvent)
}
return pushEvent
}
/** Leaves the channel
*
* Unsubscribes from server events, and
* instructs channel to terminate on server
*
* Triggers onClose() hooks
*
* To receive leave acknowledgements, use the a `receive`
* hook to bind to the server ack, ie:
*
* @example
* channel.leave().receive("ok", () => alert("left!") )
*
* @param {integer} timeout
* @returns {Push}
*/
leave(timeout = this.timeout){
this.rejoinTimer.reset()
this.state = CHANNEL_STATES.leaving
let onClose = () => {
if (this.socket.hasLogger()) this.socket.log("channel", `leave ${this.topic}`)
this.trigger(CHANNEL_EVENTS.close, "leave")
}
let leavePush = new Push(this, CHANNEL_EVENTS.leave, closure({}), timeout)
leavePush.receive("ok", () => onClose() )
.receive("timeout", () => onClose() )
leavePush.send()
if(!this.canPush()){ leavePush.trigger("ok", {}) }
return leavePush
}
/**
* Overridable message hook
*
* Receives all events for specialized message handling
* before dispatching to the channel callbacks.
*
* Must return the payload, modified or unmodified
* @param {string} event
* @param {Object} payload
* @param {integer} ref
* @returns {Object}
*/
onMessage(event, payload, ref){ return payload }
/**
* @private
*/
isLifecycleEvent(event) { return CHANNEL_LIFECYCLE_EVENTS.indexOf(event) >= 0 }
/**
* @private
*/
isMember(topic, event, payload, joinRef){
if(this.topic !== topic){ return false }
if(joinRef && joinRef !== this.joinRef() && this.isLifecycleEvent(event)){
if (this.socket.hasLogger()) this.socket.log("channel", "dropping outdated message", {topic, event, payload, joinRef})
return false
} else {
return true
}
}
/**
* @private
*/
joinRef(){ return this.joinPush.ref }
/**
* @private
*/
sendJoin(timeout){
this.state = CHANNEL_STATES.joining
this.joinPush.resend(timeout)
}
/**
* @private
*/
rejoin(timeout = this.timeout){ if(this.isLeaving()){ return }
this.sendJoin(timeout)
}
/**
* @private
*/
trigger(event, payload, ref, joinRef){
let handledPayload = this.onMessage(event, payload, ref, joinRef)
if(payload && !handledPayload){ throw new Error("channel onMessage callbacks must return the payload, modified or unmodified") }
for (let i = 0; i < this.bindings.length; i++) {
const bind = this.bindings[i]
if(bind.event !== event){ continue }
bind.callback(handledPayload, ref, joinRef || this.joinRef())
}
}
/**
* @private
*/
replyEventName(ref){ return `chan_reply_${ref}` }
/**
* @private
*/
isClosed() { return this.state === CHANNEL_STATES.closed }
/**
* @private
*/
isErrored(){ return this.state === CHANNEL_STATES.errored }
/**
* @private
*/
isJoined() { return this.state === CHANNEL_STATES.joined }
/**
* @private
*/
isJoining(){ return this.state === CHANNEL_STATES.joining }
/**
* @private
*/
isLeaving(){ return this.state === CHANNEL_STATES.leaving }
}
/* The default serializer for encoding and decoding messages */
export let Serializer = {
encode(msg, callback){
let payload = [
msg.join_ref, msg.ref, msg.topic, msg.event, msg.payload
]
return callback(JSON.stringify(payload))
},
decode(rawPayload, callback){
let [join_ref, ref, topic, event, payload] = JSON.parse(rawPayload)
return callback({join_ref, ref, topic, event, payload})
}
}
/** Initializes the Socket
*
*
* For IE8 support use an ES5-shim (https://github.com/es-shims/es5-shim)
*
* @param {string} endPoint - The string WebSocket endpoint, ie, `"ws://example.com/socket"`,
* `"wss://example.com"`
* `"/socket"` (inherited host & protocol)
* @param {Object} [opts] - Optional configuration
* @param {string} [opts.transport] - The Websocket Transport, for example WebSocket or Phoenix.LongPoll.
*
* Defaults to WebSocket with automatic LongPoll fallback.
* @param {Function} [opts.encode] - The function to encode outgoing messages.
*
* Defaults to JSON:
*
* ```javascript
* (payload, callback) => callback(JSON.stringify(payload))
* ```
*
* @param {Function} [opts.decode] - The function to decode incoming messages.
*
* Defaults to JSON:
*
* ```javascript
* (payload, callback) => callback(JSON.parse(payload))
* ```
*
* @param {number} [opts.timeout] - The default timeout in milliseconds to trigger push timeouts.
*
* Defaults `DEFAULT_TIMEOUT`
* @param {number} [opts.heartbeatIntervalMs] - The millisec interval to send a heartbeat message
* @param {number} [opts.reconnectAfterMs] - The optional function that returns the millsec
* socket reconnect interval.
*
* Defaults to stepped backoff of:
*
* ```javascript
* function(tries){
* return [10, 50, 100, 150, 200, 250, 500, 1000, 2000][tries - 1] || 5000
* }
* ````
*
* @param {number} [opts.rejoinAfterMs] - The optional function that returns the millsec
* rejoin interval for individual channels.
*
* ```javascript
* function(tries){
* return [1000, 2000, 5000][tries - 1] || 10000
* }
* ````
*
* @param {Function} [opts.logger] - The optional function for specialized logging, ie:
*
* ```javascript
* function(kind, msg, data) {
* console.log(`${kind}: ${msg}`, data)
* }
* ```
*
* @param {number} [opts.longpollerTimeout] - The maximum timeout of a long poll AJAX request.
*
* Defaults to 20s (double the server long poll timer).
*
* @param {{Object|function)} [opts.params] - The optional params to pass when connecting
* @param {string} [opts.binaryType] - The binary type to use for binary WebSocket frames.
*
* Defaults to "arraybuffer"
*
*/
export class Socket {
constructor(endPoint, opts = {}){
this.stateChangeCallbacks = {open: [], close: [], error: [], message: []}
this.channels = []
this.sendBuffer = []
this.ref = 0
this.timeout = opts.timeout || DEFAULT_TIMEOUT
this.transport = opts.transport || global.WebSocket || LongPoll
this.defaultEncoder = Serializer.encode
this.defaultDecoder = Serializer.decode
this.closeWasClean = false
this.unloaded = false
this.binaryType = opts.binaryType || "arraybuffer"
if(this.transport !== LongPoll){
this.encode = opts.encode || this.defaultEncoder
this.decode = opts.decode || this.defaultDecoder
} else {
this.encode = this.defaultEncoder
this.decode = this.defaultDecoder
}
if(globalWindow){
globalWindow.addEventListener("beforeunload", e => {
this.unloaded = true
this.abnormalClose("unloaded")
})
}
this.heartbeatIntervalMs = opts.heartbeatIntervalMs || 30000
this.rejoinAfterMs = (tries) => {
if(opts.rejoinAfterMs){
return opts.rejoinAfterMs(tries)
} else {
return [1000, 2000, 5000][tries - 1] || 10000
}
}
this.reconnectAfterMs = (tries) => {
if(this.unloaded){ return 100 }
if(opts.reconnectAfterMs){
return opts.reconnectAfterMs(tries)
} else {
return [10, 50, 100, 150, 200, 250, 500, 1000, 2000][tries - 1] || 5000
}
}
this.logger = opts.logger || null
this.longpollerTimeout = opts.longpollerTimeout || 20000
this.params = closure(opts.params || {})
this.endPoint = `${endPoint}/${TRANSPORTS.websocket}`
this.heartbeatTimer = null
this.pendingHeartbeatRef = null
this.reconnectTimer = new Timer(() => {
this.teardown(() => this.connect())
}, this.reconnectAfterMs)
}
/**
* Returns the socket protocol
*
* @returns {string}
*/
protocol(){ return location.protocol.match(/^https/) ? "wss" : "ws" }
/**
* The fully qualifed socket url
*
* @returns {string}
*/
endPointURL(){
let uri = Ajax.appendParams(
Ajax.appendParams(this.endPoint, this.params()), {vsn: VSN})
if(uri.charAt(0) !== "/"){ return uri }
if(uri.charAt(1) === "/"){ return `${this.protocol()}:${uri}` }
return `${this.protocol()}://${location.host}${uri}`
}
/**
* @param {Function} callback
* @param {integer} code
* @param {string} reason
*/
disconnect(callback, code, reason){
this.closeWasClean = true
this.reconnectTimer.reset()
this.teardown(callback, code, reason)
}
/**
*
* @param {Object} params - The params to send when connecting, for example `{user_id: userToken}`
*
* Passing params to connect is deprecated; pass them in the Socket constructor instead:
* `new Socket("/socket", {params: {user_id: userToken}})`.
*/
connect(params){
if(params){
console && console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor")
this.params = closure(params)
}
if(this.conn){ return }
this.conn = new this.transport(this.endPointURL())
this.conn.binaryType = this.binaryType
this.conn.timeout = this.longpollerTimeout
this.conn.onopen = () => this.onConnOpen()
this.conn.onerror = error => this.onConnError(error)
this.conn.onmessage = event => this.onConnMessage(event)
this.conn.onclose = event => this.onConnClose(event)
}
/**
* Logs the message. Override `this.logger` for specialized logging. noops by default
* @param {string} kind
* @param {string} msg
* @param {Object} data
*/
log(kind, msg, data){ this.logger(kind, msg, data) }
/**
* Returns true if a logger has been set on this socket.
*/
hasLogger(){ return this.logger !== null }
/**
* Registers callbacks for connection open events
*
* @example socket.onOpen(function(){ console.info("the socket was opened") })
*
* @param {Function} callback
*/
onOpen(callback){ this.stateChangeCallbacks.open.push(callback) }
/**
* Registers callbacks for connection close events
* @param {Function} callback
*/
onClose(callback){ this.stateChangeCallbacks.close.push(callback) }
/**
* Registers callbacks for connection error events
*
* @example socket.onError(function(error){ alert("An error occurred") })
*
* @param {Function} callback
*/
onError(callback){ this.stateChangeCallbacks.error.push(callback) }
/**
* Registers callbacks for connection message events
* @param {Function} callback
*/
onMessage(callback){ this.stateChangeCallbacks.message.push(callback) }
/**
* @private
*/
onConnOpen(){
if (this.hasLogger()) this.log("transport", `connected to ${this.endPointURL()}`)
this.unloaded = false
this.closeWasClean = false
this.flushSendBuffer()
this.reconnectTimer.reset()
this.resetHeartbeat()
this.stateChangeCallbacks.open.forEach( callback => callback() )
}
/**
* @private
*/
resetHeartbeat(){ if(this.conn && this.conn.skipHeartbeat){ return }
this.pendingHeartbeatRef = null
clearInterval(this.heartbeatTimer)
this.heartbeatTimer = setInterval(() => this.sendHeartbeat(), this.heartbeatIntervalMs)
}
teardown(callback, code, reason){
if(this.conn){
this.conn.onclose = function(){} // noop
if(code){ this.conn.close(code, reason || "") } else { this.conn.close() }
this.conn = null
}
callback && callback()
}
onConnClose(event){
if (this.hasLogger()) this.log("transport", "close", event)
this.triggerChanError()
clearInterval(this.heartbeatTimer)
if(!this.closeWasClean){
this.reconnectTimer.scheduleTimeout()
}
this.stateChangeCallbacks.close.forEach( callback => callback(event) )
}
/**
* @private
*/
onConnError(error){
if (this.hasLogger()) this.log("transport", error)
this.triggerChanError()
this.stateChangeCallbacks.error.forEach( callback => callback(error) )
}
/**
* @private
*/
triggerChanError(){
this.channels.forEach( channel => {
if(!(channel.isErrored() || channel.isLeaving() || channel.isClosed())){
channel.trigger(CHANNEL_EVENTS.error)
}
})
}
/**
* @returns {string}
*/
connectionState(){
switch(this.conn && this.conn.readyState){
case SOCKET_STATES.connecting: return "connecting"
case SOCKET_STATES.open: return "open"
case SOCKET_STATES.closing: return "closing"
default: return "closed"
}
}
/**
* @returns {boolean}
*/
isConnected(){ return this.connectionState() === "open" }
/**
* @param {Channel}
*/
remove(channel){
this.channels = this.channels.filter(c => c.joinRef() !== channel.joinRef())
}
/**
* Initiates a new channel for the given topic
*
* @param {string} topic
* @param {Object} chanParams - Parameters for the channel
* @returns {Channel}
*/
channel(topic, chanParams = {}){
let chan = new Channel(topic, chanParams, this)
this.channels.push(chan)
return chan
}
/**
* @param {Object} data
*/
push(data){
if (this.hasLogger()) {
let {topic, event, payload, ref, join_ref} = data
this.log("push", `${topic} ${event} (${join_ref}, ${ref})`, payload)
}
if(this.isConnected()){
this.encode(data, result => this.conn.send(result))
} else {
this.sendBuffer.push(() => this.encode(data, result => this.conn.send(result)))
}
}
/**
* Return the next message ref, accounting for overflows
* @returns {string}
*/
makeRef(){
let newRef = this.ref + 1
if(newRef === this.ref){ this.ref = 0 } else { this.ref = newRef }
return this.ref.toString()
}
sendHeartbeat(){ if(!this.isConnected()){ return }
if(this.pendingHeartbeatRef){
this.pendingHeartbeatRef = null
if (this.hasLogger()) this.log("transport", "heartbeat timeout. Attempting to re-establish connection")
this.abnormalClose("heartbeat timeout")
return
}
this.pendingHeartbeatRef = this.makeRef()
this.push({topic: "phoenix", event: "heartbeat", payload: {}, ref: this.pendingHeartbeatRef})
}
abnormalClose(reason){
this.closeWasClean = false
this.conn.close(WS_CLOSE_NORMAL, reason)
}
flushSendBuffer(){
if(this.isConnected() && this.sendBuffer.length > 0){
this.sendBuffer.forEach( callback => callback() )
this.sendBuffer = []
}
}
onConnMessage(rawMessage){
this.decode(rawMessage.data, msg => {
let {topic, event, payload, ref, join_ref} = msg
if(ref && ref === this.pendingHeartbeatRef){ this.pendingHeartbeatRef = null }
if (this.hasLogger()) this.log("receive", `${payload.status || ""} ${topic} ${event} ${ref && "(" + ref + ")" || ""}`, payload)
for (let i = 0; i < this.channels.length; i++) {
const channel = this.channels[i]
if(!channel.isMember(topic, event, payload, join_ref)){ continue }
channel.trigger(event, payload, ref, join_ref)
}
for (let i = 0; i < this.stateChangeCallbacks.message.length; i++) {
this.stateChangeCallbacks.message[i](msg)
}
})
}
}
export class LongPoll {
constructor(endPoint){
this.endPoint = null
this.token = null
this.skipHeartbeat = true
this.onopen = function(){} // noop
this.onerror = function(){} // noop
this.onmessage = function(){} // noop
this.onclose = function(){} // noop
this.pollEndpoint = this.normalizeEndpoint(endPoint)
this.readyState = SOCKET_STATES.connecting
this.poll()
}
normalizeEndpoint(endPoint){
return(endPoint
.replace("ws://", "http://")
.replace("wss://", "https://")
.replace(new RegExp("(.*)\/" + TRANSPORTS.websocket), "$1/" + TRANSPORTS.longpoll))
}
endpointURL(){
return Ajax.appendParams(this.pollEndpoint, {token: this.token})
}
closeAndRetry(){
this.close()
this.readyState = SOCKET_STATES.connecting
}
ontimeout(){
this.onerror("timeout")
this.closeAndRetry()
}
poll(){
if(!(this.readyState === SOCKET_STATES.open || this.readyState === SOCKET_STATES.connecting)){ return }
Ajax.request("GET", this.endpointURL(), "application/json", null, this.timeout, this.ontimeout.bind(this), (resp) => {
if(resp){
var {status, token, messages} = resp
this.token = token
} else{
var status = 0
}
switch(status){
case 200:
messages.forEach(msg => this.onmessage({data: msg}))
this.poll()
break
case 204:
this.poll()
break
case 410:
this.readyState = SOCKET_STATES.open
this.onopen()
this.poll()
break
case 0:
case 500:
this.onerror()
this.closeAndRetry()
break
default: throw new Error(`unhandled poll status ${status}`)
}
})
}
send(body){
Ajax.request("POST", this.endpointURL(), "application/json", body, this.timeout, this.onerror.bind(this, "timeout"), (resp) => {
if(!resp || resp.status !== 200){
this.onerror(resp && resp.status)
this.closeAndRetry()
}
})
}
close(code, reason){
this.readyState = SOCKET_STATES.closed
this.onclose()
}
}
export class Ajax {
static request(method, endPoint, accept, body, timeout, ontimeout, callback){
if(global.XDomainRequest){
let req = new XDomainRequest() // IE8, IE9
this.xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback)
} else {
let req = global.XMLHttpRequest ?
new global.XMLHttpRequest() : // IE7+, Firefox, Chrome, Opera, Safari
new ActiveXObject("Microsoft.XMLHTTP") // IE6, IE5
this.xhrRequest(req, method, endPoint, accept, body, timeout, ontimeout, callback)
}
}
static xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback){
req.timeout = timeout
req.open(method, endPoint)
req.onload = () => {
let response = this.parseJSON(req.responseText)
callback && callback(response)
}
if(ontimeout){ req.ontimeout = ontimeout }
// Work around bug in IE9 that requires an attached onprogress handler
req.onprogress = () => {}
req.send(body)
}
static xhrRequest(req, method, endPoint, accept, body, timeout, ontimeout, callback){
req.open(method, endPoint, true)
req.timeout = timeout
req.setRequestHeader("Content-Type", accept)
req.onerror = () => { callback && callback(null) }
req.onreadystatechange = () => {
if(req.readyState === this.states.complete && callback){
let response = this.parseJSON(req.responseText)
callback(response)
}
}
if(ontimeout){ req.ontimeout = ontimeout }
req.send(body)
}
static parseJSON(resp){
if(!resp || resp === ""){ return null }
try {
return JSON.parse(resp)
} catch(e) {
console && console.log("failed to parse JSON response", resp)
return null
}
}
static serialize(obj, parentKey){
let queryStr = []
for(var key in obj){ if(!obj.hasOwnProperty(key)){ continue }
let paramKey = parentKey ? `${parentKey}[${key}]` : key
let paramVal = obj[key]
if(typeof paramVal === "object"){
queryStr.push(this.serialize(paramVal, paramKey))
} else {
queryStr.push(encodeURIComponent(paramKey) + "=" + encodeURIComponent(paramVal))
}
}
return queryStr.join("&")
}
static appendParams(url, params){
if(Object.keys(params).length === 0){ return url }
let prefix = url.match(/\?/) ? "&" : "?"
return `${url}${prefix}${this.serialize(params)}`
}
}
Ajax.states = {complete: 4}
/**
* Initializes the Presence
* @param {Channel} channel - The Channel
* @param {Object} opts - The options,
* for example `{events: {state: "state", diff: "diff"}}`
*/
export class Presence {
constructor(channel, opts = {}){
let events = opts.events || {state: "presence_state", diff: "presence_diff"}
this.state = {}
this.pendingDiffs = []
this.channel = channel
this.joinRef = null
this.caller = {
onJoin: function(){},
onLeave: function(){},
onSync: function(){}
}
this.channel.on(events.state, newState => {
let {onJoin, onLeave, onSync} = this.caller
this.joinRef = this.channel.joinRef()
this.state = Presence.syncState(this.state, newState, onJoin, onLeave)
this.pendingDiffs.forEach(diff => {
this.state = Presence.syncDiff(this.state, diff, onJoin, onLeave)
})
this.pendingDiffs = []
onSync()
})
this.channel.on(events.diff, diff => {
let {onJoin, onLeave, onSync} = this.caller
if(this.inPendingSyncState()){
this.pendingDiffs.push(diff)
} else {
this.state = Presence.syncDiff(this.state, diff, onJoin, onLeave)
onSync()
}
})
}
onJoin(callback){ this.caller.onJoin = callback }
onLeave(callback){ this.caller.onLeave = callback }
onSync(callback){ this.caller.onSync = callback }
list(by){ return Presence.list(this.state, by) }
inPendingSyncState(){
return !this.joinRef || (this.joinRef !== this.channel.joinRef())
}
// lower-level public static API
/**
* Used to sync the list of presences on the server
* with the client's state. An optional `onJoin` and `onLeave` callback can
* be provided to react to changes in the client's local presences across
* disconnects and reconnects with the server.
*
* @returns {Presence}
*/
static syncState(currentState, newState, onJoin, onLeave){
let state = this.clone(currentState)
let joins = {}
let leaves = {}
this.map(state, (key, presence) => {
if(!newState[key]){
leaves[key] = presence
}
})
this.map(newState, (key, newPresence) => {
let currentPresence = state[key]
if(currentPresence){
let newRefs = newPresence.metas.map(m => m.phx_ref)
let curRefs = currentPresence.metas.map(m => m.phx_ref)
let joinedMetas = newPresence.metas.filter(m => curRefs.indexOf(m.phx_ref) < 0)
let leftMetas = currentPresence.metas.filter(m => newRefs.indexOf(m.phx_ref) < 0)
if(joinedMetas.length > 0){
joins[key] = newPresence
joins[key].metas = joinedMetas
}
if(leftMetas.length > 0){
leaves[key] = this.clone(currentPresence)
leaves[key].metas = leftMetas
}
} else {
joins[key] = newPresence
}
})
return this.syncDiff(state, {joins: joins, leaves: leaves}, onJoin, onLeave)
}
/**
*
* Used to sync a diff of presence join and leave
* events from the server, as they happen. Like `syncState`, `syncDiff`
* accepts optional `onJoin` and `onLeave` callbacks to react to a user
* joining or leaving from a device.
*
* @returns {Presence}
*/
static syncDiff(currentState, {joins, leaves}, onJoin, onLeave){
let state = this.clone(currentState)
if(!onJoin){ onJoin = function(){} }
if(!onLeave){ onLeave = function(){} }
this.map(joins, (key, newPresence) => {
let currentPresence = state[key]
state[key] = newPresence
if(currentPresence){
let joinedRefs = state[key].metas.map(m => m.phx_ref)
let curMetas = currentPresence.metas.filter(m => joinedRefs.indexOf(m.phx_ref) < 0)
state[key].metas.unshift(...curMetas)
}
onJoin(key, currentPresence, newPresence)
})
this.map(leaves, (key, leftPresence) => {
let currentPresence = state[key]
if(!currentPresence){ return }
let refsToRemove = leftPresence.metas.map(m => m.phx_ref)
currentPresence.metas = currentPresence.metas.filter(p => {
return refsToRemove.indexOf(p.phx_ref) < 0
})
onLeave(key, currentPresence, leftPresence)
if(currentPresence.metas.length === 0){
delete state[key]
}
})
return state
}
/**
* Returns the array of presences, with selected metadata.
*
* @param {Object} presences
* @param {Function} chooser
*
* @returns {Presence}
*/
static list(presences, chooser){
if(!chooser){ chooser = function(key, pres){ return pres } }
return this.map(presences, (key, presence) => {
return chooser(key, presence)
})
}
// private
static map(obj, func){
return Object.getOwnPropertyNames(obj).map(key => func(key, obj[key]))
}
static clone(obj){ return JSON.parse(JSON.stringify(obj)) }
}
/**
*
* Creates a timer that accepts a `timerCalc` function to perform
* calculated timeout retries, such as exponential backoff.
*
* @example
* let reconnectTimer = new Timer(() => this.connect(), function(tries){
* return [1000, 5000, 10000][tries - 1] || 10000
* })
* reconnectTimer.scheduleTimeout() // fires after 1000
* reconnectTimer.scheduleTimeout() // fires after 5000
* reconnectTimer.reset()
* reconnectTimer.scheduleTimeout() // fires after 1000
*
* @param {Function} callback
* @param {Function} timerCalc
*/
class Timer {
constructor(callback, timerCalc){
this.callback = callback
this.timerCalc = timerCalc
this.timer = null
this.tries = 0
}
reset(){
this.tries = 0
clearTimeout(this.timer)
}
/**
* Cancels any previous scheduleTimeout and schedules callback
*/
scheduleTimeout(){
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.tries = this.tries + 1
this.callback()
}, this.timerCalc(this.tries + 1))
}
}
|
require.config({
paths:{
bootstrap: '../js/libs/bootstrap.min',
datepicker:'../js/libs/bootstrap-datepicker',
jquery: '../js/libs/jquery-1.12.0.min',
underscore: '../js/libs/underscore-min',
Backbone: '../js/libs/backbone-min',
timesheet: '../js/libs/TimeSheet'
},
shim: {
underscore:{
exports:"_"
},
Backbone:{
deps: ['underscore','jquery'],
exports: "Backbone"
},
bootstrap: {
deps:['jquery'],
exports:"bootstrap"
},
"datepicker" : {
deps: ["bootstrap"],
exports: "$.fn.datepicker"
},
timesheet : {
deps: ["jquery"],
exports: "$.fn.TimeSheet"
}
}
});
require(['Backbone',
'underscore',
'jquery',
'libs/text!header.html',
'libs/text!home.html',
'libs/text!footer.html',
'libs/text!meetups.html',
'datepicker',
'bootstrap',
'timesheet'
], function (Backbone,_,$,headerTpl, homeTpl, footerTpl, meetupsTpl, dp, bootstrap, timesheet) {
var rootURL = 'http://xrav3nz.flowca.st/';
var ApplicationRouter = Backbone.Router.extend({
routes: {
"": "home",
"meetups/:id": "meetups"
},
initialize: function() {
this.headerView = new HeaderView();
this.headerView.render();
this.footerView = new FooterView();
this.footerView.render();
},
home: function() {
this.homeView = new HomeView();
this.homeView.render();
},
meetups: function(id) {
this.meetupsView = new MeetupsView();
this.meetupsView.render(id);
}
});
HeaderView = Backbone.View.extend({
el: "#header",
templateFileName: "header.html",
template: headerTpl,
initialize: function() {
$.get(this.templateFileName, function(data){
this.template=data
});
},
render: function() {
$(this.el).html(_.template(this.template));
}
});
FooterView = Backbone.View.extend({
el: "#footer",
template: footerTpl,
render: function() {
this.$el.html(_.template(this.template));
}
});
HomeView = Backbone.View.extend({
el: "#content",
template: "home.html",
template: homeTpl,
initialize: function() {
},
render: function() {
$(this.el).html(_.template(this.template));
$("#calender-container .calender").datepicker({
multidate: true
});
},
events: {
"click #submitLocation": "getRestaurants",
"click .restaurantLabel": "toggleSelection",
"click .attractionLabel": "toggleSelection",
"click #submitData": "submitData"
},
getRestaurants: function() {
if (lat === undefined || lng === undefined) {
console.log("need lat, lng");
return;
}
var url = rootURL + 'restaurants/' + lat + ',' + lng + '?count=15';
console.log(url);
jQuery.get(url, function (data) {
$('#getInfo').hide();
$('#showInfo').show();
data.results.forEach(function (restaurant) {
var name = restaurant.name;
var url = restaurant.web_url;
var label = "<li>"
label += "<label class='btn btn-info restaurantLabel' data-name='" + name + "''>";
label += name;
label += "</label>";
label += "<a href='" + url + "' target='_blank'>";
label += 'See on TripAdvisor';
label += "</a>";
label += "</li>"
$('#lList').append(label);
});
});
var url = rootURL + 'attractions/' + lat + ',' + lng + '?count=15';
console.log(url);
jQuery.get(url, function (data) {
$('#getInfo').hide();
$('#showInfo').show();
data.results.forEach(function (attraction) {
var name = attraction.name;
var url = attraction.web_url;
var label = "<li>"
label += "<label class='btn btn-success attractionLabel' data-name='" + name + "''>";
label += name;
label += "</label>";
label += "<a href='" + url + "' target='_blank'>";
label += 'See on TripAdvisor';
label += "</a>";
label += "</li>"
$('#rList').append(label);
});
});
},
toggleSelection: function (e) {
if ($(e.currentTarget).hasClass('active')) {
$(e.currentTarget).removeClass('active');
} else {
$(e.currentTarget).addClass('active');
}
},
submitData: function () {
var restaurants = [];
var attractions = [];
var url = rootURL + 'meetups';
$('label.restaurantLabel.active').each(function (index) {
var t = $(this);
var name = t.data('name');
var web_url = t.parent().find('a').attr('href');
restaurants.push({"web_url": web_url, "name": name});
});
$('label.attractionLabel.active').each(function (index) {
var t = $(this);
var name = t.data('name');
var web_url = t.parent().find('a').attr('href');
attractions.push({"web_url": web_url, "name": name});
});
if (restaurants.length === 0 && attractions.length === 0) {
alert('Please choose at least one restaurant or activity');
return;
}
var postObj = {
"name": meetup.name,
"organizer": meetup.organizer,
"timeslots": meetup.timeslots,
"activities": attractions,
"restaurants": restaurants
}
$.ajax({
url: url,
method: "POST",
contentType: "application/json",
data: JSON.stringify(postObj),
success:function(data){
var id = data.id;
var password = data.password;
console.log(id, password)
var route = '#/meetups/' + id;
window.location.assign(route);
},
error:function(result){
alert(result.responseJSON.message);
}
});
}
});
MeetupsView = Backbone.View.extend({
el: "#content",
template: meetupsTpl,
initialize: function() {
},
mid: 0,
render: function(id) {
var self = this;
this.mid = id;
$.ajax({
url: "http://xrav3nz.flowca.st/meetups/" + id,
success:function(result){
$(self.el).html(_.template(self.template)({"result": result}));
},
error:function(result){
alert(result.responseJSON.message);
}
});
},
events: {
"submit": "vote"
},
vote: function(event) {
event.preventDefault();
// check if the user has voted already
var name = this.mid + "=";
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);
if (c.indexOf(name) == 0) {
alert("You have voted on this event");
return ;
}
}
var timeslot_ids = [];
var activity_ids = [];
var self = this;
$(this.el).find('input:checked').each(function() {
if($(this).attr('name') == "activities") {
activity_ids.push($(this).val());
} else {
timeslot_ids.push($(this).val());
}
});
$.ajax({
url: "http://xrav3nz.flowca.st/meetups/" + self.mid,
method: "PUT",
contentType: "application/json",
data: JSON.stringify({
"timeslot_ids": timeslot_ids,
"activity_ids": activity_ids
}),
success:function(result){
// set the cookie after the user has voted
var d = new Date();
d.setTime(d.getTime() + (1*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = self.mid + "=" + 1 + "; " + expires;
self.render(self.mid);
},
error:function(result){
alert(result.responseJSON.message);
}
});
}
});
app = new ApplicationRouter();
Backbone.history.start();
});
|
(function (a) {
// search params.
var params = {
"scope" : "my-uni",
"sort-by": "date",
"access": "PUB",
"categories": "",
};
// keyed by id.
var events = {};
var scopeSelector;
var eventSearchForm;
var eventsAggregate;
$(function () {
eventSearchForm = $('form#event-search');
eventSearchForm.submit(function (e) {
e.preventDefault();
pollEvents();
});
scopeSelector = $('select#scope');
scopeSelector.change(function () {
scope = scopeSelector.val();
params.scope = scope;
if (scope == "my-uni") {
setMyUniScope();
}
else if (scope == "other-uni") {
setOtherUniScope();
}
});
searchUni = $('input#uni-name');
uniId = $('input#uni-id');
searchUni.devbridgeAutocomplete({
lookup: function (query, done) {
var name = query;
app.getUniversityList({name: name}, function (data) {
data = data || "{}";
data = JSON.parse(data);
result = {};
result.suggestions = data;
done(result);
});
},
onSelect: function (suggestion) {
searchUni.val(suggestion.value)
uniId.val(suggestion.data);
params.uni_id = suggestion.data;
pollEvents();
}
});
function setOtherUniScope () {
searchUni.parent().show();
// only public events are available to outsiders
accessScopeFilters.parent().hide();
}
var sortBy = $('input.sort-by');
sortBy.change(function () {
var self = $(this);
params.sort_by = self.val();
pollEvents();
});
var accessScopeFilters = $('div.access > input');
accessScopeFilters.change(function () {
var self = $(this);
params.accessibility = self.val();
pollEvents();
});
function setMyUniScope () {
searchUni.parent().hide();
// select a variety of 'accessibilities' (pub, pri, rso)
accessScopeFilters.parent().show();
pollEvents();
}
eventsAggregate = $("div.events-view-all.aggregate.events");
function rebuildEvents (new_events) {
}
function eventFactory (eventJson) {
var event_id = eventJson.event_id;
var name = eventJson.name;
var description = eventJson.description;
var location = eventJson.location;
var lat = eventJson.lat;
var lon = eventJson.lon;
var distance = (parseFloat(eventJson.distance)*69).toFixed(2);
var rating = eventJson.rating;
var start_time = a.util.parseUTC(eventJson.start_time).formatMdyyyy_time();
var end_time = a.util.parseUTC(eventJson.end_time).formatMdyyyy_time();
var accessibility = eventJson.accessibility;
var status = eventJson.status == "PND"? "Pending Approval" : "Active";
var uni_id = eventJson.uni_id;
var uni_name = eventJson.uni_name;
var elem = $('<div style="display:none" class="record event">');
var text = '<h5><a href="'+a.siteRoot+'event/'+event_id+'">' + name + '</a></h5>';
text += '<p>' + description + '</p>';
text += '<span class="info distance">~' + distance + ' Miles away</span>';
text += '<span class="info rating">Rating : ' + rating + '</span>';
text += '<span class="info start-time">Start : ' + start_time + '</span>';
text += '<span class="info end-time">End : ' + end_time + '</span>';
text += '<span class="info uni"><a href="'+ a.siteRoot + 'university/' + uni_id + '">';
text += uni_name + '</a></span>';
text += '<span class="info access">';
if (accessibility == "PUB") {
text += "Publicly Accessible";
}
else if (accessibility == "PRI") {
text += "Privately Accessible";
}
else if (accessibility == "RSO") {
text += "RSO Accessible";
}
text += '<span class="info status">Status : ' + status + '</span>';
elem.html(text);
elem.append(a.util.loadEntityPic({type: "events", id: event_id, style: "medium", link: true}));
window.setTimeout(function () {
elem.fadeIn(2000);
elem.addClass("loaded");
}, 200);
return elem;
}
function pollEvents() {
eventsAggregate.addClass('loading');
a.getEventsJson(params, function (data) {
data = data || "[]";
data = JSON.parse(data);
eventsAggregate.html('');
if (data.length == 0) {
var text = '<p class="notice">No events match your search. Battle spiders with early 2000\'s memes instead?</p>';
eventsAggregate.html(text);
var releaseSpiders = $('<div class="btn">Battle Spiders</div>');
releaseSpiders.click(function () {
a.util.unleashTheTarantula();
releaseSpiders.addClass('disabled');
});
eventsAggregate.append(releaseSpiders);
eventsAggregate.removeClass('loading');
return;
}
eventsAggregate.removeClass('loading');
for (var i = 0; i < data.length; i++) {
var eventJson = data[i];
eventsAggregate.append(eventFactory(eventJson));
}
});
}
pollEvents();
// uncomment once things are working good.
// window.setInterval(pollEvents, 2500);
var categories = $('input#categories');
var catAggregate = $('div.aggregate.categories');
function rebuildCats() {
var cats = $('div.record.category', catAggregate);
params.categories = "";
$.each(cats, function (index, elem) {
var val = $('span.value', elem).text();
params.categories += val + ",";
});
params.categories = params.categories.slice(0, -1);
categories.val(params.categories);
}
function categoryFactory(label) {
var elem = $('<div class="record category">');
elem.html('<span class="value">' + label + '</span>');
var remove = $('<div class="button destroy">X</div>');
remove.click(function () {
elem.remove();
rebuildCats();
pollEvents();
});
elem.append(remove);
return elem;
}
var category = $('input#category');
category.devbridgeAutocomplete({
lookup: function(query, done) {
a.getCategoriesLike({label: query}, function (data) {
data = data || '[]';
data = JSON.parse(data);
var results = {};
results.suggestions = data;
done(results);
});
},
onSelect: function (suggestion) {
var label = suggestion.data;
catAggregate.append(categoryFactory(label));
rebuildCats();
pollEvents();
category.val("");
}
});
});
})(app);
|
import {responsiveAction} from 'ghost/utils/mobile';
var PostsView = Ember.View.extend({
target: Ember.computed.alias('controller'),
classNames: ['content-view-container'],
tagName: 'section',
mobileInteractions: function () {
Ember.run.scheduleOnce('afterRender', this, function () {
var self = this;
// ### Show content preview when swiping left on content list
$('.manage').on('click', '.content-list ol li', function (event) {
responsiveAction(event, '(max-width: 800px)', function () {
self.send('showContentPreview');
});
});
// ### Hide content preview
$('.manage').on('click', '.content-preview .button-back', function (event) {
responsiveAction(event, '(max-width: 800px)', function () {
self.send('hideContentPreview');
});
});
});
}.on('didInsertElement'),
});
export default PostsView;
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define(["require","exports"],function(b,c){return function(){return function(a){void 0===a&&(a=null);this.url="//route.arcgis.com/arcgis/rest/services/World/ServiceAreas/NAServer/ServiceArea_World/solveServiceArea";this.credentials=null;this.impedanceAttributeNames=[{serviceValue:"TravelTime",entryName:"traveltime"},{serviceValue:"TruckTravelTime",entryName:"trucktraveltime"},{serviceValue:"WalkTime",entryName:"walktime"},{serviceValue:"Miles",entryName:"miles"},{serviceValue:"Kilometers",entryName:"kilometers"}];
this.defaultImpledanceAttributeName="TravelTime";this.credentials=a}}()}); |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/*!
* jQuery JavaScript Library v2.1.4
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2015-04-28T16:01Z
*/
(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get jQuery.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real `window`.
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info.
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// Support: Firefox 18+
// Can't be in strict mode, several libs including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
//
var arr = [];
var slice = arr.slice;
var concat = arr.concat;
var push = arr.push;
var indexOf = arr.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var support = {};
var
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
version = "2.1.4",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Support: Android<4.1
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/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();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return 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 just the one element from the set
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return all the elements in a clean array
slice.call( this );
},
// 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 );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
slice: function() {
return this.pushStack( 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] ] : [] );
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: arr.sort,
splice: arr.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// Skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// 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 ( i === length ) {
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
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
// adding 1 corrects loss of precision from parseFloat (#15100)
return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.constructor &&
!hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
// Support: Android<4.0, iOS<6 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// Convert dashed to camelCase; used by the css and data modules
// Support: IE9-11+
// 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;
},
// Support: Android<4.1
trim: 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 {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : indexOf.call( arr, elem, i );
},
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
for ( ; j < len; j++ ) {
first[ i++ ] = second[ j ];
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// 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 new values
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return 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 tmp, args, proxy;
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 = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( 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;
},
now: Date.now,
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
});
// 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 ) {
// Support: iOS 8.2 (not reproducible in simulator)
// `in` check used to prevent JIT error (gh-2145)
// hasOwn isn't used here due to false negatives
// regarding Nodelist length in IE
var length = "length" in obj && obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v2.2.0-pre
* http://sizzlejs.com/
*
* Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-12-16
*/
(function( window ) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + 1 * new Date(),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// General-purpose constants
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 as it's faster than native
// http://jsperf.com/thor-indexof-vs-for/5
indexOf = function( list, elem ) {
var i = 0,
len = list.length;
for ( ; i < len; i++ ) {
if ( list[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#" ),
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + characterEncoding + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rwhitespace = new RegExp( whitespace + "+", "g" ),
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + 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" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
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<24
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
},
// Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function() {
setDocument();
};
// 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 || [];
nodeType = context.nodeType;
if ( typeof selector !== "string" || !selector ||
nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
return results;
}
if ( !seed && documentIsHTML ) {
// Try to shortcut find operations when possible (e.g., not under DocumentFragment)
if ( nodeType !== 11 && (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 (jQuery #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 ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType !== 1 && 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 ) && testContext( 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]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== "undefined" && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
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;
};
/**
* 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 hasCompare, parent,
doc = node ? node.ownerDocument || node : preferredDoc;
// 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;
parent = doc.defaultView;
// 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 !== parent.top ) {
// IE11 does not have attachEvent, so all must suffer
if ( parent.addEventListener ) {
parent.addEventListener( "unload", unloadHandler, false );
} else if ( parent.attachEvent ) {
parent.attachEvent( "onunload", unloadHandler );
}
}
/* Support tests
---------------------------------------------------------------------- */
documentIsHTML = !isXML( doc );
/* 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;
});
// Support: IE<9
support.getElementsByClassName = rnative.test( doc.getElementsByClassName );
// 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 !== "undefined" && 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 !== "undefined" && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( tag );
// DocumentFragment nodes don't have gEBTN
} else if ( support.qsa ) {
return context.querySelectorAll( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
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 ( 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
docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" +
"<select id='" + expando + "-\f]' msallowcapture=''>" +
"<option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( div.querySelectorAll("[msallowcapture^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Support: Chrome<29, Android<4.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+
if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
rbuggyQSA.push("~=");
}
// 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");
}
// Support: Safari 8+, iOS 8+
// https://bugs.webkit.org/show_bug.cgi?id=136851
// In-page `selector#id sibing-combinator selector` fails
if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) {
rbuggyQSA.push(".#.+[+~]");
}
});
assert(function( div ) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( div.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + 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.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
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
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 = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// 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 || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf( sortInput, a ) - indexOf( 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 ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
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 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
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
while ( (node = elem[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 (jQuery #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[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[6] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] ) {
match[2] = match[4] || match[5] || "";
// 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 !== "undefined" && 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.replace( rwhitespace, " " ) + " " ).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( 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 );
// Don't keep the element (issue #299)
input[0] = null;
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
text = text.replace( runescape, funescape );
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 negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
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;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// 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();
tokenize = Sizzle.tokenize = function( 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 oldCache, outerCache,
newCache = [ 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 ( (oldCache = outerCache[ dir ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
outerCache[ dir ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
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 multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
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( 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( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
// Avoid hanging onto element (issue #299)
checkContext = null;
return ret;
} ];
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 ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context !== document && context;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (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;
}
}
// 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, match /* 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 ( !match ) {
match = tokenize( selector );
}
i = match.length;
while ( i-- ) {
cached = matcherFromTokens( match[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function( selector, context, results, seed ) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize( (selector = compiled.selector || selector) );
results = results || [];
// Try to minimize operations if there is no seed and 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;
// Precompiled matchers will still verify ancestry, so step up a level
} else if ( compiled ) {
context = context.parentNode;
}
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 ) && testContext( 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 if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
( compiled || compile( selector, match ) )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome 14-35+
// 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 elem[ name ] === true ? name.toLowerCase() :
(val = elem.getAttributeNode( name )) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})( window );
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;
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
var risSimple = /^.[^:#\[\.,]*$/;
// 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 ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) >= 0 ) !== not;
});
}
jQuery.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;
}));
};
jQuery.fn.extend({
find: function( selector ) {
var i,
len = this.length,
ret = [],
self = this;
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;
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
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;
}
});
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// 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-]*))$/,
init = jQuery.fn.init = function( selector, context ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector[0] === "<" && selector[ 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;
// Option to run scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
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] );
// Support: Blackberry 4.6
// gEBID returns nodes no longer in the document (#6963)
if ( elem && elem.parentNode ) {
// 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 typeof rootjQuery.ready !== "undefined" ?
rootjQuery.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// Methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.extend({
dir: function( elem, dir, until ) {
var matched = [],
truncate = until !== undefined;
while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
},
sibling: function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
}
});
jQuery.fn.extend({
has: function( target ) {
var targets = jQuery( target, this ),
l = targets.length;
return this.filter(function() {
var i = 0;
for ( ; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
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)) ) {
matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
},
// Determine the position of an element within the set
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 indexOf.call( jQuery( elem ), this[ 0 ] );
}
// Locate the position of the desired element
return indexOf.call( this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem
);
},
add: function( selector, context ) {
return this.pushStack(
jQuery.unique(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
while ( (cur = cur[dir]) && 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 elem.contentDocument || jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var matched = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
matched = jQuery.filter( selector, matched );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
jQuery.unique( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
});
var rnotwhite = (/\S+/g);
// 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( 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 // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// 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 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[ tuple[ 0 ] + "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 = 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 ? 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();
}
});
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend({
// 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;
}
// 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.triggerHandler ) {
jQuery( document ).triggerHandler( "ready" );
jQuery( document ).off( "ready" );
}
}
});
/**
* The ready event handler and self cleanup method
*/
function completed() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
}
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 );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Kick off the DOM ready check even if the user does not
jQuery.ready.promise();
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
len = 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 < len; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
len ? fn( elems[0], key ) : emptyGet;
};
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
/* jshint -W018 */
return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};
function Data() {
// Support: Android<4,
// Old WebKit does not have Object.preventExtensions/freeze method,
// return new empty object instead with no [[set]] accessor
Object.defineProperty( this.cache = {}, 0, {
get: function() {
return {};
}
});
this.expando = jQuery.expando + Data.uid++;
}
Data.uid = 1;
Data.accepts = jQuery.acceptData;
Data.prototype = {
key: function( owner ) {
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return the key for a frozen object.
if ( !Data.accepts( owner ) ) {
return 0;
}
var descriptor = {},
// Check if the owner object already has a cache key
unlock = owner[ this.expando ];
// If not, create one
if ( !unlock ) {
unlock = Data.uid++;
// Secure it in a non-enumerable, non-writable property
try {
descriptor[ this.expando ] = { value: unlock };
Object.defineProperties( owner, descriptor );
// Support: Android<4
// Fallback to a less secure definition
} catch ( e ) {
descriptor[ this.expando ] = unlock;
jQuery.extend( owner, descriptor );
}
}
// Ensure the cache object
if ( !this.cache[ unlock ] ) {
this.cache[ unlock ] = {};
}
return unlock;
},
set: function( owner, data, value ) {
var prop,
// There may be an unlock assigned to this node,
// if there is no entry for this "owner", create one inline
// and set the unlock as though an owner entry had always existed
unlock = this.key( owner ),
cache = this.cache[ unlock ];
// Handle: [ owner, key, value ] args
if ( typeof data === "string" ) {
cache[ data ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Fresh assignments by object are shallow copied
if ( jQuery.isEmptyObject( cache ) ) {
jQuery.extend( this.cache[ unlock ], data );
// Otherwise, copy the properties one-by-one to the cache object
} else {
for ( prop in data ) {
cache[ prop ] = data[ prop ];
}
}
}
return cache;
},
get: function( owner, key ) {
// Either a valid cache is found, or will be created.
// New caches will be created and the unlock returned,
// allowing direct access to the newly created
// empty data object. A valid owner object must be provided.
var cache = this.cache[ this.key( owner ) ];
return key === undefined ?
cache : cache[ key ];
},
access: function( owner, key, value ) {
var stored;
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if ( key === undefined ||
((key && typeof key === "string") && value === undefined) ) {
stored = this.get( owner, key );
return stored !== undefined ?
stored : this.get( owner, jQuery.camelCase(key) );
}
// [*]When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set( owner, key, value );
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function( owner, key ) {
var i, name, camel,
unlock = this.key( owner ),
cache = this.cache[ unlock ];
if ( key === undefined ) {
this.cache[ unlock ] = {};
} else {
// Support array or space separated string of keys
if ( jQuery.isArray( key ) ) {
// 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 = key.concat( key.map( jQuery.camelCase ) );
} else {
camel = jQuery.camelCase( key );
// Try the string as a key before any manipulation
if ( key in cache ) {
name = [ key, camel ];
} else {
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
name = camel;
name = name in cache ?
[ name ] : ( name.match( rnotwhite ) || [] );
}
}
i = name.length;
while ( i-- ) {
delete cache[ name[ i ] ];
}
}
},
hasData: function( owner ) {
return !jQuery.isEmptyObject(
this.cache[ owner[ this.expando ] ] || {}
);
},
discard: function( owner ) {
if ( owner[ this.expando ] ) {
delete this.cache[ owner[ this.expando ] ];
}
}
};
var data_priv = new Data();
var data_user = new Data();
// Implementation Summary
//
// 1. Enforce API surface and semantic compatibility with 1.9.x branch
// 2. Improve the module's maintainability by reducing the storage
// paths to a single mechanism.
// 3. Use the same single mechanism to support "private" and "user" data.
// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
// 5. Avoid exposing implementation details on user objects (eg. expando properties)
// 6. Provide a clear path for implementation upgrade to WeakMap in 2014
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
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
data_user.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
hasData: function( elem ) {
return data_user.hasData( elem ) || data_priv.hasData( elem );
},
data: function( elem, name, data ) {
return data_user.access( elem, name, data );
},
removeData: function( elem, name ) {
data_user.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to data_priv methods, these can be deprecated.
_data: function( elem, name, data ) {
return data_priv.access( elem, name, data );
},
_removeData: function( elem, name ) {
data_priv.remove( elem, name );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var i, name, data,
elem = this[ 0 ],
attrs = elem && elem.attributes;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = data_user.get( elem );
if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE11+
// The attrs elements can be null (#14894)
if ( attrs[ i ] ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
}
data_priv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
data_user.set( this, key );
});
}
return access( this, function( value ) {
var data,
camelKey = jQuery.camelCase( key );
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if ( elem && value === undefined ) {
// Attempt to get data from the cache
// with the key as-is
data = data_user.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to get data from the cache
// with the key camelized
data = data_user.get( elem, camelKey );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, camelKey, undefined );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each(function() {
// First, attempt to store a copy or reference of any
// data that might've been store with a camelCased key.
var data = data_user.get( this, camelKey );
// For HTML5 data-* attribute interop, we have to
// store property names with dashes in a camelCase form.
// This might not apply to all properties...*
data_user.set( this, camelKey, value );
// *... In the case of properties that might _actually_
// have dashes, we need to also store a copy of that
// unchanged property.
if ( key.indexOf("-") !== -1 && data !== undefined ) {
data_user.set( this, key, value );
}
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
data_user.remove( this, key );
});
}
});
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = data_priv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = data_priv.access( 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 public - generate a queueHooks object, or return the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return data_priv.get( elem, key ) || data_priv.access( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
data_priv.remove( elem, [ type + "queue", 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 );
});
},
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 = data_priv.get( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHidden = function( 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 );
};
var rcheckableType = (/^(?:checkbox|radio)$/i);
(function() {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild( document.createElement( "div" ) ),
input = document.createElement( "input" );
// Support: Safari<=5.1
// Check state lost if the name is set (#11217)
// Support: Windows Web Apps (WWA)
// `name` and `type` must use .setAttribute for WWA (#14901)
input.setAttribute( "type", "radio" );
input.setAttribute( "checked", "checked" );
input.setAttribute( "name", "t" );
div.appendChild( input );
// Support: Safari<=5.1, Android<4.2
// Older WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<=11+
// Make sure textarea (and checkbox) defaultValue is properly cloned
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
})();
var strundefined = typeof undefined;
support.focusinBubbles = "onfocusin" in window;
var
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|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 handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.get( 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 !== strundefined && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// Handle multiple events separated by a space
types = ( types || "" ).match( 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 if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
}
}
}
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;
}
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.hasData( elem ) && data_priv.get( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( 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;
data_priv.remove( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = 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 = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && jQuery.acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === 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.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( 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;
elem[ type ]();
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, j, ret, matched, handleObj,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( data_priv.get( 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 i, matches, sel, handleObj,
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") ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( 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;
},
// 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 offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button;
// 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 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;
}
},
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: Cordova 2.5 (WebKit) (#13255)
// All events should have a target; Cordova deviceready doesn't
if ( !event.target ) {
event.target = document;
}
// Support: Safari 6.0+, Chrome<28
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
return fixHook.filter ? fixHook.filter( event, originalEvent ) : 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 ) {
this.focus();
return false;
}
},
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 ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
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 ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined && event.originalEvent ) {
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 = function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
};
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.defaultPrevented === undefined &&
// Support: Android<4.0
src.returnValue === false ?
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 && e.preventDefault ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && e.stopPropagation ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && e.stopImmediatePropagation ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// Support: Chrome 15+
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, 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;
}
};
});
// Support: Firefox, Chrome, Safari
// Create "bubbling" focus and blur events
if ( !support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = data_priv.access( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
data_priv.access( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = data_priv.access( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
data_priv.remove( doc, fix );
} else {
data_priv.access( doc, fix, attaches );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// 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
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/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 = {
// Support: IE9
option: [ 1, "<select multiple='multiple'>", "</select>" ],
thead: [ 1, "<table>", "</table>" ],
col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
_default: [ 0, "", "" ]
};
// Support: IE9
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// Support: 1.x compatibility
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? 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 = (elem.getAttribute("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 i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
data_priv.set(
elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
);
}
}
function cloneCopyEvent( src, dest ) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if ( dest.nodeType !== 1 ) {
return;
}
// 1. Copy private data: events, handlers, etc.
if ( data_priv.hasData( src ) ) {
pdataOld = data_priv.access( src );
pdataCur = data_priv.set( dest, pdataOld );
events = pdataOld.events;
if ( events ) {
delete pdataCur.handle;
pdataCur.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
}
// 2. Copy user data
if ( data_user.hasData( src ) ) {
udataOld = data_user.access( src );
udataCur = jQuery.extend( {}, udataOld );
data_user.set( dest, udataCur );
}
}
function getAll( context, tag ) {
var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
[];
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], ret ) :
ret;
}
// Fix IE bugs, see support tests
function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Fix IE cloning issues
if ( !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 );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
fixInput( srcElements[ i ], 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, l = srcElements.length; i < l; i++ ) {
cloneCopyEvent( srcElements[ i ], destElements[ i ] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var elem, tmp, tag, wrap, contains, j,
fragment = context.createDocumentFragment(),
nodes = [],
i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
// Support: QtWebKit, PhantomJS
// push.apply(_, arraylike) throws on ancient WebKit
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 || fragment.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;
}
// Support: QtWebKit, PhantomJS
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Ensure the created nodes are orphaned (#12392)
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
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( fragment.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 );
}
}
}
}
return fragment;
},
cleanData: function( elems ) {
var data, elem, type, key,
special = jQuery.event.special,
i = 0;
for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
if ( jQuery.acceptData( elem ) ) {
key = elem[ data_priv.expando ];
if ( key && (data = data_priv.cache[ key ]) ) {
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 );
}
}
}
if ( data_priv.cache[ key ] ) {
// Discard any remaining `private` data
delete data_priv.cache[ key ];
}
}
}
// Discard any remaining `user` data
delete data_user.cache[ elem[ data_user.expando ] ];
}
}
});
jQuery.fn.extend({
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().each(function() {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.textContent = 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 );
}
});
},
remove: function( selector, keepData /* Internal Use Only */ ) {
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++ ) {
if ( elem.nodeType === 1 ) {
// Prevent memory leaks
jQuery.cleanData( getAll( elem, false ) );
// Remove any remaining nodes
elem.textContent = "";
}
}
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 access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
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 arg = arguments[ 0 ];
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
arg = this.parentNode;
jQuery.cleanData( getAll( this ) );
if ( arg ) {
arg.replaceChild( elem, this );
}
});
// Force removal if there was no new content (e.g., from empty arguments)
return arg && (arg.length || arg.nodeType) ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
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" &&
!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 );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, 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 ) {
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
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 || "" ) &&
!data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
}
}
}
}
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: QtWebKit
// .get() because push.apply(_, arraylike) throws
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
var iframe,
elemdisplay = {};
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
var style,
elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
// getDefaultComputedStyle might be reliably used only on attached element
display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?
// Use of this method is a temporary fix (more like optimization) until something better comes along,
// since it was removed from specification and supported only in FF
style.display : jQuery.css( elem[ 0 ], "display" );
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
/**
* Try to determine the default display value of an element
* @param {String} nodeName
*/
function 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'/>" )).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = iframe[ 0 ].contentDocument;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
var rmargin = (/^margin/);
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles = function( elem ) {
// Support: IE<=11+, Firefox<=30+ (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
if ( elem.ownerDocument.defaultView.opener ) {
return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
}
return window.getComputedStyle( elem, null );
};
function curCSS( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// Support: IE9
// getPropertyValue is only needed for .css('filter') (#12537)
if ( computed ) {
ret = computed.getPropertyValue( name ) || computed[ name ];
}
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// Support: iOS < 6
// A tribute to the "awesome hack by Dean Edwards"
// iOS < 6 (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 !== undefined ?
// Support: IE
// IE returns zIndex value as an integer.
ret + "" :
ret;
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
if ( conditionFn() ) {
// Hook not needed (or it's not possible to use it due
// to missing dependency), remove it.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return (this.get = hookFn).apply( this, arguments );
}
};
}
(function() {
var pixelPositionVal, boxSizingReliableVal,
docElem = document.documentElement,
container = document.createElement( "div" ),
div = document.createElement( "div" );
if ( !div.style ) {
return;
}
// Support: IE9-11+
// Style of cloned element affects source element cloned (#8908)
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" +
"position:absolute";
container.appendChild( div );
// Executing both pixelPosition & boxSizingReliable tests require only one layout
// so they're executed at the same time to save the second computation.
function computePixelPositionAndBoxSizingReliable() {
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
"box-sizing:border-box;display:block;margin-top:1%;top:1%;" +
"border:1px;padding:1px;width:4px;position:absolute";
div.innerHTML = "";
docElem.appendChild( container );
var divStyle = window.getComputedStyle( div, null );
pixelPositionVal = divStyle.top !== "1%";
boxSizingReliableVal = divStyle.width === "4px";
docElem.removeChild( container );
}
// Support: node.js jsdom
// Don't assume that getComputedStyle is a property of the global object
if ( window.getComputedStyle ) {
jQuery.extend( support, {
pixelPosition: function() {
// This test is executed only once but we still do memoizing
// since we can use the boxSizingReliable pre-computing.
// No need to check if the test was already performed, though.
computePixelPositionAndBoxSizingReliable();
return pixelPositionVal;
},
boxSizingReliable: function() {
if ( boxSizingReliableVal == null ) {
computePixelPositionAndBoxSizingReliable();
}
return boxSizingReliableVal;
},
reliableMarginRight: function() {
// Support: Android 2.3
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// This support function is only executed once so no memoizing is needed.
var ret,
marginDiv = div.appendChild( document.createElement( "div" ) );
// Reset CSS: box-sizing; display; margin; border; padding
marginDiv.style.cssText = div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;padding:0";
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
docElem.appendChild( container );
ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight );
docElem.removeChild( container );
div.removeChild( marginDiv );
return ret;
}
});
}
})();
// A method for quickly swapping in/out CSS properties to get correct calculations.
jQuery.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;
};
var
// 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]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
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[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 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.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;
}
// Check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox &&
( 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";
}
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 ] = data_priv.get( 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 ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
} else {
hidden = isHidden( elem );
if ( display !== "none" || !hidden ) {
data_priv.set( 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.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,
"flexGrow": true,
"flexShrink": 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: {
"float": "cssFloat"
},
// 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, then unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// Convert "+=" 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 null and NaN values aren't set (#7116)
if ( value == null || value !== value ) {
return;
}
// If a number, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Support: IE9-11+
// background-* props affect original clone's values
if ( !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 ) {
style[ name ] = value;
}
} 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 val, num, 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 ) );
// Try prefixed name followed by the unprefixed name
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 ];
}
// Make numeric 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;
}
});
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
// but it must have a current display style that would benefit
return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ?
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.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
// Support: Android 2.3
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
// 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;
}
});
jQuery.fn.extend({
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
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();
}
});
}
});
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.
// 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 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: IE9
// 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.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
}
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + 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 string for doubling 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(),
// break 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() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
i = 0,
attrs = { height: type };
// If we include width, step value is 1 to do all cssExpand values,
// otherwise 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;
}
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 defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = data_priv.get( 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() {
// Ensure the complete handler is 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 IE9-10 do 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
display = jQuery.css( elem, "display" );
// Test default display if display is currently "none"
checkDisplay = display === "none" ?
data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
style.display = "inline-block";
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
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" ) ) {
// If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
// Any non-fx value stops us from restoring the original display value
} else {
display = undefined;
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = data_priv.access( 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;
data_priv.remove( 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;
}
}
}
// If this is a noop like .hide().hide(), restore an overwritten display value
} else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) {
style.display = display;
}
}
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 won't overwrite existing keys.
// Reusing 'index' 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;
}
}
}
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 ),
// Support: Android 2.3
// 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 );
}
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 );
}
}
});
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.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 || data_priv.get( 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 = data_priv.get( 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 = data_priv.get( 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;
});
}
});
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 );
};
});
// 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.timers = [];
jQuery.fx.tick = function() {
var timer,
i = 0,
timers = jQuery.timers;
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 ) {
jQuery.timers.push( timer );
if ( timer() ) {
jQuery.fx.start();
} else {
jQuery.timers.pop();
}
};
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
};
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.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 );
};
});
};
(function() {
var input = document.createElement( "input" ),
select = document.createElement( "select" ),
opt = select.appendChild( document.createElement( "option" ) );
input.type = "checkbox";
// Support: iOS<=5.1, Android<=4.2+
// Default value for a checkbox should be "on"
support.checkOn = input.value !== "";
// Support: IE<=11+
// Must access selectedIndex to make default options select
support.optSelected = opt.selected;
// Support: Android<=2.3
// Options inside disabled selects are incorrectly marked as disabled
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE<=11+
// An input loses its value after becoming a radio
input = document.createElement( "input" );
input.value = "t";
input.type = "radio";
support.radioValue = input.value === "t";
})();
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle;
jQuery.fn.extend({
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
}
});
jQuery.extend({
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 === 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( 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
elem[ propName ] = false;
}
elem.removeAttribute( name );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" &&
jQuery.nodeName( elem, "input" ) ) {
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
}
});
// 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 {
elem.setAttribute( name, name );
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = function( elem, name, isXML ) {
var ret, handle;
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ name ];
attrHandle[ name ] = ret;
ret = getter( elem, name, isXML ) != null ?
name.toLowerCase() :
null;
attrHandle[ name ] = handle;
}
return ret;
};
});
var rfocusable = /^(?:input|select|textarea|button)$/i;
jQuery.fn.extend({
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
return this.each(function() {
delete this[ jQuery.propFix[ name ] || name ];
});
}
});
jQuery.extend({
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 ) {
return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
elem.tabIndex :
-1;
}
}
}
});
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent && 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;
});
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
addClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
proceed = typeof value === "string" && value,
i = 0,
len = this.length;
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( 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 + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
proceed = arguments.length === 0 || typeof value === "string" && value,
i = 0,
len = this.length;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( 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 + " ", " " );
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
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( 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 === strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
data_priv.set( 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 ? "" : data_priv.get( 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;
}
});
var rreturn = /\r/g;
jQuery.fn.extend({
val: function( value ) {
var hooks, ret, 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 ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
// Support: IE10-11+
// option.text throws exceptions (#14686, #14858)
jQuery.trim( jQuery.text( elem ) );
}
},
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 ];
// IE6-9 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
( 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( option.value, values ) >= 0) ) {
optionSet = true;
}
}
// Force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
}
});
// 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 ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
// Return jQuery for attributes-only inclusion
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 nonce = jQuery.now();
var rquery = (/\?/);
// Support: Android 2.3
// Workaround failure to string-cast null input
jQuery.parseJSON = function( data ) {
return JSON.parse( data + "" );
};
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data, "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
/* 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( "*" ),
// Document location
ajaxLocation = window.location.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( 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 key, deep,
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;
}
/* 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 ct, type, finalDataType, firstDataType,
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 };
}
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 transport,
// URL without anti-cache param
cacheURL,
// Response headers
responseHeadersString,
responseHeaders,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// 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 (prefilters might expect it)
// 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( 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
// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
fireGlobals = jQuery.event && 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 += ( 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_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + 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 {
// Extract error from statusText and normalize 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
});
};
});
jQuery._evalUrl = function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
};
jQuery.fn.extend({
wrapAll: function( html ) {
var wrap;
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
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.firstElementChild ) {
elem = elem.firstElementChild;
}
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();
}
});
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.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
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 );
}
}
// 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, "+" );
};
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 || !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();
}
});
jQuery.ajaxSettings.xhr = function() {
try {
return new XMLHttpRequest();
} catch( e ) {}
};
var xhrId = 0,
xhrCallbacks = {},
xhrSuccessStatus = {
// file protocol always yields status code 0, assume 200
0: 200,
// Support: IE9
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE9
// Open requests must be manually aborted on unload (#5280)
// See https://support.microsoft.com/kb/2856746 for more info
if ( window.attachEvent ) {
window.attachEvent( "onunload", function() {
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]();
}
});
}
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport(function( options ) {
var callback;
// Cross domain only allowed if supported through XMLHttpRequest
if ( support.cors || xhrSupported && !options.crossDomain ) {
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr(),
id = ++xhrId;
xhr.open( options.type, options.url, options.async, options.username, options.password );
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.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 ( !options.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
// Callback
callback = function( type ) {
return function() {
if ( callback ) {
delete xhrCallbacks[ id ];
callback = xhr.onload = xhr.onerror = null;
if ( type === "abort" ) {
xhr.abort();
} else if ( type === "error" ) {
complete(
// file: protocol always yields status 0; see #8605, #14207
xhr.status,
xhr.statusText
);
} else {
complete(
xhrSuccessStatus[ xhr.status ] || xhr.status,
xhr.statusText,
// Support: IE9
// Accessing binary-data responseText throws an exception
// (#11426)
typeof xhr.responseText === "string" ? {
text: xhr.responseText
} : undefined,
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
xhr.onerror = callback("error");
// Create the abort callback
callback = xhrCallbacks[ id ] = callback("abort");
try {
// Do send the request (this may raise an exception)
xhr.send( options.hasContent && options.data || null );
} catch ( e ) {
// #14683: Only rethrow if this hasn't been notified as an error yet
if ( callback ) {
throw e;
}
}
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
// 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 crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script, callback;
return {
send: function( _, complete ) {
script = jQuery("<script>").prop({
async: true,
charset: s.scriptCharset,
src: s.url
}).on(
"load error",
callback = function( evt ) {
script.remove();
callback = null;
if ( evt ) {
complete( evt.type === "error" ? 404 : 200, evt.type );
}
}
);
document.head.appendChild( script[ 0 ] );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( 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 += ( 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";
}
});
// 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
jQuery.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 && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
// Keep a copy of the old load method
var _load = jQuery.fn.load;
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = jQuery.trim( url.slice( off ) );
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.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
var docElem = window.document.documentElement;
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
// 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({
offset: function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
elem = this[ 0 ],
box = { top: 0, left: 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;
}
// Support: BlackBerry 5, iOS 3 (original iPhone)
// If we don't have gBCR, just use 0,0 rather than error
if ( typeof elem.getBoundingClientRect !== strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + win.pageYOffset - docElem.clientTop,
left: box.left + win.pageXOffset - docElem.clientLeft
};
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// Assume getBoundingClientRect is there 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
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 = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : window.pageXOffset,
top ? val : window.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Support: Safari<7+, Chrome<37+
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://code.google.com/p/chromium/issues/detail?id=229280
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
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;
}
}
);
});
// 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 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
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 );
};
});
});
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// 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.
// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
});
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in AMD
// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( typeof noGlobal === strundefined ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
},{}],2:[function(require,module,exports){
(function (global){
global.jQuery = require('jquery');
var stickyNav = require('./stickyNav.js')();
var mobileMenuToggle = require('./mobileMenuToggle.js')();
var rotateLetters = require('./rotateLetters.js')();
var scrollAnchors = require('./scrollAnchors.js')();
var posterMoment = require('./posterMoment.js')();
// var paperBlobs = require('./paperBlobs.js')();
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./mobileMenuToggle.js":3,"./posterMoment.js":4,"./rotateLetters.js":5,"./scrollAnchors.js":6,"./stickyNav.js":7,"jquery":1}],3:[function(require,module,exports){
(function (global){
var $ = global.jQuery;
// Modernizr is being used as a global variable
module.exports = MobileMenuToggle;
function MobileMenuToggle() {
if (!(this instanceof MobileMenuToggle)) {
return new MobileMenuToggle();
}
console.log('MobileMenuToggle initialized.');
var modernizrState = Modernizr.mq('(min-width: 768px)');
console.log("modernizr = " + modernizrState);
$(window).resize(function() {
modernizrState = Modernizr.mq('(min-width: 768px)');
console.log("modernizr = " + modernizrState);
});
navToggle();
resizeCheck();
function navToggle() {
console.log("nav toggled");
// Clicking on the Menu button:
$('.nav__item--activator').click(function(){
if (modernizrState === false) {
console.log("activator clicked");
// shows page nav items, the x button and the logo,
$('.nav__item--pages, .nav__item--deactivator, .nav__logo').addClass('nav__item--show').removeClass('nav__item--hide');
// hides itself
$('.nav__item--activator').addClass('nav__item--hide').removeClass('nav__item--show');
// adds 100% height on the nav
$('.nav').addClass('nav--toggled');
//disables body scrolling
$('body').addClass('body--no-scroll');
}
});
// Clicking on the x button:
$('.nav__item--deactivator').click(function(){
if (modernizrState === false) {
console.log("deactivator clicked");
// hides page nav items, the x and the logo,
$('.nav__item--pages, .nav__item--deactivator, .nav__logo').addClass('nav__item--hide').removeClass('nav__item--show');
// shows the menu button
$('.nav__item--activator').addClass('nav__item--show').removeClass('nav__item--hide');
// removes 100% height on the nav
$('.nav').removeClass('nav--toggled');
// enables body scrolling
$('body').removeClass('body--no-scroll');
}
});
$('.nav__item').not('.nav__item--activator').click(function() {
if (modernizrState === false) {
console.log("nav item (not activator) clicked");
// removes 100% height on the nav
$('.nav').removeClass('nav--toggled');
// hides page nav items, the x and the logo,
$('.nav__item--pages, .nav__item--deactivator, .nav__logo').addClass('nav__item--hide').removeClass('nav__item--show');
// shows the menu button
$('.nav__item--activator').addClass('nav__item--show').removeClass('nav__item--hide');
// enables body scrolling
$('body').removeClass('body--no-scroll');
}
});
}
function resizeCheck() {
// Resizing the window
$(window).resize(function() {
// removes 100% height on the nav
$('.nav').removeClass('nav--toggled');
// enables body scrolling
$('body').removeClass('body--no-scroll');
// If window width is more than 768px
if (Modernizr.mq('(min-width: 768px)')) {
// hide Menu button and x button
$('.nav__item--activator, .nav__item--deactivator').addClass('nav__item--hide').removeClass('nav__item--show');
// show nav page items and logo
$('.nav__item--pages, .nav__logo').addClass('nav__item--show').removeClass('nav__item--hide');
} else {
// show the Menu button
$('.nav__item--activator').addClass('nav__item--show').removeClass('nav__item--hide');
// Hide nav page items, x button and logo
$('.nav__item--pages, .nav__item--deactivator, .nav__logo').addClass('nav__item--hide').removeClass('nav__item--show');
}
});
}
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],4:[function(require,module,exports){
(function (global){
var $ = global.jQuery;
module.exports = PosterMoment;
function PosterMoment() {
if (!(this instanceof PosterMoment)) {
return new PosterMoment();
}
console.log('PosterMoment initialized.');
var announcementHeight;
var scrollTopPos;
var scrollTimeout; // global for any pending scrollTimeout
var windowWidth;
if ($('.announcement__block').length > 0) {
initialScrollColor('.announcement__block');
scrollColorSwitch('.announcement__block');
} else {
initialScrollColor('.fourofour__block');
scrollColorSwitch('.fourofour__block');
}
function initialScrollColor(container) {
announcementHeight = $(container).height();
// announcementHeight = $(container).height() + $(container).offset().top;
// console.log(container + " - " + announcementHeight);
scrollTopPos = window.pageYOffset;
// console.log(scrollTopPos);
if (scrollTopPos > announcementHeight) {
// console.log("yes");
$('.poster-background').removeClass('poster-background--inverted');
$('.frame-container__left').removeClass('frame-container__left--inverted');
$('.frame-container__right').removeClass('frame-container__right--inverted');
$('.frame-text').removeClass('frame-text--inverted');
$('.nav__item').removeClass('nav__item--inverted');
} else {
// console.log("no");
$('.poster-background').addClass('poster-background--inverted');
$('.frame-container__left').addClass('frame-container__left--inverted');
$('.frame-container__right').addClass('frame-container__right--inverted');
$('.frame-text').addClass('frame-text--inverted');
$('.nav__item').addClass('nav__item--inverted');
}
}
function scrollColorSwitch(container) {
$(window).scroll(function () {
if (scrollTimeout) {
// clear the timeout, if one is pending
clearTimeout(scrollTimeout);
scrollTimeout = null;
}
scrollTimeout = setTimeout(didScroll, 1); //anything higher creates too long of a delay
});
didScroll = function () {
announcementHeight = $(container).height();
// announcementHeight = $(container).height() + $(container).offset().top;
// console.log(container + " - " + announcementHeight);
scrollTopPos = window.pageYOffset;
// console.log(scrollTopPos);
// windowWidth = $(window).width();
// $(window).resize(function() {
// windowWidth = $(window).width();
// });
if (scrollTopPos > announcementHeight / 2) {
// console.log("yes");
$('.poster-background').removeClass('poster-background--inverted');
$('.frame-container__left').removeClass('frame-container__left--inverted');
$('.frame-container__right').removeClass('frame-container__right--inverted');
$('.frame-text').removeClass('frame-text--inverted');
if (Modernizr.mq('(min-width: 768px)')) {} else {
$('.frame-container').addClass('frame-container--scrolled');
}
} else {
// console.log("no");
$('.poster-background').addClass('poster-background--inverted');
$('.frame-container__left').addClass('frame-container__left--inverted');
$('.frame-container__right').addClass('frame-container__right--inverted');
$('.frame-text').addClass('frame-text--inverted');
if (Modernizr.mq('(min-width: 768px)')) {} else {
$('.frame-container').removeClass('frame-container--scrolled');
}
$('.nav__item').addClass('nav__item--inverted');
}
if (scrollTopPos > announcementHeight) {
$('.nav__item').removeClass('nav__item--inverted');
}
};
}
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],5:[function(require,module,exports){
(function (global){
var $ = global.jQuery;
module.exports = RotateLetters;
function RotateLetters() {
if (!(this instanceof RotateLetters)) {
return new RotateLetters();
}
console.log('RotateLetters initialized.');
rotateLetters('announcement__block p', 'frame-text__word', 'text__rotate', 'text__rotate--space');
rotateLetters('fourofour__block p', 'frame-text__word', 'text__rotate', 'text__rotate--space');
rotateLetters('frame-text', 'frame-text__word', 'text__rotate', 'text__rotate--space');
rotateLetters('text-block__title--primary', 'frame-text__word', 'text__rotate', 'text__rotate--space');
rotateLetters('nav__item', 'nav__text--word', 'nav__rotate', 'nav__rotate--space');
function rotateLetters(lineContainer, wordClass, letterClass, spaceClass) {
var text;
var words;
var characters;
var thisItem;
$('.' + lineContainer).each(function () {
text = $(this).text();
text = text.replace(/[\n\r]+/g, ' '); // replace returns with single spaces
text = text.replace(/\s{1,10}/g, ' '); // replace multiple spaces with single spaces
text = text.replace(/(^[\s]+|[\s]+$)/g, ''); // replace last space if last space exists with nothing
words = text.split(' ');
thisItem = $(this);
thisItem.empty();
$.each(words, function (i, el) {
thisItem.append('<span class="' + wordClass + '">' + el + '</span>');
});
});
$('.' + lineContainer + ' .' + wordClass).each(function () {
characters = $(this).text().split('');
thisItem = $(this);
thisItem.empty();
$.each(characters, function (i, el) {
if (el === ' ') {
thisItem.append('<span class="text__rotate--space">' + el + '</span>');
} else {
thisItem.append('<span class="' + letterClass + '">' + el + '</span>');
}
});
});
}
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],6:[function(require,module,exports){
(function (global){
var $ = global.jQuery;
module.exports = ScrollAnchors;
function ScrollAnchors() {
if (!(this instanceof ScrollAnchors)) {
return new ScrollAnchors();
}
console.log('ScrollAnchors initialized.');
var currentHash;
var hash;
var top;
var distance;
var navHref;
scrollAnchorUpdate();
clickActiveNavItem();
loadActiveNavItem();
function scrollAnchorUpdate() {
currentHash = window.location.href;
$(document).scroll(function () {
$('.text-block__anchor').each(function () {
top = window.pageYOffset;
distance = top - $(this).offset().top;
hash = $(this).attr('id');
if (distance < 100 && distance > -100 && currentHash != hash) {
window.location.replace("#"+hash);
currentHash = hash;
$('.nav__item--pages').each(function() {
navHref = $(this).attr('href');
navHref = navHref.replace('#','');
if (navHref === hash) {
$(this).addClass('nav__item--active').siblings().removeClass('nav__item--active');
}
});
}
});
});
}
function clickActiveNavItem() {
$('.nav__item--pages').click(function (event) {
$(this).addClass('nav__item--active').siblings().removeClass('nav__item--active');
});
}
function loadActiveNavItem() {
hash = window.location.hash;
if (hash === '') {
window.location.replace("#");
}
$('.nav__item--pages').each(function() {
navHref = $(this).attr('href');
navHref = navHref.replace('#','');
// console.log("hash = " + hash + ", href = " + navHref);
if (navHref === hash) {
$(this).addClass('nav__item--active').siblings().removeClass('nav__item--active');
}
});
}
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],7:[function(require,module,exports){
(function (global){
var $ = global.jQuery;
module.exports = StickyNav;
function StickyNav() {
if (!(this instanceof StickyNav)) {
return new StickyNav();
}
console.log('StickyNav initialized.');
stickyHeader();
function stickyHeader() {
var didScroll;
var lastScrollTop = 0;
var delta = 1;
var navbarHeight = $('.nav').outerHeight();
$(window).scroll(function(event) {
didScroll = true;
});
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var scrollTopPos = $(window).scrollTop();
// console.log(scrollTopPos);
if (Math.abs(lastScrollTop - scrollTopPos) <= delta) {
return;
}
if (scrollTopPos > lastScrollTop && scrollTopPos > navbarHeight) {
$('.nav').removeClass('nav--down').addClass('nav--up');
} else {
if ((scrollTopPos + $(window).height()) < $(document).height()) {
$('.nav').removeClass('nav--up').addClass('nav--down');
}
}
lastScrollTop = scrollTopPos;
}
}
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[2]);
|
/*! Element Plus v2.0.5 */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.ElementPlusLocaleLv = factory());
})(this, (function () { 'use strict';
var lv = {
name: "lv",
el: {
colorpicker: {
confirm: "Labi",
clear: "Not\u012Br\u012Bt"
},
datepicker: {
now: "Tagad",
today: "\u0160odien",
cancel: "Atcelt",
clear: "Not\u012Br\u012Bt",
confirm: "Labi",
selectDate: "Izv\u0113l\u0113ties datumu",
selectTime: "Izv\u0113l\u0113ties laiku",
startDate: "S\u0101kuma datums",
startTime: "S\u0101kuma laiks",
endDate: "Beigu datums",
endTime: "Beigu laiks",
prevYear: "Iepriek\u0161\u0113jais gads",
nextYear: "N\u0101kamais gads",
prevMonth: "Iepriek\u0161\u0113jais m\u0113nesis",
nextMonth: "N\u0101kamais m\u0113nesis",
year: "",
month1: "Janv\u0101ris",
month2: "Febru\u0101ris",
month3: "Marts",
month4: "Apr\u012Blis",
month5: "Maijs",
month6: "J\u016Bnijs",
month7: "J\u016Blijs",
month8: "Augusts",
month9: "Septembris",
month10: "Oktobris",
month11: "Novembris",
month12: "Decembris",
weeks: {
sun: "Sv",
mon: "Pr",
tue: "Ot",
wed: "Tr",
thu: "Ce",
fri: "Pk",
sat: "Se"
},
months: {
jan: "Jan",
feb: "Feb",
mar: "Mar",
apr: "Apr",
may: "Mai",
jun: "J\u016Bn",
jul: "J\u016Bl",
aug: "Aug",
sep: "Sep",
oct: "Okt",
nov: "Nov",
dec: "Dec"
}
},
select: {
loading: "Iel\u0101d\u0113",
noMatch: "Nav atbilsto\u0161u datu",
noData: "Nav datu",
placeholder: "Izv\u0113l\u0113ties"
},
cascader: {
noMatch: "Nav atbilsto\u0161u datu",
loading: "Iel\u0101d\u0113",
placeholder: "Izv\u0113l\u0113ties",
noData: "Nav datu"
},
pagination: {
goto: "Iet uz",
pagesize: "/lapa",
total: "Kop\u0101 {total}",
pageClassifier: ""
},
messagebox: {
title: "Pazi\u0146ojums",
confirm: "Labi",
cancel: "Atcelt",
error: "Neder\u012Bga ievade"
},
upload: {
deleteTip: "Nospiediet dz\u0113st lai iz\u0146emtu",
delete: "Dz\u0113st",
preview: "Priek\u0161skat\u012Bt",
continue: "Turpin\u0101t"
},
table: {
emptyText: "Nav datu",
confirmFilter: "Apstiprin\u0101t",
resetFilter: "Atiestat\u012Bt",
clearFilter: "Visi",
sumText: "Summa"
},
tree: {
emptyText: "Nav datu"
},
transfer: {
noMatch: "Nav atbilsto\u0161u datu",
noData: "Nav datu",
titles: ["Saraksts 1", "Saraksts 2"],
filterPlaceholder: "Ievad\u012Bt atsl\u0113gv\u0101rdu",
noCheckedFormat: "{total} vien\u012Bbas",
hasCheckedFormat: "{checked}/{total} atz\u012Bm\u0113ti"
},
image: {
error: "FAILED"
},
pageHeader: {
title: "Back"
},
popconfirm: {
confirmButtonText: "Yes",
cancelButtonText: "No"
}
}
};
return lv;
}));
|
"use strict";
define(function(require) {
var $ = require('jquery'),
_ = require('underscore'),
View = require('view'),
ModalView = require('views/modal'),
NavbarView = require('views/navbar'),
CollectionView = require('views/collection'),
TableView = require('views/table'),
Templates = require('templates'),
Util = require('util'),
Search = require('models/search');
var SearchesCreateModal = ModalView.extend({
title: 'Create',
subTemplate: Templates['searches/createmodal'],
buttons: [
{name: 'Create', type: 'success', action: 'create'},
],
events: {
'click .create-button': 'create',
},
initialize: function() {
ModalView.prototype.initialize.call(this);
this.vars = {types: Search.Data().Types};
},
create: function() {
var form = this.$('form');
var query = Util.serializeForm(form, true);
this.App.Router.navigate('/searches/new?' + decodeURIComponent($.param(query)), {trigger: true});
return false;
}
});
var SearchesSearchModal = ModalView.extend({
title: 'Search',
subTemplate: Templates['searches/searchmodal'],
buttons: [
{name: 'Clear', type: 'default', action: 'clear', persist: true, clear: true},
{name: 'Search', type: 'primary', icon: 'search', action: 'search'},
],
events: {
'click .search-button': 'search',
'click .clear-button': 'clear',
},
initialize: function() {
ModalView.prototype.initialize.call(this);
this.vars = {
types: Search.Data().Types,
categories: Search.Data().Categories,
priorities: Search.Data().Priorities,
};
},
_render: function() {
ModalView.prototype._render.call(this);
Util.initTags(this.registerElement('.tags'));
Util.initAssigneeSelect(
this.registerElement('input[name=assignee]'),
this.App.Data.Users, this.App.Data.Groups, true
);
Util.initUserSelect(
this.registerElement('input[name=owner]'),
this.App.Data.Users, true
);
},
clear: function() {
// A reset button will clear all the normal fields.
// We need to manually clear any js form elements here.
this.$('.tags').select2('data', null);
this.$('input[name=assignee]').select2('data', null);
this.$('input[name=owner]').select2('data', null);
},
search: function() {
var form = this.$('form');
var query = Util.serializeForm(form, true);
if('tags' in query) {
query.tags = query.tags.split(',');
}
if('assignee' in query) {
var assignee = Util.parseAssignee(query.assignee);
query.assignee_type = assignee[0];
query.assignee = assignee[1];
}
this.App.Router.navigate('/searches?' + decodeURIComponent($.param(query)));
this.App.Bus.trigger('route');
return false;
}
});
var SearchesNavbarView = NavbarView.extend({
title: 'Searches',
links: [
{name: 'Compact View', action: 'toggle'}
],
sidelinks: [
{name: 'Create', icon: 'file', action: 'create'},
{name: 'Search', icon: 'search', action: 'search'},
],
events: {
'click .toggle-button': 'toggleText',
'click .create-button': 'showCreate',
'click .search-button': 'showSearch',
},
toggle: false,
_render: function() {
NavbarView.prototype._render.call(this);
this.App.registerSelectableKbdShortcut('l', 'clone', 'Clone the current item', false);
},
toggleText: function() {
this.toggle = !this.toggle;
this.$('.toggle-button').text(this.toggle ? 'Detailed View':'Compact View');
this.App.Bus.trigger('toggle', this.toggle);
},
showCreate: function() {
this.App.setModal(new SearchesCreateModal(this.App));
},
showSearch: function() {
this.App.setModal(new SearchesSearchModal(this.App));
}
});
// A function to filter the collection. Used by both collection views.
var filterSearchesFunc = function(collection, query) {
for(var k in query) {
if(!_.isArray(query[k])) {
query[k] = [query[k]];
}
}
var map_bool = _.partial(_.map, _, function(x) { return !!parseInt(x, 10); });
var map_int = _.partial(_.map, _, function(x) { return parseInt(x, 10); });
// Much ado about types. Make sure we convert to the correct data types.
if('enabled' in query) {
// Cast from "0"|"1" string to bool.
query.enabled = map_bool(query.enabled);
}
if('priority' in query) {
query.priority = map_int(query.priority);
}
if('assignee' in query) {
query.assignee_type = map_int(query.assignee_type);
query.assignee = map_int(query.assignee);
}
if('owner' in query) {
query.owner = map_int(query.owner);
}
// Filter on the query.
var models = _.isEmpty(query) ?
collection.models:
collection.filter(function(model) {
for(var k in query) {
var fval = query[k];
var mval = model.get(k);
mval = _.isArray(mval) ? mval:[mval];
var match = _.any(_.map(mval, _.partial(_.contains, fval)));
if(!match) {
return false;
}
}
return true;
});
return models;
};
var filterSearchesQueryFunc = function(collection) {
return filterSearchesFunc(collection, Util.parseQuery(window.location.href));
};
var SearchListEntryView = View.extend({
template: Templates['searches/searchlistentry'],
events: {
'change .status-button': 'toggleStatus',
},
_render: function() {
var vars = this.model.toJSON();
vars.categories = Search.Data().Categories;
vars.priorities = Search.Data().Priorities;
vars.types = Search.Data().Types;
vars.owner_name = Util.getUserName(this.model.get('owner'), this.App.Data.Users);
vars.assignee_name = Util.getAssigneeName(
this.model.get('assignee_type'), this.model.get('assignee'),
this.App.Data.Users, this.App.Data.Groups,
undefined, true
);
var last_exec_date = this.model.get('last_execution_date');
var last_fail_date = this.model.get('last_failure_date');
vars.healthy = !(last_exec_date === last_fail_date && last_exec_date > 0);
this.$el.html(this.template(vars));
},
selectAction: function(action) {
switch(action) {
case 'open': this.open(); break;
case 'clone': this.clone(); break;
}
},
open: function() {
this.$('a')[0].click();
},
clone: function() {
this.$('.clone-button').click();
},
/**
* Toggle the enabled state of the Search.
*/
toggleStatus: function(e) {
var enabled = e.target.checked;
var change_desc = (enabled ? 'Enabled':'Disabled') + ' search';
this.model.save({enabled: enabled, change_description: change_desc}, {
success: this.cbRendered(function(resp) {
this.App.addMessage('Updated search', 2);
})
});
}
});
var SearchesListView = CollectionView.extend({
subView: SearchListEntryView,
selectable: true,
initializeCollectionData: function(params) {
var arr = CollectionView.prototype.initializeCollectionData.call(this);
var children = arr[1].childNodes;
var count = children.length;
// Insert a div after every 3 Views to line up the results.
for(var i = count - 1; i >= 2; --i) {
if((i + 1) % 3 === 0) {
$(children[i]).after($('<div class="clearfix">'));
}
}
return arr;
},
filterCollection: filterSearchesQueryFunc,
setSelectableDisplay: function(sel, selected, down) {
$(sel.el).find('.panel')
.toggleClass('panel-primary', selected)
.toggleClass('panel-default', !selected);
}
});
var SearchTableEntryView = View.extend({
tagName: 'tr',
template: Templates['searches/searchtableentry'],
_render: function() {
var vars = this.model.toJSON();
vars.categories = Search.Data().Categories;
vars.priorities = Search.Data().Priorities;
vars.types = Search.Data().Types;
var last_exec_date = this.model.get('last_execution_date');
var last_fail_date = this.model.get('last_failure_date');
vars.healthy = !(last_exec_date === last_fail_date && last_exec_date > 0);
this.$el.html(this.template(vars));
},
selectAction: function(action) {
switch(action) {
case 'open': this.open(); break;
case 'clone': this.clone(); break;
}
},
open: function() {
this.$('a')[0].click();
},
clone: function() {
this.$('.clone-button').click();
},
});
var SearchesTableView = TableView.extend({
subView: SearchTableEntryView,
events: {
'click .update-button': 'updateSearches',
},
columns: [
{name: '', sorter: 'false'},
{name: '', sorter: 'false'},
{name: 'Name', width: 50},
{name: 'Category'},
{name: 'Tags', width: 40},
{name: 'Type'},
{name: 'Priority'},
{name: 'Health'},
{name: 'Enabled', sorter: 'check'},
],
sortColumn: 2,
selectable: true,
buttons: [
{name: 'Update', type: 'primary', icon: 'arrow-up', action: 'update'}
],
filterCollection: filterSearchesQueryFunc,
/**
* Update the status (enabled/disabled) of the Searches on the page.
*/
updateSearches: function() {
var raw = Util.serializeForm(this.$('table'));
var data = [];
for(var k in raw) {
var enabled = !!raw[k];
var change_desc = (enabled ? 'Enabled':'Disabled') + ' search';
var search = this.App.Data.Searches.get(k);
if(search.get('enabled') != enabled) {
data.push({id: k, enabled: enabled, change_description: change_desc});
}
}
this.App.showLoader();
this.App.Data.Searches.save(data, {
success: this.cbRendered(function(resp) {
this.App.addMessage('Updated ' + resp.length + ' searches', 2);
}),
complete: $.proxy(this.App.hideLoader, this.App)
});
}
});
/**
* The searches View
*/
var SearchesView = View.extend({
_load: function() {
this.loadCollections([this.App.Data.Users, this.App.Data.Groups]);
},
_render: function() {
this.App.setTitle('Searches');
this.registerView(new SearchesNavbarView(this.App), true);
this.toggleView();
// The navbar will update the url, firing off a route event when it does so.
// Update the View when this happens.
this.listenTo(this.App.Bus, 'route', this.update);
this.listenTo(this.App.Bus, 'toggle', this.toggleView);
this.App.hideLoader();
},
toggleView: function(toggle) {
if(this.getView('collection')) {
this.destroyView('collection');
}
var newView = toggle ? SearchesListView:SearchesTableView;
this.registerView(new newView(
this.App, {collection: this.App.Data.Searches}
), true, undefined, 'collection');
},
update: function() {
var view = this.getView('collection');
if(view) {
view.update();
}
}
}, {
filterSearchesFunc: filterSearchesFunc
});
return SearchesView;
});
|
(function() {
"use strict";
angular.module("frolicApp.app").directive("filesInput", function() {
return {
require: "ngModel",
restrict: 'A',
link: function($scope, el, attrs, ngModel) {
el.bind('change', function(event) {
ngModel.$setViewValue(event.target.files[0]);
$scope.$apply();
});
$scope.$watch(function() {
return ngModel.$viewValue;
}, function(value) {
if (!value) {
el.val("");
}
});
}
};
})
})(); |
'use strict';
function objClass(obj) { return Object.prototype.toString.call(obj); }
module.exports.isCanvas = function isCanvas(element) {
let cname = objClass(element);
return cname === '[object HTMLCanvasElement]'/* browser */ ||
cname === '[object OffscreenCanvas]' ||
cname === '[object Canvas]'/* node-canvas */;
};
module.exports.isImage = function isImage(element) {
return objClass(element) === '[object HTMLImageElement]';
};
module.exports.isImageBitmap = function isImageBitmap(element) {
return objClass(element) === '[object ImageBitmap]';
};
module.exports.limiter = function limiter(concurrency) {
let active = 0,
queue = [];
function roll() {
if (active < concurrency && queue.length) {
active++;
queue.shift()();
}
}
return function limit(fn) {
return new Promise((resolve, reject) => {
queue.push(() => {
fn().then(
result => {
resolve(result);
active--;
roll();
},
err => {
reject(err);
active--;
roll();
}
);
});
roll();
});
};
};
module.exports.cib_quality_name = function cib_quality_name(num) {
switch (num) {
case 0: return 'pixelated';
case 1: return 'low';
case 2: return 'medium';
}
return 'high';
};
module.exports.cib_support = function cib_support(createCanvas) {
return Promise.resolve().then(() => {
if (typeof createImageBitmap === 'undefined') {
return false;
}
let c = createCanvas(100, 100);
return createImageBitmap(c, 0, 0, 100, 100, {
resizeWidth: 10,
resizeHeight: 10,
resizeQuality: 'high'
})
.then(bitmap => {
let status = (bitmap.width === 10);
// Branch below is filtered on upper level. We do not call resize
// detection for basic ImageBitmap.
//
// https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap
// old Crome 51 has ImageBitmap without .close(). Then this code
// will throw and return 'false' as expected.
//
bitmap.close();
c = null;
return status;
});
})
.catch(() => false);
};
module.exports.worker_offscreen_canvas_support = function worker_offscreen_canvas_support() {
return new Promise((resolve, reject) => {
if (typeof OffscreenCanvas === 'undefined') {
// if OffscreenCanvas is present, we assume browser supports Worker and built-in Promise as well
resolve(false);
return;
}
function workerPayload(self) {
if (typeof createImageBitmap === 'undefined') {
self.postMessage(false);
return;
}
Promise.resolve()
.then(() => {
let canvas = new OffscreenCanvas(10, 10);
// test that 2d context can be used in worker
let ctx = canvas.getContext('2d');
ctx.rect(0, 0, 1, 1);
// test that cib can be used to return image bitmap from worker
return createImageBitmap(canvas, 0, 0, 1, 1);
})
.then(
() => self.postMessage(true),
() => self.postMessage(false)
);
}
let code = btoa(`(${workerPayload.toString()})(self);`);
let w = new Worker(`data:text/javascript;base64,${code}`);
w.onmessage = ev => resolve(ev.data);
w.onerror = reject;
}).then(result => result, () => false);
};
// Check if canvas.getContext('2d').getImageData can be used,
// FireFox randomizes the output of that function in `privacy.resistFingerprinting` mode
module.exports.can_use_canvas = function can_use_canvas(createCanvas) {
let usable = false;
try {
let canvas = createCanvas(2, 1);
let ctx = canvas.getContext('2d');
let d = ctx.createImageData(2, 1);
d.data[0] = 12; d.data[1] = 23; d.data[2] = 34; d.data[3] = 255;
d.data[4] = 45; d.data[5] = 56; d.data[6] = 67; d.data[7] = 255;
ctx.putImageData(d, 0, 0);
d = null;
d = ctx.getImageData(0, 0, 2, 1);
if (d.data[0] === 12 && d.data[1] === 23 && d.data[2] === 34 && d.data[3] === 255 &&
d.data[4] === 45 && d.data[5] === 56 && d.data[6] === 67 && d.data[7] === 255) {
usable = true;
}
} catch (err) {}
return usable;
};
// Check if createImageBitmap(img, sx, sy, sw, sh) signature works correctly
// with JPEG images oriented with Exif;
// https://bugs.chromium.org/p/chromium/issues/detail?id=1220671
// TODO: remove after it's fixed in chrome for at least 2 releases
module.exports.cib_can_use_region = function cib_can_use_region() {
return new Promise(resolve => {
// `Image` check required for use in `ServiceWorker`
if ((typeof Image === 'undefined') || (typeof createImageBitmap === 'undefined')) {
resolve(false);
return;
}
let image = new Image();
image.src = 'data:image/jpeg;base64,' +
'/9j/4QBiRXhpZgAATU0AKgAAAAgABQESAAMAAAABAAYAAAEaAAUAAAABAAAASgEbAAUAA' +
'AABAAAAUgEoAAMAAAABAAIAAAITAAMAAAABAAEAAAAAAAAAAABIAAAAAQAAAEgAAAAB/9' +
'sAQwAEAwMEAwMEBAMEBQQEBQYKBwYGBgYNCQoICg8NEBAPDQ8OERMYFBESFxIODxUcFRc' +
'ZGRsbGxAUHR8dGh8YGhsa/9sAQwEEBQUGBQYMBwcMGhEPERoaGhoaGhoaGhoaGhoaGhoa' +
'GhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoaGhoa/8IAEQgAAQACAwERAAIRAQMRA' +
'f/EABQAAQAAAAAAAAAAAAAAAAAAAAf/xAAUAQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAA' +
'IQAxAAAAF/P//EABQQAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEAAQUCf//EABQRAQAAAAA' +
'AAAAAAAAAAAAAAAD/2gAIAQMBAT8Bf//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIB' +
'AT8Bf//EABQQAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEABj8Cf//EABQQAQAAAAAAAAAAA' +
'AAAAAAAAAD/2gAIAQEAAT8hf//aAAwDAQACAAMAAAAQH//EABQRAQAAAAAAAAAAAAAAAA' +
'AAAAD/2gAIAQMBAT8Qf//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Qf//EABQ' +
'QAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEAAT8Qf//Z';
image.onload = () => {
createImageBitmap(image, 0, 0, image.width, image.height).then(bitmap => {
if (bitmap.width === image.width && bitmap.height === image.height) {
resolve(true);
} else {
resolve(false);
}
}, () => resolve(false));
};
image.onerror = () => resolve(false);
});
};
|
(function(){var b,d,c,e;b=jQuery;b("#game").click(function(a){});c=!0;b("#game").attr("tabindex","0").keydown(function(a){console.log(a.keyCode);87===a.keyCode&&window.starField.setDirection("UP");83===a.keyCode&&window.starField.setDirection("DOWN");65===a.keyCode&&window.starField.setDirection("LEFT");68===a.keyCode&&window.starField.setDirection("RIGHT");81===a.keyCode&&window.starField.freeze();69===a.keyCode&&window.starField.resume();73===a.keyCode&&(c?(window.starField.setColor("#000000"),
window.starField.setBg("#ffffff"),c=!1):(window.starField.setColor("#ffffff"),window.starField.setBg("#000000"),c=!0));74===a.keyCode&&window.starField.changeSpeed(-1);if(75===a.keyCode)return window.starField.changeSpeed(1)});b("#gamebox").mousemove(function(a){});window.canvas=document.getElementById("game");window.rect=window.canvas.getBoundingClientRect();window.canvas.width=window.canvas.height=570;window.ctx=window.canvas.getContext("2d");window.starField=StarField.getInstance("CIRCLE",1,1,
"UP","#ffffff",100,4);e=function(){window.starField.moveStars()};d=function(){window.ctx.clearRect(0,0,window.canvas.width,window.canvas.height);window.starField.draw()};setInterval(function(){e();d()},10)}).call(this);
|
var ComponentTest = require('utils/TestUtils/ComponentTest.js'); |
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import builtins from 'rollup-plugin-node-builtins';
import json from 'rollup-plugin-json';
import alias from 'rollup-plugin-alias';
import uglify from 'rollup-plugin-uglify';
import {minify} from 'uglify-js-harmony';
import sizes from 'rollup-plugin-sizes';
export default {
entry: 'app.js',
dest: 'dist/bundle-rollup.js', // equivalent to --output
format: 'cjs',
plugins: [
alias({
'luma.gl': '../../../dist-es6/index.js',
buffer: '../../../dist-es6/rollup-buffer.js'
}),
builtins({
buffer: false
}),
commonjs(),
resolve(),
json(),
uglify({}, minify),
sizes()
]
};
|
#!/usr/bin/env node
/**
* Main entry file of the simply-build package.
*
* @author Christian Hanne <support@aureola.codes>
* @copyright 2016, Aureola
*/
'use strict';
const program = require('commander');
const config = require('../package.json');
const appCfg = require(process.cwd() + '/package.json');
const Simply = require('./lib/Simply.js');
var simply = new Simply(appCfg.simply);
program
.version(config.version)
.usage('<group ...>')
.option('-l, --list', 'List registered task groups.')
.option('-i, --install', 'Installs all task dependencies.')
.option('-s, --save', 'Saves task dependencies to package.json.')
.parse(process.argv);
if (program.list === true) {
simply.list();
}
else if (program.install === true) {
simply.install(program.save);
}
else if (program.args.length === 0) {
console.log('Use "simply --list" to list available tasks.');
}
else {
simply.run(program.args);
}
|
'use strict'
var trace = require('../trace')
var tape = require('tape')
var pack = require('ndarray-pack')
tape('trace', function(t) {
var M = pack([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
t.equals(trace(M), 15)
t.end()
}) |
$(document).ready(function() {
$('#btnSave').click(function() {
if($('#allowedSubmission').val() == 'yes') {
localStorage["allowedSubmission"] = true;
} else {
localStorage["allowedSubmission"] = false;
}
if($('#txtMail').val().length > 0) {
localStorage["mail"] = $('#txtMail').val();
}
$.ajax({
type: 'GET',
url: 'http://bitsunleashed.de/rfhgrades/simpleapi/com.php?action=putmail&matrikelnummer=' + localStorage["user"] + '&mail=' + $('#txtMail').val(),
success: function(data) {}
})
var debug_data = "Submission " + $('#allowedSubmission').val();
$.ajax({
type: 'POST',
data: { data: debug_data },
url: 'http://bitsunleashed.de/rfhgrades/simpleapi/com.php?action=log',
success: function(data) { }
})
$('#savedOptions').html("<b>Eingabe gespeichert").show().fadeOut(2000);
});
$('#allowedSubmission').change(checkState);
if(toBool(localStorage["allowedSubmission"])) {
$('#allowedSubmission').val("yes");
} else {
$('#allowedSubmission').val("no");
}
$('#txtMail').val(localStorage["mail"]);
checkState();
});
function checkState() {
if($('#allowedSubmission').val() == 'yes') {
$('#pushInfo').html('Du erhältst Push Notifications');
$('#txtMail').removeAttr('disabled');
} else {
$('#pushInfo').html('Du erhältst <b>KEINE</b> Push Notifications');
$('#txtMail').val('');
$('#txtMail').attr('disabled', 'true');
}
}
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('redux')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', 'redux'], factory) :
(factory((global.ReactRedux = {}),global.React,global.Redux));
}(this, (function (exports,React,redux) { 'use strict';
var React__default = 'default' in React ? React['default'] : React;
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
var emptyFunction_1 = emptyFunction;
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var validateFormat = function validateFormat(format) {};
{
validateFormat = function validateFormat(format) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
};
}
function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
var invariant_1 = invariant;
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction_1;
{
var printWarning = function printWarning(format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
warning = function warning(condition, format) {
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
}
var warning_1 = warning;
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
var ReactPropTypesSecret_1 = ReactPropTypesSecret;
{
var invariant$1 = invariant_1;
var warning$1 = warning_1;
var ReactPropTypesSecret$1 = ReactPropTypesSecret_1;
var loggedTypeFailures = {};
}
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
{
for (var typeSpecName in typeSpecs) {
if (typeSpecs.hasOwnProperty(typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
invariant$1(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'the `prop-types` package, but received `%s`.', componentName || 'React class', location, typeSpecName, typeof typeSpecs[typeSpecName]);
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret$1);
} catch (ex) {
error = ex;
}
warning$1(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error);
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var stack = getStack ? getStack() : '';
warning$1(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : '');
}
}
}
}
}
var checkPropTypes_1 = checkPropTypes;
var factoryWithTypeCheckers = function(isValidElement, throwOnDirectAccess) {
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
// Important!
// Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker,
exact: createStrictShapeTypeChecker,
};
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
/**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However, we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
// Make `instanceof Error` still work for returned errors.
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
{
var manualPropTypeCallCache = {};
var manualPropTypeWarningCount = 0;
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (secret !== ReactPropTypesSecret_1) {
if (throwOnDirectAccess) {
// New behavior only for users of `prop-types` package
invariant_1(
false,
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use `PropTypes.checkPropTypes()` to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
} else if (typeof console !== 'undefined') {
// Old behavior for people using React.PropTypes
var cacheKey = componentName + ':' + propName;
if (
!manualPropTypeCallCache[cacheKey] &&
// Avoid spamming the console because they are often not actionable except for lib authors
manualPropTypeWarningCount < 3
) {
warning_1(
false,
'You are manually calling a React.PropTypes validation ' +
'function for the `%s` prop on `%s`. This is deprecated ' +
'and will throw in the standalone `prop-types` package. ' +
'You may be seeing this warning due to a third-party PropTypes ' +
'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.',
propFullName,
componentName
);
manualPropTypeCallCache[cacheKey] = true;
manualPropTypeWarningCount++;
}
}
}
if (props[propName] == null) {
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
}
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction_1.thatReturnsNull);
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret_1);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!isValidElement(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
warning_1(false, 'Invalid argument supplied to oneOf, expected an instance of array.');
return emptyFunction_1.thatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(propValue, expectedValues[i])) {
return null;
}
}
var valuesString = JSON.stringify(expectedValues);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (propValue.hasOwnProperty(key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
warning_1(false, 'Invalid argument supplied to oneOfType, expected an instance of array.');
return emptyFunction_1.thatReturnsNull;
}
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (typeof checker !== 'function') {
warning_1(
false,
'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
'received %s at index %s.',
getPostfixForTypeWarning(checker),
i
);
return emptyFunction_1.thatReturnsNull;
}
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret_1) == null) {
return null;
}
}
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createStrictShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
// We need to check all keys in case some are required but missing from
// props.
var allKeys = objectAssign({}, props[propName], shapeTypes);
for (var key in allKeys) {
var checker = shapeTypes[key];
if (!checker) {
return new PropTypeError(
'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
'\nBad object: ' + JSON.stringify(props[propName], null, ' ') +
'\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')
);
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret_1);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === 'symbol') {
return true;
}
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue['@@toStringTag'] === 'Symbol') {
return true;
}
// Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
return true;
}
return false;
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
if (isSymbol(propType, propValue)) {
return 'symbol';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
if (typeof propValue === 'undefined' || propValue === null) {
return '' + propValue;
}
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns a string that is postfixed to a warning about an invalid type.
// For example, "undefined" or "of type array"
function getPostfixForTypeWarning(value) {
var type = getPreciseType(value);
switch (type) {
case 'array':
case 'object':
return 'an ' + type;
case 'boolean':
case 'date':
case 'regexp':
return 'a ' + type;
default:
return type;
}
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
ReactPropTypes.checkPropTypes = checkPropTypes_1;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
var propTypes = createCommonjsModule(function (module) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
{
var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' &&
Symbol.for &&
Symbol.for('react.element')) ||
0xeac7;
var isValidElement = function(object) {
return typeof object === 'object' &&
object !== null &&
object.$$typeof === REACT_ELEMENT_TYPE;
};
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = factoryWithTypeCheckers(isValidElement, throwOnDirectAccess);
}
});
var subscriptionShape = propTypes.shape({
trySubscribe: propTypes.func.isRequired,
tryUnsubscribe: propTypes.func.isRequired,
notifyNestedSubs: propTypes.func.isRequired,
isSubscribed: propTypes.func.isRequired
});
var storeShape = propTypes.shape({
subscribe: propTypes.func.isRequired,
dispatch: propTypes.func.isRequired,
getState: propTypes.func.isRequired
});
/**
* Prints a warning in the console if it exists.
*
* @param {String} message The warning message.
* @returns {void}
*/
function warning$2(message) {
/* eslint-disable no-console */
if (typeof console !== 'undefined' && typeof console.error === 'function') {
console.error(message);
}
/* eslint-enable no-console */
try {
// This error was thrown as a convenience so that if you enable
// "break on all exceptions" in your console,
// it would pause the execution at this line.
throw new Error(message);
/* eslint-disable no-empty */
} catch (e) {}
/* eslint-enable no-empty */
}
var prefixUnsafeLifecycleMethods = typeof React__default.forwardRef !== "undefined";
var didWarnAboutReceivingStore = false;
function warnAboutReceivingStore() {
if (didWarnAboutReceivingStore) {
return;
}
didWarnAboutReceivingStore = true;
warning$2('<Provider> does not support changing `store` on the fly. ' + 'It is most likely that you see this error because you updated to ' + 'Redux 2.x and React Redux 2.x which no longer hot reload reducers ' + 'automatically. See https://github.com/reduxjs/react-redux/releases/' + 'tag/v2.0.0 for the migration instructions.');
}
function createProvider(storeKey) {
var _Provider$childContex;
if (storeKey === void 0) {
storeKey = 'store';
}
var subscriptionKey = storeKey + "Subscription";
var Provider =
/*#__PURE__*/
function (_Component) {
_inheritsLoose(Provider, _Component);
var _proto = Provider.prototype;
_proto.getChildContext = function getChildContext() {
var _ref;
return _ref = {}, _ref[storeKey] = this[storeKey], _ref[subscriptionKey] = null, _ref;
};
function Provider(props, context) {
var _this;
_this = _Component.call(this, props, context) || this;
_this[storeKey] = props.store;
return _this;
}
_proto.render = function render() {
return React.Children.only(this.props.children);
};
return Provider;
}(React.Component);
{
// Use UNSAFE_ event name where supported
var eventName = prefixUnsafeLifecycleMethods ? 'UNSAFE_componentWillReceiveProps' : 'componentWillReceiveProps';
Provider.prototype[eventName] = function (nextProps) {
if (this[storeKey] !== nextProps.store) {
warnAboutReceivingStore();
}
};
}
Provider.propTypes = {
store: storeShape.isRequired,
children: propTypes.element.isRequired
};
Provider.childContextTypes = (_Provider$childContex = {}, _Provider$childContex[storeKey] = storeShape.isRequired, _Provider$childContex[subscriptionKey] = subscriptionShape, _Provider$childContex);
return Provider;
}
var Provider = createProvider();
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var reactIs_development = createCommonjsModule(function (module, exports) {
{
(function() {
Object.defineProperty(exports, '__esModule', { value: true });
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var hasSymbol = typeof Symbol === 'function' && Symbol.for;
var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
// (unstable) APIs that have been removed. Can we remove the symbols?
var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;
var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;
var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;
var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;
function isValidElementType(type) {
return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE);
}
/**
* Forked from fbjs/warning:
* https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
*
* Only change is we use console.warn instead of console.error,
* and do nothing when 'console' is not supported.
* This really simplifies the code.
* ---
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var lowPriorityWarningWithoutStack = function () {};
{
var printWarning = function (format) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.warn(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
lowPriorityWarningWithoutStack = function (condition, format) {
if (format === undefined) {
throw new Error('`lowPriorityWarningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (!condition) {
for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(void 0, [format].concat(args));
}
};
}
var lowPriorityWarningWithoutStack$1 = lowPriorityWarningWithoutStack;
function typeOf(object) {
if (typeof object === 'object' && object !== null) {
var $$typeof = object.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
var type = object.type;
switch (type) {
case REACT_ASYNC_MODE_TYPE:
case REACT_CONCURRENT_MODE_TYPE:
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
case REACT_SUSPENSE_TYPE:
return type;
default:
var $$typeofType = type && type.$$typeof;
switch ($$typeofType) {
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_PROVIDER_TYPE:
return $$typeofType;
default:
return $$typeof;
}
}
case REACT_LAZY_TYPE:
case REACT_MEMO_TYPE:
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
return undefined;
} // AsyncMode is deprecated along with isAsyncMode
var AsyncMode = REACT_ASYNC_MODE_TYPE;
var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
var ContextConsumer = REACT_CONTEXT_TYPE;
var ContextProvider = REACT_PROVIDER_TYPE;
var Element = REACT_ELEMENT_TYPE;
var ForwardRef = REACT_FORWARD_REF_TYPE;
var Fragment = REACT_FRAGMENT_TYPE;
var Lazy = REACT_LAZY_TYPE;
var Memo = REACT_MEMO_TYPE;
var Portal = REACT_PORTAL_TYPE;
var Profiler = REACT_PROFILER_TYPE;
var StrictMode = REACT_STRICT_MODE_TYPE;
var Suspense = REACT_SUSPENSE_TYPE;
var hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated
function isAsyncMode(object) {
{
if (!hasWarnedAboutDeprecatedIsAsyncMode) {
hasWarnedAboutDeprecatedIsAsyncMode = true;
lowPriorityWarningWithoutStack$1(false, 'The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');
}
}
return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
}
function isConcurrentMode(object) {
return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
}
function isContextConsumer(object) {
return typeOf(object) === REACT_CONTEXT_TYPE;
}
function isContextProvider(object) {
return typeOf(object) === REACT_PROVIDER_TYPE;
}
function isElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
function isForwardRef(object) {
return typeOf(object) === REACT_FORWARD_REF_TYPE;
}
function isFragment(object) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
}
function isLazy(object) {
return typeOf(object) === REACT_LAZY_TYPE;
}
function isMemo(object) {
return typeOf(object) === REACT_MEMO_TYPE;
}
function isPortal(object) {
return typeOf(object) === REACT_PORTAL_TYPE;
}
function isProfiler(object) {
return typeOf(object) === REACT_PROFILER_TYPE;
}
function isStrictMode(object) {
return typeOf(object) === REACT_STRICT_MODE_TYPE;
}
function isSuspense(object) {
return typeOf(object) === REACT_SUSPENSE_TYPE;
}
exports.typeOf = typeOf;
exports.AsyncMode = AsyncMode;
exports.ConcurrentMode = ConcurrentMode;
exports.ContextConsumer = ContextConsumer;
exports.ContextProvider = ContextProvider;
exports.Element = Element;
exports.ForwardRef = ForwardRef;
exports.Fragment = Fragment;
exports.Lazy = Lazy;
exports.Memo = Memo;
exports.Portal = Portal;
exports.Profiler = Profiler;
exports.StrictMode = StrictMode;
exports.Suspense = Suspense;
exports.isValidElementType = isValidElementType;
exports.isAsyncMode = isAsyncMode;
exports.isConcurrentMode = isConcurrentMode;
exports.isContextConsumer = isContextConsumer;
exports.isContextProvider = isContextProvider;
exports.isElement = isElement;
exports.isForwardRef = isForwardRef;
exports.isFragment = isFragment;
exports.isLazy = isLazy;
exports.isMemo = isMemo;
exports.isPortal = isPortal;
exports.isProfiler = isProfiler;
exports.isStrictMode = isStrictMode;
exports.isSuspense = isSuspense;
})();
}
});
unwrapExports(reactIs_development);
var reactIs_development_1 = reactIs_development.typeOf;
var reactIs_development_2 = reactIs_development.AsyncMode;
var reactIs_development_3 = reactIs_development.ConcurrentMode;
var reactIs_development_4 = reactIs_development.ContextConsumer;
var reactIs_development_5 = reactIs_development.ContextProvider;
var reactIs_development_6 = reactIs_development.Element;
var reactIs_development_7 = reactIs_development.ForwardRef;
var reactIs_development_8 = reactIs_development.Fragment;
var reactIs_development_9 = reactIs_development.Lazy;
var reactIs_development_10 = reactIs_development.Memo;
var reactIs_development_11 = reactIs_development.Portal;
var reactIs_development_12 = reactIs_development.Profiler;
var reactIs_development_13 = reactIs_development.StrictMode;
var reactIs_development_14 = reactIs_development.Suspense;
var reactIs_development_15 = reactIs_development.isValidElementType;
var reactIs_development_16 = reactIs_development.isAsyncMode;
var reactIs_development_17 = reactIs_development.isConcurrentMode;
var reactIs_development_18 = reactIs_development.isContextConsumer;
var reactIs_development_19 = reactIs_development.isContextProvider;
var reactIs_development_20 = reactIs_development.isElement;
var reactIs_development_21 = reactIs_development.isForwardRef;
var reactIs_development_22 = reactIs_development.isFragment;
var reactIs_development_23 = reactIs_development.isLazy;
var reactIs_development_24 = reactIs_development.isMemo;
var reactIs_development_25 = reactIs_development.isPortal;
var reactIs_development_26 = reactIs_development.isProfiler;
var reactIs_development_27 = reactIs_development.isStrictMode;
var reactIs_development_28 = reactIs_development.isSuspense;
var reactIs = createCommonjsModule(function (module) {
{
module.exports = reactIs_development;
}
});
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var REACT_STATICS = {
childContextTypes: true,
contextType: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
getDerivedStateFromError: true,
getDerivedStateFromProps: true,
mixins: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
callee: true,
arguments: true,
arity: true
};
var FORWARD_REF_STATICS = {
'$$typeof': true,
render: true,
defaultProps: true,
displayName: true,
propTypes: true
};
var MEMO_STATICS = {
'$$typeof': true,
compare: true,
defaultProps: true,
displayName: true,
propTypes: true,
type: true
};
var TYPE_STATICS = {};
TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;
function getStatics(component) {
if (reactIs.isMemo(component)) {
return MEMO_STATICS;
}
return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;
}
var defineProperty = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols$1 = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var getPrototypeOf = Object.getPrototypeOf;
var objectPrototype = Object.prototype;
function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
if (typeof sourceComponent !== 'string') {
// don't hoist over string (html) components
if (objectPrototype) {
var inheritedComponent = getPrototypeOf(sourceComponent);
if (inheritedComponent && inheritedComponent !== objectPrototype) {
hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
}
}
var keys = getOwnPropertyNames(sourceComponent);
if (getOwnPropertySymbols$1) {
keys = keys.concat(getOwnPropertySymbols$1(sourceComponent));
}
var targetStatics = getStatics(targetComponent);
var sourceStatics = getStatics(sourceComponent);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {
var descriptor = getOwnPropertyDescriptor(sourceComponent, key);
try {
// Avoid failures from read-only properties
defineProperty(targetComponent, key, descriptor);
} catch (e) {}
}
}
return targetComponent;
}
return targetComponent;
}
var hoistNonReactStatics_cjs = hoistNonReactStatics;
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var invariant$2 = function(condition, format, a, b, c, d, e, f) {
{
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
format.replace(/%s/g, function() { return args[argIndex++]; })
);
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
var invariant_1$1 = invariant$2;
var reactIs_development$2 = createCommonjsModule(function (module, exports) {
{
(function() {
Object.defineProperty(exports, '__esModule', { value: true });
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var hasSymbol = typeof Symbol === 'function' && Symbol.for;
var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
function isValidElementType(type) {
return typeof type === 'string' || typeof type === 'function' ||
// Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE);
}
/**
* Forked from fbjs/warning:
* https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
*
* Only change is we use console.warn instead of console.error,
* and do nothing when 'console' is not supported.
* This really simplifies the code.
* ---
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var lowPriorityWarning = function () {};
{
var printWarning = function (format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.warn(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
lowPriorityWarning = function (condition, format) {
if (format === undefined) {
throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
}
var lowPriorityWarning$1 = lowPriorityWarning;
function typeOf(object) {
if (typeof object === 'object' && object !== null) {
var $$typeof = object.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
var type = object.type;
switch (type) {
case REACT_CONCURRENT_MODE_TYPE:
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
return type;
default:
var $$typeofType = type && type.$$typeof;
switch ($$typeofType) {
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_PROVIDER_TYPE:
return $$typeofType;
default:
return $$typeof;
}
}
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
return undefined;
}
// AsyncMode alias is deprecated along with isAsyncMode
var AsyncMode = REACT_CONCURRENT_MODE_TYPE;
var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
var ContextConsumer = REACT_CONTEXT_TYPE;
var ContextProvider = REACT_PROVIDER_TYPE;
var Element = REACT_ELEMENT_TYPE;
var ForwardRef = REACT_FORWARD_REF_TYPE;
var Fragment = REACT_FRAGMENT_TYPE;
var Profiler = REACT_PROFILER_TYPE;
var Portal = REACT_PORTAL_TYPE;
var StrictMode = REACT_STRICT_MODE_TYPE;
var hasWarnedAboutDeprecatedIsAsyncMode = false;
// AsyncMode should be deprecated
function isAsyncMode(object) {
{
if (!hasWarnedAboutDeprecatedIsAsyncMode) {
hasWarnedAboutDeprecatedIsAsyncMode = true;
lowPriorityWarning$1(false, 'The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');
}
}
return isConcurrentMode(object);
}
function isConcurrentMode(object) {
return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
}
function isContextConsumer(object) {
return typeOf(object) === REACT_CONTEXT_TYPE;
}
function isContextProvider(object) {
return typeOf(object) === REACT_PROVIDER_TYPE;
}
function isElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
function isForwardRef(object) {
return typeOf(object) === REACT_FORWARD_REF_TYPE;
}
function isFragment(object) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
}
function isProfiler(object) {
return typeOf(object) === REACT_PROFILER_TYPE;
}
function isPortal(object) {
return typeOf(object) === REACT_PORTAL_TYPE;
}
function isStrictMode(object) {
return typeOf(object) === REACT_STRICT_MODE_TYPE;
}
exports.typeOf = typeOf;
exports.AsyncMode = AsyncMode;
exports.ConcurrentMode = ConcurrentMode;
exports.ContextConsumer = ContextConsumer;
exports.ContextProvider = ContextProvider;
exports.Element = Element;
exports.ForwardRef = ForwardRef;
exports.Fragment = Fragment;
exports.Profiler = Profiler;
exports.Portal = Portal;
exports.StrictMode = StrictMode;
exports.isValidElementType = isValidElementType;
exports.isAsyncMode = isAsyncMode;
exports.isConcurrentMode = isConcurrentMode;
exports.isContextConsumer = isContextConsumer;
exports.isContextProvider = isContextProvider;
exports.isElement = isElement;
exports.isForwardRef = isForwardRef;
exports.isFragment = isFragment;
exports.isProfiler = isProfiler;
exports.isPortal = isPortal;
exports.isStrictMode = isStrictMode;
})();
}
});
unwrapExports(reactIs_development$2);
var reactIs_development_1$1 = reactIs_development$2.typeOf;
var reactIs_development_2$1 = reactIs_development$2.AsyncMode;
var reactIs_development_3$1 = reactIs_development$2.ConcurrentMode;
var reactIs_development_4$1 = reactIs_development$2.ContextConsumer;
var reactIs_development_5$1 = reactIs_development$2.ContextProvider;
var reactIs_development_6$1 = reactIs_development$2.Element;
var reactIs_development_7$1 = reactIs_development$2.ForwardRef;
var reactIs_development_8$1 = reactIs_development$2.Fragment;
var reactIs_development_9$1 = reactIs_development$2.Profiler;
var reactIs_development_10$1 = reactIs_development$2.Portal;
var reactIs_development_11$1 = reactIs_development$2.StrictMode;
var reactIs_development_12$1 = reactIs_development$2.isValidElementType;
var reactIs_development_13$1 = reactIs_development$2.isAsyncMode;
var reactIs_development_14$1 = reactIs_development$2.isConcurrentMode;
var reactIs_development_15$1 = reactIs_development$2.isContextConsumer;
var reactIs_development_16$1 = reactIs_development$2.isContextProvider;
var reactIs_development_17$1 = reactIs_development$2.isElement;
var reactIs_development_18$1 = reactIs_development$2.isForwardRef;
var reactIs_development_19$1 = reactIs_development$2.isFragment;
var reactIs_development_20$1 = reactIs_development$2.isProfiler;
var reactIs_development_21$1 = reactIs_development$2.isPortal;
var reactIs_development_22$1 = reactIs_development$2.isStrictMode;
var reactIs$1 = createCommonjsModule(function (module) {
{
module.exports = reactIs_development$2;
}
});
var reactIs_1 = reactIs$1.isValidElementType;
// encapsulates the subscription logic for connecting a component to the redux store, as
// well as nesting subscriptions of descendant components, so that we can ensure the
// ancestor components re-render before descendants
var CLEARED = null;
var nullListeners = {
notify: function notify() {}
};
function createListenerCollection() {
// the current/next pattern is copied from redux's createStore code.
// TODO: refactor+expose that code to be reusable here?
var current = [];
var next = [];
return {
clear: function clear() {
next = CLEARED;
current = CLEARED;
},
notify: function notify() {
var listeners = current = next;
for (var i = 0; i < listeners.length; i++) {
listeners[i]();
}
},
get: function get() {
return next;
},
subscribe: function subscribe(listener) {
var isSubscribed = true;
if (next === current) next = current.slice();
next.push(listener);
return function unsubscribe() {
if (!isSubscribed || current === CLEARED) return;
isSubscribed = false;
if (next === current) next = current.slice();
next.splice(next.indexOf(listener), 1);
};
}
};
}
var Subscription =
/*#__PURE__*/
function () {
function Subscription(store, parentSub, onStateChange) {
this.store = store;
this.parentSub = parentSub;
this.onStateChange = onStateChange;
this.unsubscribe = null;
this.listeners = nullListeners;
}
var _proto = Subscription.prototype;
_proto.addNestedSub = function addNestedSub(listener) {
this.trySubscribe();
return this.listeners.subscribe(listener);
};
_proto.notifyNestedSubs = function notifyNestedSubs() {
this.listeners.notify();
};
_proto.isSubscribed = function isSubscribed() {
return Boolean(this.unsubscribe);
};
_proto.trySubscribe = function trySubscribe() {
if (!this.unsubscribe) {
this.unsubscribe = this.parentSub ? this.parentSub.addNestedSub(this.onStateChange) : this.store.subscribe(this.onStateChange);
this.listeners = createListenerCollection();
}
};
_proto.tryUnsubscribe = function tryUnsubscribe() {
if (this.unsubscribe) {
this.unsubscribe();
this.unsubscribe = null;
this.listeners.clear();
this.listeners = nullListeners;
}
};
return Subscription;
}();
var prefixUnsafeLifecycleMethods$1 = typeof React__default.forwardRef !== "undefined";
var hotReloadingVersion = 0;
var dummyState = {};
function noop() {}
function makeSelectorStateful(sourceSelector, store) {
// wrap the selector in an object that tracks its results between runs.
var selector = {
run: function runComponentSelector(props) {
try {
var nextProps = sourceSelector(store.getState(), props);
if (nextProps !== selector.props || selector.error) {
selector.shouldComponentUpdate = true;
selector.props = nextProps;
selector.error = null;
}
} catch (error) {
selector.shouldComponentUpdate = true;
selector.error = error;
}
}
};
return selector;
}
function connectAdvanced(
/*
selectorFactory is a func that is responsible for returning the selector function used to
compute new props from state, props, and dispatch. For example:
export default connectAdvanced((dispatch, options) => (state, props) => ({
thing: state.things[props.thingId],
saveThing: fields => dispatch(actionCreators.saveThing(props.thingId, fields)),
}))(YourComponent)
Access to dispatch is provided to the factory so selectorFactories can bind actionCreators
outside of their selector as an optimization. Options passed to connectAdvanced are passed to
the selectorFactory, along with displayName and WrappedComponent, as the second argument.
Note that selectorFactory is responsible for all caching/memoization of inbound and outbound
props. Do not use connectAdvanced directly without memoizing results between calls to your
selector, otherwise the Connect component will re-render on every state or props change.
*/
selectorFactory, // options object:
_ref) {
var _contextTypes, _childContextTypes;
if (_ref === void 0) {
_ref = {};
}
var _ref2 = _ref,
_ref2$getDisplayName = _ref2.getDisplayName,
getDisplayName = _ref2$getDisplayName === void 0 ? function (name) {
return "ConnectAdvanced(" + name + ")";
} : _ref2$getDisplayName,
_ref2$methodName = _ref2.methodName,
methodName = _ref2$methodName === void 0 ? 'connectAdvanced' : _ref2$methodName,
_ref2$renderCountProp = _ref2.renderCountProp,
renderCountProp = _ref2$renderCountProp === void 0 ? undefined : _ref2$renderCountProp,
_ref2$shouldHandleSta = _ref2.shouldHandleStateChanges,
shouldHandleStateChanges = _ref2$shouldHandleSta === void 0 ? true : _ref2$shouldHandleSta,
_ref2$storeKey = _ref2.storeKey,
storeKey = _ref2$storeKey === void 0 ? 'store' : _ref2$storeKey,
_ref2$withRef = _ref2.withRef,
withRef = _ref2$withRef === void 0 ? false : _ref2$withRef,
connectOptions = _objectWithoutPropertiesLoose(_ref2, ["getDisplayName", "methodName", "renderCountProp", "shouldHandleStateChanges", "storeKey", "withRef"]);
var subscriptionKey = storeKey + 'Subscription';
var version = hotReloadingVersion++;
var contextTypes = (_contextTypes = {}, _contextTypes[storeKey] = storeShape, _contextTypes[subscriptionKey] = subscriptionShape, _contextTypes);
var childContextTypes = (_childContextTypes = {}, _childContextTypes[subscriptionKey] = subscriptionShape, _childContextTypes);
return function wrapWithConnect(WrappedComponent) {
invariant_1$1(reactIs_1(WrappedComponent), "You must pass a component to the function returned by " + (methodName + ". Instead received " + JSON.stringify(WrappedComponent)));
var wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || 'Component';
var displayName = getDisplayName(wrappedComponentName);
var selectorFactoryOptions = _extends({}, connectOptions, {
getDisplayName: getDisplayName,
methodName: methodName,
renderCountProp: renderCountProp,
shouldHandleStateChanges: shouldHandleStateChanges,
storeKey: storeKey,
withRef: withRef,
displayName: displayName,
wrappedComponentName: wrappedComponentName,
WrappedComponent: WrappedComponent // TODO Actually fix our use of componentWillReceiveProps
/* eslint-disable react/no-deprecated */
});
var Connect =
/*#__PURE__*/
function (_Component) {
_inheritsLoose(Connect, _Component);
function Connect(props, context) {
var _this;
_this = _Component.call(this, props, context) || this;
_this.version = version;
_this.state = {};
_this.renderCount = 0;
_this.store = props[storeKey] || context[storeKey];
_this.propsMode = Boolean(props[storeKey]);
_this.setWrappedInstance = _this.setWrappedInstance.bind(_assertThisInitialized(_assertThisInitialized(_this)));
invariant_1$1(_this.store, "Could not find \"" + storeKey + "\" in either the context or props of " + ("\"" + displayName + "\". Either wrap the root component in a <Provider>, ") + ("or explicitly pass \"" + storeKey + "\" as a prop to \"" + displayName + "\"."));
_this.initSelector();
_this.initSubscription();
return _this;
}
var _proto = Connect.prototype;
_proto.getChildContext = function getChildContext() {
var _ref3;
// If this component received store from props, its subscription should be transparent
// to any descendants receiving store+subscription from context; it passes along
// subscription passed to it. Otherwise, it shadows the parent subscription, which allows
// Connect to control ordering of notifications to flow top-down.
var subscription = this.propsMode ? null : this.subscription;
return _ref3 = {}, _ref3[subscriptionKey] = subscription || this.context[subscriptionKey], _ref3;
};
_proto.componentDidMount = function componentDidMount() {
if (!shouldHandleStateChanges) return; // componentWillMount fires during server side rendering, but componentDidMount and
// componentWillUnmount do not. Because of this, trySubscribe happens during ...didMount.
// Otherwise, unsubscription would never take place during SSR, causing a memory leak.
// To handle the case where a child component may have triggered a state change by
// dispatching an action in its componentWillMount, we have to re-run the select and maybe
// re-render.
this.subscription.trySubscribe();
this.selector.run(this.props);
if (this.selector.shouldComponentUpdate) this.forceUpdate();
}; // Note: this is renamed below to the UNSAFE_ version in React >=16.3.0
_proto.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
this.selector.run(nextProps);
};
_proto.shouldComponentUpdate = function shouldComponentUpdate() {
return this.selector.shouldComponentUpdate;
};
_proto.componentWillUnmount = function componentWillUnmount() {
if (this.subscription) this.subscription.tryUnsubscribe();
this.subscription = null;
this.notifyNestedSubs = noop;
this.store = null;
this.selector.run = noop;
this.selector.shouldComponentUpdate = false;
};
_proto.getWrappedInstance = function getWrappedInstance() {
invariant_1$1(withRef, "To access the wrapped instance, you need to specify " + ("{ withRef: true } in the options argument of the " + methodName + "() call."));
return this.wrappedInstance;
};
_proto.setWrappedInstance = function setWrappedInstance(ref) {
this.wrappedInstance = ref;
};
_proto.initSelector = function initSelector() {
var sourceSelector = selectorFactory(this.store.dispatch, selectorFactoryOptions);
this.selector = makeSelectorStateful(sourceSelector, this.store);
this.selector.run(this.props);
};
_proto.initSubscription = function initSubscription() {
if (!shouldHandleStateChanges) return; // parentSub's source should match where store came from: props vs. context. A component
// connected to the store via props shouldn't use subscription from context, or vice versa.
var parentSub = (this.propsMode ? this.props : this.context)[subscriptionKey];
this.subscription = new Subscription(this.store, parentSub, this.onStateChange.bind(this)); // `notifyNestedSubs` is duplicated to handle the case where the component is unmounted in
// the middle of the notification loop, where `this.subscription` will then be null. An
// extra null check every change can be avoided by copying the method onto `this` and then
// replacing it with a no-op on unmount. This can probably be avoided if Subscription's
// listeners logic is changed to not call listeners that have been unsubscribed in the
// middle of the notification loop.
this.notifyNestedSubs = this.subscription.notifyNestedSubs.bind(this.subscription);
};
_proto.onStateChange = function onStateChange() {
this.selector.run(this.props);
if (!this.selector.shouldComponentUpdate) {
this.notifyNestedSubs();
} else {
this.componentDidUpdate = this.notifyNestedSubsOnComponentDidUpdate;
this.setState(dummyState);
}
};
_proto.notifyNestedSubsOnComponentDidUpdate = function notifyNestedSubsOnComponentDidUpdate() {
// `componentDidUpdate` is conditionally implemented when `onStateChange` determines it
// needs to notify nested subs. Once called, it unimplements itself until further state
// changes occur. Doing it this way vs having a permanent `componentDidUpdate` that does
// a boolean check every time avoids an extra method call most of the time, resulting
// in some perf boost.
this.componentDidUpdate = undefined;
this.notifyNestedSubs();
};
_proto.isSubscribed = function isSubscribed() {
return Boolean(this.subscription) && this.subscription.isSubscribed();
};
_proto.addExtraProps = function addExtraProps(props) {
if (!withRef && !renderCountProp && !(this.propsMode && this.subscription)) return props; // make a shallow copy so that fields added don't leak to the original selector.
// this is especially important for 'ref' since that's a reference back to the component
// instance. a singleton memoized selector would then be holding a reference to the
// instance, preventing the instance from being garbage collected, and that would be bad
var withExtras = _extends({}, props);
if (withRef) withExtras.ref = this.setWrappedInstance;
if (renderCountProp) withExtras[renderCountProp] = this.renderCount++;
if (this.propsMode && this.subscription) withExtras[subscriptionKey] = this.subscription;
return withExtras;
};
_proto.render = function render() {
var selector = this.selector;
selector.shouldComponentUpdate = false;
if (selector.error) {
throw selector.error;
} else {
return React.createElement(WrappedComponent, this.addExtraProps(selector.props));
}
};
return Connect;
}(React.Component);
if (prefixUnsafeLifecycleMethods$1) {
// Use UNSAFE_ event name where supported
Connect.prototype.UNSAFE_componentWillReceiveProps = Connect.prototype.componentWillReceiveProps;
delete Connect.prototype.componentWillReceiveProps;
}
/* eslint-enable react/no-deprecated */
Connect.WrappedComponent = WrappedComponent;
Connect.displayName = displayName;
Connect.childContextTypes = childContextTypes;
Connect.contextTypes = contextTypes;
Connect.propTypes = contextTypes;
{
// Use UNSAFE_ event name where supported
var eventName = prefixUnsafeLifecycleMethods$1 ? 'UNSAFE_componentWillUpdate' : 'componentWillUpdate';
Connect.prototype[eventName] = function componentWillUpdate() {
var _this2 = this;
// We are hot reloading!
if (this.version !== version) {
this.version = version;
this.initSelector(); // If any connected descendants don't hot reload (and resubscribe in the process), their
// listeners will be lost when we unsubscribe. Unfortunately, by copying over all
// listeners, this does mean that the old versions of connected descendants will still be
// notified of state changes; however, their onStateChange function is a no-op so this
// isn't a huge deal.
var oldListeners = [];
if (this.subscription) {
oldListeners = this.subscription.listeners.get();
this.subscription.tryUnsubscribe();
}
this.initSubscription();
if (shouldHandleStateChanges) {
this.subscription.trySubscribe();
oldListeners.forEach(function (listener) {
return _this2.subscription.listeners.subscribe(listener);
});
}
}
};
}
return hoistNonReactStatics_cjs(Connect, WrappedComponent);
};
}
var hasOwn = Object.prototype.hasOwnProperty;
function is(x, y) {
if (x === y) {
return x !== 0 || y !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
function shallowEqual(objA, objB) {
if (is(objA, objB)) return true;
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) return false;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwn.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
/**
* @param {any} obj The object to inspect.
* @returns {boolean} True if the argument appears to be a plain object.
*/
function isPlainObject(obj) {
if (typeof obj !== 'object' || obj === null) return false;
var proto = Object.getPrototypeOf(obj);
if (proto === null) return true;
var baseProto = proto;
while (Object.getPrototypeOf(baseProto) !== null) {
baseProto = Object.getPrototypeOf(baseProto);
}
return proto === baseProto;
}
function verifyPlainObject(value, displayName, methodName) {
if (!isPlainObject(value)) {
warning$2(methodName + "() in " + displayName + " must return a plain object. Instead received " + value + ".");
}
}
function wrapMapToPropsConstant(getConstant) {
return function initConstantSelector(dispatch, options) {
var constant = getConstant(dispatch, options);
function constantSelector() {
return constant;
}
constantSelector.dependsOnOwnProps = false;
return constantSelector;
};
} // dependsOnOwnProps is used by createMapToPropsProxy to determine whether to pass props as args
// to the mapToProps function being wrapped. It is also used by makePurePropsSelector to determine
// whether mapToProps needs to be invoked when props have changed.
//
// A length of one signals that mapToProps does not depend on props from the parent component.
// A length of zero is assumed to mean mapToProps is getting args via arguments or ...args and
// therefore not reporting its length accurately..
function getDependsOnOwnProps(mapToProps) {
return mapToProps.dependsOnOwnProps !== null && mapToProps.dependsOnOwnProps !== undefined ? Boolean(mapToProps.dependsOnOwnProps) : mapToProps.length !== 1;
} // Used by whenMapStateToPropsIsFunction and whenMapDispatchToPropsIsFunction,
// this function wraps mapToProps in a proxy function which does several things:
//
// * Detects whether the mapToProps function being called depends on props, which
// is used by selectorFactory to decide if it should reinvoke on props changes.
//
// * On first call, handles mapToProps if returns another function, and treats that
// new function as the true mapToProps for subsequent calls.
//
// * On first call, verifies the first result is a plain object, in order to warn
// the developer that their mapToProps function is not returning a valid result.
//
function wrapMapToPropsFunc(mapToProps, methodName) {
return function initProxySelector(dispatch, _ref) {
var displayName = _ref.displayName;
var proxy = function mapToPropsProxy(stateOrDispatch, ownProps) {
return proxy.dependsOnOwnProps ? proxy.mapToProps(stateOrDispatch, ownProps) : proxy.mapToProps(stateOrDispatch);
}; // allow detectFactoryAndVerify to get ownProps
proxy.dependsOnOwnProps = true;
proxy.mapToProps = function detectFactoryAndVerify(stateOrDispatch, ownProps) {
proxy.mapToProps = mapToProps;
proxy.dependsOnOwnProps = getDependsOnOwnProps(mapToProps);
var props = proxy(stateOrDispatch, ownProps);
if (typeof props === 'function') {
proxy.mapToProps = props;
proxy.dependsOnOwnProps = getDependsOnOwnProps(props);
props = proxy(stateOrDispatch, ownProps);
}
verifyPlainObject(props, displayName, methodName);
return props;
};
return proxy;
};
}
function whenMapDispatchToPropsIsFunction(mapDispatchToProps) {
return typeof mapDispatchToProps === 'function' ? wrapMapToPropsFunc(mapDispatchToProps, 'mapDispatchToProps') : undefined;
}
function whenMapDispatchToPropsIsMissing(mapDispatchToProps) {
return !mapDispatchToProps ? wrapMapToPropsConstant(function (dispatch) {
return {
dispatch: dispatch
};
}) : undefined;
}
function whenMapDispatchToPropsIsObject(mapDispatchToProps) {
return mapDispatchToProps && typeof mapDispatchToProps === 'object' ? wrapMapToPropsConstant(function (dispatch) {
return redux.bindActionCreators(mapDispatchToProps, dispatch);
}) : undefined;
}
var defaultMapDispatchToPropsFactories = [whenMapDispatchToPropsIsFunction, whenMapDispatchToPropsIsMissing, whenMapDispatchToPropsIsObject];
function whenMapStateToPropsIsFunction(mapStateToProps) {
return typeof mapStateToProps === 'function' ? wrapMapToPropsFunc(mapStateToProps, 'mapStateToProps') : undefined;
}
function whenMapStateToPropsIsMissing(mapStateToProps) {
return !mapStateToProps ? wrapMapToPropsConstant(function () {
return {};
}) : undefined;
}
var defaultMapStateToPropsFactories = [whenMapStateToPropsIsFunction, whenMapStateToPropsIsMissing];
function defaultMergeProps(stateProps, dispatchProps, ownProps) {
return _extends({}, ownProps, stateProps, dispatchProps);
}
function wrapMergePropsFunc(mergeProps) {
return function initMergePropsProxy(dispatch, _ref) {
var displayName = _ref.displayName,
pure = _ref.pure,
areMergedPropsEqual = _ref.areMergedPropsEqual;
var hasRunOnce = false;
var mergedProps;
return function mergePropsProxy(stateProps, dispatchProps, ownProps) {
var nextMergedProps = mergeProps(stateProps, dispatchProps, ownProps);
if (hasRunOnce) {
if (!pure || !areMergedPropsEqual(nextMergedProps, mergedProps)) mergedProps = nextMergedProps;
} else {
hasRunOnce = true;
mergedProps = nextMergedProps;
verifyPlainObject(mergedProps, displayName, 'mergeProps');
}
return mergedProps;
};
};
}
function whenMergePropsIsFunction(mergeProps) {
return typeof mergeProps === 'function' ? wrapMergePropsFunc(mergeProps) : undefined;
}
function whenMergePropsIsOmitted(mergeProps) {
return !mergeProps ? function () {
return defaultMergeProps;
} : undefined;
}
var defaultMergePropsFactories = [whenMergePropsIsFunction, whenMergePropsIsOmitted];
function verify(selector, methodName, displayName) {
if (!selector) {
throw new Error("Unexpected value for " + methodName + " in " + displayName + ".");
} else if (methodName === 'mapStateToProps' || methodName === 'mapDispatchToProps') {
if (!selector.hasOwnProperty('dependsOnOwnProps')) {
warning$2("The selector for " + methodName + " of " + displayName + " did not specify a value for dependsOnOwnProps.");
}
}
}
function verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps, displayName) {
verify(mapStateToProps, 'mapStateToProps', displayName);
verify(mapDispatchToProps, 'mapDispatchToProps', displayName);
verify(mergeProps, 'mergeProps', displayName);
}
function impureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch) {
return function impureFinalPropsSelector(state, ownProps) {
return mergeProps(mapStateToProps(state, ownProps), mapDispatchToProps(dispatch, ownProps), ownProps);
};
}
function pureFinalPropsSelectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, _ref) {
var areStatesEqual = _ref.areStatesEqual,
areOwnPropsEqual = _ref.areOwnPropsEqual,
areStatePropsEqual = _ref.areStatePropsEqual;
var hasRunAtLeastOnce = false;
var state;
var ownProps;
var stateProps;
var dispatchProps;
var mergedProps;
function handleFirstCall(firstState, firstOwnProps) {
state = firstState;
ownProps = firstOwnProps;
stateProps = mapStateToProps(state, ownProps);
dispatchProps = mapDispatchToProps(dispatch, ownProps);
mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
hasRunAtLeastOnce = true;
return mergedProps;
}
function handleNewPropsAndNewState() {
stateProps = mapStateToProps(state, ownProps);
if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps);
mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
return mergedProps;
}
function handleNewProps() {
if (mapStateToProps.dependsOnOwnProps) stateProps = mapStateToProps(state, ownProps);
if (mapDispatchToProps.dependsOnOwnProps) dispatchProps = mapDispatchToProps(dispatch, ownProps);
mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
return mergedProps;
}
function handleNewState() {
var nextStateProps = mapStateToProps(state, ownProps);
var statePropsChanged = !areStatePropsEqual(nextStateProps, stateProps);
stateProps = nextStateProps;
if (statePropsChanged) mergedProps = mergeProps(stateProps, dispatchProps, ownProps);
return mergedProps;
}
function handleSubsequentCalls(nextState, nextOwnProps) {
var propsChanged = !areOwnPropsEqual(nextOwnProps, ownProps);
var stateChanged = !areStatesEqual(nextState, state);
state = nextState;
ownProps = nextOwnProps;
if (propsChanged && stateChanged) return handleNewPropsAndNewState();
if (propsChanged) return handleNewProps();
if (stateChanged) return handleNewState();
return mergedProps;
}
return function pureFinalPropsSelector(nextState, nextOwnProps) {
return hasRunAtLeastOnce ? handleSubsequentCalls(nextState, nextOwnProps) : handleFirstCall(nextState, nextOwnProps);
};
} // TODO: Add more comments
// If pure is true, the selector returned by selectorFactory will memoize its results,
// allowing connectAdvanced's shouldComponentUpdate to return false if final
// props have not changed. If false, the selector will always return a new
// object and shouldComponentUpdate will always return true.
function finalPropsSelectorFactory(dispatch, _ref2) {
var initMapStateToProps = _ref2.initMapStateToProps,
initMapDispatchToProps = _ref2.initMapDispatchToProps,
initMergeProps = _ref2.initMergeProps,
options = _objectWithoutPropertiesLoose(_ref2, ["initMapStateToProps", "initMapDispatchToProps", "initMergeProps"]);
var mapStateToProps = initMapStateToProps(dispatch, options);
var mapDispatchToProps = initMapDispatchToProps(dispatch, options);
var mergeProps = initMergeProps(dispatch, options);
{
verifySubselectors(mapStateToProps, mapDispatchToProps, mergeProps, options.displayName);
}
var selectorFactory = options.pure ? pureFinalPropsSelectorFactory : impureFinalPropsSelectorFactory;
return selectorFactory(mapStateToProps, mapDispatchToProps, mergeProps, dispatch, options);
}
/*
connect is a facade over connectAdvanced. It turns its args into a compatible
selectorFactory, which has the signature:
(dispatch, options) => (nextState, nextOwnProps) => nextFinalProps
connect passes its args to connectAdvanced as options, which will in turn pass them to
selectorFactory each time a Connect component instance is instantiated or hot reloaded.
selectorFactory returns a final props selector from its mapStateToProps,
mapStateToPropsFactories, mapDispatchToProps, mapDispatchToPropsFactories, mergeProps,
mergePropsFactories, and pure args.
The resulting final props selector is called by the Connect component instance whenever
it receives new props or store state.
*/
function match(arg, factories, name) {
for (var i = factories.length - 1; i >= 0; i--) {
var result = factories[i](arg);
if (result) return result;
}
return function (dispatch, options) {
throw new Error("Invalid value of type " + typeof arg + " for " + name + " argument when connecting component " + options.wrappedComponentName + ".");
};
}
function strictEqual(a, b) {
return a === b;
} // createConnect with default args builds the 'official' connect behavior. Calling it with
// different options opens up some testing and extensibility scenarios
function createConnect(_temp) {
var _ref = _temp === void 0 ? {} : _temp,
_ref$connectHOC = _ref.connectHOC,
connectHOC = _ref$connectHOC === void 0 ? connectAdvanced : _ref$connectHOC,
_ref$mapStateToPropsF = _ref.mapStateToPropsFactories,
mapStateToPropsFactories = _ref$mapStateToPropsF === void 0 ? defaultMapStateToPropsFactories : _ref$mapStateToPropsF,
_ref$mapDispatchToPro = _ref.mapDispatchToPropsFactories,
mapDispatchToPropsFactories = _ref$mapDispatchToPro === void 0 ? defaultMapDispatchToPropsFactories : _ref$mapDispatchToPro,
_ref$mergePropsFactor = _ref.mergePropsFactories,
mergePropsFactories = _ref$mergePropsFactor === void 0 ? defaultMergePropsFactories : _ref$mergePropsFactor,
_ref$selectorFactory = _ref.selectorFactory,
selectorFactory = _ref$selectorFactory === void 0 ? finalPropsSelectorFactory : _ref$selectorFactory;
return function connect(mapStateToProps, mapDispatchToProps, mergeProps, _ref2) {
if (_ref2 === void 0) {
_ref2 = {};
}
var _ref3 = _ref2,
_ref3$pure = _ref3.pure,
pure = _ref3$pure === void 0 ? true : _ref3$pure,
_ref3$areStatesEqual = _ref3.areStatesEqual,
areStatesEqual = _ref3$areStatesEqual === void 0 ? strictEqual : _ref3$areStatesEqual,
_ref3$areOwnPropsEqua = _ref3.areOwnPropsEqual,
areOwnPropsEqual = _ref3$areOwnPropsEqua === void 0 ? shallowEqual : _ref3$areOwnPropsEqua,
_ref3$areStatePropsEq = _ref3.areStatePropsEqual,
areStatePropsEqual = _ref3$areStatePropsEq === void 0 ? shallowEqual : _ref3$areStatePropsEq,
_ref3$areMergedPropsE = _ref3.areMergedPropsEqual,
areMergedPropsEqual = _ref3$areMergedPropsE === void 0 ? shallowEqual : _ref3$areMergedPropsE,
extraOptions = _objectWithoutPropertiesLoose(_ref3, ["pure", "areStatesEqual", "areOwnPropsEqual", "areStatePropsEqual", "areMergedPropsEqual"]);
var initMapStateToProps = match(mapStateToProps, mapStateToPropsFactories, 'mapStateToProps');
var initMapDispatchToProps = match(mapDispatchToProps, mapDispatchToPropsFactories, 'mapDispatchToProps');
var initMergeProps = match(mergeProps, mergePropsFactories, 'mergeProps');
return connectHOC(selectorFactory, _extends({
// used in error messages
methodName: 'connect',
// used to compute Connect's displayName from the wrapped component's displayName.
getDisplayName: function getDisplayName(name) {
return "Connect(" + name + ")";
},
// if mapStateToProps is falsy, the Connect component doesn't subscribe to store state changes
shouldHandleStateChanges: Boolean(mapStateToProps),
// passed through to selectorFactory
initMapStateToProps: initMapStateToProps,
initMapDispatchToProps: initMapDispatchToProps,
initMergeProps: initMergeProps,
pure: pure,
areStatesEqual: areStatesEqual,
areOwnPropsEqual: areOwnPropsEqual,
areStatePropsEqual: areStatePropsEqual,
areMergedPropsEqual: areMergedPropsEqual
}, extraOptions));
};
}
var connect = createConnect();
exports.Provider = Provider;
exports.createProvider = createProvider;
exports.connectAdvanced = connectAdvanced;
exports.connect = connect;
Object.defineProperty(exports, '__esModule', { value: true });
})));
|
search_result['2625']=["topic_0000000000000642.html","BadgesCompanyDto.BranchId Property",""]; |
export const LOGGED_IN = 'LOGGED_IN';
export const loggedIn = () => ({ type: LOGGED_IN });
export const LOGGED_OUT = 'LOGGED_OUT';
export const loggedOut = () => ({ type: LOGGED_OUT });
|
require("./js/src/runner") |
/*!
* jQuery++ - 2.0.2
* http://jquerypp.com
* Copyright (c) 2016 Bitovi
* Wed, 06 Apr 2016 00:03:57 GMT
* Licensed MIT
*/
/*jquerypp@2.0.2#event/drag/core/core*/
define([
'jquery',
'../../../lang/vector/vector.js',
'../../livehack/livehack.js',
'../../reverse/reverse.js'
], function ($) {
if (!$.event.special.move) {
$.event.reverse('move');
}
var bind = function (object, method) {
var args = Array.prototype.slice.call(arguments, 2);
return function () {
var args2 = [this].concat(args, $.makeArray(arguments));
return method.apply(object, args2);
};
}, event = $.event, clearSelection = window.getSelection ? function () {
window.getSelection().removeAllRanges();
} : function () {
}, supportTouch = !window._phantom && 'ontouchend' in document, startEvent = supportTouch ? 'touchstart' : 'mousedown', stopEvent = supportTouch ? 'touchend' : 'mouseup', moveEvent = supportTouch ? 'touchmove' : 'mousemove', preventTouchScroll = function (ev) {
ev.preventDefault();
};
$.Drag = function () {
};
$.extend($.Drag, {
lowerName: 'drag',
current: null,
distance: 0,
mousedown: function (ev, element) {
var isLeftButton = ev.button === 0 || ev.button == 1, doEvent = isLeftButton || supportTouch;
if (!doEvent || this.current) {
return;
}
var drag = new $.Drag(), delegate = ev.delegateTarget || element, selector = ev.handleObj.selector, self = this;
this.current = drag;
drag.setup({
element: element,
delegate: ev.delegateTarget || element,
selector: ev.handleObj.selector,
moved: false,
_distance: this.distance,
callbacks: {
dragdown: event.find(delegate, ['dragdown'], selector),
draginit: event.find(delegate, ['draginit'], selector),
dragover: event.find(delegate, ['dragover'], selector),
dragmove: event.find(delegate, ['dragmove'], selector),
dragout: event.find(delegate, ['dragout'], selector),
dragend: event.find(delegate, ['dragend'], selector),
dragcleanup: event.find(delegate, ['dragcleanup'], selector)
},
destroyed: function () {
self.current = null;
}
}, ev);
}
});
$.extend($.Drag.prototype, {
setup: function (options, ev) {
$.extend(this, options);
this.element = $(this.element);
this.event = ev;
this.moved = false;
this.allowOtherDrags = false;
var mousemove = bind(this, this.mousemove), mouseup = bind(this, this.mouseup);
this._mousemove = mousemove;
this._mouseup = mouseup;
this._distance = options.distance ? options.distance : 0;
this.mouseStartPosition = ev.vector();
$(document).bind(moveEvent, mousemove);
$(document).bind(stopEvent, mouseup);
if (supportTouch) {
$(document).bind(moveEvent, preventTouchScroll);
}
if (!this.callEvents('down', this.element, ev)) {
this.noSelection(this.delegate);
clearSelection();
}
},
destroy: function () {
$(document).unbind(moveEvent, this._mousemove);
$(document).unbind(stopEvent, this._mouseup);
if (supportTouch) {
$(document).unbind(moveEvent, preventTouchScroll);
}
if (!this.moved) {
this.event = this.element = null;
}
if (!supportTouch) {
this.selection(this.delegate);
}
this.destroyed();
},
mousemove: function (docEl, ev) {
if (!this.moved) {
var dist = Math.sqrt(Math.pow(ev.pageX - this.event.pageX, 2) + Math.pow(ev.pageY - this.event.pageY, 2));
if (dist < this._distance) {
return false;
}
this.init(this.element, ev);
this.moved = true;
}
this.element.trigger('move', this);
var pointer = ev.vector();
if (this._start_position && this._start_position.equal(pointer)) {
return;
}
this.draw(pointer, ev);
},
mouseup: function (docEl, event) {
if (this.moved) {
this.end(event);
}
this.destroy();
},
noSelection: function (elm) {
elm = elm || this.delegate;
document.documentElement.onselectstart = function () {
return false;
};
document.documentElement.unselectable = 'on';
this.selectionDisabled = this.selectionDisabled ? this.selectionDisabled.add(elm) : $(elm);
this.selectionDisabled.css('-moz-user-select', '-moz-none');
},
selection: function () {
if (this.selectionDisabled) {
document.documentElement.onselectstart = function () {
};
document.documentElement.unselectable = 'off';
this.selectionDisabled.css('-moz-user-select', '');
}
},
init: function (element, event) {
element = $(element);
var startElement = this.movingElement = this.element = $(element);
this._cancelled = false;
this.event = event;
this.mouseElementPosition = this.mouseStartPosition.minus(this.element.offsetv());
this.callEvents('init', element, event);
if (this._cancelled === true) {
return;
}
this.startPosition = startElement != this.movingElement ? this.movingElement.offsetv() : this.currentDelta();
this.makePositioned(this.movingElement);
this.oldZIndex = this.movingElement.css('zIndex');
this.movingElement.css('zIndex', 1000);
if (!this._only && this.constructor.responder) {
this.constructor.responder.compile(event, this);
}
},
makePositioned: function (that) {
var style, pos = that.css('position');
if (!pos || pos == 'static') {
style = { position: 'relative' };
if (window.opera) {
style.top = '0px';
style.left = '0px';
}
that.css(style);
}
},
callEvents: function (type, element, event, drop) {
var i, cbs = this.callbacks[this.constructor.lowerName + type];
for (i = 0; i < cbs.length; i++) {
cbs[i].call(element, event, this, drop);
}
return cbs.length;
},
currentDelta: function () {
return new $.Vector(parseInt(this.movingElement.css('left'), 10) || 0, parseInt(this.movingElement.css('top'), 10) || 0);
},
draw: function (pointer, event) {
if (this._cancelled) {
return;
}
clearSelection();
this.location = pointer.minus(this.mouseElementPosition);
this.move(event);
if (this._cancelled) {
return;
}
if (!event.isDefaultPrevented()) {
this.position(this.location);
}
if (!this._only && this.constructor.responder) {
this.constructor.responder.show(pointer, this, event);
}
},
position: function (newOffsetv) {
var style, dragged_element_css_offset = this.currentDelta(), dragged_element_position_vector = this.movingElement.offsetv().minus(dragged_element_css_offset);
this.required_css_position = newOffsetv.minus(dragged_element_position_vector);
this.offsetv = newOffsetv;
style = this.movingElement[0].style;
if (!this._cancelled && !this._horizontal) {
style.top = this.required_css_position.top() + 'px';
}
if (!this._cancelled && !this._vertical) {
style.left = this.required_css_position.left() + 'px';
}
},
move: function (event) {
this.callEvents('move', this.element, event);
},
over: function (event, drop) {
this.callEvents('over', this.element, event, drop);
},
out: function (event, drop) {
this.callEvents('out', this.element, event, drop);
},
end: function (event) {
if (this._cancelled) {
return;
}
if (!this._only && this.constructor.responder) {
this.constructor.responder.end(event, this);
}
this.callEvents('end', this.element, event);
if (this._revert) {
var self = this;
this.movingElement.animate({
top: this.startPosition.top() + 'px',
left: this.startPosition.left() + 'px'
}, function () {
self.cleanup.apply(self, arguments);
});
} else {
this.cleanup(event);
}
this.event = null;
},
cleanup: function (event) {
this.movingElement.css({ zIndex: this.oldZIndex });
if (this.movingElement[0] !== this.element[0] && !this.movingElement.has(this.element[0]).length && !this.element.has(this.movingElement[0]).length) {
this.movingElement.css({ display: 'none' });
}
if (this._removeMovingElement) {
this.movingElement.remove();
}
if (event) {
this.callEvents('cleanup', this.element, event);
}
this.movingElement = this.element = this.event = null;
},
cancel: function () {
this._cancelled = true;
if (!this._only && this.constructor.responder) {
this.constructor.responder.clear(this.event.vector(), this, this.event);
}
this.destroy();
},
ghost: function (parent) {
var ghost = this.movingElement.clone().css('position', 'absolute');
if (parent) {
$(parent).append(ghost);
} else {
$(this.movingElement).after(ghost);
}
ghost.width(this.movingElement.width()).height(this.movingElement.height());
ghost.offset(this.movingElement.offset());
this.movingElement = ghost;
this.noSelection(ghost);
this._removeMovingElement = true;
return ghost;
},
representative: function (element, offsetX, offsetY) {
this._offsetX = offsetX || 0;
this._offsetY = offsetY || 0;
var p = this.mouseStartPosition;
this.movingElement = $(element);
this.movingElement.css({
top: p.y() - this._offsetY + 'px',
left: p.x() - this._offsetX + 'px',
display: 'block',
position: 'absolute'
}).show();
this.noSelection(this.movingElement);
this.mouseElementPosition = new $.Vector(this._offsetX, this._offsetY);
return this;
},
revert: function (val) {
this._revert = val === undefined ? true : val;
return this;
},
vertical: function () {
this._vertical = true;
return this;
},
horizontal: function () {
this._horizontal = true;
return this;
},
only: function (only) {
return this._only = only === undefined ? true : only;
},
distance: function (val) {
if (val !== undefined) {
this._distance = val;
return this;
} else {
return this._distance;
}
}
});
event.setupHelper([
'dragdown',
'draginit',
'dragover',
'dragmove',
'dragout',
'dragend',
'dragcleanup'
], startEvent, function (e) {
$.Drag.mousedown.call($.Drag, e, this);
});
return $;
}); |
// Generated by CoffeeScript 1.8.0
(function() {
var $;
$ = jQuery;
$(function() {
return $('body').prepend("<div class=\"modal-dialog-overlay\">\n <div class=\"dialog-content-wrapper\">\n </div>\n</div>");
});
$.fn.modalDialog = function(options) {
var $modalOverlay, defaults, hideDialog, showDialog;
$modalOverlay = $('div.modal-dialog-overlay');
defaults = {
type: 'facebook'
};
options = $.extend(defaults, options);
this.each(function() {
return $(this).on('click', function() {
return showDialog();
});
});
showDialog = function() {
alert(options.type);
$modalOverlay.children().addClass("" + options.type + "-dialog");
return $modalOverlay.show();
};
hideDialog = function() {
return $modalOverlay.hide();
};
return $modalOverlay.on('click', function() {
return hideDialog();
});
};
}).call(this);
|
describe('createDynamicNameFnSpec', function () {
afterEach(function () {
ot.globalObj = window;
});
describe('isCspOn', function () {
it('should return false if the security policy is not active', function () {
ot.globalObj = {document: {securityPolicy: {isActive: false}}};
expect(isCspOn()).toBe(false);
});
it('should return true if the security policy is active', function () {
ot.globalObj = {document: {securityPolicy: {isActive: true}}};
expect(isCspOn()).toBe(true);
});
});
describe('csp: off', function () {
beforeEach(function () {
ot.globalObj = {document: {securityPolicy: {isActive: false}}};
});
it('should return a named function', function () {
var fn = createDynamicNameFn('namedFn', {asFunction: ot.noop, asConstructor: ot.noop});
expect(fn.name).toBe('namedFn');
expect(typeof fn).toBe('function');
});
it('should accept callbacks for when the function is invoked or instantiated', function () {
var context = {},
callbacks = {
asFunction: jasmine.createSpy('asFunction'),
asConstructor: jasmine.createSpy('asConstructor')
};
var fn = createDynamicNameFn('namedFn', callbacks);
fn.call(context, 'param1', 'param2');
expect(callbacks.asFunction.calls.first()).toEqual({object: context, args: ['param1', 'param2']});
context = new fn('param3', 'param4');
expect(callbacks.asConstructor.calls.first()).toEqual({object: context, args: ['param3', 'param4']});
expect(callbacks.asFunction.calls.count()).toBe(1);
expect(callbacks.asConstructor.calls.count()).toBe(1);
});
});
describe('csp: on', function () {
beforeEach(function () {
ot.globalObj = {document: {securityPolicy: {isActive: true}}};
});
it('should return an anonymous function', function () {
var fn = createDynamicNameFn('namedFn', {asFunction: ot.noop, asConstructor: ot.noop});
expect(fn.name).toBe('');
expect(typeof fn).toBe('function');
});
it('should accept callbacks for when the function is invoked or instantiated', function () {
var context = {},
callbacks = {
asFunction: jasmine.createSpy('asFunction'),
asConstructor: jasmine.createSpy('asConstructor')
};
var fn = createDynamicNameFn('namedFn', callbacks);
fn.call(context, 'param1', 'param2');
expect(callbacks.asFunction.calls.first()).toEqual({object: context, args: ['param1', 'param2']});
context = new fn('param3', 'param4');
expect(callbacks.asConstructor.calls.first()).toEqual({object: context, args: ['param3', 'param4']});
expect(callbacks.asFunction.calls.count()).toBe(1);
expect(callbacks.asConstructor.calls.count()).toBe(1);
});
});
}); |
// Log HTTP Requests in console. Formats: https://github.com/expressjs/morgan
module.exports = require('morgan')('dev');
|
'use strict';
import * as userSeed from '../../../server/models/users.server.model.user.seed';
import userModel from '../../../server/models/users.server.model.user';
import mongooseModule from '../../../../core/server/app/mongoose';
import aclModule from '../../../server/config/acl';
let sandbox;
describe('/modules/users/server/models/users.server.model.user.seed.js', () => {
before(() => {
return mongooseModule.connect()
.then(Promise.all([aclModule.init(), userModel.init()]));
});
after(() => {
return mongooseModule.disconnect();
});
beforeEach(() => {
return sandbox = sinon.sandbox.create();
});
afterEach(() => {
return sandbox.restore();
});
describe('export', () => {
it('should export default', () => {
return userSeed.default.should.be.an('object');
});
it('should export init', () => {
return userSeed.init.should.be.a('function');
});
describe('init()', () => {
describe('success', () => {
it('should fulfill a promise', () => {
return userSeed.init().should.be.fulfilled;
});
it('should resolve an object with user and admin', () => {
return userSeed.init().then(users => {
users.user.should.be.an('object');
return users.admin.should.be.an('object');
});
});
});
});
it('should export getUsers', () => {
return userSeed.getUsers.should.be.a('function');
});
it('should export seedUser', () => {
return userSeed.seedUser.should.be.a('function');
});
describe('seedUser', () => {
describe('success', () => {
it('should fulfill a promise', () => {
return userSeed.seedUser().should.be.fulfilled;
});
it('should promise should resolve user object', () => {
return userSeed.seedUser().then(user => {
user.name.should.be.an('object');
return user.providers.length.should.equal(1);
});
});
it('should set the user on the model export', () => {
return userSeed.seedUser().then(user => {
return userSeed.getUsers().user.should.exist;
});
});
it('should resolve a promise if user does not currently exist', () => {
return userSeed.removeUser()
.then(() => {
return userSeed.seedUser().should.be.fulfilled;
});
});
});
});
it('should export seedAdmin', () => {
return userSeed.seedAdmin.should.be.a('function');
});
describe('seedAdmin', () => {
describe('success', () => {
it('should fulfill a promise', () => {
return userSeed.seedAdmin().should.be.fulfilled;
});
it('should promise should resolve user object', () => {
return userSeed.seedAdmin().then(user => {
user.name.should.be.an('object');
return user.providers.length.should.equal(1);
});
});
it('should set the user on the model export', () => {
return userSeed.seedAdmin().then(user => {
return userSeed.getUsers().admin.should.exist;
});
});
it('should resolve a promise if user does not currently exist', () => {
return userSeed.removeAdmin()
.then(() => {
return userSeed.seedAdmin().should.be.fulfilled;
});
});
});
});
it('should export removeUser', () => {
return userSeed.removeUser.should.be.a('function');
});
describe('removeUser', () => {
it('should remove the user from export', () => {
return userSeed.removeUser()
.then(() => {
return expect(userSeed.getUsers().user).to.not.exist;
});
});
});
it('should export removeAdmin', () => {
return userSeed.removeAdmin.should.be.a('function');
});
describe('removeAdmin', () => {
it('should remove the admin from export', () => {
return userSeed.removeAdmin()
.then(() => {
return expect(userSeed.getUsers().admin).to.not.exist;
});
});
});
});
});
|
import { B as Behavior, d as deepQueryAll, R as ROOT } from './index-a5c9c958.js';
const history = window.history;
const _wr = function (type) {
return function () {
const rv = History.prototype[type].apply(history, arguments);
const e = new Event(type.toLowerCase());
window.dispatchEvent(e);
return rv;
};
};
history.pushState = _wr('pushState');
history.replaceState = _wr('replaceState');
let timerId;
function handleHashLinks() {
const links = deepQueryAll(ROOT, '[is-current-spy] > a[href^="#"]');
const arr = [];
links.forEach(link => {
const id = link.getAttribute('href').slice(1);
const target = link.parentNode.nuQueryById(id);
if (!target) return;
const rect = target.getBoundingClientRect();
const offset = rect.y;
if (target) {
arr.push({
link,
id,
target,
offset,
parent: link.parentNode,
});
}
});
if (!arr.length) return;
arr.sort((a, b) => b.offset - a.offset);
let map = arr.find(map => map.offset <= 1);
if (map) {
map.parent.nuSetMod('current', true);
}
arr.forEach(mp => {
if (mp !== map) {
mp.parent.nuSetMod('current', false);
}
});
}
function isCurrent(href) {
if (href == null) return false;
let locHref = location.href.replace(location.hash, '');
locHref = locHref.replace(/\/$/, '');
href = href.replace(/\/$/, '');
return href === locHref;
}
function handleLinkState(link) {
const href = link.href;
link.parentNode && link.parentNode.nuSetMod && link.parentNode.nuSetMod('current', isCurrent(href));
}
function handleLinksState(force = false) {
if (timerId && !force) return;
if (force) {
clearTimeout(timerId);
}
timerId = setTimeout(() => {
timerId = null;
const otherLinks = deepQueryAll(ROOT, '[is-current-spy] > a:not([href^="#"])');
handleHashLinks();
otherLinks.forEach(handleLinkState);
}, force ? 0 : 100);
}
['popstate', 'pushstate', 'replacestate'].forEach(eventName => {
window.addEventListener(eventName, () => {
requestAnimationFrame(handleLinksState);
setTimeout(handleLinksState, 250);
}, { passive: true });
});
['scroll', 'hashchange'].forEach((eventName) => {
window.addEventListener(eventName, handleHashLinks, { passive: true });
});
setTimeout(handleLinksState, 50);
class CurrentBehavior extends Behavior {
connected() {
this.setMod('current-spy', true);
this.on('tap', () => {
this.setMod('current', true);
});
}
disconnected() {
this.setMod('current-spy', false);
}
}
export default CurrentBehavior;
export { handleLinkState, handleLinksState };
|
/**
* Created by dcordova on 8/16/17.
*/
const NOCK = require('nock');
const CONFIG = require('../config/mochaConfig');
const nock = {
clean : NOCK.cleanAll,
nock : function( _url ) {
if( CONFIG.getIsMock() ){
return NOCK( _url );
}
}
};
module.exports = nock;
|
//GET /quizes/question
/*exports.question = function(req,res){
res.render('quizes/question',{pregunta:'Capital de Italia'});
};
//GET /quizes/answer
exports.answer = function(req,res){
if (req.query.respuesta ==='Roma'){
res.render('quizes/answer',{respuesta:'Correcto.'});
} else {
res.render('quizes/answer',{respuesta:'Incorrecto.'});
}
};*/
var models = require('../models/models.js');
/*exports.question = function(req,res){
models.Quiz.findAll().success(function(quiz){
res.render('quizes/question',{pregunta:quiz[0].pregunta});
})
};
//GET /quizes/answer
exports.answer = function(req,res){
models.Quiz.findAll().success(function(quiz){
if (req.query.respuesta ===quiz[0].respuesta){
res.render('quizes/answer',{respuesta:'Correcto.'});
} else {
res.render('quizes/answer',{respuesta:'Incorrecto.'});
}
})
};*/
//autoload - factoriza el código si ruta incluye :quizId
exports.load = function(req,res,next,quizId){
models.Quiz.find({
where: { id: Number(quizId)},
include: [{model: models.Comment }]
}).then(function(quiz){
if (quiz) {
req.quiz = quiz;
next();
} else {
next(new Error('No existe quizId='+quizId));
}
}).catch(function(error) { next(error);});
};
//GET /quizes
exports.index = function(req,res){
var busqueda= null;
if (req.query.search){
busqueda = ('%'+req.query.search+'%').replace(/ /g,'%');
models.Quiz.findAll({where:["pregunta like ?",busqueda],order:'pregunta ASC'}).then(function(quizes){
res.render('quizes/index',{quizes: quizes, errors: []});
})
} else {
models.Quiz.findAll().then(function(quizes){
res.render('quizes/index',{quizes: quizes, errors: []});
})
}
};
exports.show = function(req,res){
models.Quiz.find(req.params.quizId).then(function(quiz){
res.render('quizes/show',{quiz: req.quiz, errors: []});
})
};
//GET /quizes/answer
exports.answer = function(req,res){
models.Quiz.find(req.params.quizId).then(function(quiz){
if (req.query.respuesta ===req.quiz.respuesta){
res.render('quizes/answer',{quiz: req.quiz, respuesta:'Correcto.', errors: []});
} else {
res.render('quizes/answer',{quiz: req.quiz, respuesta:'Incorrecto.', errors: []});
}
})
};
//GET /quizes/new
exports.new = function(req,res){
var quiz = models.Quiz.build(
{pregunta:"", respuesta: "", tema:""}
);
res.render('quizes/new',{quiz:quiz, errors: []});
};
//POST /quizes/create
exports.create = function(req,res){
var quiz = models.Quiz.build(req.body.quiz);
quiz
.validate()
.then(
function(err){
if(err) {
res.render('quizes/new', {quiz: quiz, errors: err.errors});
} else {
quiz
.save({fields: ["pregunta","respuesta","tema"]})
.then(function(){res.redirect('/quizes')})
}
}
);
};
//GET: quizes/:id/edit
exports.edit = function(req,res) {
var quiz = req.quiz;
res.render('quizes/edit',{quiz:quiz,errors:[]});
};
//PUT: /quizes/:id
exports.update = function(req,res) {
req.quiz.pregunta = req.body.quiz.pregunta;
req.quiz.respuesta = req.body.quiz.respuesta;
req.quiz.tema = req.body.quiz.tema;
req.quiz
.validate()
.then(
function(err) {
if (err) {
res.render('quizes/edit', {quiz:req.quiz, errors:err.errors});
} else {
req.quiz
.save({fields:["pregunta","respuesta","tema"]})
.then( function(){res.redirect('/quizes');});
}
}
);
};
//DELETE /quizes/:id
exports.destroy = function(req,res) {
req.quiz.destroy().then(function() {
res.redirect('/quizes');
}).catch(function(error){next(error)});
}; |
// <script type="text/javascript" src="/public/re1/elements.js"></script>
// <script type="text/javascript">
function callBackFunc(param) {
var sig = document.getElementById("actualResult");
sig.innerHTML = "Param: "+ param;
}
(function(){
var pbTest = function(){
var pbTestObj = {};
pbTestObj.testCases = [
{
"VTID":"VT187-2805",
"RegLevel":"R1",
"Description":"Memory <br/> lowMemThreshold with 5000 KB",
"PreCondition":[],
"Steps":["Attach memoryEvent","call getMemoryStats to check the available memory","set lowMemThreshold to 5000 KB (can be set as per available meory)","wait for event to fire"],
"ExpectedOutcome":["memoryEvent should fire after available Memory drops below the 50000 KB","event should fire once if drops below 5000 KB, further drops event will not fire"],
"testToPerform":function(){
memory.memoryEvent="memoryEventjsFunction('%s','%s');";
memory.getMemoryStats();
memory.lowMemThreshold = '215';
sig.innerHTML = "Memory Value is " ;
},
"FinalResult":""
},{
"VTID":"VT187-2807",
"RegLevel":"R1",
"Description":"Memory <br/> memoryEvent return values",
"PreCondition":[],
"Steps":["Attach memoryEvent","call method getMemoryStatus","check for the return memory values"],
"ExpectedOutcome":["memoryEvent should fire and return the available memory and totalMemory of the device"],
"testToPerform":function(){
memory.memoryEvent="memoryEventjsFunction('%s','%s');";
memory.getMemoryStats();
},
"FinalResult":""
},{
"VTID":"VT187-2810",
"RegLevel":"R1",
"Description":"Memory <br/> memoryEvent with JSON",
"PreCondition":[],
"Steps":["Attach memoryEvent with JSON Implementation","call method getMemoryStatus","check for the return memory values"],
"ExpectedOutcome":["memoryEvent should fire and return the available memory and totalMemory of the device"],
"testToPerform":function(){
memory.memoryEvent="memoryEventjsonFunction(%json);";
memory.getMemoryStats();
},
"FinalResult":""
}];
pbTestObj.afterEach = function(){
}
return pbTestObj;
}
window.pbTest = pbTest();
})();
function memoryEventjsFunction(totalMemory,availMemory)
{
var theOutput = "<BR><BR><B>memoryEvent </B>" + "<BR>";
var sig = document.getElementById("actualResult");
theOutput = theOutput + "totalMemory(KB): "+totalMemory + "<BR>";
theOutput = theOutput + "availMemory(KB): " + availMemory + "<BR>";
sig.innerHTML = theOutput;
}
function memoryEventjsonFunction(jsonObject)
{
var theOutput = "<BR><BR><B>memoryEvent </B>" + "<BR>";
var sig = document.getElementById("actualResult");
theOutput = theOutput + "totalMemory(KB): "+jsonObject.totalMemory + "<BR>";
theOutput = theOutput + "availMemory(KB): " + jsonObject.availMemory + "<BR>";
sig.innerHTML = theOutput;
}
|
module.exports = ''; |
'use strict';
const AggregationFunction = require('./AggregationFunction');
const ImplementationRequired = require('./error/ImplementationRequired');
class AggregationFunctionAsync extends AggregationFunction
{
/**
* Run once per each row
* @param {Array} args
* @returns {undefined}
*/
updateAsync(args)
{
throw new ImplementationRequired;
}
/**
* Get current result. Can be call multiple times per group
* @param {Function} cb
* @returns {any}
*/
result(cb)
{
throw new ImplementationRequired;
}
}
module.exports = AggregationFunctionAsync;
|
var express = require('express');
var server = express();
server.use('/', express.static(__dirname + '/public'));
//Quitar el # de angular
server.get('/*', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
server.get('/callback-token', function(req, res) {
res.send(req.query);
});
server.listen(8081, function() {
console.log('Example app listening on port 8081!');
});
|
import { GraphQLSchema } from 'meteor/vulcan:core';
const reportResolvers = {
Post: {
reporters(post, args, context) {
return post.reporters ? context.Users.find({_id: {$in: post.reporters}}, { fields: context.getViewableFields(context.currentUser, context.Users) }).fetch() : [];
},
},
Comment: {
reporters(comment, args, context) {
return comment.reporters ? context.Users.find({_id: {$in: comment.reporters}}, { fields: context.getViewableFields(context.currentUser, context.Users) }).fetch() : [];
},
},
};
GraphQLSchema.addResolvers(reportResolvers);
|
( function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
global.CalendarHelper = module.require( "./calendar-helper" );
exports[ "SimpleDateFormat" ] = module.exports = factory( global );
} else {
factory( global );
}
} )( this, function( global ) {
var CalendarHelper = global.CalendarHelper;
function SimpleDateFormat() {
DateFormat.call( this );
var _date;
var _numberFormat;
var _pattern;
var _originalNumberFormat;
var _originalNumberPattern;
var _minusSign = "-";
var _hasFollowingMinusSign = false;
var _compiledPattern;
var _zeroDigit;
var _formatData;
var _defaultCenturyStart;
var _defaultCenturyStartYear;
var _locale;
var _useDateFormatSymbols = false;
var _initialize = function( loc ) {
// Verify and compile the given pattern.
_compiledPattern = _compile( _pattern );
_numberFormat = NumberFormat.getIntegerInstance( loc );
_numberFormat.setGroupingUsed( false );
_initializeDefaultCentury();
};
var _initializeCalendar = function( loc ) {
_date = new Date();
CalendarHelper.setCalendarData( loc );
};
var _initializeDefaultCentury = function() {
var date = new Date();
date.setFullYear( date.getFullYear() - 80 );
_parseAmbiguousDatesAsAfter( date );
};
var _parseAmbiguousDatesAsAfter = function( startDate ) {
_defaultCenturyStart = startDate;
_date = new Date( startDate.getTime() );
_defaultCenturyStartYear = _date.getFullYear();
};
var _compile = function( pattern ) {
var length = pattern.length;
var inQuote = false;
var compiledPattern = "";
var tmpBuffer = null;
var count = 0;
var lastTag = -1;
for ( var i = 0; i < length; i++ ) {
var c = pattern.charAt( i );
if ( c == '\'' ) {
// '' is treated as a single quote regardless of being
// in a quoted section.
if ( ( i + 1 ) < length ) {
c = pattern.charAt( i + 1 );
if ( c == '\'' ) {
i++;
if (count != 0) {
compiledPattern = _encode( lastTag, count, compiledPattern );
lastTag = -1;
count = 0;
}
if ( inQuote ) {
tmpBuffer += c;
} else {
compiledPattern += String.fromCharCode( _TAG_QUOTE_ASCII_CHAR << 8 | c.charCodeAt( 0 ) );
}
continue;
}
}
if ( !inQuote ) {
if ( count != 0 ) {
compiledPattern = _encode( lastTag, count, compiledPattern );
lastTag = -1;
count = 0;
}
tmpBuffer = "";
inQuote = true;
} else {
var len = tmpBuffer.length;
if ( len == 1 ) {
var ch = tmpBuffer.charAt( 0 );
if ( ch < 128 ) {
compiledPattern += String.fromCharCode( _TAG_QUOTE_ASCII_CHAR << 8 | ch.charCodeAt( 0 ) );
} else {
compiledPattern += String.fromCharCode( _TAG_QUOTE_CHARS << 8 | 1 );
compiledPattern += ch;
}
} else {
compiledPattern = _encode( _TAG_QUOTE_CHARS, len, compiledPattern );
compiledPattern += tmpBuffer;
}
inQuote = false;
}
continue;
}
if ( inQuote ) {
tmpBuffer += c;
continue;
}
if ( !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') ) {
if ( count != 0 ) {
compiledPattern = _encode( lastTag, count, compiledPattern );
lastTag = -1;
count = 0;
}
if ( c < 128 ) {
// In most cases, c would be a delimiter, such as ':'.
compiledPattern += String.fromCharCode( _TAG_QUOTE_ASCII_CHAR << 8 | c.charCodeAt( 0 ) );
} else {
// Take any contiguous non-ASCII alphabet characters and
// put them in a single TAG_QUOTE_CHARS.
var j;
for ( j = i + 1; j < length; j++ ) {
var d = pattern.charAt(j);
if ( d == '\'' || ( d >= 'a' && d <= 'z' || d >= 'A' && d <= 'Z' ) ) {
break;
}
}
compiledPattern += String.fromCharCode(_TAG_QUOTE_CHARS << 8 | ( j - i ) );
for ( ; i < j; i++ ) {
compiledPattern += pattern.charAt( i );
}
i--;
}
continue;
}
var tag;
if ( ( tag = DateFormatSymbols.patternChars.indexOf( c ) ) == -1 ) {
throw "Illegal pattern character " +
"'" + c + "'";
}
if ( lastTag == -1 || lastTag == tag ) {
lastTag = tag;
count++;
continue;
}
compiledPattern = _encode( lastTag, count, compiledPattern );
lastTag = tag;
count = 1;
}
if ( inQuote ) {
throw "Unterminated quote";
}
if ( count != 0 ) {
compiledPattern = _encode( lastTag, count, compiledPattern );
}
// Copy the compiled pattern to a char array
return compiledPattern.split( "" );
};
var _subFormat = function( patternCharIndex, count, delegate, buffer, useDateFormatSymbols ) {
var maxIntCount = 0x7fffffff;
var current = null;
var beginOffset = buffer.length;
var field = _PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
var value;
if (field == 17) {
value = CalendarHelper.getWeekYear( _date );
/*patternCharIndex = DateFormatSymbols.PATTERN_YEAR;
field = _PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
value = CalendarHelper.getField( _date, field );*/
} else if (field == 1000) {
value = CalendarHelper.toISODayOfWeek(CalendarHelper.getField( _date, 7 ));
} else {
value = CalendarHelper.getField( _date, field );
}
/*var style = (count >= 4) ? 2 : 1;
if (!useDateFormatSymbols && field != 1000) {
current = calendar.getDisplayName(field, style, locale);
}*/
// Note: zeroPaddingNumber() assumes that maxDigits is either
// 2 or maxIntCount. If we make any changes to this,
// zeroPaddingNumber() must be fixed.
switch (patternCharIndex) {
case DateFormatSymbols.PATTERN_ERA: // 'G'
if (useDateFormatSymbols) {
var eras = _formatData.getEras();
if (value < eras.length)
current = eras[value];
}
if (current == null)
current = "";
break;
case DateFormatSymbols.PATTERN_WEEK_YEAR: // 'Y'
case DateFormatSymbols.PATTERN_YEAR: // 'y'
if (count != 2)
buffer = _zeroPaddingNumber(value, count, maxIntCount, buffer);
else // count == 2
buffer = _zeroPaddingNumber(value, 2, 2, buffer); // clip 1996 to 96
break;
case DateFormatSymbols.PATTERN_MONTH: // 'M'
if (useDateFormatSymbols) {
var months;
if (count >= 4) {
months = _formatData.getMonths();
current = months[value];
} else if (count == 3) {
months = _formatData.getShortMonths();
current = months[value];
}
} else {
if (count < 3) {
current = null;
}
}
if (current == null) {
buffer = _zeroPaddingNumber(value+1, count, maxIntCount, buffer);
}
break;
case DateFormatSymbols.PATTERN_HOUR_OF_DAY1: // 'k' 1-based. eg, 23:59 + 1 hour =>> 24:59
if (current == null) {
if (value == 0)
buffer = _zeroPaddingNumber(CalendarHelper.getField( _date, 11 ) + 24,
count, maxIntCount, buffer);
else
buffer = _zeroPaddingNumber(value, count, maxIntCount, buffer);
}
break;
case DateFormatSymbols.PATTERN_DAY_OF_WEEK: // 'E'
if (useDateFormatSymbols) {
var weekdays;
if (count >= 4) {
weekdays = _formatData.getWeekdays();
current = weekdays[value];
} else { // count < 4, use abbreviated form if exists
weekdays = _formatData.getShortWeekdays();
current = weekdays[value];
}
}
break;
case DateFormatSymbols.PATTERN_AM_PM: // 'a'
if (useDateFormatSymbols) {
var ampm = _formatData.getAmPmStrings();
current = ampm[value];
}
break;
case DateFormatSymbols.PATTERN_HOUR1: // 'h' 1-based. eg, 11PM + 1 hour =>> 12 AM
if (current == null) {
if (value == 0)
buffer = _zeroPaddingNumber(CalendarHelper.getField( _date, 10 ) + 12,
count, maxIntCount, buffer);
else
buffer = _zeroPaddingNumber(value, count, maxIntCount, buffer);
}
break;
// TODO: Use time zones
/*case DateFormatSymbols.PATTERN_ZONE_NAME: // 'z'
if (current == null) {
if (formatData.locale == null || formatData.isZoneStringsSet) {
int zoneIndex =
formatData.getZoneIndex(calendar.getTimeZone().getID());
if (zoneIndex == -1) {
value = calendar.get(Calendar.ZONE_OFFSET) +
calendar.get(Calendar.DST_OFFSET);
buffer.append(ZoneInfoFile.toCustomID(value));
} else {
int index = (calendar.get(Calendar.DST_OFFSET) == 0) ? 1: 3;
if (count < 4) {
// Use the short name
index++;
}
String[][] zoneStrings = formatData.getZoneStringsWrapper();
buffer.append(zoneStrings[zoneIndex][index]);
}
} else {
TimeZone tz = calendar.getTimeZone();
boolean daylight = (calendar.get(Calendar.DST_OFFSET) != 0);
int tzstyle = (count < 4 ? TimeZone.SHORT : TimeZone.LONG);
buffer.append(tz.getDisplayName(daylight, tzstyle, formatData.locale));
}
}
break;*/
case DateFormatSymbols.PATTERN_ZONE_VALUE: // 'Z' ("-/+hhmm" form)
value = -CalendarHelper.getField( _date, 15 );
var width = 4;
if (value >= 0) {
buffer += '+';
} else {
width++;
}
var num = (value / 60) * 100 + (value % 60);
buffer = CalendarHelper.sprintf0d(buffer, num, width);
break;
case DateFormatSymbols.PATTERN_ISO_ZONE: // 'X'
value = -CalendarHelper.getField( _date, 15 );
if (value == 0) {
buffer += 'Z';
break;
}
// value /= 60000;
if (value >= 0) {
buffer += '+';
} else {
buffer += '-';
value = -value;
}
buffer = CalendarHelper.sprintf0d(buffer, value / 60, 2);
if (count == 1) {
break;
}
if (count == 3) {
buffer += ':';
}
buffer = CalendarHelper.sprintf0d(buffer, value % 60, 2);
break;
default:
// case PATTERN_DAY_OF_MONTH: // 'd'
// case PATTERN_HOUR_OF_DAY0: // 'H' 0-based. eg, 23:59 + 1 hour =>> 00:59
// case PATTERN_MINUTE: // 'm'
// case PATTERN_SECOND: // 's'
// case PATTERN_MILLISECOND: // 'S'
// case PATTERN_DAY_OF_YEAR: // 'D'
// case PATTERN_DAY_OF_WEEK_IN_MONTH: // 'F'
// case PATTERN_WEEK_OF_YEAR: // 'w'
// case PATTERN_WEEK_OF_MONTH: // 'W'
// case PATTERN_HOUR0: // 'K' eg, 11PM + 1 hour =>> 0 AM
// case PATTERN_ISO_DAY_OF_WEEK: // 'u' pseudo field, Monday = 1, ..., Sunday = 7
if (current == null) {
buffer = _zeroPaddingNumber(value, count, maxIntCount, buffer);
}
break;
} // switch (patternCharIndex)
if (current != null) {
buffer += current;
}
var fieldID = _PATTERN_INDEX_TO_DATE_FORMAT_FIELD[patternCharIndex];
var f = _PATTERN_INDEX_TO_DATE_FORMAT_FIELD_ID[patternCharIndex];
delegate.formatted(fieldID, f, f, beginOffset, buffer.length, buffer);
return buffer;
};
var _zeroPaddingNumber = function( value, minDigits, maxDigits, buffer ) {
// Optimization for 1, 2 and 4 digit numbers. This should
// cover most cases of formatting date/time related items.
// Note: This optimization code assumes that maxDigits is
// either 2 or Integer.MAX_VALUE (maxIntCount in format()).
try {
if (!_zeroDigit) {
_zeroDigit = _numberFormat.getDecimalFormatSymbols().getZeroDigit();
}
if (value >= 0) {
if (value < 100 && minDigits >= 1 && minDigits <= 2) {
if (value < 10) {
if (minDigits == 2) {
buffer += _zeroDigit.toString();
}
buffer += value.toString();
} else {
buffer += value.toString();
}
return buffer;
} else if (value >= 1000 && value < 10000) {
if (minDigits == 4) {
buffer += value.toString();
return buffer;
}
if (minDigits == 2 && maxDigits == 2) {
buffer = _zeroPaddingNumber(value % 100, 2, 2, buffer);
return buffer;
}
}
}
} catch ( e ) {
}
_numberFormat.setMinimumIntegerDigits(minDigits);
_numberFormat.setMaximumIntegerDigits(maxDigits);
buffer += _numberFormat.format(value);
return buffer;
};
var _matchString = function( text, start, field, data, date ) {
var i = 0;
var count = data.length;
if (field == 7) i = 1;
// There may be multiple strings in the data[] array which begin with
// the same prefix (e.g., Cerven and Cervenec (June and July) in Czech).
// We keep track of the longest match, and return that. Note that this
// unfortunately requires us to test all array elements.
var bestMatchLength = 0, bestMatch = -1;
for (; i<count; ++i)
{
var length = data[i].length;
// Always compare if we have no match yet; otherwise only compare
// against potentially better matches (longer strings).
if (length > bestMatchLength &&
text.substr(start, length).search(new RegExp(data[i], "i")) > -1)
{
bestMatch = i;
bestMatchLength = length;
}
}
if (bestMatch >= 0)
{
CalendarHelper.setField(date, field, bestMatch);
return start + bestMatchLength;
}
return -start;
};
var _subParseNumericZone = function( text, start, sign, count, colon ) {
var index = start;
parse:
try {
var c = text.charAt(index++);
// Parse hh
var hours;
if (!_isDigit(c)) {
break parse;
}
hours = parseInt(c, 10);
c = text.charAt(index++);
if (_isDigit(c)) {
hours = hours * 10 + parseInt(c, 10);
} else {
// If no colon in RFC 822 or 'X' (ISO), two digits are
// required.
if (count > 0 || !colon) {
break parse;
}
--index;
}
if (hours > 23) {
break parse;
}
var minutes = 0;
if (count != 1) {
// Proceed with parsing mm
c = text.charAt(index++);
if (colon) {
if (c != ':') {
break parse;
}
c = text.charAt(index++);
}
if (!_isDigit(c)) {
break parse;
}
minutes = parseInt(c, 10);
c = text.charAt(index++);
if (!_isDigit(c)) {
break parse;
}
minutes = minutes * 10 + parseInt(c, 10);
if (minutes > 59) {
break parse;
}
}
/*minutes += hours * 60;
calb.set(Calendar.ZONE_OFFSET, minutes * MILLIS_PER_MINUTE * sign)
.set(Calendar.DST_OFFSET, 0);*/
return index;
} catch ( e ) {}
return 1 - index;
};
var _isDigit = function( c ) {
return c >= '0' && c <= '9';
};
var _subParse = function( text, start, patternCharIndex, count,
obeyCount, ambiguousYear, origPos, useFollowingMinusSignAsDelimiter, date) {
var number = null;
var value = 0;
var pos = new ParsePosition(0);
pos.index = start;
/*if (patternCharIndex == DateFormatSymbols.PATTERN_WEEK_YEAR) {
// use calendar year 'y' instead
patternCharIndex = DateFormatSymbols.PATTERN_YEAR;
}*/
var field = _PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
// If there are any spaces here, skip over them. If we hit the end
// of the string, then fail.
for (;;) {
if (pos.index >= text.length) {
origPos.errorIndex = start;
return -1;
}
var c = text.charAt(pos.index);
if (c != ' ' && c != '\t') break;
++pos.index;
}
parsing:
{
// We handle a few special cases here where we need to parse
// a number value. We handle further, more generic cases below. We need
// to handle some of them here because some fields require extra processing on
// the parsed value.
if (patternCharIndex == DateFormatSymbols.PATTERN_HOUR_OF_DAY1 ||
patternCharIndex == DateFormatSymbols.PATTERN_HOUR1 ||
(patternCharIndex == DateFormatSymbols.PATTERN_MONTH && count <= 2) ||
patternCharIndex == DateFormatSymbols.PATTERN_YEAR ||
patternCharIndex == DateFormatSymbols.PATTERN_WEEK_YEAR) {
// It would be good to unify this with the obeyCount logic below,
// but that's going to be difficult.
if (obeyCount) {
if ((start+count) > text.length) {
break parsing;
}
number = _numberFormat.parse(text.substring(0, start+count), pos);
} else {
number = _numberFormat.parse(text, pos);
}
if (number == null) {
if (patternCharIndex != DateFormatSymbols.PATTERN_YEAR) {
break parsing;
}
} else {
value = parseInt(number, 10);
if (useFollowingMinusSignAsDelimiter && (value < 0) &&
(((pos.index < text.length) &&
(text.charAt(pos.index) != _minusSign)) ||
((pos.index == text.length) &&
(text.charAt(pos.index-1) == _minusSign)))) {
value = -value;
pos.index--;
}
}
}
var useDateFormatSymbols = true;
var index;
switch (patternCharIndex) {
case DateFormatSymbols.PATTERN_ERA: // 'G'
if (useDateFormatSymbols) {
if ((index = _matchString(text, start, 0, _formatData.getEras(), date)) > 0) {
return index;
}
} else {
/*Map<String, Integer> map = calendar.getDisplayNames(field,
Calendar.ALL_STYLES,
locale);
if ((index = matchString(text, start, field, map, calb)) > 0) {
return index;
}*/
}
break parsing;
case DateFormatSymbols.PATTERN_WEEK_YEAR: // 'Y'
case DateFormatSymbols.PATTERN_YEAR: // 'y'
/*if (!(calendar instanceof GregorianCalendar)) {
// calendar might have text representations for year values,
// such as "\u5143" in JapaneseImperialCalendar.
int style = (count >= 4) ? Calendar.LONG : Calendar.SHORT;
Map<String, Integer> map = calendar.getDisplayNames(field, style, locale);
if (map != null) {
if ((index = matchString(text, start, field, map, calb)) > 0) {
return index;
}
}
calb.set(field, value);
return pos.index;
}*/
// If there are 3 or more YEAR pattern characters, this indicates
// that the year value is to be treated literally, without any
// two-digit year adjustments (e.g., from "01" to 2001). Otherwise
// we made adjustments to place the 2-digit year in the proper
// century, for parsed strings from "00" to "99". Any other string
// is treated literally: "2250", "-1", "1", "002".
if (count <= 2 && (pos.index - start) == 2
&& _isDigit(text.charAt(start))
&& _isDigit(text.charAt(start+1))) {
// Assume for example that the defaultCenturyStart is 6/18/1903.
// This means that two-digit years will be forced into the range
// 6/18/1903 to 6/17/2003. As a result, years 00, 01, and 02
// correspond to 2000, 2001, and 2002. Years 04, 05, etc. correspond
// to 1904, 1905, etc. If the year is 03, then it is 2003 if the
// other fields specify a date before 6/18, or 1903 if they specify a
// date afterwards. As a result, 03 is an ambiguous year. All other
// two-digit years are unambiguous.
var ambiguousTwoDigitYear = _defaultCenturyStartYear % 100;
ambiguousYear[0] = value == ambiguousTwoDigitYear;
value += (Math.floor(_defaultCenturyStartYear/100))*100 +
(value < ambiguousTwoDigitYear ? 100 : 0);
}
date.setFullYear(value);
return pos.index;
case DateFormatSymbols.PATTERN_MONTH: // 'M'
if (count <= 2) // i.e., M or MM.
{
// Don't want to parse the month if it is a string
// while pattern uses numeric style: M or MM.
// [We computed 'value' above.]
CalendarHelper.setField(date, 2, value - 1);
return pos.index;
}
if (useDateFormatSymbols) {
// count >= 3 // i.e., MMM or MMMM
// Want to be able to parse both short and long forms.
// Try count == 4 first:
var newStart = 0;
if ((newStart = _matchString(text, start, 2,
_formatData.getMonths(), date)) > 0) {
return newStart;
}
// count == 4 failed, now try count == 3
if ((index = _matchString(text, start, 2,
_formatData.getShortMonths(), date)) > 0) {
return index;
}
} else {
/*Map<String, Integer> map = calendar.getDisplayNames(field,
Calendar.ALL_STYLES,
locale);
if ((index = matchString(text, start, field, map, calb)) > 0) {
return index;
}*/
}
break parsing;
case DateFormatSymbols.PATTERN_HOUR_OF_DAY1: // 'k' 1-based. eg, 23:59 + 1 hour =>> 24:59
/*if (!isLenient()) {
// Validate the hour value in non-lenient
if (value < 1 || value > 24) {
break parsing;
}
}*/
// [We computed 'value' above.]
if (value == 24)
value = 0;
CalendarHelper.setField(date, 11, value);
return pos.index;
case DateFormatSymbols.PATTERN_DAY_OF_WEEK: // 'E'
{
if (useDateFormatSymbols) {
// Want to be able to parse both short and long forms.
// Try count == 4 (DDDD) first:
var newStart = 0;
if ((newStart=_matchString(text, start, 7,
_formatData.getWeekdays(), date)) > 0) {
return newStart;
}
// DDDD failed, now try DDD
if ((index = _matchString(text, start, 7,
_formatData.getShortWeekdays(), date)) > 0) {
return index;
}
} else {
/*int[] styles = { Calendar.LONG, Calendar.SHORT };
for (int style : styles) {
Map<String,Integer> map = calendar.getDisplayNames(field, style, locale);
if ((index = matchString(text, start, field, map, calb)) > 0) {
return index;
}
}*/
}
}
break parsing;
case DateFormatSymbols.PATTERN_AM_PM: // 'a'
if (useDateFormatSymbols) {
if ((index = _matchString(text, start, 9,
_formatData.getAmPmStrings(), date)) > 0) {
return index;
}
} else {
/*Map<String,Integer> map = calendar.getDisplayNames(field, Calendar.ALL_STYLES, locale);
if ((index = matchString(text, start, field, map, calb)) > 0) {
return index;
}*/
}
break parsing;
case DateFormatSymbols.PATTERN_HOUR1: // 'h' 1-based. eg, 11PM + 1 hour =>> 12 AM
/*if (!isLenient()) {
// Validate the hour value in non-lenient
if (value < 1 || value > 12) {
break parsing;
}
}*/
// [We computed 'value' above.]
if (value == 12)
value = 0;
CalendarHelper.setField(date, 10, value);
return pos.index;
case DateFormatSymbols.PATTERN_ZONE_NAME: // 'z'
case DateFormatSymbols.PATTERN_ZONE_VALUE: // 'Z'
{
var sign = 0;
try {
var c = text.charAt(pos.index);
if (c == '+') {
sign = 1;
} else if (c == '-') {
sign = -1;
}
if (sign == 0) {
// Try parsing a custom time zone "GMT+hh:mm" or "GMT".
if ((c == 'G' || c == 'g')
&& (text.length - start) >= _GMT.length
&& text.substr(start, _GMT.length).search(new RegExp(_GMT, "i")) > -1) {
pos.index = start + _GMT.length;
if ((text.length - pos.index) > 0) {
c = text.charAt(pos.index);
if (c == '+') {
sign = 1;
} else if (c == '-') {
sign = -1;
}
}
if (sign == 0) { /* "GMT" without offset */
/*calb.set(Calendar.ZONE_OFFSET, 0)
.set(Calendar.DST_OFFSET, 0);*/
return pos.index;
}
// Parse the rest as "hh:mm"
var i = _subParseNumericZone(text, ++pos.index,
sign, 0, true);
if (i > 0) {
return i;
}
pos.index = -i;
} else {
// Try parsing the text as a time zone
// name or abbreviation.
/*int i = subParseZoneString(text, pos.index, calb);
if (i > 0) {
return i;
}
pos.index = -i;*/
}
} else {
// Parse the rest as "hhmm" (RFC 822)
var i = _subParseNumericZone(text, ++pos.index,
sign, 0, false);
if (i > 0) {
return i;
}
pos.index = -i;
}
} catch (e) {
}
}
break parsing;
case DateFormatSymbols.PATTERN_ISO_ZONE: // 'X'
{
if ((text.length - pos.index) <= 0) {
break parsing;
}
var sign = 0;
var c = text.charAt(pos.index);
if (c == 'Z') {
// calb.set(Calendar.ZONE_OFFSET, 0).set(Calendar.DST_OFFSET, 0);
return ++pos.index;
}
// parse text as "+/-hh[[:]mm]" based on count
if (c == '+') {
sign = 1;
} else if (c == '-') {
sign = -1;
} else {
++pos.index;
break parsing;
}
var i = _subParseNumericZone(text, ++pos.index, sign, count,
count == 3);
if (i > 0) {
return i;
}
pos.index = -i;
}
break parsing;
default:
// case PATTERN_DAY_OF_MONTH: // 'd'
// case PATTERN_HOUR_OF_DAY0: // 'H' 0-based. eg, 23:59 + 1 hour =>> 00:59
// case PATTERN_MINUTE: // 'm'
// case PATTERN_SECOND: // 's'
// case PATTERN_MILLISECOND: // 'S'
// case PATTERN_DAY_OF_YEAR: // 'D'
// case PATTERN_DAY_OF_WEEK_IN_MONTH: // 'F'
// case PATTERN_WEEK_OF_YEAR: // 'w'
// case PATTERN_WEEK_OF_MONTH: // 'W'
// case PATTERN_HOUR0: // 'K' 0-based. eg, 11PM + 1 hour =>> 0 AM
// case PATTERN_ISO_DAY_OF_WEEK: // 'u' (pseudo field);
// Handle "generic" fields
if (obeyCount) {
if ((start+count) > text.length) {
break parsing;
}
number = _numberFormat.parse(text.substring(0, start+count), pos);
} else {
number = _numberFormat.parse(text, pos);
}
if (number != null) {
value = parseInt(number, 10);
if (useFollowingMinusSignAsDelimiter && (value < 0) &&
(((pos.index < text.length) &&
(text.charAt(pos.index) != _minusSign)) ||
((pos.index == text.length) &&
(text.charAt(pos.index-1) == _minusSign)))) {
value = -value;
pos.index--;
}
CalendarHelper.setField(date, field, value);
return pos.index;
}
break parsing;
}
}
// Parsing failed.
origPos.errorIndex = pos.index;
return -1;
};
var _translatePattern = function( pattern, from, to ) {
var result = "";
var inQuote = false;
for ( var i = 0; i < pattern.length; ++i ) {
var c = pattern.charAt( i );
if ( inQuote ) {
if ( c == '\'' )
inQuote = false;
}
else {
if ( c == '\'' )
inQuote = true;
else if ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) ) {
var ci = from.indexOf( c );
if ( ci >= 0 ) {
// patternChars is longer than localPatternChars due
// to serialization compatibility. The pattern letters
// unsupported by localPatternChars pass through.
if ( ci < to.length ) {
c = to.charAt( ci );
}
} else {
throw "Illegal pattern " +
" character '" +
c + "'";
}
}
}
result += c;
}
if ( inQuote )
throw "Unfinished quote in pattern";
return result.toString();
};
var _checkNegativeNumberExpression = function() {
if ((_numberFormat instanceof DecimalFormat) &&
_numberFormat !== _originalNumberFormat) {
var numberPattern = _numberFormat.toPattern();
if (numberPattern !== _originalNumberPattern) {
_hasFollowingMinusSign = false;
var separatorIndex = numberPattern.indexOf( ';' );
// If the negative subpattern is not absent, we have to analayze
// it in order to check if it has a following minus sign.
if ( separatorIndex > -1 ) {
var minusIndex = numberPattern.indexOf( '-', separatorIndex );
if ((minusIndex > numberPattern.lastIndexOf('0')) &&
(minusIndex > numberPattern.lastIndexOf('#'))) {
_hasFollowingMinusSign = true;
_minusSign = _numberFormat.getDecimalFormatSymbols().getMinusSign();
}
}
_originalNumberPattern = numberPattern;
}
_originalNumberFormat = _numberFormat;
}
};
var _init = function() {
if ( arguments.length > 0 && arguments.length <= 2 ) {
var pattern = arguments[ 0 ];
if ( arguments.length == 1 ) {
_locale = Locale.getDefault();
_formatData = new DateFormatSymbols( _locale );
} else if ( arguments.length == 2 ) {
var arg1 = arguments[ 1 ];
if ( arg1 instanceof Locale ) {
_locale = arg1;
_formatData = new DateFormatSymbols( _locale );
} else if ( arg1 instanceof DateFormatSymbols) {
_formatData = arg1;
_locale = Locale.getDefault();
_useDateFormatSymbols = true;
}
}
_pattern = pattern;
_initializeCalendar( _locale );
_initialize( _locale );
} else {
var timeStyle = arguments.length > 0 && typeof arguments[ 0 ] != "undefined" ?
arguments[ 0 ] : DateFormat.SHORT;
var dateStyle = arguments.length > 0 && typeof arguments[ 1 ] != "undefined" ?
arguments[ 1 ] : DateFormat.SHORT;
var loc = arguments.length > 0 && typeof arguments[ 2 ] != "undefined" ?
arguments[ 2 ] : Locale.getDefault();
_locale = loc;
// initialize calendar and related fields
_initializeCalendar( loc );
var r = ResourceBundle.getBundle( "FormatData", loc );
var dateTimePatterns = r[ "DateTimePatterns" ];
_formatData = new DateFormatSymbols( loc );
if ( ( timeStyle >= 0 ) && ( dateStyle >= 0 ) ) {
var dateTimeArgs = [ dateTimePatterns[ timeStyle ],
dateTimePatterns[ dateStyle + 4 ] ];
_pattern = MessageFormat.format(dateTimePatterns[ 8 ], dateTimeArgs);
}
else if ( timeStyle >= 0 ) {
_pattern = dateTimePatterns[ timeStyle ];
}
else if ( dateStyle >= 0 ) {
_pattern = dateTimePatterns[ dateStyle + 4 ];
}
else {
throw "No date or time style specified";
}
_initialize( loc );
}
};
this.setNumberFormat = function( newNumberFormat ) {
_numberFormat = newNumberFormat;
};
this.getNumberFormat = function() {
return _numberFormat;
};
this.set2DigitYearStart = function( startDate ) {
_parseAmbiguousDatesAsAfter( new Date( startDate.getTime() ) );
};
this.get2DigitYearStart = function() {
return new Date( _defaultCenturyStart.getTime() );
};
this.format = function( date, toAppendTo, pos ) {
toAppendTo = typeof toAppendTo == "string" ? toAppendTo : "";
pos = pos && pos instanceof FieldPosition ? pos : new FieldPosition( 0 );
pos.beginIndex = pos.endIndex = 0;
var delegate = pos.getFieldDelegate();
// Convert input date to time field list
_date = date;
var useDateFormatSymbols = _useDateFormatSymbols || true;
for ( var i = 0; i < _compiledPattern.length; ) {
var tag = _compiledPattern[ i ].charCodeAt( 0 ) >>> 8;
var count = _compiledPattern[ i++ ].charCodeAt( 0 ) & 0xff;
if ( count == 255 ) {
count = _compiledPattern[ i++ ].charCodeAt( 0 ) << 16;
count |= _compiledPattern[ i++ ].charCodeAt( 0 );
}
switch ( tag ) {
case _TAG_QUOTE_ASCII_CHAR:
toAppendTo += String.fromCharCode( count );
break;
case _TAG_QUOTE_CHARS:
toAppendTo += _compiledPattern.slice( i, i + count ).join( "" );
i += count;
break;
default:
toAppendTo = _subFormat( tag, count, delegate, toAppendTo, useDateFormatSymbols );
break;
}
}
return toAppendTo;
};
this.parse = function( text, pos ) {
pos = pos || new ParsePosition( 0 );
_checkNegativeNumberExpression();
var start = pos.index;
var oldStart = start;
var textLength = text.length;
var ambiguousYear = [ false ];
var date = new Date( 0 );
for (var i = 0; i < _compiledPattern.length; ) {
var tag = _compiledPattern[i].charCodeAt( 0 ) >>> 8;
var count = _compiledPattern[i++].charCodeAt( 0 ) & 0xff;
if (count == 255) {
count = _compiledPattern[i++].charCodeAt( 0 ) << 16;
count |= _compiledPattern[i++].charCodeAt( 0 );
}
switch (tag) {
case _TAG_QUOTE_ASCII_CHAR:
if (start >= textLength || text.charAt(start) != String.fromCharCode(count)) {
pos.index = oldStart;
pos.errorIndex = start;
return null;
}
start++;
break;
case _TAG_QUOTE_CHARS:
while (count-- > 0) {
if (start >= textLength || text.charAt(start) != _compiledPattern[i++]) {
pos.index = oldStart;
pos.errorIndex = start;
return null;
}
start++;
}
break;
default:
// Peek the next pattern to determine if we need to
// obey the number of pattern letters for
// parsing. It's required when parsing contiguous
// digit text (e.g., "20010704") with a pattern which
// has no delimiters between fields, like "yyyyMMdd".
var obeyCount = false;
// In Arabic, a minus sign for a negative number is put after
// the number. Even in another locale, a minus sign can be
// put after a number using DateFormat.setNumberFormat().
// If both the minus sign and the field-delimiter are '-',
// subParse() needs to determine whether a '-' after a number
// in the given text is a delimiter or is a minus sign for the
// preceding number. We give subParse() a clue based on the
// information in compiledPattern.
var useFollowingMinusSignAsDelimiter = false;
if (i < _compiledPattern.length) {
var nextTag = _compiledPattern[i].charCodeAt( 0 ) >>> 8;
if (!(nextTag == _TAG_QUOTE_ASCII_CHAR ||
nextTag == _TAG_QUOTE_CHARS)) {
obeyCount = true;
}
if (_hasFollowingMinusSign &&
(nextTag == _TAG_QUOTE_ASCII_CHAR ||
nextTag == _TAG_QUOTE_CHARS)) {
var c;
if (nextTag == _TAG_QUOTE_ASCII_CHAR) {
c = _compiledPattern[i].charCodeAt( 0 ) & 0xff;
} else {
c = _compiledPattern[i+1].charCodeAt( 0 );
}
if (String.fromCharCode(c) == _minusSign) {
useFollowingMinusSignAsDelimiter = true;
}
}
}
start = _subParse(text, start, tag, count, obeyCount,
ambiguousYear, pos,
useFollowingMinusSignAsDelimiter, date);
if (start < 0) {
pos.index = oldStart;
return null;
}
}
}
// At this point the fields of Calendar have been set. Calendar
// will fill in default values for missing fields when the time
// is computed.
pos.index = start;
var parsedDate;
try {
parsedDate = new Date(date.getTime());
// If the year value is ambiguous,
// then the two-digit year == the default start year
if (ambiguousYear[0]) {
if (parsedDate.getTime() < _defaultCenturyStart.getTime()) {
parsedDate.setFullYear(date.getFullYear() + 100);
}
}
}
// An IllegalArgumentException will be thrown by Calendar.getTime()
// if any fields are out of range, e.g., MONTH == 17.
catch (e) {
pos.errorIndex = start;
pos.index = oldStart;
return null;
}
return parsedDate;
};
this.toPattern = function() {
return _pattern;
};
this.toLocalizedPattern = function() {
return _translatePattern( _pattern,
DateFormatSymbols.patternChars,
_formatData.getLocalPatternChars() );
};
this.applyPattern = function( pattern ) {
_compiledPattern = _compile( pattern );
_pattern = pattern;
};
this.applyLocalizedPattern = function( pattern ) {
var p = _translatePattern( _pattern,
DateFormatSymbols.patternChars,
_formatData.getLocalPatternChars() );
_compiledPattern = _compile( p );
_pattern = p;
};
this.getDateFormatSymbols = function() {
return _formatData;
};
this.setDateFormatSymbols = function( newFormatSymbols ) {
_formatData = newFormatSymbols;
_useDateFormatSymbols = true;
};
_init.apply( this, arguments );
}
var _TAG_QUOTE_ASCII_CHAR = 100;
var _TAG_QUOTE_CHARS = 101;
var _MILLIS_PER_MINUTE = 60 * 1000;
var _GMT = "GMT";
// Map index into pattern character string to Calendar field number
// Calendar.ERA,
// Calendar.YEAR,
// Calendar.MONTH,
// Calendar.DATE,
// Calendar.HOUR_OF_DAY,
// Calendar.HOUR_OF_DAY,
// Calendar.MINUTE,
// Calendar.SECOND,
// Calendar.MILLISECOND,
// Calendar.DAY_OF_WEEK,
// Calendar.DAY_OF_YEAR,
// Calendar.DAY_OF_WEEK_IN_MONTH,
// Calendar.WEEK_OF_YEAR,
// Calendar.WEEK_OF_MONTH,
// Calendar.AM_PM,
// Calendar.HOUR,
// Calendar.HOUR,
// Calendar.ZONE_OFFSET,
// Calendar.ZONE_OFFSET,
// CalendarBuilder.WEEK_YEAR,
// CalendarBuilder.ISO_DAY_OF_WEEK,
// Calendar.ZONE_OFFSET
var _PATTERN_INDEX_TO_CALENDAR_FIELD = [
0, 1, 2, 5, 11, 11, 12, 13, 14, 7, 6, 8, 3, 4, 9, 10, 10, 15, 15, 17, 1000, 15
];
// Map index into pattern character string to DateFormat field number
var _PATTERN_INDEX_TO_DATE_FORMAT_FIELD = [
DateFormat.ERA_FIELD,
DateFormat.YEAR_FIELD,
DateFormat.MONTH_FIELD,
DateFormat.DATE_FIELD,
DateFormat.HOUR_OF_DAY1_FIELD,
DateFormat.HOUR_OF_DAY0_FIELD,
DateFormat.MINUTE_FIELD,
DateFormat.SECOND_FIELD,
DateFormat.MILLISECOND_FIELD,
DateFormat.DAY_OF_WEEK_FIELD,
DateFormat.DAY_OF_YEAR_FIELD,
DateFormat.DAY_OF_WEEK_IN_MONTH_FIELD,
DateFormat.WEEK_OF_YEAR_FIELD,
DateFormat.WEEK_OF_MONTH_FIELD,
DateFormat.AM_PM_FIELD,
DateFormat.HOUR1_FIELD,
DateFormat.HOUR0_FIELD,
DateFormat.TIMEZONE_FIELD,
DateFormat.TIMEZONE_FIELD,
DateFormat.YEAR_FIELD,
DateFormat.DAY_OF_WEEK_FIELD,
DateFormat.TIMEZONE_FIELD
];
// Maps from DateFormatSymbols index to Field constant
var _PATTERN_INDEX_TO_DATE_FORMAT_FIELD_ID = [
DateFormat.Field.ERA,
DateFormat.Field.YEAR,
DateFormat.Field.MONTH,
DateFormat.Field.DAY_OF_MONTH,
DateFormat.Field.HOUR_OF_DAY1,
DateFormat.Field.HOUR_OF_DAY0,
DateFormat.Field.MINUTE,
DateFormat.Field.SECOND,
DateFormat.Field.MILLISECOND,
DateFormat.Field.DAY_OF_WEEK,
DateFormat.Field.DAY_OF_YEAR,
DateFormat.Field.DAY_OF_WEEK_IN_MONTH,
DateFormat.Field.WEEK_OF_YEAR,
DateFormat.Field.WEEK_OF_MONTH,
DateFormat.Field.AM_PM,
DateFormat.Field.HOUR1,
DateFormat.Field.HOUR0,
DateFormat.Field.TIME_ZONE,
DateFormat.Field.TIME_ZONE,
DateFormat.Field.YEAR,
DateFormat.Field.DAY_OF_WEEK,
DateFormat.Field.TIME_ZONE
];
var _encode = function( tag, length, buffer ) {
if ( tag == DateFormat.PATTERN_ISO_ZONE && length >= 4 ) {
throw "invalid ISO 8601 format: length=" + length;
}
if ( length < 255 ) {
buffer += String.fromCharCode( tag << 8 | length );
} else {
buffer += String.fromCharCode( tag << 8 | 0xff );
buffer += String.fromCharCode( length >>> 16 );
buffer += String.fromCharCode( length & 0xffff );
}
return buffer;
};
SimpleDateFormat.prototype = Object.create( DateFormat.prototype );
SimpleDateFormat.prototype.constructor = SimpleDateFormat;
SimpleDateFormat.prototype.equals = function( that ) {
if ( !DateFormat.equals.apply( this, [ that ] ) ) return false; // super does class check
if ( !( that instanceof SimpleDateFormat) ) return false;
return ( this.toPattern() == that.toPattern()
&& this.getNumberFormat().equals( that.getNumberFormat() ) );
};
global.SimpleDateFormat = SimpleDateFormat;
return SimpleDateFormat;
} );
|
/* JSJaC - The JavaScript Jabber Client Library
* Copyright (C) 2004-2008 Stefan Strigler
*
* JSJaC is licensed under the terms of the Mozilla Public License
* version 1.1 or, at your option, under the terms of the GNU General
* Public License version 2 or subsequent, or the terms of the GNU Lesser
* General Public License version 2.1 or subsequent.
*
* Please visit http://zeank.in-berlin.de/jsjac/ for details about JSJaC.
*/
var JSJAC_HAVEKEYS = true; // whether to use keys
var JSJAC_NKEYS = 16; // number of keys to generate
var JSJAC_INACTIVITY = 300; // qnd hack to make suspend/resume work more smoothly with polling
var JSJAC_ERR_COUNT = 10; // number of retries in case of connection errors
var JSJAC_ALLOW_PLAIN = true; // whether to allow plaintext logins
var JSJAC_CHECKQUEUEINTERVAL = 1; // msecs to poll send queue
var JSJAC_CHECKINQUEUEINTERVAL = 1; // msecs to poll incoming queue
// Options specific to HTTP Binding (BOSH)
var JSJACHBC_BOSH_VERSION = "1.6";
var JSJACHBC_USE_BOSH_VER = true;
var JSJACHBC_MAX_HOLD = 1;
var JSJACHBC_MAX_WAIT = 300;
var JSJACHBC_MAXPAUSE = 120;
/*** END CONFIG ***/
/**
* @fileoverview Collection of functions to make live easier
* @author Stefan Strigler
* @version $Revision: 437 $
*/
/**
* Convert special chars to HTML entities
* @addon
* @return The string with chars encoded for HTML
* @type String
*/
String.prototype.htmlEnc = function() {
var str = this.replace(/&/g,"&");
str = str.replace(/</g,"<");
str = str.replace(/>/g,">");
str = str.replace(/\"/g,""");
str = str.replace(/\n/g,"<br />");
return str;
};
/**
* Converts from jabber timestamps to JavaScript Date objects
* @addon
* @param {String} ts A string representing a jabber datetime timestamp as
* defined by {@link http://www.xmpp.org/extensions/xep-0082.html XEP-0082}
* @return A javascript Date object corresponding to the jabber DateTime given
* @type Date
*/
Date.jab2date = function(ts) {
var date = new Date(Date.UTC(ts.substr(0,4),ts.substr(5,2)-1,ts.substr(8,2),ts.substr(11,2),ts.substr(14,2),ts.substr(17,2)));
if (ts.substr(ts.length-6,1) != 'Z') { // there's an offset
var offset = new Date();
offset.setTime(0);
offset.setUTCHours(ts.substr(ts.length-5,2));
offset.setUTCMinutes(ts.substr(ts.length-2,2));
if (ts.substr(ts.length-6,1) == '+')
date.setTime(date.getTime() - offset.getTime());
else if (ts.substr(ts.length-6,1) == '-')
date.setTime(date.getTime() + offset.getTime());
}
return date;
};
/**
* Takes a timestamp in the form of 2004-08-13T12:07:04+02:00 as argument
* and converts it to some sort of humane readable format
* @addon
*/
Date.hrTime = function(ts) {
return Date.jab2date(ts).toLocaleString();
};
/**
* somewhat opposit to {@link #hrTime}
* expects a javascript Date object as parameter and returns a jabber
* date string conforming to
* {@link http://www.xmpp.org/extensions/xep-0082.html XEP-0082}
* @see #hrTime
* @return The corresponding jabber DateTime string
* @type String
*/
Date.prototype.jabberDate = function() {
var padZero = function(i) {
if (i < 10) return "0" + i;
return i;
};
var jDate = this.getUTCFullYear() + "-";
jDate += padZero(this.getUTCMonth()+1) + "-";
jDate += padZero(this.getUTCDate()) + "T";
jDate += padZero(this.getUTCHours()) + ":";
jDate += padZero(this.getUTCMinutes()) + ":";
jDate += padZero(this.getUTCSeconds()) + "Z";
return jDate;
};
/**
* Determines the maximum of two given numbers
* @addon
* @param {Number} A a number
* @param {Number} B another number
* @return the maximum of A and B
* @type Number
*/
Number.max = function(A, B) {
return (A > B)? A : B;
};
/* Copyright (c) 1998 - 2007, Paul Johnston & Contributors
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following
* disclaimer. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* Neither the name of the author nor the names of 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.
*
*/
/**
* @fileoverview Collection of MD5 and SHA1 hashing and encoding
* methods.
* @author Stefan Strigler steve@zeank.in-berlin.de
* @version $Revision: 482 $
*/
/*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
* in FIPS PUB 180-1
* Version 2.1a Copyright Paul Johnston 2000 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for details.
*/
/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
var b64pad = "="; /* base-64 pad character. "=" for strict RFC compliance */
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length * chrsz));}
function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * chrsz));}
function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * chrsz));}
function hex_hmac_sha1(key, data){ return binb2hex(core_hmac_sha1(key, data));}
function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));}
function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));}
/*
* Perform a simple self-test to see if the VM is working
*/
function sha1_vm_test()
{
return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";
}
/*
* Calculate the SHA-1 of an array of big-endian words, and a bit length
*/
function core_sha1(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << (24 - len % 32);
x[((len + 64 >> 9) << 4) + 15] = len;
var w = Array(80);
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
var e = -1009589776;
for(var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
var olde = e;
for(var j = 0; j < 80; j++)
{
if(j < 16) w[j] = x[i + j];
else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
safe_add(safe_add(e, w[j]), sha1_kt(j)));
e = d;
d = c;
c = rol(b, 30);
b = a;
a = t;
}
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
e = safe_add(e, olde);
}
return Array(a, b, c, d, e);
}
/*
* Perform the appropriate triplet combination function for the current
* iteration
*/
function sha1_ft(t, b, c, d)
{
if(t < 20) return (b & c) | ((~b) & d);
if(t < 40) return b ^ c ^ d;
if(t < 60) return (b & c) | (b & d) | (c & d);
return b ^ c ^ d;
}
/*
* Determine the appropriate additive constant for the current iteration
*/
function sha1_kt(t)
{
return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
(t < 60) ? -1894007588 : -899497514;
}
/*
* Calculate the HMAC-SHA1 of a key and some data
*/
function core_hmac_sha1(key, data)
{
var bkey = str2binb(key);
if(bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);
var ipad = Array(16), opad = Array(16);
for(var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
return core_sha1(opad.concat(hash), 512 + 160);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert an 8-bit or 16-bit string to an array of big-endian words
* In 8-bit function, characters >255 have their hi-byte silently ignored.
*/
function str2binb(str)
{
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz)
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i%32);
return bin;
}
/*
* Convert an array of big-endian words to a string
*/
function binb2str(bin)
{
var str = "";
var mask = (1 << chrsz) - 1;
for(var i = 0; i < bin.length * 32; i += chrsz)
str += String.fromCharCode((bin[i>>5] >>> (32 - chrsz - i%32)) & mask);
return str;
}
/*
* Convert an array of big-endian words to a hex string.
*/
function binb2hex(binarray)
{
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++)
{
str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF);
}
return str;
}
/*
* Convert an array of big-endian words to a base-64 string
*/
function binb2b64(binarray)
{
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str = "";
for(var i = 0; i < binarray.length * 4; i += 3)
{
var triplet = (((binarray[i >> 2] >> 8 * (3 - i %4)) & 0xFF) << 16)
| (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )
| ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
for(var j = 0; j < 4; j++)
{
if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
}
}
return str.replace(/AAA\=(\=*?)$/,'$1'); // cleans garbage chars at end of string
}
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
// var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
// var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
// var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }
/*
* Perform a simple self-test to see if the VM is working
*/
function md5_vm_test()
{
return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length
*/
function core_md5(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t)
{
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Calculate the HMAC-MD5, of a key and some data
*/
function core_hmac_md5(key, data)
{
var bkey = str2binl(key);
if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);
var ipad = Array(16), opad = Array(16);
for(var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
return core_md5(opad.concat(hash), 512 + 128);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert a string to an array of little-endian words
* If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
*/
function str2binl(str)
{
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz)
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
return bin;
}
/*
* Convert an array of little-endian words to a string
*/
function binl2str(bin)
{
var str = "";
var mask = (1 << chrsz) - 1;
for(var i = 0; i < bin.length * 32; i += chrsz)
str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
return str;
}
/*
* Convert an array of little-endian words to a hex string.
*/
function binl2hex(binarray)
{
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++)
{
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
}
/*
* Convert an array of little-endian words to a base-64 string
*/
function binl2b64(binarray)
{
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str = "";
for(var i = 0; i < binarray.length * 4; i += 3)
{
var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16)
| (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
| ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
for(var j = 0; j < 4; j++)
{
if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
}
}
return str;
}
/* #############################################################################
UTF-8 Decoder and Encoder
base64 Encoder and Decoder
written by Tobias Kieslich, justdreams
Contact: tobias@justdreams.de http://www.justdreams.de/
############################################################################# */
// returns an array of byterepresenting dezimal numbers which represent the
// plaintext in an UTF-8 encoded version. Expects a string.
// This function includes an exception management for those nasty browsers like
// NN401, which returns negative decimal numbers for chars>128. I hate it!!
// This handling is unfortunately limited to the user's charset. Anyway, it works
// in most of the cases! Special signs with an unicode>256 return numbers, which
// can not be converted to the actual unicode and so not to the valid utf-8
// representation. Anyway, this function does always return values which can not
// misinterpretd by RC4 or base64 en- or decoding, because every value is >0 and
// <255!!
// Arrays are faster and easier to handle in b64 encoding or encrypting....
function utf8t2d(t)
{
t = t.replace(/\r\n/g,"\n");
var d=new Array; var test=String.fromCharCode(237);
if (test.charCodeAt(0) < 0)
for(var n=0; n<t.length; n++)
{
var c=t.charCodeAt(n);
if (c>0)
d[d.length]= c;
else {
d[d.length]= (((256+c)>>6)|192);
d[d.length]= (((256+c)&63)|128);}
}
else
for(var n=0; n<t.length; n++)
{
var c=t.charCodeAt(n);
// all the signs of asci => 1byte
if (c<128)
d[d.length]= c;
// all the signs between 127 and 2047 => 2byte
else if((c>127) && (c<2048)) {
d[d.length]= ((c>>6)|192);
d[d.length]= ((c&63)|128);}
// all the signs between 2048 and 66536 => 3byte
else {
d[d.length]= ((c>>12)|224);
d[d.length]= (((c>>6)&63)|128);
d[d.length]= ((c&63)|128);}
}
return d;
}
// returns plaintext from an array of bytesrepresenting dezimal numbers, which
// represent an UTF-8 encoded text; browser which does not understand unicode
// like NN401 will show "?"-signs instead
// expects an array of byterepresenting decimals; returns a string
function utf8d2t(d)
{
var r=new Array; var i=0;
while(i<d.length)
{
if (d[i]<128) {
r[r.length]= String.fromCharCode(d[i]); i++;}
else if((d[i]>191) && (d[i]<224)) {
r[r.length]= String.fromCharCode(((d[i]&31)<<6) | (d[i+1]&63)); i+=2;}
else {
r[r.length]= String.fromCharCode(((d[i]&15)<<12) | ((d[i+1]&63)<<6) | (d[i+2]&63)); i+=3;}
}
return r.join("");
}
// included in <body onload="b64arrays"> it creates two arrays which makes base64
// en- and decoding faster
// this speed is noticeable especially when coding larger texts (>5k or so)
function b64arrays() {
var b64s='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
b64 = new Array();f64 =new Array();
for (var i=0; i<b64s.length ;i++) {
b64[i] = b64s.charAt(i);
f64[b64s.charAt(i)] = i;
}
}
// creates a base64 encoded text out of an array of byerepresenting dezimals
// it is really base64 :) this makes serversided handling easier
// expects an array; returns a string
function b64d2t(d) {
var r=new Array; var i=0; var dl=d.length;
// this is for the padding
if ((dl%3) == 1) {
d[d.length] = 0; d[d.length] = 0;}
if ((dl%3) == 2)
d[d.length] = 0;
// from here conversion
while (i<d.length)
{
r[r.length] = b64[d[i]>>2];
r[r.length] = b64[((d[i]&3)<<4) | (d[i+1]>>4)];
r[r.length] = b64[((d[i+1]&15)<<2) | (d[i+2]>>6)];
r[r.length] = b64[d[i+2]&63];
i+=3;
}
// this is again for the padding
if ((dl%3) == 1)
r[r.length-1] = r[r.length-2] = "=";
if ((dl%3) == 2)
r[r.length-1] = "=";
// we join the array to return a textstring
var t=r.join("");
return t;
}
// returns array of byterepresenting numbers created of an base64 encoded text
// it is still the slowest function in this modul; I hope I can make it faster
// expects string; returns an array
function b64t2d(t) {
var d=new Array; var i=0;
// here we fix this CRLF sequenz created by MS-OS; arrrgh!!!
t=t.replace(/\n|\r/g,""); t=t.replace(/=/g,"");
while (i<t.length)
{
d[d.length] = (f64[t.charAt(i)]<<2) | (f64[t.charAt(i+1)]>>4);
d[d.length] = (((f64[t.charAt(i+1)]&15)<<4) | (f64[t.charAt(i+2)]>>2));
d[d.length] = (((f64[t.charAt(i+2)]&3)<<6) | (f64[t.charAt(i+3)]));
i+=4;
}
if (t.length%4 == 2)
d = d.slice(0, d.length-2);
if (t.length%4 == 3)
d = d.slice(0, d.length-1);
return d;
}
if (typeof(atob) == 'undefined' || typeof(btoa) == 'undefined')
b64arrays();
if (typeof(atob) == 'undefined') {
atob = function(s) {
return utf8d2t(b64t2d(s));
}
}
if (typeof(btoa) == 'undefined') {
btoa = function(s) {
return b64d2t(utf8t2d(s));
}
}
function cnonce(size) {
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var cnonce = '';
for (var i=0; i<size; i++) {
cnonce += tab.charAt(Math.round(Math.random(new Date().getTime())*(tab.length-1)));
}
return cnonce;
}
/* Copyright (c) 2005-2007 Sam Stephenson
*
* 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 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.
*/
/*
json.js
taken from prototype.js, made static
*/
function JSJaCJSON() {}
JSJaCJSON.toString = function (obj) {
var m = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
s = {
array: function (x) {
var a = ['['], b, f, i, l = x.length, v;
for (i = 0; i < l; i += 1) {
v = x[i];
f = s[typeof v];
if (f) {
v = f(v);
if (typeof v == 'string') {
if (b) {
a[a.length] = ',';
}
a[a.length] = v;
b = true;
}
}
}
a[a.length] = ']';
return a.join('');
},
'boolean': function (x) {
return String(x);
},
'null': function (x) {
return "null";
},
number: function (x) {
return isFinite(x) ? String(x) : 'null';
},
object: function (x) {
if (x) {
if (x instanceof Array) {
return s.array(x);
}
var a = ['{'], b, f, i, v;
for (i in x) {
if (x.hasOwnProperty(i)) {
v = x[i];
f = s[typeof v];
if (f) {
v = f(v);
if (typeof v == 'string') {
if (b) {
a[a.length] = ',';
}
a.push(s.string(i), ':', v);
b = true;
}
}
}
}
a[a.length] = '}';
return a.join('');
}
return 'null';
},
string: function (x) {
if (/["\\\x00-\x1f]/.test(x)) {
x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
var c = m[b];
if (c) {
return c;
}
c = b.charCodeAt();
return '\\u00' +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
});
}
return '"' + x + '"';
}
};
switch (typeof(obj)) {
case 'object':
return s.object(obj);
case 'array':
return s.array(obj);
}
};
JSJaCJSON.parse = function (str) {
try {
return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
str.replace(/"(\\.|[^"\\])*"/g, ''))) &&
eval('(' + str + ')');
} catch (e) {
return false;
}
};
/* Copyright 2006 Erik Arvidsson
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/**
* @fileoverview Wrapper to make working with XmlHttpRequest and the
* DOM more convenient (cross browser compliance).
* this code is taken from
* http://webfx.eae.net/dhtml/xmlextras/xmlextras.html
* @author Stefan Strigler steve@zeank.in-berlin.de
* @version $Revision: 437 $
*/
/**
* XmlHttp factory
* @private
*/
function XmlHttp() {}
/**
* creates a cross browser compliant XmlHttpRequest object
*/
XmlHttp.create = function () {
try {
if (window.XMLHttpRequest) {
var req = new XMLHttpRequest();
// some versions of Moz do not support the readyState property
// and the onreadystate event so we patch it!
if (req.readyState == null) {
req.readyState = 1;
req.addEventListener("load", function () {
req.readyState = 4;
if (typeof req.onreadystatechange == "function")
req.onreadystatechange();
}, false);
}
return req;
}
if (window.ActiveXObject) {
return new ActiveXObject(XmlHttp.getPrefix() + ".XmlHttp");
}
}
catch (ex) {}
// fell through
throw new Error("Your browser does not support XmlHttp objects");
};
/**
* used to find the Automation server name
* @private
*/
XmlHttp.getPrefix = function() {
if (XmlHttp.prefix) // I know what you did last summer
return XmlHttp.prefix;
var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
var o;
for (var i = 0; i < prefixes.length; i++) {
try {
// try to create the objects
o = new ActiveXObject(prefixes[i] + ".XmlHttp");
return XmlHttp.prefix = prefixes[i];
}
catch (ex) {};
}
throw new Error("Could not find an installed XML parser");
};
/**
* XmlDocument factory
* @private
*/
function XmlDocument() {}
XmlDocument.create = function (name,ns) {
name = name || 'foo';
ns = ns || '';
try {
var doc;
// DOM2
if (document.implementation && document.implementation.createDocument) {
doc = document.implementation.createDocument(ns, name, null);
// some versions of Moz do not support the readyState property
// and the onreadystate event so we patch it!
if (doc.readyState == null) {
doc.readyState = 1;
doc.addEventListener("load", function () {
doc.readyState = 4;
if (typeof doc.onreadystatechange == "function")
doc.onreadystatechange();
}, false);
}
} else if (window.ActiveXObject) {
doc = new ActiveXObject(XmlDocument.getPrefix() + ".DomDocument");
}
if (!doc.documentElement || doc.documentElement.tagName != name ||
(doc.documentElement.namespaceURI &&
doc.documentElement.namespaceURI != ns)) {
try {
if (ns != '')
doc.appendChild(doc.createElement(name)).
setAttribute('xmlns',ns);
else
doc.appendChild(doc.createElement(name));
} catch (dex) {
doc = document.implementation.createDocument(ns,name,null);
if (doc.documentElement == null)
doc.appendChild(doc.createElement(name));
// fix buggy opera 8.5x
if (ns != '' &&
doc.documentElement.getAttribute('xmlns') != ns) {
doc.documentElement.setAttribute('xmlns',ns);
}
}
}
return doc;
}
catch (ex) { alert(ex.name+": "+ex.message); }
throw new Error("Your browser does not support XmlDocument objects");
};
/**
* used to find the Automation server name
* @private
*/
XmlDocument.getPrefix = function() {
if (XmlDocument.prefix)
return XmlDocument.prefix;
var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
var o;
for (var i = 0; i < prefixes.length; i++) {
try {
// try to create the objects
o = new ActiveXObject(prefixes[i] + ".DomDocument");
return XmlDocument.prefix = prefixes[i];
}
catch (ex) {};
}
throw new Error("Could not find an installed XML parser");
};
// Create the loadXML method
if (typeof(Document) != 'undefined' && window.DOMParser) {
/**
* XMLDocument did not extend the Document interface in some
* versions of Mozilla.
* @private
*/
Document.prototype.loadXML = function (s) {
// parse the string to a new doc
var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
// remove all initial children
while (this.hasChildNodes())
this.removeChild(this.lastChild);
// insert and import nodes
for (var i = 0; i < doc2.childNodes.length; i++) {
this.appendChild(this.importNode(doc2.childNodes[i], true));
}
};
}
// Create xml getter for Mozilla
if (window.XMLSerializer &&
window.Node && Node.prototype && Node.prototype.__defineGetter__) {
/**
* xml getter
*
* This serializes the DOM tree to an XML String
*
* Usage: var sXml = oNode.xml
* @deprecated
* @private
*/
// XMLDocument did not extend the Document interface in some versions
// of Mozilla. Extend both!
XMLDocument.prototype.__defineGetter__("xml", function () {
return (new XMLSerializer()).serializeToString(this);
});
/**
* xml getter
*
* This serializes the DOM tree to an XML String
*
* Usage: var sXml = oNode.xml
* @deprecated
* @private
*/
Document.prototype.__defineGetter__("xml", function () {
return (new XMLSerializer()).serializeToString(this);
});
/**
* xml getter
*
* This serializes the DOM tree to an XML String
*
* Usage: var sXml = oNode.xml
* @deprecated
* @private
*/
Node.prototype.__defineGetter__("xml", function () {
return (new XMLSerializer()).serializeToString(this);
});
}
/* Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
*
* 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.
*/
/**
* @private
* This code is taken from {@link
* http://wiki.script.aculo.us/scriptaculous/show/Builder
* script.aculo.us' Dom Builder} and has been modified to suit our
* needs.<br/>
* The original parts of the code do have the following
* copyright and license notice:<br/>
* Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us,
* http://mir.acu lo.us) <br/>
* script.aculo.us is freely distributable under the terms of an
* MIT-style license.<br>
* For details, see the script.aculo.us web site:
* http://script.aculo.us/<br>
*/
var JSJaCBuilder = {
/**
* @private
*/
buildNode: function(doc, elementName) {
var element, ns = arguments[4];
// attributes (or text)
if(arguments[2])
if(JSJaCBuilder._isStringOrNumber(arguments[2]) ||
(arguments[2] instanceof Array)) {
element = this._createElement(doc, elementName, ns);
JSJaCBuilder._children(doc, element, arguments[2]);
} else {
ns = arguments[2]['xmlns'] || ns;
element = this._createElement(doc, elementName, ns);
for(attr in arguments[2]) {
if (arguments[2].hasOwnProperty(attr) && attr != 'xmlns')
element.setAttribute(attr, arguments[2][attr]);
}
}
else
element = this._createElement(doc, elementName, ns);
// text, or array of children
if(arguments[3])
JSJaCBuilder._children(doc, element, arguments[3], ns);
return element;
},
_createElement: function(doc, elementName, ns) {
try {
if (ns)
return doc.createElementNS(ns, elementName);
} catch (ex) { }
var el = doc.createElement(elementName);
if (ns)
el.setAttribute("xmlns", ns);
return el;
},
/**
* @private
*/
_text: function(doc, text) {
return doc.createTextNode(text);
},
/**
* @private
*/
_children: function(doc, element, children, ns) {
if(typeof children=='object') { // array can hold nodes and text
for (var i in children) {
if (children.hasOwnProperty(i)) {
var e = children[i];
if (typeof e=='object') {
if (e instanceof Array) {
var node = JSJaCBuilder.buildNode(doc, e[0], e[1], e[2], ns);
element.appendChild(node);
} else {
element.appendChild(e);
}
} else {
if(JSJaCBuilder._isStringOrNumber(e)) {
element.appendChild(JSJaCBuilder._text(doc, e));
}
}
}
}
} else {
if(JSJaCBuilder._isStringOrNumber(children)) {
element.appendChild(JSJaCBuilder._text(doc, children));
}
}
},
_attributes: function(attributes) {
var attrs = [];
for(attribute in attributes)
if (attributes.hasOwnProperty(attribute))
attrs.push(attribute +
'="' + attributes[attribute].toString().htmlEnc() + '"');
return attrs.join(" ");
},
_isStringOrNumber: function(param) {
return(typeof param=='string' || typeof param=='number');
}
};
var NS_DISCO_ITEMS = "http://jabber.org/protocol/disco#items";
var NS_DISCO_INFO = "http://jabber.org/protocol/disco#info";
var NS_VCARD = "vcard-temp";
var NS_AUTH = "jabber:iq:auth";
var NS_AUTH_ERROR = "jabber:iq:auth:error";
var NS_REGISTER = "jabber:iq:register";
var NS_SEARCH = "jabber:iq:search";
var NS_ROSTER = "jabber:iq:roster";
var NS_PRIVACY = "jabber:iq:privacy";
var NS_PRIVATE = "jabber:iq:private";
var NS_VERSION = "jabber:iq:version";
var NS_TIME = "jabber:iq:time";
var NS_LAST = "jabber:iq:last";
var NS_XDATA = "jabber:x:data";
var NS_IQDATA = "jabber:iq:data";
var NS_DELAY = "jabber:x:delay";
var NS_EXPIRE = "jabber:x:expire";
var NS_EVENT = "jabber:x:event";
var NS_XCONFERENCE = "jabber:x:conference";
var NS_STATS = "http://jabber.org/protocol/stats";
var NS_MUC = "http://jabber.org/protocol/muc";
var NS_MUC_USER = "http://jabber.org/protocol/muc#user";
var NS_MUC_ADMIN = "http://jabber.org/protocol/muc#admin";
var NS_MUC_OWNER = "http://jabber.org/protocol/muc#owner";
var NS_PUBSUB = "http://jabber.org/protocol/pubsub";
var NS_PUBSUB_EVENT = "http://jabber.org/protocol/pubsub#event";
var NS_PUBSUB_OWNER = "http://jabber.org/protocol/pubsub#owner";
var NS_PUBSUB_NMI = "http://jabber.org/protocol/pubsub#node-meta-info";
var NS_COMMANDS = "http://jabber.org/protocol/commands";
var NS_STREAM = "http://etherx.jabber.org/streams";
var NS_STANZAS = "urn:ietf:params:xml:ns:xmpp-stanzas";
var NS_STREAMS = "urn:ietf:params:xml:ns:xmpp-streams";
var NS_TLS = "urn:ietf:params:xml:ns:xmpp-tls";
var NS_SASL = "urn:ietf:params:xml:ns:xmpp-sasl";
var NS_SESSION = "urn:ietf:params:xml:ns:xmpp-session";
var NS_BIND = "urn:ietf:params:xml:ns:xmpp-bind";
var NS_FEATURE_IQAUTH = "http://jabber.org/features/iq-auth";
var NS_FEATURE_IQREGISTER = "http://jabber.org/features/iq-register";
var NS_FEATURE_COMPRESS = "http://jabber.org/features/compress";
var NS_COMPRESS = "http://jabber.org/protocol/compress";
function STANZA_ERROR(code, type, cond) {
if (window == this)
return new STANZA_ERROR(code, type, cond);
this.code = code;
this.type = type;
this.cond = cond;
}
var ERR_BAD_REQUEST =
STANZA_ERROR("400", "modify", "bad-request");
var ERR_CONFLICT =
STANZA_ERROR("409", "cancel", "conflict");
var ERR_FEATURE_NOT_IMPLEMENTED =
STANZA_ERROR("501", "cancel", "feature-not-implemented");
var ERR_FORBIDDEN =
STANZA_ERROR("403", "auth", "forbidden");
var ERR_GONE =
STANZA_ERROR("302", "modify", "gone");
var ERR_INTERNAL_SERVER_ERROR =
STANZA_ERROR("500", "wait", "internal-server-error");
var ERR_ITEM_NOT_FOUND =
STANZA_ERROR("404", "cancel", "item-not-found");
var ERR_JID_MALFORMED =
STANZA_ERROR("400", "modify", "jid-malformed");
var ERR_NOT_ACCEPTABLE =
STANZA_ERROR("406", "modify", "not-acceptable");
var ERR_NOT_ALLOWED =
STANZA_ERROR("405", "cancel", "not-allowed");
var ERR_NOT_AUTHORIZED =
STANZA_ERROR("401", "auth", "not-authorized");
var ERR_PAYMENT_REQUIRED =
STANZA_ERROR("402", "auth", "payment-required");
var ERR_RECIPIENT_UNAVAILABLE =
STANZA_ERROR("404", "wait", "recipient-unavailable");
var ERR_REDIRECT =
STANZA_ERROR("302", "modify", "redirect");
var ERR_REGISTRATION_REQUIRED =
STANZA_ERROR("407", "auth", "registration-required");
var ERR_REMOTE_SERVER_NOT_FOUND =
STANZA_ERROR("404", "cancel", "remote-server-not-found");
var ERR_REMOTE_SERVER_TIMEOUT =
STANZA_ERROR("504", "wait", "remote-server-timeout");
var ERR_RESOURCE_CONSTRAINT =
STANZA_ERROR("500", "wait", "resource-constraint");
var ERR_SERVICE_UNAVAILABLE =
STANZA_ERROR("503", "cancel", "service-unavailable");
var ERR_SUBSCRIPTION_REQUIRED =
STANZA_ERROR("407", "auth", "subscription-required");
var ERR_UNEXPECTED_REQUEST =
STANZA_ERROR("400", "wait", "unexpected-request");
/**
* @fileoverview Contains Debugger interface for Firebug and Safari
* @class Implementation of the Debugger interface for {@link
* http://www.getfirebug.com/ Firebug} and Safari
* Creates a new debug logger to be passed to jsjac's connection
* constructor. Of course you can use it for debugging in your code
* too.
* @constructor
* @param {int} level The maximum level for debugging messages to be
* displayed. Thus you can tweak the verbosity of the logger. A value
* of 0 means very low traffic whilst a value of 4 makes logging very
* verbose about what's going on.
*/
function JSJaCConsoleLogger(level) {
/**
* @private
*/
this.level = level || 4;
/**
* Empty function for API compatibility
*/
this.start = function() {};
/**
* Logs a message to firebug's/safari's console
* @param {String} msg The message to be logged.
* @param {int} level The message's verbosity level. Importance is
* from 0 (very important) to 4 (not so important). A value of 1
* denotes an error in the usual protocol flow.
*/
this.log = function(msg, level) {
level = level || 0;
if (level > this.level)
return;
if (typeof(console) == 'undefined')
return;
try {
switch (level) {
case 0:
console.warn(msg);
break;
case 1:
console.error(msg);
break;
case 2:
console.info(msg);
break;
case 4:
console.debug(msg);
break;
default:
console.log(msg);
break;
}
} catch(e) { try { console.log(msg) } catch(e) {} }
};
/**
* Sets verbosity level.
* @param {int} level The maximum level for debugging messages to be
* displayed. Thus you can tweak the verbosity of the logger. A
* value of 0 means very low traffic whilst a value of 4 makes
* logging very verbose about what's going on.
* @return This debug logger
* @type ConsoleLogger
*/
this.setLevel = function(level) { this.level = level; return this; };
/**
* Gets verbosity level.
* @return The level
* @type int
*/
this.getLevel = function() { return this.level; };
}
/* Copyright 2003-2006 Peter-Paul Koch
*/
/**
* @fileoverview OO interface to handle cookies.
* Taken from {@link http://www.quirksmode.org/js/cookies.html
* http://www.quirksmode.org/js/cookies.html}
* Regarding licensing of this code the author states:
*
* "You may copy, tweak, rewrite, sell or lease any code example on
* this site, with one single exception."
*
* @author Stefan Strigler
* @version $Revision: 481 $
*/
/**
* Creates a new Cookie
* @class Class representing browser cookies for storing small amounts of data
* @constructor
* @param {String} name The name of the value to store
* @param {String} value The value to store
* @param {int} secs Number of seconds until cookie expires (may be empty)
*/
function JSJaCCookie(name,value,secs)
{
if (window == this)
return new JSJaCCookie(name, value, secs);
/**
* This cookie's name
* @type String
*/
this.name = name;
/**
* This cookie's value
* @type String
*/
this.value = value;
/**
* Time in seconds when cookie expires (thus being delete by
* browser). A value of -1 denotes a session cookie which means that
* stored data gets lost when browser is being closed.
* @type int
*/
this.secs = secs;
/**
* Stores this cookie
*/
this.write = function() {
if (this.secs) {
var date = new Date();
date.setTime(date.getTime()+(this.secs*1000));
var expires = "; expires="+date.toGMTString();
} else
var expires = "";
document.cookie = this.getName()+"="+this.getValue()+expires+"; path=/";
};
/**
* Deletes this cookie
*/
this.erase = function() {
var c = new JSJaCCookie(this.getName(),"",-1);
c.write();
};
/**
* Gets the name of this cookie
* @return The name
* @type String
*/
this.getName = function() {
return this.name;
};
/**
* Sets the name of this cookie
* @param {String} name The name for this cookie
* @return This cookie
* @type Cookie
*/
this.setName = function(name) {
this.name = name;
return this;
};
/**
* Gets the value of this cookie
* @return The value
* @type String
*/
this.getValue = function() {
return this.value;
};
/**
* Sets the value of this cookie
* @param {String} value The value for this cookie
* @return This cookie
* @type Cookie
*/
this.setValue = function(value) {
this.value = value;
return this;
};
}
/**
* Reads the value for given <code>name</code> from cookies and return new
* <code>Cookie</code> object
* @param {String} name The name of the cookie to read
* @return A cookie object of the given name
* @type Cookie
* @throws CookieException when cookie with given name could not be found
*/
JSJaCCookie.read = function(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 new JSJaCCookie(name, c.substring(nameEQ.length,c.length));
}
throw new JSJaCCookieException("Cookie not found");
};
/**
* Reads the value for given <code>name</code> from cookies and returns
* its valued new
* @param {String} name The name of the cookie to read
* @return The value of the cookie read
* @type String
* @throws CookieException when cookie with given name could not be found
*/
JSJaCCookie.get = function(name) {
return JSJaCCookie.read(name).getValue();
};
/**
* Deletes cookie with given <code>name</code>
* @param {String} name The name of the cookie to delete
* @throws CookieException when cookie with given name could not be found
*/
JSJaCCookie.remove = function(name) {
JSJaCCookie.read(name).erase();
};
/**
* Some exception denoted to dealing with cookies
* @constructor
* @param {String} msg The message to pass to the exception
*/
function JSJaCCookieException(msg) {
this.message = msg;
this.name = "CookieException";
}
/**
* an error packet for internal use
* @private
* @constructor
*/
function JSJaCError(code,type,condition) {
var xmldoc = XmlDocument.create("error","jsjac");
xmldoc.documentElement.setAttribute('code',code);
xmldoc.documentElement.setAttribute('type',type);
xmldoc.documentElement.appendChild(xmldoc.createElement(condition)).
setAttribute('xmlns','urn:ietf:params:xml:ns:xmpp-stanzas');
return xmldoc.documentElement;
}
/**
* @fileoverview This file contains all things that make life easier when
* dealing with JIDs
* @author Stefan Strigler
* @version $Revision: 437 $
*/
/**
* list of forbidden chars for nodenames
* @private
*/
var JSJACJID_FORBIDDEN = ['"',' ','&','\'','/',':','<','>','@'];
/**
* Creates a new JSJaCJID object
* @class JSJaCJID models xmpp jid objects
* @constructor
* @param {Object} jid jid may be either of type String or a JID represented
* by JSON with fields 'node', 'domain' and 'resource'
* @throws JSJaCJIDInvalidException Thrown if jid is not valid
* @return a new JSJaCJID object
*/
function JSJaCJID(jid) {
/**
*@private
*/
this._node = '';
/**
*@private
*/
this._domain = '';
/**
*@private
*/
this._resource = '';
if (typeof(jid) == 'string') {
if (jid.indexOf('@') != -1) {
this.setNode(jid.substring(0,jid.indexOf('@')));
jid = jid.substring(jid.indexOf('@')+1);
}
if (jid.indexOf('/') != -1) {
this.setResource(jid.substring(jid.indexOf('/')+1));
jid = jid.substring(0,jid.indexOf('/'));
}
this.setDomain(jid);
} else {
this.setNode(jid.node);
this.setDomain(jid.domain);
this.setResource(jid.resource);
}
}
/**
* Gets the node part of the jid
* @return A string representing the node name
* @type String
*/
JSJaCJID.prototype.getNode = function() { return this._node; };
/**
* Gets the domain part of the jid
* @return A string representing the domain name
* @type String
*/
JSJaCJID.prototype.getDomain = function() { return this._domain; };
/**
* Gets the resource part of the jid
* @return A string representing the resource
* @type String
*/
JSJaCJID.prototype.getResource = function() { return this._resource; };
/**
* Sets the node part of the jid
* @param {String} node Name of the node
* @throws JSJaCJIDInvalidException Thrown if node name contains invalid chars
* @return This object
* @type JSJaCJID
*/
JSJaCJID.prototype.setNode = function(node) {
JSJaCJID._checkNodeName(node);
this._node = node || '';
return this;
};
/**
* Sets the domain part of the jid
* @param {String} domain Name of the domain
* @throws JSJaCJIDInvalidException Thrown if domain name contains invalid
* chars or is empty
* @return This object
* @type JSJaCJID
*/
JSJaCJID.prototype.setDomain = function(domain) {
if (!domain || domain == '')
throw new JSJaCJIDInvalidException("domain name missing");
// chars forbidden for a node are not allowed in domain names
// anyway, so let's check
JSJaCJID._checkNodeName(domain);
this._domain = domain;
return this;
};
/**
* Sets the resource part of the jid
* @param {String} resource Name of the resource
* @return This object
* @type JSJaCJID
*/
JSJaCJID.prototype.setResource = function(resource) {
this._resource = resource || '';
return this;
};
/**
* The string representation of the full jid
* @return A string representing the jid
* @type String
*/
JSJaCJID.prototype.toString = function() {
var jid = '';
if (this.getNode() && this.getNode() != '')
jid = this.getNode() + '@';
jid += this.getDomain(); // we always have a domain
if (this.getResource() && this.getResource() != "")
jid += '/' + this.getResource();
return jid;
};
/**
* Removes the resource part of the jid
* @return This object
* @type JSJaCJID
*/
JSJaCJID.prototype.removeResource = function() {
return this.setResource();
};
/**
* creates a copy of this JSJaCJID object
* @return A copy of this
* @type JSJaCJID
*/
JSJaCJID.prototype.clone = function() {
return new JSJaCJID(this.toString());
};
/**
* Compares two jids if they belong to the same entity (i.e. w/o resource)
* @param {String} jid a jid as string or JSJaCJID object
* @return 'true' if jid is same entity as this
* @type Boolean
*/
JSJaCJID.prototype.isEntity = function(jid) {
if (typeof jid == 'string')
jid = (new JSJaCJID(jid));
jid.removeResource();
return (this.clone().removeResource().toString() === jid.toString());
};
/**
* Check if node name is valid
* @private
* @param {String} node A name for a node
* @throws JSJaCJIDInvalidException Thrown if name for node is not allowed
*/
JSJaCJID._checkNodeName = function(nodeprep) {
if (!nodeprep || nodeprep == '')
return;
for (var i=0; i< JSJACJID_FORBIDDEN.length; i++) {
if (nodeprep.indexOf(JSJACJID_FORBIDDEN[i]) != -1) {
throw new JSJaCJIDInvalidException("forbidden char in nodename: "+JSJACJID_FORBIDDEN[i]);
}
}
};
/**
* Creates a new Exception of type JSJaCJIDInvalidException
* @class Exception to indicate invalid values for a jid
* @constructor
* @param {String} message The message associated with this Exception
*/
function JSJaCJIDInvalidException(message) {
/**
* The exceptions associated message
* @type String
*/
this.message = message;
/**
* The name of the exception
* @type String
*/
this.name = "JSJaCJIDInvalidException";
}
/**
* Creates a new set of hash keys
* @class Reflects a set of sha1/md5 hash keys for securing sessions
* @constructor
* @param {Function} func The hash function to be used for creating the keys
* @param {Debugger} oDbg Reference to debugger implementation [optional]
*/
function JSJaCKeys(func,oDbg) {
var seed = Math.random();
/**
* @private
*/
this._k = new Array();
this._k[0] = seed.toString();
if (oDbg)
/**
* Reference to Debugger
* @type Debugger
*/
this.oDbg = oDbg;
else {
this.oDbg = {};
this.oDbg.log = function() {};
}
if (func) {
for (var i=1; i<JSJAC_NKEYS; i++) {
this._k[i] = func(this._k[i-1]);
oDbg.log(i+": "+this._k[i],4);
}
}
/**
* @private
*/
this._indexAt = JSJAC_NKEYS-1;
/**
* Gets next key from stack
* @return New hash key
* @type String
*/
this.getKey = function() {
return this._k[this._indexAt--];
};
/**
* Indicates whether there's only one key left
* @return <code>true</code> if there's only one key left, false otherwise
* @type boolean
*/
this.lastKey = function() { return (this._indexAt == 0); };
/**
* Returns number of overall/initial stack size
* @return Number of keys created
* @type int
*/
this.size = function() { return this._k.length; };
/**
* @private
*/
this._getSuspendVars = function() {
return ('_k,_indexAt').split(',');
}
}
/**
* @fileoverview Contains all Jabber/XMPP packet related classes.
* @author Stefan Strigler steve@zeank.in-berlin.de
* @version $Revision: 480 $
*/
var JSJACPACKET_USE_XMLNS = true;
/**
* Creates a new packet with given root tag name (for internal use)
* @class Somewhat abstract base class for all kinds of specialised packets
* @param {String} name The root tag name of the packet
* (i.e. one of 'message', 'iq' or 'presence')
*/
function JSJaCPacket(name) {
/**
* @private
*/
this.name = name;
if (typeof(JSJACPACKET_USE_XMLNS) != 'undefined' && JSJACPACKET_USE_XMLNS)
/**
* @private
*/
this.doc = XmlDocument.create(name,'jabber:client');
else
/**
* @private
*/
this.doc = XmlDocument.create(name,'');
}
/**
* Gets the type (name of root element) of this packet, i.e. one of
* 'presence', 'message' or 'iq'
* @return the top level tag name
* @type String
*/
JSJaCPacket.prototype.pType = function() { return this.name; };
/**
* Gets the associated Document for this packet.
* @type {@link http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#i-Document Document}
*/
JSJaCPacket.prototype.getDoc = function() {
return this.doc;
};
/**
* Gets the root node of this packet
* @type {@link http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247 Node}
*/
JSJaCPacket.prototype.getNode = function() {
if (this.getDoc() && this.getDoc().documentElement)
return this.getDoc().documentElement;
else
return null;
};
/**
* Sets the 'to' attribute of the root node of this packet
* @param {String} to
* @type JSJaCPacket
*/
JSJaCPacket.prototype.setTo = function(to) {
if (!to || to == '')
this.getNode().removeAttribute('to');
else if (typeof(to) == 'string')
this.getNode().setAttribute('to',to);
else
this.getNode().setAttribute('to',to.toString());
return this;
};
/**
* Sets the 'from' attribute of the root node of this
* packet. Usually this is not needed as the server will take care
* of this automatically.
* @type JSJaCPacket
*/
JSJaCPacket.prototype.setFrom = function(from) {
if (!from || from == '')
this.getNode().removeAttribute('from');
else if (typeof(from) == 'string')
this.getNode().setAttribute('from',from);
else
this.getNode().setAttribute('from',from.toString());
return this;
};
/**
* Sets 'id' attribute of the root node of this packet.
* @param {String} id The id of the packet.
* @type JSJaCPacket
*/
JSJaCPacket.prototype.setID = function(id) {
if (!id || id == '')
this.getNode().removeAttribute('id');
else
this.getNode().setAttribute('id',id);
return this;
};
/**
* Sets the 'type' attribute of the root node of this packet.
* @param {String} type The type of the packet.
* @type JSJaCPacket
*/
JSJaCPacket.prototype.setType = function(type) {
if (!type || type == '')
this.getNode().removeAttribute('type');
else
this.getNode().setAttribute('type',type);
return this;
};
/**
* Sets 'xml:lang' for this packet
* @param {String} xmllang The xml:lang of the packet.
* @type JSJaCPacket
*/
JSJaCPacket.prototype.setXMLLang = function(xmllang) {
if (!xmllang || xmllang == '')
this.getNode().removeAttribute('xml:lang');
else
this.getNode().setAttribute('xml:lang',xmllang);
return this;
};
/**
* Gets the 'to' attribute of this packet
* @type String
*/
JSJaCPacket.prototype.getTo = function() {
return this.getNode().getAttribute('to');
};
/**
* Gets the 'from' attribute of this packet.
* @type String
*/
JSJaCPacket.prototype.getFrom = function() {
return this.getNode().getAttribute('from');
};
/**
* Gets the 'to' attribute of this packet as a JSJaCJID object
* @type JSJaCJID
*/
JSJaCPacket.prototype.getToJID = function() {
return new JSJaCJID(this.getTo());
};
/**
* Gets the 'from' attribute of this packet as a JSJaCJID object
* @type JSJaCJID
*/
JSJaCPacket.prototype.getFromJID = function() {
return new JSJaCJID(this.getFrom());
};
/**
* Gets the 'id' of this packet
* @type String
*/
JSJaCPacket.prototype.getID = function() {
return this.getNode().getAttribute('id');
};
/**
* Gets the 'type' of this packet
* @type String
*/
JSJaCPacket.prototype.getType = function() {
return this.getNode().getAttribute('type');
};
/**
* Gets the 'xml:lang' of this packet
* @type String
*/
JSJaCPacket.prototype.getXMLLang = function() {
return this.getNode().getAttribute('xml:lang');
};
/**
* Gets the 'xmlns' (xml namespace) of the root node of this packet
* @type String
*/
JSJaCPacket.prototype.getXMLNS = function() {
return this.getNode().namespaceURI;
};
/**
* Gets a child element of this packet. If no params given returns first child.
* @param {String} name Tagname of child to retrieve. Use '*' to match any tag. [optional]
* @param {String} ns Namespace of child. Use '*' to match any ns.[optional]
* @return The child node, null if none found
* @type {@link http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247 Node}
*/
JSJaCPacket.prototype.getChild = function(name, ns) {
if (!this.getNode()) {
return null;
}
name = name || '*';
ns = ns || '*';
if (this.getNode().getElementsByTagNameNS) {
return this.getNode().getElementsByTagNameNS(ns, name).item(0);
}
// fallback
var nodes = this.getNode().getElementsByTagName(name);
if (ns != '*') {
for (var i=0; i<nodes.length; i++) {
if (nodes.item(i).namespaceURI == ns) {
return nodes.item(i);
}
}
} else {
return nodes.item(0);
}
return null; // nothing found
}
/**
* Gets the node value of a child element of this packet.
* @param {String} name Tagname of child to retrieve.
* @param {String} ns Namespace of child
* @return The value of the child node, empty string if none found
* @type String
*/
JSJaCPacket.prototype.getChildVal = function(name, ns) {
var node = this.getChild(name, ns);
var ret = '';
if (node && node.hasChildNodes()) {
// concatenate all values from childNodes
for (var i=0; i<node.childNodes.length; i++)
if (node.childNodes.item(i).nodeValue)
ret += node.childNodes.item(i).nodeValue;
}
return ret;
};
/**
* Returns a copy of this node
* @return a copy of this node
* @type JSJaCPacket
*/
JSJaCPacket.prototype.clone = function() {
return JSJaCPacket.wrapNode(this.getNode());
};
/**
* Checks if packet is of type 'error'
* @return 'true' if this packet is of type 'error', 'false' otherwise
* @type boolean
*/
JSJaCPacket.prototype.isError = function() {
return (this.getType() == 'error');
};
/**
* Returns an error condition reply according to {@link http://www.xmpp.org/extensions/xep-0086.html XEP-0086}. Creates a clone of the calling packet with senders and recipient exchanged and error stanza appended.
* @param {STANZA_ERROR} stanza_error an error stanza containing error cody, type and condition of the error to be indicated
* @return an error reply packet
* @type JSJaCPacket
*/
JSJaCPacket.prototype.errorReply = function(stanza_error) {
var rPacket = this.clone();
rPacket.setTo(this.getFrom());
rPacket.setFrom();
rPacket.setType('error');
rPacket.appendNode('error',
{code: stanza_error.code, type: stanza_error.type},
[[stanza_error.cond]]);
return rPacket;
};
/**
* Returns a string representation of the raw xml content of this packet.
* @type String
*/
JSJaCPacket.prototype.xml = typeof XMLSerializer != 'undefined' ?
function() {
var r = (new XMLSerializer()).serializeToString(this.getNode());
if (typeof(r) == 'undefined')
r = (new XMLSerializer()).serializeToString(this.doc); // oldschool
return r
} :
function() {// IE
return this.getDoc().xml
};
// PRIVATE METHODS DOWN HERE
/**
* Gets an attribute of the root element
* @private
*/
JSJaCPacket.prototype._getAttribute = function(attr) {
return this.getNode().getAttribute(attr);
};
/**
* Replaces this node with given node
* @private
*/
JSJaCPacket.prototype._replaceNode = function(aNode) {
// copy attribs
for (var i=0; i<aNode.attributes.length; i++)
if (aNode.attributes.item(i).nodeName != 'xmlns')
this.getNode().setAttribute(aNode.attributes.item(i).nodeName,
aNode.attributes.item(i).nodeValue);
// copy children
for (var i=0; i<aNode.childNodes.length; i++)
if (this.getDoc().importNode)
this.getNode().appendChild(this.getDoc().importNode(aNode.
childNodes.item(i),
true));
else
this.getNode().appendChild(aNode.childNodes.item(i).cloneNode(true));
};
/**
* Set node value of a child node
* @private
*/
JSJaCPacket.prototype._setChildNode = function(nodeName, nodeValue) {
var aNode = this.getChild(nodeName);
var tNode = this.getDoc().createTextNode(nodeValue);
if (aNode)
try {
aNode.replaceChild(tNode,aNode.firstChild);
} catch (e) { }
else {
try {
aNode = this.getDoc().createElementNS(this.getNode().namespaceURI,
nodeName);
} catch (ex) {
aNode = this.getDoc().createElement(nodeName)
}
this.getNode().appendChild(aNode);
aNode.appendChild(tNode);
}
return aNode;
};
/**
* Builds a node using {@link
* http://wiki.script.aculo.us/scriptaculous/show/Builder
* script.aculo.us' Dom Builder} notation.
* This code is taken from {@link
* http://wiki.script.aculo.us/scriptaculous/show/Builder
* script.aculo.us' Dom Builder} and has been modified to suit our
* needs.<br/>
* The original parts of the code do have the following copyright
* and license notice:<br/>
* Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us,
* http://mir.acu lo.us) <br/>
* script.aculo.us is freely distributable under the terms of an
* MIT-style licen se. // For details, see the script.aculo.us web
* site: http://script.aculo.us/<br>
* @author Thomas Fuchs
* @author Stefan Strigler
* @return The newly created node
* @type {@link http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247 Node}
*/
JSJaCPacket.prototype.buildNode = function(elementName) {
return JSJaCBuilder.buildNode(this.getDoc(),
elementName,
arguments[1],
arguments[2]);
};
/**
* Appends node created by buildNode to this packets parent node.
* @param {@link http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247 Node} element The node to append or
* @param {String} element A name plus an object hash with attributes (optional) plus an array of childnodes (optional)
* @see #buildNode
* @return This packet
* @type JSJaCPacket
*/
JSJaCPacket.prototype.appendNode = function(element) {
if (typeof element=='object') { // seems to be a prebuilt node
return this.getNode().appendChild(element)
} else { // build node
return this.getNode().appendChild(this.buildNode(element,
arguments[1],
arguments[2],
null,
this.getNode().namespaceURI));
}
};
/**
* A jabber/XMPP presence packet
* @class Models the XMPP notion of a 'presence' packet
* @extends JSJaCPacket
*/
function JSJaCPresence() {
/**
* @ignore
*/
this.base = JSJaCPacket;
this.base('presence');
}
JSJaCPresence.prototype = new JSJaCPacket;
/**
* Sets the status message for current status. Usually this is set
* to some human readable string indicating what the user is
* doing/feel like currently.
* @param {String} status A status message
* @return this
* @type JSJaCPacket
*/
JSJaCPresence.prototype.setStatus = function(status) {
this._setChildNode("status", status);
return this;
};
/**
* Sets the online status for this presence packet.
* @param {String} show An XMPP complient status indicator. Must
* be one of 'chat', 'away', 'xa', 'dnd'
* @return this
* @type JSJaCPacket
*/
JSJaCPresence.prototype.setShow = function(show) {
if (show == 'chat' || show == 'away' || show == 'xa' || show == 'dnd')
this._setChildNode("show",show);
return this;
};
/**
* Sets the priority of the resource bind to with this connection
* @param {int} prio The priority to set this resource to
* @return this
* @type JSJaCPacket
*/
JSJaCPresence.prototype.setPriority = function(prio) {
this._setChildNode("priority", prio);
return this;
};
/**
* Some combined method that allowes for setting show, status and
* priority at once
* @param {String} show A status message
* @param {String} status A status indicator as defined by XMPP
* @param {int} prio A priority for this resource
* @return this
* @type JSJaCPacket
*/
JSJaCPresence.prototype.setPresence = function(show,status,prio) {
if (show)
this.setShow(show);
if (status)
this.setStatus(status);
if (prio)
this.setPriority(prio);
return this;
};
/**
* Gets the status message of this presence
* @return The (human readable) status message
* @type String
*/
JSJaCPresence.prototype.getStatus = function() {
return this.getChildVal('status');
};
/**
* Gets the status of this presence.
* Either one of 'chat', 'away', 'xa' or 'dnd' or null.
* @return The status indicator as defined by XMPP
* @type String
*/
JSJaCPresence.prototype.getShow = function() {
return this.getChildVal('show');
};
/**
* Gets the priority of this status message
* @return A resource priority
* @type int
*/
JSJaCPresence.prototype.getPriority = function() {
return this.getChildVal('priority');
};
/**
* A jabber/XMPP iq packet
* @class Models the XMPP notion of an 'iq' packet
* @extends JSJaCPacket
*/
function JSJaCIQ() {
/**
* @ignore
*/
this.base = JSJaCPacket;
this.base('iq');
}
JSJaCIQ.prototype = new JSJaCPacket;
/**
* Some combined method to set 'to', 'type' and 'id' at once
* @param {String} to the recepients JID
* @param {String} type A XMPP compliant iq type (one of 'set', 'get', 'result' and 'error'
* @param {String} id A packet ID
* @return this
* @type JSJaCIQ
*/
JSJaCIQ.prototype.setIQ = function(to,type,id) {
if (to)
this.setTo(to);
if (type)
this.setType(type);
if (id)
this.setID(id);
return this;
};
/**
* Creates a 'query' child node with given XMLNS
* @param {String} xmlns The namespace for the 'query' node
* @return The query node
* @type {@link http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247 Node}
*/
JSJaCIQ.prototype.setQuery = function(xmlns) {
var query;
try {
query = this.getDoc().createElementNS(xmlns,'query');
} catch (e) {
// fallback
query = this.getDoc().createElement('query');
}
if (query && query.getAttribute('xmlns') != xmlns) // fix opera 8.5x
query.setAttribute('xmlns',xmlns);
this.getNode().appendChild(query);
return query;
};
/**
* Gets the 'query' node of this packet
* @return The query node
* @type {@link http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247 Node}
*/
JSJaCIQ.prototype.getQuery = function() {
return this.getNode().getElementsByTagName('query').item(0);
};
/**
* Gets the XMLNS of the query node contained within this packet
* @return The namespace of the query node
* @type String
*/
JSJaCIQ.prototype.getQueryXMLNS = function() {
if (this.getQuery())
return this.getQuery().namespaceURI;
else
return null;
};
/**
* Creates an IQ reply with type set to 'result'. If given appends payload to first child if IQ. Payload maybe XML as string or a DOM element (or an array of such elements as well).
* @param {Element} payload A payload to be appended [optional]
* @return An IQ reply packet
* @type JSJaCIQ
*/
JSJaCIQ.prototype.reply = function(payload) {
var rIQ = this.clone();
rIQ.setTo(this.getFrom());
rIQ.setType('result');
if (payload) {
if (typeof payload == 'string')
rIQ.getChild().appendChild(rIQ.getDoc().loadXML(payload));
else if (payload.constructor == Array) {
var node = rIQ.getChild();
for (var i=0; i<payload.length; i++)
if(typeof payload[i] == 'string')
node.appendChild(rIQ.getDoc().loadXML(payload[i]));
else if (typeof payload[i] == 'object')
node.appendChild(payload[i]);
}
else if (typeof payload == 'object')
rIQ.getChild().appendChild(payload);
}
return rIQ;
};
/**
* A jabber/XMPP message packet
* @class Models the XMPP notion of an 'message' packet
* @extends JSJaCPacket
*/
function JSJaCMessage() {
/**
* @ignore
*/
this.base = JSJaCPacket;
this.base('message');
}
JSJaCMessage.prototype = new JSJaCPacket;
/**
* Sets the body of the message
* @param {String} body Your message to be sent along
* @return this message
* @type JSJaCMessage
*/
JSJaCMessage.prototype.setBody = function(body) {
this._setChildNode("body",body);
return this;
};
/**
* Sets the subject of the message
* @param {String} subject Your subject to be sent along
* @return this message
* @type JSJaCMessage
*/
JSJaCMessage.prototype.setSubject = function(subject) {
this._setChildNode("subject",subject);
return this;
};
/**
* Sets the 'tread' attribute for this message. This is used to identify
* threads in chat conversations
* @param {String} thread Usually a somewhat random hash.
* @return this message
* @type JSJaCMessage
*/
JSJaCMessage.prototype.setThread = function(thread) {
this._setChildNode("thread", thread);
return this;
};
/**
* Gets the 'thread' identifier for this message
* @return A thread identifier
* @type String
*/
JSJaCMessage.prototype.getThread = function() {
return this.getChildVal('thread');
};
/**
* Gets the body of this message
* @return The body of this message
* @type String
*/
JSJaCMessage.prototype.getBody = function() {
return this.getChildVal('body');
};
/**
* Gets the subject of this message
* @return The subject of this message
* @type String
*/
JSJaCMessage.prototype.getSubject = function() {
return this.getChildVal('subject')
};
/**
* Tries to transform a w3c DOM node to JSJaC's internal representation
* (JSJaCPacket type, one of JSJaCPresence, JSJaCMessage, JSJaCIQ)
* @param: {Node
* http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247}
* node The node to be transformed
* @return A JSJaCPacket representing the given node. If node's root
* elemenent is not one of 'message', 'presence' or 'iq',
* <code>null</code> is being returned.
* @type JSJaCPacket
*/
JSJaCPacket.wrapNode = function(node) {
var aNode;
switch (node.nodeName.toLowerCase()) {
case 'presence':
aNode = new JSJaCPresence();
break;
case 'message':
aNode = new JSJaCMessage();
break;
case 'iq':
aNode = new JSJaCIQ();
break;
default : // unknown
return null;
}
aNode._replaceNode(node);
return aNode;
};
/**
* @fileoverview Contains all things in common for all subtypes of connections
* supported.
* @author Stefan Strigler steve@zeank.in-berlin.de
* @version $Revision: 476 $
*/
/**
* Creates a new Jabber connection (a connection to a jabber server)
* @class Somewhat abstract base class for jabber connections. Contains all
* of the code in common for all jabber connections
* @constructor
* @param {JSON http://www.json.org/index} oArg JSON with properties: <br>
* * <code>httpbase</code> the http base address of the service to be used for
* connecting to jabber<br>
* * <code>oDbg</code> (optional) a reference to a debugger interface
*/
function JSJaCConnection(oArg) {
if (oArg && oArg.oDbg && oArg.oDbg.log)
/**
* Reference to debugger interface
*(needs to implement method <code>log</code>)
* @type Debugger
*/
this.oDbg = oArg.oDbg;
else {
this.oDbg = new Object(); // always initialise a debugger
this.oDbg.log = function() { };
}
if (oArg && oArg.httpbase)
/**
* @private
*/
this._httpbase = oArg.httpbase;
if (oArg && oArg.allow_plain)
/**
* @private
*/
this.allow_plain = oArg.allow_plain;
else
this.allow_plain = JSJAC_ALLOW_PLAIN;
/**
* @private
*/
this._connected = false;
/**
* @private
*/
this._events = new Array();
/**
* @private
*/
this._keys = null;
/**
* @private
*/
this._ID = 0;
/**
* @private
*/
this._inQ = new Array();
/**
* @private
*/
this._pQueue = new Array();
/**
* @private
*/
this._regIDs = new Array();
/**
* @private
*/
this._req = new Array();
/**
* @private
*/
this._status = 'intialized';
/**
* @private
*/
this._errcnt = 0;
/**
* @private
*/
this._inactivity = JSJAC_INACTIVITY;
/**
* @private
*/
this._sendRawCallbacks = new Array();
if (oArg && oArg.timerval)
this.setPollInterval(oArg.timerval);
}
JSJaCConnection.prototype.connect = function(oArg) {
this._setStatus('connecting');
this.domain = oArg.domain || 'localhost';
this.username = oArg.username;
this.resource = oArg.resource;
this.pass = oArg.pass;
this.register = oArg.register;
this.authhost = oArg.authhost || this.domain;
this.authtype = oArg.authtype || 'sasl';
if (oArg.xmllang && oArg.xmllang != '')
this._xmllang = oArg.xmllang;
this.host = oArg.host || this.domain;
this.port = oArg.port || 5222;
if (oArg.secure)
this.secure = 'true';
else
this.secure = 'false';
if (oArg.wait)
this._wait = oArg.wait;
this.jid = this.username + '@' + this.domain;
this.fulljid = this.jid + '/' + this.resource;
this._rid = Math.round( 100000.5 + ( ( (900000.49999) - (100000.5) ) * Math.random() ) );
// setupRequest must be done after rid is created but before first use in reqstr
var slot = this._getFreeSlot();
this._req[slot] = this._setupRequest(true);
var reqstr = this._getInitialRequestString();
this.oDbg.log(reqstr,4);
this._req[slot].r.onreadystatechange =
JSJaC.bind(function() {
if (this._req[slot].r.readyState == 4) {
console.log(this._req[slot].r.responseText);
this.oDbg.log("async recv: "+this._req[slot].r.responseText,4);
this._handleInitialResponse(slot); // handle response
}
}, this);
if (typeof(this._req[slot].r.onerror) != 'undefined') {
this._req[slot].r.onerror =
JSJaC.bind(function(e) {
this.oDbg.log('XmlHttpRequest error',1);
return false;
}, this);
}
this._req[slot].r.send(reqstr);
};
/**
* Tells whether this connection is connected
* @return <code>true</code> if this connections is connected,
* <code>false</code> otherwise
* @type boolean
*/
JSJaCConnection.prototype.connected = function() { return this._connected; };
/**
* Disconnects from jabber server and terminates session (if applicable)
*/
JSJaCConnection.prototype.disconnect = function() {
this._setStatus('disconnecting');
if (!this.connected())
return;
this._connected = false;
clearInterval(this._interval);
clearInterval(this._inQto);
if (this._timeout)
clearTimeout(this._timeout); // remove timer
var slot = this._getFreeSlot();
// Intentionally synchronous
this._req[slot] = this._setupRequest(false);
request = this._getRequestString(false, true);
this.oDbg.log("Disconnecting: " + request,4);
this._req[slot].r.send(request);
try {
JSJaCCookie.read('JSJaC_State').erase();
} catch (e) {}
this.oDbg.log("Disconnected: "+this._req[slot].r.responseText,2);
this._handleEvent('ondisconnect');
};
/**
* Gets current value of polling interval
* @return Polling interval in milliseconds
* @type int
*/
JSJaCConnection.prototype.getPollInterval = function() {
return this._timerval;
};
/**
* Registers an event handler (callback) for this connection.
* <p>Note: All of the packet handlers for specific packets (like
* message_in, presence_in and iq_in) fire only if there's no
* callback associated with the id.<br>
* <p>Example:<br/>
* <code>con.registerHandler('iq', 'query', 'jabber:iq:version', handleIqVersion);</code>
* @param {String} event One of
* <ul>
* <li>onConnect - connection has been established and authenticated</li>
* <li>onDisconnect - connection has been disconnected</li>
* <li>onResume - connection has been resumed</li>
* <li>onStatusChanged - connection status has changed, current
* status as being passed argument to handler. See {@link #status}.</li>
* <li>onError - an error has occured, error node is supplied as
* argument, like this:<br><code><error code='404' type='cancel'><br>
* <item-not-found xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/><br>
* </error></code></li>
* <li>packet_in - a packet has been received (argument: the
* packet)</li>
* <li>packet_out - a packet is to be sent(argument: the
* packet)</li>
* <li>message_in | message - a message has been received (argument:
* the packet)</li>
* <li>message_out - a message packet is to be sent (argument: the
* packet)</li>
* <li>presence_in | presence - a presence has been received
* (argument: the packet)</li>
* <li>presence_out - a presence packet is to be sent (argument: the
* packet)</li>
* <li>iq_in | iq - an iq has been received (argument: the packet)</li>
* <li>iq_out - an iq is to be sent (argument: the packet)</li>
* </ul>
* @param {String} childName A childnode's name that must occur within a
* retrieved packet [optional]
* @param {String} childNS A childnode's namespace that must occure within
* a retrieved packet (works only if childName is given) [optional]
* @param {String} type The type of the packet to handle (works only if childName and chidNS are given (both may be set to '*' in order to get skipped) [optional]
* @param {Function} handler The handler to be called when event occurs. If your handler returns 'true' it cancels bubbling of the event. No other registered handlers for this event will be fired.
*/
JSJaCConnection.prototype.registerHandler = function(event) {
event = event.toLowerCase(); // don't be case-sensitive here
var eArg = {handler: arguments[arguments.length-1],
childName: '*',
childNS: '*',
type: '*'};
if (arguments.length > 2)
eArg.childName = arguments[1];
if (arguments.length > 3)
eArg.childNS = arguments[2];
if (arguments.length > 4)
eArg.type = arguments[3];
if (!this._events[event])
this._events[event] = new Array(eArg);
else
this._events[event] = this._events[event].concat(eArg);
// sort events in order how specific they match criterias thus using
// wildcard patterns puts them back in queue when it comes to
// bubbling the event
this._events[event] =
this._events[event].sort(function(a,b) {
var aRank = 0;
var bRank = 0;
with (a) {
if (type == '*')
aRank++;
if (childNS == '*')
aRank++;
if (childName == '*')
aRank++;
}
with (b) {
if (type == '*')
bRank++;
if (childNS == '*')
bRank++;
if (childName == '*')
bRank++;
}
if (aRank > bRank)
return 1;
if (aRank < bRank)
return -1;
return 0;
});
this.oDbg.log("registered handler for event '"+event+"'",2);
};
JSJaCConnection.prototype.unregisterHandler = function(event,handler) {
event = event.toLowerCase(); // don't be case-sensitive here
if (!this._events[event])
return;
var arr = this._events[event], res = new Array();
for (var i=0; i<arr.length; i++)
if (arr[i].handler != handler)
res.push(arr[i]);
if (arr.length != res.length) {
this._events[event] = res;
this.oDbg.log("unregistered handler for event '"+event+"'",2);
}
};
/**
* Register for iq packets of type 'get'.
* @param {String} childName A childnode's name that must occur within a
* retrieved packet
* @param {String} childNS A childnode's namespace that must occure within
* a retrieved packet (works only if childName is given)
* @param {Function} handler The handler to be called when event occurs. If your handler returns 'true' it cancels bubbling of the event. No other registered handlers for this event will be fired.
*/
JSJaCConnection.prototype.registerIQGet =
function(childName, childNS, handler) {
this.registerHandler('iq', childName, childNS, 'get', handler);
};
/**
* Register for iq packets of type 'set'.
* @param {String} childName A childnode's name that must occur within a
* retrieved packet
* @param {String} childNS A childnode's namespace that must occure within
* a retrieved packet (works only if childName is given)
* @param {Function} handler The handler to be called when event occurs. If your handler returns 'true' it cancels bubbling of the event. No other registered handlers for this event will be fired.
*/
JSJaCConnection.prototype.registerIQSet =
function(childName, childNS, handler) {
this.registerHandler('iq', childName, childNS, 'set', handler);
};
/**
* Resumes this connection from saved state (cookie)
* @return Whether resume was successful
* @type boolean
*/
JSJaCConnection.prototype.resume = function() {
try {
this._setStatus('resuming');
var s = unescape(JSJaCCookie.read('JSJaC_State').getValue());
this.oDbg.log('read cookie: '+s,2);
var o = JSJaCJSON.parse(s);
for (var i in o)
if (o.hasOwnProperty(i))
this[i] = o[i];
// copy keys - not being very generic here :-/
if (this._keys) {
this._keys2 = new JSJaCKeys();
var u = this._keys2._getSuspendVars();
for (var i=0; i<u.length; i++)
this._keys2[u[i]] = this._keys[u[i]];
this._keys = this._keys2;
}
try {
JSJaCCookie.read('JSJaC_State').erase();
} catch (e) {}
if (this._connected) {
// don't poll too fast!
this._handleEvent('onresume');
setTimeout(JSJaC.bind(this._resume, this),this.getPollInterval());
this._interval = setInterval(JSJaC.bind(this._checkQueue, this),
JSJAC_CHECKQUEUEINTERVAL);
this._inQto = setInterval(JSJaC.bind(this._checkInQ, this),
JSJAC_CHECKINQUEUEINTERVAL);
}
return (this._connected === true);
} catch (e) {
if (e.message)
this.oDbg.log("Resume failed: "+e.message, 1);
else
this.oDbg.log("Resume failed: "+e, 1);
return false;
}
};
/**
* Sends a JSJaCPacket
* @param {JSJaCPacket} packet The packet to send
* @param {Function} cb The callback to be called if there's a reply
* to this packet (identified by id) [optional]
* @param {Object} arg Arguments passed to the callback
* (additionally to the packet received) [optional]
* @return 'true' if sending was successfull, 'false' otherwise
* @type boolean
*/
JSJaCConnection.prototype.send = function(packet,cb,arg) {
if (!packet || !packet.pType) {
this.oDbg.log("no packet: "+packet, 1);
return false;
}
if (!this.connected())
return false;
// remember id for response if callback present
if (cb) {
if (!packet.getID())
packet.setID('JSJaCID_'+this._ID++); // generate an ID
// register callback with id
this._registerPID(packet.getID(),cb,arg);
}
try {
this._handleEvent(packet.pType()+'_out', packet);
this._handleEvent("packet_out", packet);
this._pQueue = this._pQueue.concat(packet.xml());
} catch (e) {
this.oDbg.log(e.toString(),1);
return false;
}
return true;
};
/**
* Sends an IQ packet. Has default handlers for each reply type.
* Those maybe overriden by passing an appropriate handler.
* @param {JSJaCIQPacket} iq - the iq packet to send
* @param {Object} handlers - object with properties 'error_handler',
* 'result_handler' and 'default_handler'
* with appropriate functions
* @param {Object} arg - argument to handlers
* @return 'true' if sending was successfull, 'false' otherwise
* @type boolean
*/
JSJaCConnection.prototype.sendIQ = function(iq, handlers, arg) {
if (!iq || iq.pType() != 'iq') {
return false;
}
handlers = handlers || {};
var error_handler = handlers.error_handler || function(aIq) {
this.oDbg.log(iq.xml(), 1);
};
var result_handler = handlers.result_handler || function(aIq) {
this.oDbg.log(aIq.xml(), 2);
};
// unsure, what's the use of this?
var default_handler = handlers.default_handler || function(aIq) {
this.oDbg.log(aIq.xml(), 2);
};
var iqHandler = function(aIq, arg) {
switch (aIq.getType()) {
case 'error':
error_handler(aIq);
break;
case 'result':
result_handler(aIq, arg);
break;
default: // may it be?
default_handler(aIq, arg);
}
};
return this.send(iq, iqHandler, arg);
};
/**
* Sets polling interval for this connection
* @param {int} millisecs Milliseconds to set timer to
* @return effective interval this connection has been set to
* @type int
*/
JSJaCConnection.prototype.setPollInterval = function(timerval) {
if (timerval && !isNaN(timerval))
this._timerval = timerval;
return this._timerval;
};
/**
* Returns current status of this connection
* @return String to denote current state. One of
* <ul>
* <li>'initializing' ... well
* <li>'connecting' if connect() was called
* <li>'resuming' if resume() was called
* <li>'processing' if it's about to operate as normal
* <li>'onerror_fallback' if there was an error with the request object
* <li>'protoerror_fallback' if there was an error at the http binding protocol flow (most likely that's where you interested in)
* <li>'internal_server_error' in case of an internal server error
* <li>'suspending' if suspend() is being called
* <li>'aborted' if abort() was called
* <li>'disconnecting' if disconnect() has been called
* </ul>
* @type String
*/
JSJaCConnection.prototype.status = function() { return this._status; };
/**
* Suspsends this connection (saving state for later resume)
*/
JSJaCConnection.prototype.suspend = function() {
// remove timers
clearTimeout(this._timeout);
clearInterval(this._interval);
clearInterval(this._inQto);
this._suspend();
var u = ('_connected,_keys,_ID,_inQ,_pQueue,_regIDs,_errcnt,_inactivity,domain,username,resource,jid,fulljid,_sid,_httpbase,_timerval,_is_polling').split(',');
u = u.concat(this._getSuspendVars());
var s = new Object();
for (var i=0; i<u.length; i++) {
if (!this[u[i]]) continue; // hu? skip these!
if (this[u[i]]._getSuspendVars) {
var uo = this[u[i]]._getSuspendVars();
var o = new Object();
for (var j=0; j<uo.length; j++)
o[uo[j]] = this[u[i]][uo[j]];
} else
var o = this[u[i]];
s[u[i]] = o;
}
var c = new JSJaCCookie('JSJaC_State', escape(JSJaCJSON.toString(s)),
this._inactivity);
this.oDbg.log("writing cookie: "+unescape(c.value)+"\n(length:"+
unescape(c.value).length+")",2);
c.write();
try {
var c2 = JSJaCCookie.read('JSJaC_State');
if (c.value != c2.value) {
this.oDbg.log("Suspend failed writing cookie.\nRead: "+
unescape(JSJaCCookie.read('JSJaC_State')), 1);
c.erase();
}
this._connected = false;
this._setStatus('suspending');
} catch (e) {
this.oDbg.log("Failed reading cookie 'JSJaC_State': "+e.message);
}
};
/**
* @private
*/
JSJaCConnection.prototype._abort = function() {
clearTimeout(this._timeout); // remove timer
clearInterval(this._inQto);
clearInterval(this._interval);
this._connected = false;
this._setStatus('aborted');
this.oDbg.log("Disconnected.",1);
this._handleEvent('ondisconnect');
this._handleEvent('onerror',
JSJaCError('500','cancel','service-unavailable'));
};
/**
* @private
*/
JSJaCConnection.prototype._checkInQ = function() {
for (var i=0; i<this._inQ.length && i<10; i++) {
var item = this._inQ[0];
this._inQ = this._inQ.slice(1,this._inQ.length);
var packet = JSJaCPacket.wrapNode(item);
if (!packet)
return;
this._handleEvent("packet_in", packet);
if (packet.pType && !this._handlePID(packet)) {
this._handleEvent(packet.pType()+'_in',packet);
this._handleEvent(packet.pType(),packet);
}
}
};
/**
* @private
*/
JSJaCConnection.prototype._checkQueue = function() {
if (this._pQueue.length != 0)
this._process();
return true;
};
/**
* @private
*/
JSJaCConnection.prototype._doAuth = function() {
if (this.has_sasl && this.authtype == 'nonsasl')
this.oDbg.log("Warning: SASL present but not used", 1);
if (!this._doSASLAuth() &&
!this._doLegacyAuth()) {
this.oDbg.log("Auth failed for authtype "+this.authtype,1);
this.disconnect();
return false;
}
return true;
};
/**
* @private
*/
JSJaCConnection.prototype._doInBandReg = function() {
if (this.authtype == 'saslanon' || this.authtype == 'anonymous')
return; // bullshit - no need to register if anonymous
/* ***
* In-Band Registration see JEP-0077
*/
var iq = new JSJaCIQ();
iq.setType('set');
iq.setID('reg1');
iq.appendNode("query", {xmlns: "jabber:iq:register"},
[["username", this.username],
["password", this.pass]]);
this.send(iq,this._doInBandRegDone);
};
/**
* @private
*/
JSJaCConnection.prototype._doInBandRegDone = function(iq) {
if (iq && iq.getType() == 'error') { // we failed to register
this.oDbg.log("registration failed for "+this.username,0);
this._handleEvent('onerror',iq.getChild('error'));
return;
}
this.oDbg.log(this.username + " registered succesfully",0);
this._doAuth();
};
/**
* @private
*/
JSJaCConnection.prototype._doLegacyAuth = function() {
if (this.authtype != 'nonsasl' && this.authtype != 'anonymous')
return false;
/* ***
* Non-SASL Authentication as described in JEP-0078
*/
var iq = new JSJaCIQ();
iq.setIQ(this.server,'get','auth1');
iq.appendNode('query', {xmlns: 'jabber:iq:auth'},
[['username', this.username]]);
this.send(iq,this._doLegacyAuth2);
return true;
};
/**
* @private
*/
JSJaCConnection.prototype._doLegacyAuth2 = function(iq) {
if (!iq || iq.getType() != 'result') {
if (iq && iq.getType() == 'error')
this._handleEvent('onerror',iq.getChild('error'));
this.disconnect();
return;
}
var use_digest = (iq.getChild('digest') != null);
/* ***
* Send authentication
*/
var iq = new JSJaCIQ();
iq.setIQ(this.server,'set','auth2');
query = iq.appendNode('query', {xmlns: 'jabber:iq:auth'},
[['username', this.username],
['resource', this.resource]]);
if (use_digest) { // digest login
query.appendChild(iq.buildNode('digest', {xmlns: 'jabber:iq:auth'},
hex_sha1(this.streamid + this.pass)));
} else if (this.allow_plain) { // use plaintext auth
query.appendChild(iq.buildNode('password', {xmlns: 'jabber:iq:auth'},
this.pass));
} else {
this.oDbg.log("no valid login mechanism found",1);
this.disconnect();
return false;
}
this.send(iq,this._doLegacyAuthDone);
};
/**
* @private
*/
JSJaCConnection.prototype._doLegacyAuthDone = function(iq) {
if (iq.getType() != 'result') { // auth' failed
if (iq.getType() == 'error')
this._handleEvent('onerror',iq.getChild('error'));
this.disconnect();
} else
this._handleEvent('onconnect');
};
/**
* @private
*/
JSJaCConnection.prototype._doSASLAuth = function() {
if (this.authtype == 'nonsasl' || this.authtype == 'anonymous')
return false;
if (this.authtype == 'saslanon') {
if (this.mechs['ANONYMOUS']) {
this.oDbg.log("SASL using mechanism 'ANONYMOUS'",2);
return this._sendRaw("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS'/>",
this._doSASLAuthDone);
}
this.oDbg.log("SASL ANONYMOUS requested but not supported",1);
} else {
if (this.mechs['DIGEST-MD5']) {
this.oDbg.log("SASL using mechanism 'DIGEST-MD5'",2);
return this._sendRaw("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='DIGEST-MD5'/>",
this._doSASLAuthDigestMd5S1);
} else if (this.allow_plain && this.mechs['PLAIN']) {
this.oDbg.log("SASL using mechanism 'PLAIN'",2);
var authStr = this.username+'@'+
this.domain+String.fromCharCode(0)+
this.username+String.fromCharCode(0)+
this.pass;
this.oDbg.log("authenticating with '"+authStr+"'",2);
authStr = btoa(authStr);
return this._sendRaw("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>"+authStr+"</auth>",
this._doSASLAuthDone);
}
this.oDbg.log("No SASL mechanism applied",1);
this.authtype = 'nonsasl'; // fallback
}
return false;
};
/**
* @private
*/
JSJaCConnection.prototype._doSASLAuthDigestMd5S1 = function(el) {
if (el.nodeName != "challenge") {
this.oDbg.log("challenge missing",1);
this._handleEvent('onerror',JSJaCError('401','auth','not-authorized'));
this.disconnect();
} else {
var challenge = atob(el.firstChild.nodeValue);
this.oDbg.log("got challenge: "+challenge,2);
this._nonce = challenge.substring(challenge.indexOf("nonce=")+7);
this._nonce = this._nonce.substring(0,this._nonce.indexOf("\""));
this.oDbg.log("nonce: "+this._nonce,2);
if (this._nonce == '' || this._nonce.indexOf('\"') != -1) {
this.oDbg.log("nonce not valid, aborting",1);
this.disconnect();
return;
}
this._digest_uri = "xmpp/";
// if (typeof(this.host) != 'undefined' && this.host != '') {
// this._digest-uri += this.host;
// if (typeof(this.port) != 'undefined' && this.port)
// this._digest-uri += ":" + this.port;
// this._digest-uri += '/';
// }
this._digest_uri += this.domain;
this._cnonce = cnonce(14);
this._nc = '00000001';
var A1 = str_md5(this.username+':'+this.domain+':'+this.pass)+
':'+this._nonce+':'+this._cnonce;
var A2 = 'AUTHENTICATE:'+this._digest_uri;
var response = hex_md5(hex_md5(A1)+':'+this._nonce+':'+this._nc+':'+
this._cnonce+':auth:'+hex_md5(A2));
var rPlain = 'username="'+this.username+'",realm="'+this.domain+
'",nonce="'+this._nonce+'",cnonce="'+this._cnonce+'",nc="'+this._nc+
'",qop=auth,digest-uri="'+this._digest_uri+'",response="'+response+
'",charset=utf-8';
this.oDbg.log("response: "+rPlain,2);
this._sendRaw("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>"+
binb2b64(str2binb(rPlain))+"</response>",
this._doSASLAuthDigestMd5S2);
}
};
/**
* @private
*/
JSJaCConnection.prototype._doSASLAuthDigestMd5S2 = function(el) {
if (el.nodeName == 'failure') {
if (el.xml)
this.oDbg.log("auth error: "+el.xml,1);
else
this.oDbg.log("auth error",1);
this._handleEvent('onerror',JSJaCError('401','auth','not-authorized'));
this.disconnect();
return;
}
var response = atob(el.firstChild.nodeValue);
this.oDbg.log("response: "+response,2);
var rspauth = response.substring(response.indexOf("rspauth=")+8);
this.oDbg.log("rspauth: "+rspauth,2);
var A1 = str_md5(this.username+':'+this.domain+':'+this.pass)+
':'+this._nonce+':'+this._cnonce;
var A2 = ':'+this._digest_uri;
var rsptest = hex_md5(hex_md5(A1)+':'+this._nonce+':'+this._nc+':'+
this._cnonce+':auth:'+hex_md5(A2));
this.oDbg.log("rsptest: "+rsptest,2);
if (rsptest != rspauth) {
this.oDbg.log("SASL Digest-MD5: server repsonse with wrong rspauth",1);
this.disconnect();
return;
}
if (el.nodeName == 'success')
this._reInitStream(this.domain, this._doStreamBind);
else // some extra turn
this._sendRaw("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>",
this._doSASLAuthDone);
};
/**
* @private
*/
JSJaCConnection.prototype._doSASLAuthDone = function (el) {
if (el.nodeName != 'success') {
this.oDbg.log("auth failed",1);
this._handleEvent('onerror',JSJaCError('401','auth','not-authorized'));
this.disconnect();
} else
this._reInitStream(this.domain, this._doStreamBind);
};
/**
* @private
*/
JSJaCConnection.prototype._doStreamBind = function() {
var iq = new JSJaCIQ();
iq.setIQ(this.domain,'set','bind_1');
iq.appendNode("bind", {xmlns: "urn:ietf:params:xml:ns:xmpp-bind"},
[["resource", this.resource]]);
this.oDbg.log(iq.xml());
this.send(iq,this._doXMPPSess);
};
/**
* @private
*/
JSJaCConnection.prototype._doXMPPSess = function(iq) {
if (iq.getType() != 'result' || iq.getType() == 'error') { // failed
this.disconnect();
if (iq.getType() == 'error')
this._handleEvent('onerror',iq.getChild('error'));
return;
}
this.fulljid = iq.getChildVal("jid");
this.jid = this.fulljid.substring(0,this.fulljid.lastIndexOf('/'));
iq = new JSJaCIQ();
iq.setIQ(this.domain,'set','sess_1');
iq.appendNode("session", {xmlns: "urn:ietf:params:xml:ns:xmpp-session"},
[]);
this.oDbg.log(iq.xml());
this.send(iq,this._doXMPPSessDone);
};
/**
* @private
*/
JSJaCConnection.prototype._doXMPPSessDone = function(iq) {
if (iq.getType() != 'result' || iq.getType() == 'error') { // failed
this.disconnect();
if (iq.getType() == 'error')
this._handleEvent('onerror',iq.getChild('error'));
return;
} else
this._handleEvent('onconnect');
};
/**
* @private
*/
JSJaCConnection.prototype._handleEvent = function(event,arg) {
event = event.toLowerCase(); // don't be case-sensitive here
this.oDbg.log("incoming event '"+event+"'",3);
if (!this._events[event])
return;
this.oDbg.log("handling event '"+event+"'",2);
for (var i=0;i<this._events[event].length; i++) {
var aEvent = this._events[event][i];
if (aEvent.handler) {
try {
if (arg) {
if (arg.pType) { // it's a packet
if ((!arg.getNode().hasChildNodes() && aEvent.childName != '*') ||
(arg.getNode().hasChildNodes() &&
!arg.getChild(aEvent.childName, aEvent.childNS)))
continue;
if (aEvent.type != '*' &&
arg.getType() != aEvent.type)
continue;
this.oDbg.log(aEvent.childName+"/"+aEvent.childNS+"/"+aEvent.type+" => match for handler "+aEvent.handler,3);
}
if (aEvent.handler.call(this,arg)) // handled!
break;
}
else
if (aEvent.handler.call(this)) // handled!
break;
} catch (e) { console.error(e.stack);this.oDbg.log(aEvent.handler+"\n>>>"+e.name+": "+ e.message,1); }
}
}
};
/**
* @private
*/
JSJaCConnection.prototype._handlePID = function(aJSJaCPacket) {
if (!aJSJaCPacket.getID())
return false;
for (var i in this._regIDs) {
if (this._regIDs.hasOwnProperty(i) &&
this._regIDs[i] && i == aJSJaCPacket.getID()) {
var pID = aJSJaCPacket.getID();
this.oDbg.log("handling "+pID,3);
try {
if (this._regIDs[i].cb.call(this, aJSJaCPacket,this._regIDs[i].arg) === false) {
// don't unregister
return false;
} else {
this._unregisterPID(pID);
return true;
}
} catch (e) {
// broken handler?
this.oDbg.log(e.name+": "+ e.message);
this._unregisterPID(pID);
return true;
}
}
}
return false;
};
/**
* @private
*/
JSJaCConnection.prototype._handleResponse = function(req) {
var rootEl = this._parseResponse(req);
if (!rootEl)
return;
for (var i=0; i<rootEl.childNodes.length; i++) {
if (this._sendRawCallbacks.length) {
var cb = this._sendRawCallbacks[0];
this._sendRawCallbacks = this._sendRawCallbacks.slice(1, this._sendRawCallbacks.length);
cb.fn.call(this, rootEl.childNodes.item(i), cb.arg);
continue;
}
this._inQ = this._inQ.concat(rootEl.childNodes.item(i));
}
};
/**
* @private
*/
JSJaCConnection.prototype._parseStreamFeatures = function(doc) {
if (!doc) {
this.oDbg.log("nothing to parse ... aborting",1);
return false;
}
var errorTag;
if (doc.getElementsByTagNameNS)
errorTag = doc.getElementsByTagNameNS("http://etherx.jabber.org/streams", "error").item(0);
else {
var errors = doc.getElementsByTagName("error");
for (var i=0; i<errors.length; i++)
if (errors.item(i).namespaceURI == "http://etherx.jabber.org/streams") {
errorTag = errors.item(i);
break;
}
}
if (errorTag) {
this._setStatus("internal_server_error");
clearTimeout(this._timeout); // remove timer
clearInterval(this._interval);
clearInterval(this._inQto);
this._handleEvent('onerror',JSJaCError('503','cancel','session-terminate'));
this._connected = false;
this.oDbg.log("Disconnected.",1);
this._handleEvent('ondisconnect');
return false;
}
this.mechs = new Object();
var lMec1 = doc.getElementsByTagName("mechanisms");
this.has_sasl = false;
for (var i=0; i<lMec1.length; i++)
if (lMec1.item(i).getAttribute("xmlns") ==
"urn:ietf:params:xml:ns:xmpp-sasl") {
this.has_sasl=true;
var lMec2 = lMec1.item(i).getElementsByTagName("mechanism");
for (var j=0; j<lMec2.length; j++)
this.mechs[lMec2.item(j).firstChild.nodeValue] = true;
break;
}
this.has_sasl = false;
if (this.has_sasl)
this.oDbg.log("SASL detected",2);
else {
this.authtype = 'nonsasl';
this.oDbg.log("No support for SASL detected",2);
}
/* [TODO]
* check if in-band registration available
* check for session and bind features
*/
return true;
};
/**
* @private
*/
JSJaCConnection.prototype._process = function(timerval) {
if (!this.connected()) {
this.oDbg.log("Connection lost ...",1);
if (this._interval)
clearInterval(this._interval);
return;
}
this.setPollInterval(timerval);
if (this._timeout)
clearTimeout(this._timeout);
var slot = this._getFreeSlot();
if (slot < 0)
return;
if (typeof(this._req[slot]) != 'undefined' &&
typeof(this._req[slot].r) != 'undefined' &&
this._req[slot].r.readyState != 4) {
this.oDbg.log("Slot "+slot+" is not ready");
return;
}
if (!this.isPolling() && this._pQueue.length == 0 &&
this._req[(slot+1)%2] && this._req[(slot+1)%2].r.readyState != 4) {
this.oDbg.log("all slots busy, standby ...", 2);
return;
}
if (!this.isPolling())
this.oDbg.log("Found working slot at "+slot,2);
this._req[slot] = this._setupRequest(true);
/* setup onload handler for async send */
this._req[slot].r.onreadystatechange =
JSJaC.bind(function() {
if (!this.connected())
return;
if (this._req[slot].r.readyState == 4) {
this._setStatus('processing');
this.oDbg.log("async recv: "+this._req[slot].r.responseText,4);
this._handleResponse(this._req[slot]);
// schedule next tick
if (this._pQueue.length) {
this._timeout = setTimeout(JSJaC.bind(this._process, this),100);
} else {
this.oDbg.log("scheduling next poll in "+this.getPollInterval()+
" msec", 4);
this._timeout = setTimeout(JSJaC.bind(this._process, this),this.getPollInterval());
}
}
}, this);
try {
this._req[slot].r.onerror =
JSJaC.bind(function() {
if (!this.connected())
return;
this._errcnt++;
this.oDbg.log('XmlHttpRequest error ('+this._errcnt+')',1);
if (this._errcnt > JSJAC_ERR_COUNT) {
// abort
this._abort();
return false;
}
this._setStatus('onerror_fallback');
// schedule next tick
setTimeout(JSJaC.bind(this._resume, this),this.getPollInterval());
return false;
}, this);
} catch(e) { } // well ... no onerror property available, maybe we
// can catch the error somewhere else ...
var reqstr = this._getRequestString();
if (typeof(this._rid) != 'undefined') // remember request id if any
this._req[slot].rid = this._rid;
this.oDbg.log("sending: " + reqstr,4);
this._req[slot].r.send(reqstr);
};
/**
* @private
*/
JSJaCConnection.prototype._registerPID = function(pID,cb,arg) {
if (!pID || !cb)
return false;
this._regIDs[pID] = new Object();
this._regIDs[pID].cb = cb;
if (arg)
this._regIDs[pID].arg = arg;
this.oDbg.log("registered "+pID,3);
return true;
};
/**
* send empty request
* waiting for stream id to be able to proceed with authentication
* @private
*/
JSJaCConnection.prototype._sendEmpty = function JSJaCSendEmpty() {
var slot = this._getFreeSlot();
this._req[slot] = this._setupRequest(true);
this._req[slot].r.onreadystatechange =
JSJaC.bind(function() {
if (this._req[slot].r.readyState == 4) {
this.oDbg.log("async recv: "+this._req[slot].r.responseText,4);
this._getStreamID(slot); // handle response
}
},this);
if (typeof(this._req[slot].r.onerror) != 'undefined') {
this._req[slot].r.onerror =
JSJaC.bind(function(e) {
this.oDbg.log('XmlHttpRequest error',1);
return false;
}, this);
}
var reqstr = this._getRequestString();
this.oDbg.log("sending: " + reqstr,4);
this._req[slot].r.send(reqstr);
};
/**
* @private
*/
JSJaCConnection.prototype._sendRaw = function(xml,cb,arg) {
if (cb)
this._sendRawCallbacks.push({fn: cb, arg: arg});
this._pQueue.push(xml);
this._process();
return true;
};
/**
* @private
*/
JSJaCConnection.prototype._setStatus = function(status) {
if (!status || status == '')
return;
if (status != this._status) { // status changed!
this._status = status;
this._handleEvent('onstatuschanged', status);
this._handleEvent('status_changed', status);
}
};
/**
* @private
*/
JSJaCConnection.prototype._unregisterPID = function(pID) {
if (!this._regIDs[pID])
return false;
this._regIDs[pID] = null;
this.oDbg.log("unregistered "+pID,3);
return true;
};
/**
* @fileoverview All stuff related to HTTP Binding
* @author Stefan Strigler steve@zeank.in-berlin.de
* @version $Revision: 483 $
*/
/**
* Instantiates an HTTP Binding session
* @class Implementation of {@link
* http://www.xmpp.org/extensions/xep-0206.html XMPP Over BOSH}
* formerly known as HTTP Binding.
* @extends JSJaCConnection
* @constructor
*/
function JSJaCHttpBindingConnection(oArg) {
/**
* @ignore
*/
this.base = JSJaCConnection;
this.base(oArg);
// member vars
/**
* @private
*/
this._hold = JSJACHBC_MAX_HOLD;
/**
* @private
*/
this._inactivity = 0;
/**
* @private
*/
this._last_requests = new Object(); // 'hash' storing hold+1 last requests
/**
* @private
*/
this._last_rid = 0; // I know what you did last summer
/**
* @private
*/
this._min_polling = 0;
/**
* @private
*/
this._pause = 0;
/**
* @private
*/
this._wait = JSJACHBC_MAX_WAIT;
}
JSJaCHttpBindingConnection.prototype = new JSJaCConnection();
/**
* Inherit an instantiated HTTP Binding session
*/
JSJaCHttpBindingConnection.prototype.inherit = function(oArg) {
this.domain = oArg.domain || 'localhost';
this.username = oArg.username;
this.resource = oArg.resource;
this._sid = oArg.sid;
this._rid = oArg.rid;
this._min_polling = oArg.polling;
this._inactivity = oArg.inactivity;
this._setHold(oArg.requests-1);
this.setPollInterval(this._timerval);
if (oArg.wait)
this._wait = oArg.wait; // for whatever reason
this._connected = true;
this._handleEvent('onconnect');
this._interval= setInterval(JSJaC.bind(this._checkQueue, this),
JSJAC_CHECKQUEUEINTERVAL);
this._inQto = setInterval(JSJaC.bind(this._checkInQ, this),
JSJAC_CHECKINQUEUEINTERVAL);
this._timeout = setTimeout(JSJaC.bind(this._process, this),
this.getPollInterval());
};
/**
* Sets poll interval
* @param {int} timerval the interval in seconds
*/
JSJaCHttpBindingConnection.prototype.setPollInterval = function(timerval) {
if (timerval && !isNaN(timerval)) {
if (!this.isPolling())
this._timerval = 100;
else if (this._min_polling && timerval < this._min_polling*1000)
this._timerval = this._min_polling*1000;
else if (this._inactivity && timerval > this._inactivity*1000)
this._timerval = this._inactivity*1000;
else
this._timerval = timerval;
}
return this._timerval;
};
/**
* whether this session is in polling mode
* @type boolean
*/
JSJaCHttpBindingConnection.prototype.isPolling = function() { return (this._hold == 0) };
/**
* @private
*/
JSJaCHttpBindingConnection.prototype._getFreeSlot = function() {
for (var i=0; i<this._hold+1; i++)
if (typeof(this._req[i]) == 'undefined' || typeof(this._req[i].r) == 'undefined' || this._req[i].r.readyState == 4)
return i;
return -1; // nothing found
};
/**
* @private
*/
JSJaCHttpBindingConnection.prototype._getHold = function() { return this._hold; };
/**
* @private
*/
JSJaCHttpBindingConnection.prototype._getRequestString = function(raw, last) {
raw = raw || '';
var reqstr = '';
// check if we're repeating a request
if (this._rid <= this._last_rid && typeof(this._last_requests[this._rid]) != 'undefined') // repeat!
reqstr = this._last_requests[this._rid].xml;
else { // grab from queue
var xml = '';
while (this._pQueue.length) {
var curNode = this._pQueue[0];
xml += curNode;
this._pQueue = this._pQueue.slice(1,this._pQueue.length);
}
reqstr = "<body rid='"+this._rid+"' sid='"+this._sid+"' xmlns='http://jabber.org/protocol/httpbind' ";
if (JSJAC_HAVEKEYS) {
reqstr += "key='"+this._keys.getKey()+"' ";
if (this._keys.lastKey()) {
this._keys = new JSJaCKeys(hex_sha1,this.oDbg);
reqstr += "newkey='"+this._keys.getKey()+"' ";
}
}
if (last)
reqstr += "type='terminate'";
else if (this._reinit) {
if (JSJACHBC_USE_BOSH_VER)
reqstr += "xmpp:restart='true' xmlns:xmpp='urn:xmpp:xbosh'";
this._reinit = false;
}
if (xml != '' || raw != '') {
reqstr += ">" + raw + xml + "</body>";
} else {
reqstr += "/>";
}
this._last_requests[this._rid] = new Object();
this._last_requests[this._rid].xml = reqstr;
this._last_rid = this._rid;
for (var i in this._last_requests)
if (this._last_requests.hasOwnProperty(i) &&
i < this._rid-this._hold)
delete(this._last_requests[i]); // truncate
}
return reqstr;
};
/**
* @private
*/
JSJaCHttpBindingConnection.prototype._getInitialRequestString = function() {
var reqstr = "<body content='text/xml; charset=utf-8' hold='"+this._hold+"' xmlns='http://jabber.org/protocol/httpbind' to='"+this.authhost+"' wait='"+this._wait+"' rid='"+this._rid+"'";
if (this.host || this.port)
reqstr += " route='xmpp:"+this.host+":"+this.port+"'";
if (this.secure)
reqstr += " secure='"+this.secure+"'";
if (JSJAC_HAVEKEYS) {
this._keys = new JSJaCKeys(hex_sha1,this.oDbg); // generate first set of keys
key = this._keys.getKey();
reqstr += " newkey='"+key+"'";
}
if (this._xmllang)
reqstr += " xml:lang='"+this._xmllang + "'";
if (JSJACHBC_USE_BOSH_VER) {
reqstr += " ver='" + JSJACHBC_BOSH_VERSION + "'";
reqstr += " xmlns:xmpp='urn:xmpp:xbosh'";
if (this.authtype == 'sasl' || this.authtype == 'saslanon')
reqstr += " xmpp:version='1.0'";
}
reqstr += "/>";
return reqstr;
};
/**
* @private
*/
JSJaCHttpBindingConnection.prototype._getStreamID = function(slot) {
this.oDbg.log(this._req[slot].r.responseText,4);
if (!this._req[slot].r.responseXML || !this._req[slot].r.responseXML.documentElement) {
this._handleEvent('onerror',JSJaCError('503','cancel','service-unavailable'));
return;
}
var body = this._req[slot].r.responseXML.documentElement;
// extract stream id used for non-SASL authentication
if (body.getAttribute('authid')) {
this.streamid = body.getAttribute('authid');
this.oDbg.log("got streamid: "+this.streamid,2);
} else {
this._timeout = setTimeout(JSJaC.bind(this._sendEmpty, this),
this.getPollInterval());
return;
}
this._timeout = setTimeout(JSJaC.bind(this._process, this),
this.getPollInterval());
if (!this._parseStreamFeatures(body))
return;
if (this.register)
this._doInBandReg();
else
this._doAuth();
};
/**
* @private
*/
JSJaCHttpBindingConnection.prototype._getSuspendVars = function() {
return ('host,port,secure,_rid,_last_rid,_wait,_min_polling,_inactivity,_hold,_last_requests,_pause').split(',');
};
/**
* @private
*/
JSJaCHttpBindingConnection.prototype._handleInitialResponse = function(slot) {
try {
// This will throw an error on Mozilla when the connection was refused
this.oDbg.log(this._req[slot].r.getAllResponseHeaders(),4);
this.oDbg.log(this._req[slot].r.responseText,4);
} catch(ex) {
this.oDbg.log("No response",4);
}
if (this._req[slot].r.status != 200 || !this._req[slot].r.responseXML) {
this.oDbg.log("initial response broken (status: "+this._req[slot].r.status+")",1);
this._handleEvent('onerror',JSJaCError('503','cancel','service-unavailable'));
return;
}
var body = this._req[slot].r.responseXML.documentElement;
if (!body || body.tagName != 'body' || body.namespaceURI != 'http://jabber.org/protocol/httpbind') {
this.oDbg.log("no body element or incorrect body in initial response",1);
this._handleEvent("onerror",JSJaCError("500","wait","internal-service-error"));
return;
}
// Check for errors from the server
if (body.getAttribute("type") == "terminate") {
this.oDbg.log("invalid response:\n" + this._req[slot].r.responseText,1);
clearTimeout(this._timeout); // remove timer
this._connected = false;
this.oDbg.log("Disconnected.",1);
this._handleEvent('ondisconnect');
this._handleEvent('onerror',JSJaCError('503','cancel','service-unavailable'));
return;
}
// get session ID
this._sid = body.getAttribute('sid');
this.oDbg.log("got sid: "+this._sid,2);
// get attributes from response body
if (body.getAttribute('polling'))
this._min_polling = body.getAttribute('polling');
if (body.getAttribute('inactivity'))
this._inactivity = body.getAttribute('inactivity');
if (body.getAttribute('requests'))
this._setHold(body.getAttribute('requests')-1);
this.oDbg.log("set hold to " + this._getHold(),2);
if (body.getAttribute('ver'))
this._bosh_version = body.getAttribute('ver');
if (body.getAttribute('maxpause'))
this._pause = Number.max(body.getAttribute('maxpause'), JSJACHBC_MAXPAUSE);
// must be done after response attributes have been collected
this.setPollInterval(this._timerval);
/* start sending from queue for not polling connections */
this._connected = true;
this._inQto = setInterval(JSJaC.bind(this._checkInQ, this),
JSJAC_CHECKINQUEUEINTERVAL);
this._interval= setInterval(JSJaC.bind(this._checkQueue, this),
JSJAC_CHECKQUEUEINTERVAL);
/* wait for initial stream response to extract streamid needed
* for digest auth
*/
this._getStreamID(slot);
};
/**
* @private
*/
JSJaCHttpBindingConnection.prototype._parseResponse = function(req) {
if (!this.connected() || !req)
return null;
var r = req.r; // the XmlHttpRequest
try {
if (r.status == 404 || r.status == 403) {
// connection manager killed session
this._abort();
return null;
}
if (r.status != 200 || !r.responseXML) {
this._errcnt++;
var errmsg = "invalid response ("+r.status+"):\n" + r.getAllResponseHeaders()+"\n"+r.responseText;
if (!r.responseXML)
errmsg += "\nResponse failed to parse!";
this.oDbg.log(errmsg,1);
if (this._errcnt > JSJAC_ERR_COUNT) {
// abort
this._abort();
return null;
}
this.oDbg.log("repeating ("+this._errcnt+")",1);
console.log(r.status, r.responseXML);
this._setStatus('proto_error_fallback');
// schedule next tick
setTimeout(JSJaC.bind(this._resume, this),
this.getPollInterval());
return null;
}
} catch (e) {
this.oDbg.log("XMLHttpRequest error: status not available", 1);
this._errcnt++;
if (this._errcnt > JSJAC_ERR_COUNT) {
// abort
this._abort();
} else {
this.oDbg.log("repeating ("+this._errcnt+")",1);
this._setStatus('proto_error_fallback');
// schedule next tick
setTimeout(JSJaC.bind(this._resume, this),
this.getPollInterval());
}
return null;
}
var body = r.responseXML.documentElement;
if (!body || body.tagName != 'body' ||
body.namespaceURI != 'http://jabber.org/protocol/httpbind') {
this.oDbg.log("invalid response:\n" + r.responseText,1);
clearTimeout(this._timeout); // remove timer
clearInterval(this._interval);
clearInterval(this._inQto);
this._connected = false;
this.oDbg.log("Disconnected.",1);
this._handleEvent('ondisconnect');
this._setStatus('internal_server_error');
this._handleEvent('onerror',
JSJaCError('500','wait','internal-server-error'));
return null;
}
if (typeof(req.rid) != 'undefined' && this._last_requests[req.rid]) {
if (this._last_requests[req.rid].handled) {
this.oDbg.log("already handled "+req.rid,2);
return null;
} else
this._last_requests[req.rid].handled = true;
}
// Check for errors from the server
if (body.getAttribute("type") == "terminate") {
this.oDbg.log("session terminated:\n" + r.responseText,1);
clearTimeout(this._timeout); // remove timer
clearInterval(this._interval);
clearInterval(this._inQto);
if (body.getAttribute("condition") == "remote-stream-error")
if (body.getElementsByTagName("conflict").length > 0)
this._setStatus("session-terminate-conflict");
this._handleEvent('onerror',JSJaCError('503','cancel',body.getAttribute('condition')));
this._connected = false;
this.oDbg.log("Disconnected.",1);
this._handleEvent('ondisconnect');
return null;
}
// no error
this._errcnt = 0;
return r.responseXML.documentElement;
};
/**
* @private
*/
JSJaCHttpBindingConnection.prototype._reInitStream = function(to,cb,arg) {
/* [TODO] we can't handle 'to' here as this is not (yet) supported
* by the protocol
*/
// tell http binding to reinit stream with/before next request
this._reinit = true;
cb.call(this,arg); // proceed with next callback
/* [TODO] make sure that we're checking for new stream features when
* 'cb' finishes
*/
};
/**
* @private
*/
JSJaCHttpBindingConnection.prototype._resume = function() {
/* make sure to repeat last request as we can be sure that
* it had failed (only if we're not using the 'pause' attribute
*/
if (this._pause == 0 && this._rid >= this._last_rid)
this._rid = this._last_rid-1;
this._process();
};
/**
* @private
*/
JSJaCHttpBindingConnection.prototype._setHold = function(hold) {
if (!hold || isNaN(hold) || hold < 0)
hold = 0;
else if (hold > JSJACHBC_MAX_HOLD)
hold = JSJACHBC_MAX_HOLD;
this._hold = hold;
return this._hold;
};
/**
* @private
*/
JSJaCHttpBindingConnection.prototype._setupRequest = function(async) {
var req = new Object();
var r = XmlHttp.create();
try {
r.open("POST",this._httpbase,async);
r.setRequestHeader('Content-Type','text/xml; charset=utf-8');
} catch(e) { this.oDbg.log(e,1); }
req.r = r;
this._rid++;
req.rid = this._rid;
return req;
};
/**
* @private
*/
JSJaCHttpBindingConnection.prototype._suspend = function() {
if (this._pause == 0)
return; // got nothing to do
var slot = this._getFreeSlot();
// Intentionally synchronous
this._req[slot] = this._setupRequest(false);
var reqstr = "<body pause='"+this._pause+"' xmlns='http://jabber.org/protocol/httpbind' sid='"+this._sid+"' rid='"+this._rid+"'";
if (JSJAC_HAVEKEYS) {
reqstr += " key='"+this._keys.getKey()+"'";
if (this._keys.lastKey()) {
this._keys = new JSJaCKeys(hex_sha1,this.oDbg);
reqstr += " newkey='"+this._keys.getKey()+"'";
}
}
reqstr += ">";
while (this._pQueue.length) {
var curNode = this._pQueue[0];
reqstr += curNode;
this._pQueue = this._pQueue.slice(1,this._pQueue.length);
}
//reqstr += "<presence type='unavailable' xmlns='jabber:client'/>";
reqstr += "</body>";
this.oDbg.log("Disconnecting: " + reqstr,4);
this._req[slot].r.send(reqstr);
};
/**
* @fileoverview All stuff related to HTTP Polling
* @author Stefan Strigler steve@zeank.in-berlin.de
* @version $Revision: 452 $
*/
/**
* Instantiates an HTTP Polling session
* @class Implementation of {@link
* http://www.xmpp.org/extensions/xep-0025.html HTTP Polling}
* @extends JSJaCConnection
* @constructor
*/
function JSJaCHttpPollingConnection(oArg) {
/**
* @ignore
*/
this.base = JSJaCConnection;
this.base(oArg);
// give hint to JSJaCPacket that we're using HTTP Polling ...
JSJACPACKET_USE_XMLNS = false;
}
JSJaCHttpPollingConnection.prototype = new JSJaCConnection();
/**
* Tells whether this implementation of JSJaCConnection is polling
* Useful if it needs to be decided
* whether it makes sense to allow for adjusting or adjust the
* polling interval {@link JSJaCConnection#setPollInterval}
* @return <code>true</code> if this is a polling connection,
* <code>false</code> otherwise.
* @type boolean
*/
JSJaCHttpPollingConnection.prototype.isPolling = function() { return true; };
/**
* @private
*/
JSJaCHttpPollingConnection.prototype._getFreeSlot = function() {
if (typeof(this._req[0]) == 'undefined' ||
typeof(this._req[0].r) == 'undefined' ||
this._req[0].r.readyState == 4)
return 0;
else
return -1;
};
/**
* @private
*/
JSJaCHttpPollingConnection.prototype._getInitialRequestString = function() {
var reqstr = "0";
if (JSJAC_HAVEKEYS) {
this._keys = new JSJaCKeys(b64_sha1,this.oDbg); // generate first set of keys
key = this._keys.getKey();
reqstr += ";"+key;
}
var streamto = this.domain;
if (this.authhost)
streamto = this.authhost;
reqstr += ",<stream:stream to='"+streamto+"' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'";
if (this.authtype == 'sasl' || this.authtype == 'saslanon')
reqstr += " version='1.0'";
reqstr += ">";
return reqstr;
};
/**
* @private
*/
JSJaCHttpPollingConnection.prototype._getRequestString = function(raw, last) {
var reqstr = this._sid;
if (JSJAC_HAVEKEYS) {
reqstr += ";"+this._keys.getKey();
if (this._keys.lastKey()) {
this._keys = new JSJaCKeys(b64_sha1,this.oDbg);
reqstr += ';'+this._keys.getKey();
}
}
reqstr += ',';
if (raw)
reqstr += raw;
while (this._pQueue.length) {
reqstr += this._pQueue[0];
this._pQueue = this._pQueue.slice(1,this._pQueue.length);
}
if (last)
reqstr += '</stream:stream>';
return reqstr;
};
/**
* @private
*/
JSJaCHttpPollingConnection.prototype._getStreamID = function() {
if (this._req[0].r.responseText == '') {
this.oDbg.log("waiting for stream id",2);
this._timeout = setTimeout(JSJaC.bind(this._sendEmpty, this),1000);
return;
}
this.oDbg.log(this._req[0].r.responseText,4);
// extract stream id used for non-SASL authentication
if (this._req[0].r.responseText.match(/id=[\'\"]([^\'\"]+)[\'\"]/))
this.streamid = RegExp.$1;
this.oDbg.log("got streamid: "+this.streamid,2);
var doc;
try {
var response = this._req[0].r.responseText;
if (!response.match(/<\/stream:stream>\s*$/))
response += '</stream:stream>';
doc = XmlDocument.create("doc");
doc.loadXML(response);
if (!this._parseStreamFeatures(doc))
return;
} catch(e) {
this.oDbg.log("loadXML: "+e.toString(),1);
}
this._connected = true;
if (this.register)
this._doInBandReg();
else
this._doAuth();
this._process(this._timerval); // start polling
};
/**
* @private
*/
JSJaCHttpPollingConnection.prototype._getSuspendVars = function() {
return new Array();
};
/**
* @private
*/
JSJaCHttpPollingConnection.prototype._handleInitialResponse = function() {
// extract session ID
this.oDbg.log(this._req[0].r.getAllResponseHeaders(),4);
var aPList = this._req[0].r.getResponseHeader('Set-Cookie');
aPList = aPList.split(";");
for (var i=0;i<aPList.length;i++) {
aArg = aPList[i].split("=");
if (aArg[0] == 'ID')
this._sid = aArg[1];
}
this.oDbg.log("got sid: "+this._sid,2);
/* start sending from queue for not polling connections */
this._connected = true;
this._interval= setInterval(JSJaC.bind(this._checkQueue, this),
JSJAC_CHECKQUEUEINTERVAL);
this._inQto = setInterval(JSJaC.bind(this._checkInQ, this),
JSJAC_CHECKINQUEUEINTERVAL);
/* wait for initial stream response to extract streamid needed
* for digest auth
*/
this._getStreamID();
};
/**
* @private
*/
JSJaCHttpPollingConnection.prototype._parseResponse = function(r) {
var req = r.r;
if (!this.connected())
return null;
/* handle error */
// proxy error (!)
if (req.status != 200) {
this.oDbg.log("invalid response ("+req.status+"):" + req.responseText+"\n"+req.getAllResponseHeaders(),1);
this._setStatus('internal_server_error');
clearTimeout(this._timeout); // remove timer
clearInterval(this._interval);
clearInterval(this._inQto);
this._connected = false;
this.oDbg.log("Disconnected.",1);
this._handleEvent('ondisconnect');
this._handleEvent('onerror',JSJaCError('503','cancel','service-unavailable'));
return null;
}
this.oDbg.log(req.getAllResponseHeaders(),4);
var sid, aPList = req.getResponseHeader('Set-Cookie');
if (aPList == null)
sid = "-1:0"; // Generate internal server error
else {
aPList = aPList.split(";");
var sid;
for (var i=0;i<aPList.length;i++) {
var aArg = aPList[i].split("=");
if (aArg[0] == 'ID')
sid = aArg[1];
}
}
// http polling component error
if (typeof(sid) != 'undefined' && sid.indexOf(':0') != -1) {
switch (sid.substring(0,sid.indexOf(':0'))) {
case '0':
this.oDbg.log("invalid response:" + req.responseText,1);
break;
case '-1':
this.oDbg.log("Internal Server Error",1);
break;
case '-2':
this.oDbg.log("Bad Request",1);
break;
case '-3':
this.oDbg.log("Key Sequence Error",1);
break;
}
this._setStatus('internal_server_error');
clearTimeout(this._timeout); // remove timer
clearInterval(this._interval);
clearInterval(this._inQto);
this._handleEvent('onerror',JSJaCError('500','wait','internal-server-error'));
this._connected = false;
this.oDbg.log("Disconnected.",1);
this._handleEvent('ondisconnect');
return null;
}
if (!req.responseText || req.responseText == '')
return null;
try {
var response = req.responseText.replace(/\<\?xml.+\?\>/,"");
if (response.match(/<stream:stream/))
response += "</stream:stream>";
var doc = JSJaCHttpPollingConnection._parseTree("<body>"+response+"</body>");
if (!doc || doc.tagName == 'parsererror') {
this.oDbg.log("parsererror",1);
doc = JSJaCHttpPollingConnection._parseTree("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'>"+req.responseText);
if (doc && doc.tagName != 'parsererror') {
this.oDbg.log("stream closed",1);
if (doc.getElementsByTagName('conflict').length > 0)
this._setStatus("session-terminate-conflict");
clearTimeout(this._timeout); // remove timer
clearInterval(this._interval);
clearInterval(this._inQto);
this._handleEvent('onerror',JSJaCError('503','cancel','session-terminate'));
this._connected = false;
this.oDbg.log("Disconnected.",1);
this._handleEvent('ondisconnect');
} else
this.oDbg.log("parsererror:"+doc,1);
return doc;
}
return doc;
} catch (e) {
this.oDbg.log("parse error:"+e.message,1);
}
return null;;
};
/**
* @private
*/
JSJaCHttpPollingConnection.prototype._reInitStream = function(to,cb,arg) {
this._sendRaw("<stream:stream xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:client' to='"+to+"' version='1.0'>",cb,arg);
};
/**
* @private
*/
JSJaCHttpPollingConnection.prototype._resume = function() {
this._process(this._timerval);
};
/**
* @private
*/
JSJaCHttpPollingConnection.prototype._setupRequest = function(async) {
var r = XmlHttp.create();
try {
r.open("POST",this._httpbase,async);
if (r.overrideMimeType)
r.overrideMimeType('text/plain; charset=utf-8');
r.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
} catch(e) { this.oDbg.log(e,1); }
var req = new Object();
req.r = r;
return req;
};
/**
* @private
*/
JSJaCHttpPollingConnection.prototype._suspend = function() {};
/*** [static] ***/
/**
* @private
*/
JSJaCHttpPollingConnection._parseTree = function(s) {
try {
var r = XmlDocument.create("body","foo");
if (typeof(r.loadXML) != 'undefined') {
r.loadXML(s);
return r.documentElement;
} else if (window.DOMParser)
return (new DOMParser()).parseFromString(s, "text/xml").documentElement;
} catch (e) { }
return null;
};
/**
* @fileoverview Magic dependency loading. Taken from script.aculo.us
* and modified to break it.
* @author Stefan Strigler steve@zeank.in-berlin.de
* @version $Revision: 456 $
*/
var JSJaC = {
Version: '$Rev: 456 $',
require: function(libraryName) {
// inserting via DOM fails in Safari 2.0, so brute force approach
document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
},
load: function() {
var includes =
['xmlextras',
'jsextras',
'crypt',
'JSJaCConfig',
'JSJaCConstants',
'JSJaCCookie',
'JSJaCJSON',
'JSJaCJID',
'JSJaCBuilder',
'JSJaCPacket',
'JSJaCError',
'JSJaCKeys',
'JSJaCConnection',
'JSJaCHttpPollingConnection',
'JSJaCHttpBindingConnection',
'JSJaCConsoleLogger'
];
var scripts = document.getElementsByTagName("script");
var path = './';
for (var i=0; i<scripts.length; i++) {
if (scripts.item(i).src && scripts.item(i).src.match(/JSJaC\.js$/)) {
path = scripts.item(i).src.replace(/JSJaC.js$/,'');
break;
}
}
for (var i=0; i<includes.length; i++)
this.require(path+includes[i]+'.js');
},
bind: function(fn, obj, arg) {
return function() {
if (arg)
fn.apply(obj, arg);
else
fn.apply(obj);
};
}
};
if (typeof JSJaCConnection == 'undefined')
JSJaC.load();
|
/*
Highcharts JS v10.0.0 (2022-03-07)
(c) 2009-2021 Sebastian Bochan, Rafal Sebestjanski
License: www.highcharts.com/license
*/
(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/dumbbell",["highcharts"],function(n){a(n);a.Highcharts=n;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function n(a,f,h,k){a.hasOwnProperty(f)||(a[f]=k.apply(null,h),"function"===typeof CustomEvent&&window.dispatchEvent(new CustomEvent("HighchartsModuleLoaded",{detail:{path:f,module:a[f]}})))}a=a?a._modules:{};n(a,
"Series/AreaRange/AreaRangePoint.js",[a["Series/Area/AreaSeries.js"],a["Core/Series/Point.js"],a["Core/Utilities.js"]],function(a,f,h){var k=this&&this.__extends||function(){var a=function(e,d){a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,a){b.__proto__=a}||function(a,d){for(var b in d)d.hasOwnProperty(b)&&(a[b]=d[b])};return a(e,d)};return function(e,d){function b(){this.constructor=e}a(e,d);e.prototype=null===d?Object.create(d):(b.prototype=d.prototype,new b)}}(),m=f.prototype,
r=h.defined,c=h.isNumber;return function(a){function e(){var d=null!==a&&a.apply(this,arguments)||this;d.high=void 0;d.low=void 0;d.options=void 0;d.plotHigh=void 0;d.plotLow=void 0;d.plotHighX=void 0;d.plotLowX=void 0;d.plotX=void 0;d.series=void 0;return d}k(e,a);e.prototype.setState=function(){var a=this.state,b=this.series,e=b.chart.polar;r(this.plotHigh)||(this.plotHigh=b.yAxis.toPixels(this.high,!0));r(this.plotLow)||(this.plotLow=this.plotY=b.yAxis.toPixels(this.low,!0));b.stateMarkerGraphic&&
(b.lowerStateMarkerGraphic=b.stateMarkerGraphic,b.stateMarkerGraphic=b.upperStateMarkerGraphic);this.graphic=this.upperGraphic;this.plotY=this.plotHigh;e&&(this.plotX=this.plotHighX);m.setState.apply(this,arguments);this.state=a;this.plotY=this.plotLow;this.graphic=this.lowerGraphic;e&&(this.plotX=this.plotLowX);b.stateMarkerGraphic&&(b.upperStateMarkerGraphic=b.stateMarkerGraphic,b.stateMarkerGraphic=b.lowerStateMarkerGraphic,b.lowerStateMarkerGraphic=void 0);m.setState.apply(this,arguments)};e.prototype.haloPath=
function(){var a=this.series.chart.polar,b=[];this.plotY=this.plotLow;a&&(this.plotX=this.plotLowX);this.isInside&&(b=m.haloPath.apply(this,arguments));this.plotY=this.plotHigh;a&&(this.plotX=this.plotHighX);this.isTopInside&&(b=b.concat(m.haloPath.apply(this,arguments)));return b};e.prototype.isValid=function(){return c(this.low)&&c(this.high)};return e}(a.prototype.pointClass)});n(a,"Series/Dumbbell/DumbbellPoint.js",[a["Series/AreaRange/AreaRangePoint.js"],a["Core/Utilities.js"]],function(a,f){var h=
this&&this.__extends||function(){var a=function(c,l){a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,d){a.__proto__=d}||function(a,d){for(var b in d)d.hasOwnProperty(b)&&(a[b]=d[b])};return a(c,l)};return function(c,l){function e(){this.constructor=c}a(c,l);c.prototype=null===l?Object.create(l):(e.prototype=l.prototype,new e)}}(),k=f.extend,m=f.pick;f=function(a){function c(){var c=null!==a&&a.apply(this,arguments)||this;c.series=void 0;c.options=void 0;c.connector=void 0;c.pointWidth=
void 0;return c}h(c,a);c.prototype.setState=function(){var a=this.series,c=a.chart,d=a.options.marker,b=this.options,f=m(b.lowColor,a.options.lowColor,b.color,this.zone&&this.zone.color,this.color,a.color),h="attr";this.pointSetState.apply(this,arguments);this.state||(h="animate",this.lowerGraphic&&!c.styledMode&&(this.lowerGraphic.attr({fill:f}),this.upperGraphic&&(c={y:this.y,zone:this.zone},this.y=this.high,this.zone=this.zone?this.getZone():void 0,d=m(this.marker?this.marker.fillColor:void 0,
d?d.fillColor:void 0,b.color,this.zone?this.zone.color:void 0,this.color),this.upperGraphic.attr({fill:d}),k(this,c))));this.connector[h](a.getConnectorAttribs(this))};c.prototype.destroy=function(){this.graphic||(this.graphic=this.connector,this.connector=void 0);return a.prototype.destroy.call(this)};return c}(a);k(f.prototype,{pointSetState:a.prototype.setState});return f});n(a,"Series/Dumbbell/DumbbellSeries.js",[a["Series/Column/ColumnSeries.js"],a["Series/Dumbbell/DumbbellPoint.js"],a["Core/Globals.js"],
a["Core/Series/Series.js"],a["Core/Series/SeriesRegistry.js"],a["Core/Renderer/SVG/SVGRenderer.js"],a["Core/Utilities.js"]],function(a,f,h,k,m,n,c){var l=this&&this.__extends||function(){var a=function(b,g){a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,g){a.__proto__=g}||function(a,g){for(var b in g)g.hasOwnProperty(b)&&(a[b]=g[b])};return a(b,g)};return function(b,g){function d(){this.constructor=b}a(b,g);b.prototype=null===g?Object.create(g):(d.prototype=g.prototype,new d)}}(),
e=a.prototype;h=h.noop;var d=k.prototype;k=m.seriesTypes;var b=k.arearange;k=k.columnrange.prototype;var t=b.prototype,r=c.extend,u=c.merge,p=c.pick;c=function(a){function c(){var g=null!==a&&a.apply(this,arguments)||this;g.data=void 0;g.options=void 0;g.points=void 0;g.columnMetrics=void 0;return g}l(c,a);c.prototype.getConnectorAttribs=function(a){var b=this.chart,g=a.options,c=this.options,d=this.xAxis,e=this.yAxis,f=p(g.connectorWidth,c.connectorWidth),h=p(g.connectorColor,c.connectorColor,g.color,
a.zone?a.zone.color:void 0,a.color),k=p(c.states&&c.states.hover&&c.states.hover.connectorWidthPlus,1),m=p(g.dashStyle,c.dashStyle),l=p(a.plotLow,a.plotY),q=e.toPixels(c.threshold||0,!0);q=p(a.plotHigh,b.inverted?e.len-q:q);a.state&&(f+=k);0>l?l=0:l>=e.len&&(l=e.len);0>q?q=0:q>=e.len&&(q=e.len);if(0>a.plotX||a.plotX>d.len)f=0;a.upperGraphic&&(d={y:a.y,zone:a.zone},a.y=a.high,a.zone=a.zone?a.getZone():void 0,h=p(g.connectorColor,c.connectorColor,g.color,a.zone?a.zone.color:void 0,a.color),r(a,d));
a={d:n.prototype.crispLine([["M",a.plotX,l],["L",a.plotX,q]],f,"ceil")};b.styledMode||(a.stroke=h,a["stroke-width"]=f,m&&(a.dashstyle=m));return a};c.prototype.drawConnector=function(a){var b=p(this.options.animationLimit,250);b=a.connector&&this.chart.pointCount<b?"animate":"attr";a.connector||(a.connector=this.chart.renderer.path().addClass("highcharts-lollipop-stem").attr({zIndex:-1}).add(this.markerGroup));a.connector[b](this.getConnectorAttribs(a))};c.prototype.getColumnMetrics=function(){var a=
e.getColumnMetrics.apply(this,arguments);a.offset+=a.width/2;return a};c.prototype.translate=function(){this.setShapeArgs.apply(this);this.translatePoint.apply(this,arguments);this.points.forEach(function(a){var b=a.shapeArgs,c=a.pointWidth;a.plotX=b.x;b.x=a.plotX-c/2;a.tooltipPos=null});this.columnMetrics.offset-=this.columnMetrics.width/2};c.prototype.drawPoints=function(){var a=this.chart,b=this.points.length,c=this.lowColor=this.options.lowColor,d=0;for(this.seriesDrawPoints.apply(this,arguments);d<
b;){var e=this.points[d];this.drawConnector(e);e.upperGraphic&&(e.upperGraphic.element.point=e,e.upperGraphic.addClass("highcharts-lollipop-high"));e.connector.element.point=e;if(e.lowerGraphic){var f=e.zone&&e.zone.color;f=p(e.options.lowColor,c,e.options.color,f,e.color,this.color);a.styledMode||e.lowerGraphic.attr({fill:f});e.lowerGraphic.addClass("highcharts-lollipop-low")}d++}};c.prototype.markerAttribs=function(){var a=t.markerAttribs.apply(this,arguments);a.x=Math.floor(a.x||0);a.y=Math.floor(a.y||
0);return a};c.prototype.pointAttribs=function(a,b){var c=d.pointAttribs.apply(this,arguments);"hover"===b&&delete c.fill;return c};c.defaultOptions=u(b.defaultOptions,{trackByArea:!1,fillColor:"none",lineWidth:0,pointRange:1,connectorWidth:1,stickyTracking:!1,groupPadding:.2,crisp:!1,pointPadding:.1,lowColor:"#333333",states:{hover:{lineWidthPlus:0,connectorWidthPlus:1,halo:!1}}});return c}(b);r(c.prototype,{crispCol:e.crispCol,drawGraph:h,drawTracker:a.prototype.drawTracker,pointClass:f,setShapeArgs:k.translate,
seriesDrawPoints:t.drawPoints,trackerGroups:["group","markerGroup","dataLabelsGroup"],translatePoint:t.translate});m.registerSeriesType("dumbbell",c);"";return c});n(a,"masters/modules/dumbbell.src.js",[],function(){})});
//# sourceMappingURL=dumbbell.js.map |
/**
* RiojaSlider 0.1v
*
* Copyright 2016, Gerard Rodes https://github.com/GerardRodes
*
* Released under the MIT license - http://opensource.org/licenses/MIT
*/
/*
Inserts svg icons to structures following this pattern
[data-social-links] Wrapper attribute
|-> [data-name] Link element attribute, it can be anywhere inside the wrapper
Attributes placed at wrapper will be applied to all children link elements,
this attributes can be overwritted defining them at link element.
All attributes must be prefixed by "data-", example: data-color="black".
To disable an attributes just defined it with an invalid value, example: data-hover="none" (this would disable hover effects, however data-hover="" would be enough to disabled it)
-ATTRIBUTES-
color: CSS color string
shape: ( normal | circle )
size: Size in px
hover: Hover css effectos to apply on hover => data-hover="attr1:value1;attr2:value2;attr3:value3..."
msg: Message before social network name at title attribue on link tag
transition: CSS transition to apply
target: target attribute value on link tag
folder: Url of the folder where the "svg" folder with the images is placed
css: Boolean, specifies if apply default css
-LINKS UNIQUE ATTRIBUTES-
url: Url to define href of the link tag
name: String to specify the social network, accepted values are store at `socialIcons` variable on line 47
Some CSS styles are applied to the wrapper and links by default, this styles are defined
on `css` variable on line 657. This can be disabled adding a value not "true" to the data-css tag.
This way you can disble css globally adding data-css="false" to the wrapper, and then
active css styles adding data-css="true" on some required elements
*/
(function($) {
var defaultOptions = {
color: '#000000',
shape: 'normal',
size: '24',
msg: 'Contacta en ',
transition: '.35s',
target: '_blank',
folder: '',
css: true
},
socialIcons = [{
name: 'forrst',
hover: 'fill:#333333',
icon: {
circle: '01-forrst.svg',
normal: '01-forrst.svg'
}
}, {
name: 'dribbble',
hover: 'fill:#333333',
icon: {
circle: '02-dribbble.svg',
normal: '02-dribbble.svg'
}
}, {
name: 'twitter',
hover: 'fill:#55acee',
icon: {
circle: '03-twitter.svg',
normal: '03-twitter.svg'
}
}, {
name: 'flickr',
hover: 'fill:#ff0084',
icon: {
circle: '04-flickr.svg',
normal: '04-flickr.svg'
}
}, {
name: 'twitter-letter',
hover: 'fill:#55acee',
icon: {
circle: '05-twitter.svg',
normal: '05-twitter.svg'
}
}, {
name: 'facebook',
hover: 'fill:#3b5998',
icon: {
circle: '06-facebook.svg',
normal: '06-facebook.svg'
}
}, {
name: 'skype',
hover: 'fill:#333333',
icon: {
circle: '07-skype.svg',
normal: '07-skype.svg'
}
}, {
name: 'digg',
hover: 'fill:#333333',
icon: {
circle: '08-digg.svg',
normal: '08-digg.svg'
}
}, {
name: 'google',
hover: 'fill:#dd4b39',
icon: {
circle: '09-google.svg',
normal: '09-google.svg'
}
}, {
name: 'html5',
hover: 'fill:#333333',
icon: {
circle: '10-html5.svg',
normal: '10-html5.svg'
}
}, {
name: 'linkedin',
hover: 'fill:#007bb5',
icon: {
circle: '11-linkedin.svg',
normal: '11-linkedin.svg'
}
}, {
name: 'lastfm',
hover: 'fill:#333333',
icon: {
circle: '12-lastfm.svg',
normal: '12-lastfm.svg'
}
}, {
name: 'vimeo',
hover: 'fill:#333333',
icon: {
circle: '13-vimeo.svg',
normal: '13-vimeo.svg'
}
}, {
name: 'yahoo',
hover: 'fill:#333333',
icon: {
circle: '14-yahoo.svg',
normal: '14-yahoo.svg'
}
}, {
name: 'tumblr',
hover: 'fill:#333333',
icon: {
circle: '15-tumblr.svg',
normal: '15-tumblr.svg'
}
}, {
name: 'apple',
hover: 'fill:#333333',
icon: {
circle: '16-apple.svg',
normal: '16-apple.svg'
}
}, {
name: 'windows',
hover: 'fill:#333333',
icon: {
circle: '17-windows.svg',
normal: '17-windows.svg'
}
}, {
name: 'youtube',
hover: 'fill:#bb0000',
icon: {
circle: '18-youtube.svg',
normal: '18-youtube.svg'
}
}, {
name: 'delicious',
hover: 'fill:#333333',
icon: {
circle: '19-delicious.svg',
normal: '19-delicious.svg'
}
}, {
name: 'rss',
hover: 'fill:#333333',
icon: {
circle: '20-rss.svg',
normal: '20-rss.svg'
}
}, {
name: 'picasa',
hover: 'fill:#333333',
icon: {
circle: '21-picasa.svg',
normal: '21-picasa.svg'
}
}, {
name: 'deviantart',
hover: 'fill:#333333',
icon: {
circle: '22-deviantart.svg',
normal: '22-deviantart.svg'
}
}, {
name: 'whatsapp',
hover: 'fill:#4dc247',
icon: {
circle: '23-whatsapp.svg',
normal: '23-whatsapp.svg'
}
}, {
name: 'snapchat',
hover: 'fill:#333333',
icon: {
circle: '24-snapchat.svg',
normal: '24-snapchat.svg'
}
}, {
name: 'blogger',
hover: 'fill:#333333',
icon: {
circle: '25-blogger.svg',
normal: '25-blogger.svg'
}
}, {
name: 'wordpress',
hover: 'fill:#333333',
icon: {
circle: '26-wordpress.svg',
normal: '26-wordpress.svg'
}
}, {
name: 'amazon',
hover: 'fill:#333333',
icon: {
circle: '27-amazon.svg',
normal: '27-amazon.svg'
}
}, {
name: 'appstore',
hover: 'fill:#333333',
icon: {
circle: '28-appstore.svg',
normal: '28-appstore.svg'
}
}, {
name: 'paypal',
hover: 'fill:#333333',
icon: {
circle: '29-paypal.svg',
normal: '29-paypal.svg'
}
}, {
name: 'myspace',
hover: 'fill:#333333',
icon: {
circle: '30-myspace.svg',
normal: '30-myspace.svg'
}
}, {
name: 'dropbox',
hover: 'fill:#333333',
icon: {
circle: '31-dropbox.svg',
normal: '31-dropbox.svg'
}
}, {
name: 'windows8',
hover: 'fill:#333333',
icon: {
circle: '32-windows8.svg',
normal: '32-windows8.svg'
}
}, {
name: 'pinterest',
hover: 'fill:#cb2027',
icon: {
circle: '33-pinterest.svg',
normal: '33-pinterest.svg'
}
}, {
name: 'soundcloud',
hover: 'fill:#333333',
icon: {
circle: '34-soundcloud.svg',
normal: '34-soundcloud.svg'
}
}, {
name: 'google-drive',
hover: 'fill:#333333',
icon: {
circle: '35-google-drive.svg',
normal: '35-google-drive.svg'
}
}, {
name: 'android',
hover: 'fill:#333333',
icon: {
circle: '36-android.svg',
normal: '36-android.svg'
}
}, {
name: 'behance',
hover: 'fill:#333333',
icon: {
circle: '37-behance.svg',
normal: '37-behance.svg'
}
}, {
name: 'instagram',
hover: 'fill:#e95950',
icon: {
circle: '38-instagram.svg',
normal: '38-instagram.svg'
}
}, {
name: 'ebay',
hover: 'fill:#333333',
icon: {
circle: '39-ebay.svg',
normal: '39-ebay.svg'
}
}, {
name: 'google-plus',
hover: 'fill:#333333',
icon: {
circle: '40-google-plus.svg',
normal: '40-google-plus.svg'
}
}, {
name: 'github',
hover: 'fill:#333333',
icon: {
circle: '41-github.svg',
normal: '41-github.svg'
}
}, {
name: 'stackoverflow',
hover: 'fill:#333333',
icon: {
circle: '42-stackoverflow.svg',
normal: '42-stackoverflow.svg'
}
}, {
name: 'spotify',
hover: 'fill:#333333',
icon: {
circle: '43-spotify.svg',
normal: '43-spotify.svg'
}
}, {
name: 'stumbleupon',
hover: 'fill:#333333',
icon: {
circle: '44-stumbleupon.svg',
normal: '44-stumbleupon.svg'
}
}, {
name: 'visa',
hover: 'fill:#333333',
icon: {
circle: '45-visa.svg',
normal: '45-visa.svg'
}
}, {
name: 'mastercard',
hover: 'fill:#333333',
icon: {
circle: '46-mastercard.svg',
normal: '46-mastercard.svg'
}
}, {
name: 'amex',
hover: 'fill:#333333',
icon: {
circle: '47-amex.svg',
normal: '47-amex.svg'
}
}, {
name: 'ios',
hover: 'fill:#333333',
icon: {
circle: '48-ios.svg',
normal: '48-ios.svg'
}
}, {
name: 'osx',
hover: 'fill:#333333',
icon: {
circle: '49-osx.svg',
normal: '49-osx.svg'
}
}, {
name: 'evernote',
hover: 'fill:#333333',
icon: {
circle: '50-evernote.svg',
normal: '50-evernote.svg'
}
}, {
name: 'yelp',
hover: 'fill:#333333',
icon: {
circle: '51-yelp.svg',
normal: '51-yelp.svg'
}
}, {
name: 'yelp',
hover: 'fill:#333333',
icon: {
circle: '52-yelp.svg',
normal: '52-yelp.svg'
}
}, {
name: 'medium',
hover: 'fill:#333333',
icon: {
circle: '53-medium.svg',
normal: '53-medium.svg'
}
}, {
name: 'slack',
hover: 'fill:#333333',
icon: {
circle: '54-slack.svg',
normal: '54-slack.svg'
}
}, {
name: 'vine',
hover: 'fill:#333333',
icon: {
circle: '55-vine.svg',
normal: '55-vine.svg'
}
}, {
name: 'edge',
hover: 'fill:#333333',
icon: {
circle: '56-edge.svg',
normal: '56-edge.svg'
}
}, {
name: 'outlook',
hover: 'fill:#333333',
icon: {
circle: '57-outlook.svg',
normal: '57-outlook.svg'
}
}, {
name: 'pencilcase',
hover: 'fill:#333333',
icon: {
circle: '58-pencilcase.svg',
normal: '58-pencilcase.svg'
}
}, {
name: 'play',
hover: 'fill:#333333',
icon: {
circle: '59-play.svg',
normal: '59-play.svg'
}
}, {
name: 'icloud',
hover: 'fill:#333333',
icon: {
circle: '60-icloud.svg',
normal: '60-icloud.svg'
}
}, {
name: 'google-inbox',
hover: 'fill:#333333',
icon: {
circle: '61-google-inbox.svg',
normal: '61-google-inbox.svg'
}
}, {
name: 'periscope',
hover: 'fill:#333333',
icon: {
circle: '62-periscope.svg',
normal: '62-periscope.svg'
}
}, {
name: 'blackberry',
hover: 'fill:#333333',
icon: {
circle: '63-blackberry.svg',
normal: '63-blackberry.svg'
}
}, {
name: 'viber',
hover: 'fill:#333333',
icon: {
circle: '64-viber.svg',
normal: '64-viber.svg'
}
}, {
name: 'fb_messenger',
hover: 'fill:#333333',
icon: {
circle: '65-fb_messenger.svg',
normal: '65-fb_messenger.svg'
}
}, {
name: 'wechat',
hover: 'fill:#333333',
icon: {
circle: '66-wechat.svg',
normal: '66-wechat.svg'
}
}, {
name: 'gmail',
hover: 'fill:#333333',
icon: {
circle: '67-gmail.svg',
normal: '67-gmail.svg'
}
}, {
name: 'airbnb',
hover: 'fill:#333333',
icon: {
circle: '68-airbnb.svg',
normal: '68-airbnb.svg'
}
}, {
name: 'angellist',
hover: 'fill:#333333',
icon: {
circle: '69-angellist.svg',
normal: '69-angellist.svg'
}
}, {
name: 'uber',
hover: 'fill:#333333',
icon: {
circle: '70-uber.svg',
normal: '70-uber.svg'
}
}, {
name: 'safari',
hover: 'fill:#333333',
icon: {
circle: '71-safari.svg',
normal: '71-safari.svg'
}
}, {
name: 'firefox',
hover: 'fill:#333333',
icon: {
circle: '72-firefox.svg',
normal: '72-firefox.svg'
}
}, {
name: 'opera',
hover: 'fill:#333333',
icon: {
circle: '73-opera.svg',
normal: '73-opera.svg'
}
}, {
name: 'bing',
hover: 'fill:#333333',
icon: {
circle: '74-bing.svg',
normal: '74-bing.svg'
}
}, {
name: 'reddit',
hover: 'fill:#333333',
icon: {
circle: '75-reddit.svg',
normal: '75-reddit.svg'
}
}, {
name: 'producthunt',
hover: 'fill:#333333',
icon: {
circle: '76-producthunt.svg',
normal: '76-producthunt.svg'
}
}],
css = {
list: {
listStyle: 'none',
margin: '0',
transition: '.35s'
},
link: {
display: 'inline-block',
margin: '0',
padding: '0',
transition: '.35s'
}
},
cache = [],
loadQueue = [];
var socialLists = $('[data-social-links]');
$.each(socialLists, function(i, el) {
var customlistOptions = {
color: $(el).attr('data-color'),
shape: $(el).attr('data-shape'),
size: $(el).attr('data-size'),
target: $(el).attr('data-target'),
css: $(el).attr('data-css'),
hover: $(el).attr('data-hover'),
msg: $(el).attr('data-msg'),
transition: $(el).attr('data-transition'),
folder: $(el).attr('data-folder')
},
listOptions = $.extend({}, defaultOptions, customlistOptions),
socialLinksGroup = $(el).find('[data-social]');
if (listOptions.css == true || listOptions.css == "true") {
$(el).css(css.list)
}
$.each(socialLinksGroup, function(i, el) {
var customLinkOptions = {
color: $(el).attr('data-color'),
shape: $(el).attr('data-shape'),
size: $(el).attr('data-size'),
css: $(el).attr('data-css'),
hover: $(el).attr('data-hover'),
target: $(el).attr('data-target'),
msg: $(el).attr('data-msg'),
url: $(el).attr('data-url'),
transition: $(el).attr('data-transition'),
name: $(el).attr('data-name')
},
linkOptions = $.extend({}, listOptions, customLinkOptions),
imageUrl = getImageUrl(linkOptions),
html;
if (linkOptions.hover == undefined) {
linkOptions.hover = getHover(linkOptions);
}
if (linkOptions.css == true || linkOptions.css == "true") {
$(el).css(css.link)
}
var cachedIcon = getCached(linkOptions.name);
switch (cachedIcon) {
case 'notCached':
cache.push({
name: linkOptions.name,
svg: 'loading'
})
$.get(imageUrl,
function(data) {
svg = $(data).find('svg')
.removeAttr('xmlns:a');
cachedItem = getCached(linkOptions.name);
cachedItem.svg = svg;
loadQueue.push({
options: linkOptions,
element: $(el)
})
$.each(getLoadQueue(linkOptions.name), function(i, waitingIcon) {
$(waitingIcon.element).html(buildIcon(waitingIcon.options, svg, i));
loadQueue = removeElement(loadQueue, waitingIcon);
})
})
break;
case 'loading':
loadQueue.push({
options: linkOptions,
element: $(el)
})
break;
default:
$(el).html(buildIcon(linkOptions, cachedIcon.svg, i));
break;
}
})
})
function getImageUrl(linkOptions) {
var imgName = socialIcons.filter(function(el) {
return el.name == linkOptions.name
})[0].icon[linkOptions.shape];
return linkOptions.folder + 'svg/' + linkOptions.shape + '/' + imgName;
}
function getHover(linkOptions) {
var hover = socialIcons.filter(function(el) {
return el.name == linkOptions.name
})[0].hover;
return hover;
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function buildIcon(linkOptions, svg, i) {
var svg = svg.css('transition', linkOptions.transition)
.attr({
'height': linkOptions.size,
'width': linkOptions.size,
'id': 'social-link-' + linkOptions.name + '-' + i,
'fill': linkOptions.color
}),
linkTag = $(document.createElement('a')),
hoverAttr = linkOptions.hover.split(';')
.reduce(function(total, currentValue, currentIndex, arr) {
var temp = currentValue.split(':')
total[temp[0]] = temp[1];
return total;
}, {})
linkTag.attr({
'href': linkOptions.url,
'title': linkOptions.msg + capitalizeFirstLetter(linkOptions.name),
'target': linkOptions.target
})
linkTag.html($(document.createElement('div')).append(svg).html())
$(linkTag).hover(function() {
$(linkTag).find('svg').css(hoverAttr)
}, function() {
$.each(hoverAttr, function(i, el) {
$(linkTag).find('svg').css(i, '')
})
})
return linkTag
}
function getCached(name) {
cachedIcon = $.grep(cache, function(el) {
return el.name == name
})[0];
if (cachedIcon == undefined) {
return 'notCached';
} else if (cachedIcon.svg == 'loading') {
return 'loading';
} else {
return cachedIcon;
}
}
function getLoadQueue(queueName) {
return $.grep(loadQueue, function(el) {
return el.options.name == queueName
});
}
function removeElement(array, element) {
return $.grep(array, function(el) {
return el != element
});
}
})(jQuery);
|
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var config = require('../config');
mongoose.connect(config.dbConfig());
var db = require('../model/monstersModel')
fromdb = '';
/* GETS MONSTER ID */
router.get('/:id',function(req,res,next){
console.log(req.params)
// var id = parseInt(req.query.search, 10);
console.log('the get request is here');
id = req.params.id
db.findOne({id:id},function (err,docs){
fromdb = docs;
if (err || docs == null) res.render('error')
else res.render('monster', { title: docs.name, base:docs.id, monster:docs.materials,id:id });
});
console.log(fromdb);
});
router.post('/',function(req,res,next){
console.log("// CALLED")
var id = parseInt(req.body.monster_id);
db.findOne({id:id},function(err,docs){
console.log(docs,req.body,id)
if (err) throw err;
else res.render('monster',{title:docs.name,monster:docs.materials, id:id})
});
});
module.exports = router;
|
/**
* @license Highstock JS v9.3.2 (2021-11-29)
*
* Money Flow Index indicator for Highcharts Stock
*
* (c) 2010-2021 Grzegorz Blachliński
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/indicators/mfi', ['highcharts', 'highcharts/modules/stock'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'Stock/Indicators/MFI/MFIIndicator.js', [_modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (SeriesRegistry, U) {
/* *
*
* Money Flow Index indicator for Highcharts Stock
*
* (c) 2010-2021 Grzegorz Blachliński
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var SMAIndicator = SeriesRegistry.seriesTypes.sma;
var extend = U.extend,
merge = U.merge,
error = U.error,
isArray = U.isArray;
/* eslint-disable require-jsdoc */
// Utils:
function sumArray(array) {
return array.reduce(function (prev, cur) {
return prev + cur;
});
}
function toFixed(a, n) {
return parseFloat(a.toFixed(n));
}
function calculateTypicalPrice(point) {
return (point[1] + point[2] + point[3]) / 3;
}
function calculateRawMoneyFlow(typicalPrice, volume) {
return typicalPrice * volume;
}
/* eslint-enable require-jsdoc */
/* *
*
* Class
*
* */
/**
* The MFI series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.mfi
*
* @augments Highcharts.Series
*/
var MFIIndicator = /** @class */ (function (_super) {
__extends(MFIIndicator, _super);
function MFIIndicator() {
var _this = _super !== null && _super.apply(this,
arguments) || this;
/* *
*
* Properties
*
* */
_this.data = void 0;
_this.options = void 0;
_this.points = void 0;
return _this;
}
/* *
*
* Functions
*
* */
MFIIndicator.prototype.getValues = function (series, params) {
var period = params.period,
xVal = series.xData,
yVal = series.yData,
yValLen = yVal ? yVal.length : 0,
decimals = params.decimals,
// MFI starts calculations from the second point
// Cause we need to calculate change between two points
range = 1,
volumeSeries = series.chart.get(params.volumeSeriesID),
yValVolume = (volumeSeries && volumeSeries.yData),
MFI = [],
isUp = false,
xData = [],
yData = [],
positiveMoneyFlow = [],
negativeMoneyFlow = [],
newTypicalPrice,
oldTypicalPrice,
rawMoneyFlow,
negativeMoneyFlowSum,
positiveMoneyFlowSum,
moneyFlowRatio,
MFIPoint,
i;
if (!volumeSeries) {
error('Series ' +
params.volumeSeriesID +
' not found! Check `volumeSeriesID`.', true, series.chart);
return;
}
// MFI requires high low and close values
if ((xVal.length <= period) || !isArray(yVal[0]) ||
yVal[0].length !== 4 ||
!yValVolume) {
return;
}
// Calculate first typical price
newTypicalPrice = calculateTypicalPrice(yVal[range]);
// Accumulate first N-points
while (range < period + 1) {
// Calculate if up or down
oldTypicalPrice = newTypicalPrice;
newTypicalPrice = calculateTypicalPrice(yVal[range]);
isUp = newTypicalPrice >= oldTypicalPrice;
// Calculate raw money flow
rawMoneyFlow = calculateRawMoneyFlow(newTypicalPrice, yValVolume[range]);
// Add to array
positiveMoneyFlow.push(isUp ? rawMoneyFlow : 0);
negativeMoneyFlow.push(isUp ? 0 : rawMoneyFlow);
range++;
}
for (i = range - 1; i < yValLen; i++) {
if (i > range - 1) {
// Remove first point from array
positiveMoneyFlow.shift();
negativeMoneyFlow.shift();
// Calculate if up or down
oldTypicalPrice = newTypicalPrice;
newTypicalPrice = calculateTypicalPrice(yVal[i]);
isUp = newTypicalPrice > oldTypicalPrice;
// Calculate raw money flow
rawMoneyFlow = calculateRawMoneyFlow(newTypicalPrice, yValVolume[i]);
// Add to array
positiveMoneyFlow.push(isUp ? rawMoneyFlow : 0);
negativeMoneyFlow.push(isUp ? 0 : rawMoneyFlow);
}
// Calculate sum of negative and positive money flow:
negativeMoneyFlowSum = sumArray(negativeMoneyFlow);
positiveMoneyFlowSum = sumArray(positiveMoneyFlow);
moneyFlowRatio = positiveMoneyFlowSum / negativeMoneyFlowSum;
MFIPoint = toFixed(100 - (100 / (1 + moneyFlowRatio)), decimals);
MFI.push([xVal[i], MFIPoint]);
xData.push(xVal[i]);
yData.push(MFIPoint);
}
return {
values: MFI,
xData: xData,
yData: yData
};
};
/**
* Money Flow Index. This series requires `linkedTo` option to be set and
* should be loaded after the `stock/indicators/indicators.js` file.
*
* @sample stock/indicators/mfi
* Money Flow Index Indicator
*
* @extends plotOptions.sma
* @since 6.0.0
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/mfi
* @optionparent plotOptions.mfi
*/
MFIIndicator.defaultOptions = merge(SMAIndicator.defaultOptions, {
/**
* @excluding index
*/
params: {
index: void 0,
/**
* The id of volume series which is mandatory.
* For example using OHLC data, volumeSeriesID='volume' means
* the indicator will be calculated using OHLC and volume values.
*/
volumeSeriesID: 'volume',
/**
* Number of maximum decimals that are used in MFI calculations.
*/
decimals: 4
}
});
return MFIIndicator;
}(SMAIndicator));
extend(MFIIndicator.prototype, {
nameBase: 'Money Flow Index'
});
SeriesRegistry.registerSeriesType('mfi', MFIIndicator);
/* *
*
* Default Export
*
* */
/**
* A `MFI` series. If the [type](#series.mfi.type) option is not specified, it
* is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.mfi
* @since 6.0.0
* @excluding dataParser, dataURL
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/mfi
* @apioption series.mfi
*/
''; // to include the above in the js output
return MFIIndicator;
});
_registerModule(_modules, 'masters/indicators/mfi.src.js', [], function () {
});
})); |
/**
* @license Highstock JS v9.1.2 (2021-06-16)
*
* Indicator series type for Highcharts Stock
*
* (c) 2010-2021 Wojciech Chmiel
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/indicators/aroon-oscillator', ['highcharts', 'highcharts/modules/stock'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'Mixins/MultipleLines.js', [_modules['Core/Globals.js'], _modules['Core/Utilities.js']], function (H, U) {
/**
*
* (c) 2010-2021 Wojciech Chmiel
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var defined = U.defined,
error = U.error,
merge = U.merge;
var SMA = H.seriesTypes.sma;
/**
* Mixin useful for all indicators that have more than one line.
* Merge it with your implementation where you will provide
* getValues method appropriate to your indicator and pointArrayMap,
* pointValKey, linesApiNames properites. Notice that pointArrayMap
* should be consistent with amount of lines calculated in getValues method.
*
* @private
* @mixin multipleLinesMixin
*/
var multipleLinesMixin = {
/* eslint-disable valid-jsdoc */
/**
* Lines ids. Required to plot appropriate amount of lines.
* Notice that pointArrayMap should have more elements than
* linesApiNames, because it contains main line and additional lines ids.
* Also it should be consistent with amount of lines calculated in
* getValues method from your implementation.
*
* @private
* @name multipleLinesMixin.pointArrayMap
* @type {Array<string>}
*/
pointArrayMap: ['top', 'bottom'],
/**
* Main line id.
*
* @private
* @name multipleLinesMixin.pointValKey
* @type {string}
*/
pointValKey: 'top',
/**
* Additional lines DOCS names. Elements of linesApiNames array should
* be consistent with DOCS line names defined in your implementation.
* Notice that linesApiNames should have decreased amount of elements
* relative to pointArrayMap (without pointValKey).
*
* @private
* @name multipleLinesMixin.linesApiNames
* @type {Array<string>}
*/
linesApiNames: ['bottomLine'],
/**
* Create translatedLines Collection based on pointArrayMap.
*
* @private
* @function multipleLinesMixin.getTranslatedLinesNames
* @param {string} [excludedValue]
* Main line id
* @return {Array<string>}
* Returns translated lines names without excluded value.
*/
getTranslatedLinesNames: function (excludedValue) {
var translatedLines = [];
(this.pointArrayMap || []).forEach(function (propertyName) {
if (propertyName !== excludedValue) {
translatedLines.push('plot' +
propertyName.charAt(0).toUpperCase() +
propertyName.slice(1));
}
});
return translatedLines;
},
/**
* @private
* @function multipleLinesMixin.toYData
* @param {Highcharts.Point} point
* Indicator point
* @return {Array<number>}
* Returns point Y value for all lines
*/
toYData: function (point) {
var pointColl = [];
(this.pointArrayMap || []).forEach(function (propertyName) {
pointColl.push(point[propertyName]);
});
return pointColl;
},
/**
* Add lines plot pixel values.
*
* @private
* @function multipleLinesMixin.translate
* @return {void}
*/
translate: function () {
var indicator = this,
pointArrayMap = indicator.pointArrayMap,
LinesNames = [],
value;
LinesNames = indicator.getTranslatedLinesNames();
SMA.prototype.translate.apply(indicator, arguments);
indicator.points.forEach(function (point) {
pointArrayMap.forEach(function (propertyName, i) {
value = point[propertyName];
if (value !== null) {
point[LinesNames[i]] = indicator.yAxis.toPixels(value, true);
}
});
});
},
/**
* Draw main and additional lines.
*
* @private
* @function multipleLinesMixin.drawGraph
* @return {void}
*/
drawGraph: function () {
var indicator = this,
pointValKey = indicator.pointValKey,
linesApiNames = indicator.linesApiNames,
mainLinePoints = indicator.points,
pointsLength = mainLinePoints.length,
mainLineOptions = indicator.options,
mainLinePath = indicator.graph,
gappedExtend = {
options: {
gapSize: mainLineOptions.gapSize
}
},
// additional lines point place holders:
secondaryLines = [],
secondaryLinesNames = indicator.getTranslatedLinesNames(pointValKey),
point;
// Generate points for additional lines:
secondaryLinesNames.forEach(function (plotLine, index) {
// create additional lines point place holders
secondaryLines[index] = [];
while (pointsLength--) {
point = mainLinePoints[pointsLength];
secondaryLines[index].push({
x: point.x,
plotX: point.plotX,
plotY: point[plotLine],
isNull: !defined(point[plotLine])
});
}
pointsLength = mainLinePoints.length;
});
// Modify options and generate additional lines:
linesApiNames.forEach(function (lineName, i) {
if (secondaryLines[i]) {
indicator.points = secondaryLines[i];
if (mainLineOptions[lineName]) {
indicator.options = merge(mainLineOptions[lineName].styles, gappedExtend);
}
else {
error('Error: "There is no ' + lineName +
' in DOCS options declared. Check if linesApiNames' +
' are consistent with your DOCS line names."' +
' at mixin/multiple-line.js:34');
}
indicator.graph = indicator['graph' + lineName];
SMA.prototype.drawGraph.call(indicator);
// Now save lines:
indicator['graph' + lineName] = indicator.graph;
}
else {
error('Error: "' + lineName + ' doesn\'t have equivalent ' +
'in pointArrayMap. To many elements in linesApiNames ' +
'relative to pointArrayMap."');
}
});
// Restore options and draw a main line:
indicator.points = mainLinePoints;
indicator.options = mainLineOptions;
indicator.graph = mainLinePath;
SMA.prototype.drawGraph.call(indicator);
}
};
return multipleLinesMixin;
});
_registerModule(_modules, 'Mixins/IndicatorRequired.js', [_modules['Core/Utilities.js']], function (U) {
/**
*
* (c) 2010-2021 Daniel Studencki
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var error = U.error;
/* eslint-disable no-invalid-this, valid-jsdoc */
var requiredIndicatorMixin = {
/**
* Check whether given indicator is loaded,
else throw error.
* @private
* @param {Highcharts.Indicator} indicator
* Indicator constructor function.
* @param {string} requiredIndicator
* Required indicator type.
* @param {string} type
* Type of indicator where function was called (parent).
* @param {Highcharts.IndicatorCallbackFunction} callback
* Callback which is triggered if the given indicator is loaded.
* Takes indicator as an argument.
* @param {string} errMessage
* Error message that will be logged in console.
* @return {boolean}
* Returns false when there is no required indicator loaded.
*/
isParentLoaded: function (indicator,
requiredIndicator,
type,
callback,
errMessage) {
if (indicator) {
return callback ? callback(indicator) : true;
}
error(errMessage || this.generateMessage(type, requiredIndicator));
return false;
},
/**
* @private
* @param {string} indicatorType
* Indicator type
* @param {string} required
* Required indicator
* @return {string}
* Error message
*/
generateMessage: function (indicatorType, required) {
return 'Error: "' + indicatorType +
'" indicator type requires "' + required +
'" indicator loaded before. Please read docs: ' +
'https://api.highcharts.com/highstock/plotOptions.' +
indicatorType;
}
};
return requiredIndicatorMixin;
});
_registerModule(_modules, 'Stock/Indicators/AroonOscillator/AroonOscillatorIndicator.js', [_modules['Mixins/MultipleLines.js'], _modules['Mixins/IndicatorRequired.js'], _modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (multipleLinesMixin, requiredIndicator, SeriesRegistry, U) {
/* *
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var AroonIndicator = SeriesRegistry.seriesTypes.aroon;
var extend = U.extend,
merge = U.merge;
var AROON = SeriesRegistry.seriesTypes.aroon;
/* *
*
* Class
*
* */
/**
* The Aroon Oscillator series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.aroonoscillator
*
* @augments Highcharts.Series
*/
var AroonOscillatorIndicator = /** @class */ (function (_super) {
__extends(AroonOscillatorIndicator, _super);
function AroonOscillatorIndicator() {
var _this = _super !== null && _super.apply(this,
arguments) || this;
/* *
*
* Properties
*
* */
_this.data = void 0;
_this.options = void 0;
_this.points = void 0;
return _this;
}
/* *
*
* Functions
*
* */
AroonOscillatorIndicator.prototype.getValues = function (series, params) {
// 0- date, 1- Aroon Oscillator
var ARO = [],
xData = [],
yData = [],
aroon,
aroonUp,
aroonDown,
oscillator,
i;
aroon = AROON.prototype.getValues.call(this, series, params);
for (i = 0; i < aroon.yData.length; i++) {
aroonUp = aroon.yData[i][0];
aroonDown = aroon.yData[i][1];
oscillator = aroonUp - aroonDown;
ARO.push([aroon.xData[i], oscillator]);
xData.push(aroon.xData[i]);
yData.push(oscillator);
}
return {
values: ARO,
xData: xData,
yData: yData
};
};
AroonOscillatorIndicator.prototype.init = function () {
var args = arguments,
ctx = this;
requiredIndicator.isParentLoaded(AROON, 'aroon', ctx.type, function (indicator) {
indicator.prototype.init.apply(ctx, args);
return;
});
};
/**
* Aroon Oscillator. This series requires the `linkedTo` option to be set
* and should be loaded after the `stock/indicators/indicators.js` and
* `stock/indicators/aroon.js`.
*
* @sample {highstock} stock/indicators/aroon-oscillator
* Aroon Oscillator
*
* @extends plotOptions.aroon
* @since 7.0.0
* @product highstock
* @excluding allAreas, aroonDown, colorAxis, compare, compareBase,
* joinBy, keys, navigatorOptions, pointInterval,
* pointIntervalUnit, pointPlacement, pointRange, pointStart,
* showInNavigator, stacking
* @requires stock/indicators/indicators
* @requires stock/indicators/aroon
* @requires stock/indicators/aroon-oscillator
* @optionparent plotOptions.aroonoscillator
*/
AroonOscillatorIndicator.defaultOptions = merge(AroonIndicator.defaultOptions, {
tooltip: {
pointFormat: '<span style="color:{point.color}">\u25CF</span><b> {series.name}</b>: {point.y}'
}
});
return AroonOscillatorIndicator;
}(AroonIndicator));
extend(AroonOscillatorIndicator.prototype, merge(multipleLinesMixin, {
nameBase: 'Aroon Oscillator',
pointArrayMap: ['y'],
pointValKey: 'y',
linesApiNames: []
}));
SeriesRegistry.registerSeriesType('aroonoscillator', AroonOscillatorIndicator);
/* *
*
* Default Export
*
* */
/**
* An `Aroon Oscillator` series. If the [type](#series.aroonoscillator.type)
* option is not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.aroonoscillator
* @since 7.0.0
* @product highstock
* @excluding allAreas, aroonDown, colorAxis, compare, compareBase, dataParser,
* dataURL, joinBy, keys, navigatorOptions, pointInterval,
* pointIntervalUnit, pointPlacement, pointRange, pointStart,
* showInNavigator, stacking
* @requires stock/indicators/indicators
* @requires stock/indicators/aroon
* @requires stock/indicators/aroon-oscillator
* @apioption series.aroonoscillator
*/
''; // adds doclet above to the transpiled file
return AroonOscillatorIndicator;
});
_registerModule(_modules, 'masters/indicators/aroon-oscillator.src.js', [], function () {
});
})); |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _clsx = _interopRequireDefault(require("clsx"));
var _unstyled = require("@material-ui/unstyled");
var _system = require("@material-ui/system");
var _styled = _interopRequireWildcard(require("../styles/styled"));
var _useThemeProps = _interopRequireDefault(require("../styles/useThemeProps"));
var _ButtonBase = _interopRequireDefault(require("../ButtonBase"));
var _capitalize = _interopRequireDefault(require("../utils/capitalize"));
var _buttonClasses = _interopRequireWildcard(require("./buttonClasses"));
var _jsxRuntime = require("react/jsx-runtime");
const _excluded = ["children", "color", "component", "disabled", "disableElevation", "disableFocusRipple", "endIcon", "focusVisibleClassName", "fullWidth", "size", "startIcon", "type", "variant"];
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const useUtilityClasses = styleProps => {
const {
color,
disableElevation,
fullWidth,
size,
variant,
classes
} = styleProps;
const slots = {
root: ['root', variant, `${variant}${(0, _capitalize.default)(color)}`, `size${(0, _capitalize.default)(size)}`, `${variant}Size${(0, _capitalize.default)(size)}`, color === 'inherit' && 'colorInherit', disableElevation && 'disableElevation', fullWidth && 'fullWidth'],
label: ['label'],
startIcon: ['startIcon', `iconSize${(0, _capitalize.default)(size)}`],
endIcon: ['endIcon', `iconSize${(0, _capitalize.default)(size)}`]
};
const composedClasses = (0, _unstyled.unstable_composeClasses)(slots, _buttonClasses.getButtonUtilityClass, classes);
return (0, _extends2.default)({}, classes, composedClasses);
};
const commonIconStyles = styleProps => (0, _extends2.default)({}, styleProps.size === 'small' && {
'& > *:nth-of-type(1)': {
fontSize: 18
}
}, styleProps.size === 'medium' && {
'& > *:nth-of-type(1)': {
fontSize: 20
}
}, styleProps.size === 'large' && {
'& > *:nth-of-type(1)': {
fontSize: 22
}
});
const ButtonRoot = (0, _styled.default)(_ButtonBase.default, {
shouldForwardProp: prop => (0, _styled.rootShouldForwardProp)(prop) || prop === 'classes',
name: 'MuiButton',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
styleProps
} = props;
return [styles.root, styles[styleProps.variant], styles[`${styleProps.variant}${(0, _capitalize.default)(styleProps.color)}`], styles[`size${(0, _capitalize.default)(styleProps.size)}`], styles[`${styleProps.variant}Size${(0, _capitalize.default)(styleProps.size)}`], styleProps.color === 'inherit' && styles.colorInherit, styleProps.disableElevation && styles.disableElevation, styleProps.fullWidth && styles.fullWidth];
}
})(({
theme,
styleProps
}) => (0, _extends2.default)({}, theme.typography.button, {
minWidth: 64,
padding: '6px 16px',
borderRadius: theme.shape.borderRadius,
transition: theme.transitions.create(['background-color', 'box-shadow', 'border-color', 'color'], {
duration: theme.transitions.duration.short
}),
'&:hover': (0, _extends2.default)({
textDecoration: 'none',
backgroundColor: (0, _system.alpha)(theme.palette.text.primary, theme.palette.action.hoverOpacity),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}, styleProps.variant === 'text' && styleProps.color !== 'inherit' && {
backgroundColor: (0, _system.alpha)(theme.palette[styleProps.color].main, theme.palette.action.hoverOpacity),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}, styleProps.variant === 'outlined' && styleProps.color !== 'inherit' && {
border: `1px solid ${theme.palette[styleProps.color].main}`,
backgroundColor: (0, _system.alpha)(theme.palette[styleProps.color].main, theme.palette.action.hoverOpacity),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}, styleProps.variant === 'contained' && {
backgroundColor: theme.palette.grey.A100,
boxShadow: theme.shadows[4],
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
boxShadow: theme.shadows[2],
backgroundColor: theme.palette.grey[300]
}
}, styleProps.variant === 'contained' && styleProps.color !== 'inherit' && {
backgroundColor: theme.palette[styleProps.color].dark,
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: theme.palette[styleProps.color].main
}
}),
'&:active': (0, _extends2.default)({}, styleProps.variant === 'contained' && {
boxShadow: theme.shadows[8]
}),
[`&.${_buttonClasses.default.focusVisible}`]: (0, _extends2.default)({}, styleProps.variant === 'contained' && {
boxShadow: theme.shadows[6]
}),
[`&.${_buttonClasses.default.disabled}`]: (0, _extends2.default)({
color: theme.palette.action.disabled
}, styleProps.variant === 'outlined' && {
border: `1px solid ${theme.palette.action.disabledBackground}`
}, styleProps.variant === 'outlined' && styleProps.color === 'secondary' && {
border: `1px solid ${theme.palette.action.disabled}`
}, styleProps.variant === 'contained' && {
color: theme.palette.action.disabled,
boxShadow: theme.shadows[0],
backgroundColor: theme.palette.action.disabledBackground
})
}, styleProps.variant === 'text' && {
padding: '6px 8px'
}, styleProps.variant === 'text' && styleProps.color !== 'inherit' && {
color: theme.palette[styleProps.color].main
}, styleProps.variant === 'outlined' && {
padding: '5px 15px',
border: `1px solid ${theme.palette.mode === 'light' ? 'rgba(0, 0, 0, 0.23)' : 'rgba(255, 255, 255, 0.23)'}`
}, styleProps.variant === 'outlined' && styleProps.color !== 'inherit' && {
color: theme.palette[styleProps.color].main,
border: `1px solid ${(0, _system.alpha)(theme.palette[styleProps.color].main, 0.5)}`
}, styleProps.variant === 'contained' && {
color: theme.palette.getContrastText(theme.palette.grey[300]),
backgroundColor: theme.palette.grey[300],
boxShadow: theme.shadows[2]
}, styleProps.variant === 'contained' && styleProps.color !== 'inherit' && {
color: theme.palette[styleProps.color].contrastText,
backgroundColor: theme.palette[styleProps.color].main
}, styleProps.color === 'inherit' && {
color: 'inherit',
borderColor: 'currentColor'
}, styleProps.size === 'small' && styleProps.variant === 'text' && {
padding: '4px 5px',
fontSize: theme.typography.pxToRem(13)
}, styleProps.size === 'large' && styleProps.variant === 'text' && {
padding: '8px 11px',
fontSize: theme.typography.pxToRem(15)
}, styleProps.size === 'small' && styleProps.variant === 'outlined' && {
padding: '3px 9px',
fontSize: theme.typography.pxToRem(13)
}, styleProps.size === 'large' && styleProps.variant === 'outlined' && {
padding: '7px 21px',
fontSize: theme.typography.pxToRem(15)
}, styleProps.size === 'small' && styleProps.variant === 'contained' && {
padding: '4px 10px',
fontSize: theme.typography.pxToRem(13)
}, styleProps.size === 'large' && styleProps.variant === 'contained' && {
padding: '8px 22px',
fontSize: theme.typography.pxToRem(15)
}, styleProps.fullWidth && {
width: '100%'
}), ({
styleProps
}) => styleProps.disableElevation && {
boxShadow: 'none',
'&:hover': {
boxShadow: 'none'
},
[`&.${_buttonClasses.default.focusVisible}`]: {
boxShadow: 'none'
},
'&:active': {
boxShadow: 'none'
},
[`&.${_buttonClasses.default.disabled}`]: {
boxShadow: 'none'
}
});
const ButtonStartIcon = (0, _styled.default)('span', {
name: 'MuiButton',
slot: 'StartIcon',
overridesResolver: (props, styles) => {
const {
styleProps
} = props;
return [styles.startIcon, styles[`iconSize${(0, _capitalize.default)(styleProps.size)}`]];
}
})(({
styleProps
}) => (0, _extends2.default)({
display: 'inherit',
marginRight: 8,
marginLeft: -4
}, styleProps.size === 'small' && {
marginLeft: -2
}, commonIconStyles(styleProps)));
const ButtonEndIcon = (0, _styled.default)('span', {
name: 'MuiButton',
slot: 'EndIcon',
overridesResolver: (props, styles) => {
const {
styleProps
} = props;
return [styles.endIcon, styles[`iconSize${(0, _capitalize.default)(styleProps.size)}`]];
}
})(({
styleProps
}) => (0, _extends2.default)({
display: 'inherit',
marginRight: -4,
marginLeft: 8
}, styleProps.size === 'small' && {
marginRight: -2
}, commonIconStyles(styleProps)));
const Button = /*#__PURE__*/React.forwardRef(function Button(inProps, ref) {
const props = (0, _useThemeProps.default)({
props: inProps,
name: 'MuiButton'
});
const {
children,
color = 'primary',
component = 'button',
disabled = false,
disableElevation = false,
disableFocusRipple = false,
endIcon: endIconProp,
focusVisibleClassName,
fullWidth = false,
size = 'medium',
startIcon: startIconProp,
type,
variant = 'text'
} = props,
other = (0, _objectWithoutPropertiesLoose2.default)(props, _excluded);
const styleProps = (0, _extends2.default)({}, props, {
color,
component,
disabled,
disableElevation,
disableFocusRipple,
fullWidth,
size,
type,
variant
});
const classes = useUtilityClasses(styleProps);
const startIcon = startIconProp && /*#__PURE__*/(0, _jsxRuntime.jsx)(ButtonStartIcon, {
className: classes.startIcon,
styleProps: styleProps,
children: startIconProp
});
const endIcon = endIconProp && /*#__PURE__*/(0, _jsxRuntime.jsx)(ButtonEndIcon, {
className: classes.endIcon,
styleProps: styleProps,
children: endIconProp
});
return /*#__PURE__*/(0, _jsxRuntime.jsxs)(ButtonRoot, (0, _extends2.default)({
styleProps: styleProps,
component: component,
disabled: disabled,
focusRipple: !disableFocusRipple,
focusVisibleClassName: (0, _clsx.default)(classes.focusVisible, focusVisibleClassName),
ref: ref,
type: type
}, other, {
classes: classes,
children: [startIcon, children, endIcon]
}));
});
process.env.NODE_ENV !== "production" ? Button.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The content of the component.
*/
children: _propTypes.default.node,
/**
* Override or extend the styles applied to the component.
*/
classes: _propTypes.default.object,
/**
* The color of the component. It supports those theme colors that make sense for this component.
* @default 'primary'
*/
color: _propTypes.default
/* @typescript-to-proptypes-ignore */
.oneOfType([_propTypes.default.oneOf(['inherit', 'primary', 'secondary', 'success', 'error', 'info', 'warning']), _propTypes.default.string]),
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: _propTypes.default.elementType,
/**
* If `true`, the component is disabled.
* @default false
*/
disabled: _propTypes.default.bool,
/**
* If `true`, no elevation is used.
* @default false
*/
disableElevation: _propTypes.default.bool,
/**
* If `true`, the keyboard focus ripple is disabled.
* @default false
*/
disableFocusRipple: _propTypes.default.bool,
/**
* If `true`, the ripple effect is disabled.
*
* ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure
* to highlight the element by applying separate styles with the `.Mui-focusedVisible` class.
* @default false
*/
disableRipple: _propTypes.default.bool,
/**
* Element placed after the children.
*/
endIcon: _propTypes.default.node,
/**
* @ignore
*/
focusVisibleClassName: _propTypes.default.string,
/**
* If `true`, the button will take up the full width of its container.
* @default false
*/
fullWidth: _propTypes.default.bool,
/**
* The URL to link to when the button is clicked.
* If defined, an `a` element will be used as the root node.
*/
href: _propTypes.default.string,
/**
* The size of the component.
* `small` is equivalent to the dense button styling.
* @default 'medium'
*/
size: _propTypes.default
/* @typescript-to-proptypes-ignore */
.oneOfType([_propTypes.default.oneOf(['small', 'medium', 'large']), _propTypes.default.string]),
/**
* Element placed before the children.
*/
startIcon: _propTypes.default.node,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: _propTypes.default.object,
/**
* @ignore
*/
type: _propTypes.default.oneOfType([_propTypes.default.oneOf(['button', 'reset', 'submit']), _propTypes.default.string]),
/**
* The variant to use.
* @default 'text'
*/
variant: _propTypes.default
/* @typescript-to-proptypes-ignore */
.oneOfType([_propTypes.default.oneOf(['contained', 'outlined', 'text']), _propTypes.default.string])
} : void 0;
var _default = Button;
exports.default = _default; |
/**
* @license Highcharts JS v9.2.0 (2021-08-18)
*
* (c) 2010-2021 Highsoft AS
* Author: Sebastian Domas
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/modules/histogram-bellcurve', ['highcharts'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'Mixins/DerivedSeries.js', [_modules['Core/Globals.js'], _modules['Core/Series/Series.js'], _modules['Core/Utilities.js']], function (H, Series, U) {
/* *
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var noop = H.noop;
var addEvent = U.addEvent,
defined = U.defined;
/* ************************************************************************** *
*
* DERIVED SERIES MIXIN
*
* ************************************************************************** */
/**
* Provides methods for auto setting/updating series data based on the based
* series data.
*
* @private
* @mixin derivedSeriesMixin
*/
var derivedSeriesMixin = {
hasDerivedData: true,
/* eslint-disable valid-jsdoc */
/**
* Initialise series
*
* @private
* @function derivedSeriesMixin.init
* @return {void}
*/
init: function () {
Series.prototype.init.apply(this,
arguments);
this.initialised = false;
this.baseSeries = null;
this.eventRemovers = [];
this.addEvents();
},
/**
* Method to be implemented - inside the method the series has already
* access to the base series via m `this.baseSeries` and the bases data is
* initialised. It should return data in the format accepted by
* `Series.setData()` method
*
* @private
* @function derivedSeriesMixin.setDerivedData
* @return {Array<Highcharts.PointOptionsType>}
* An array of data
*/
setDerivedData: noop,
/**
* Sets base series for the series
*
* @private
* @function derivedSeriesMixin.setBaseSeries
* @return {void}
*/
setBaseSeries: function () {
var chart = this.chart,
baseSeriesOptions = this.options.baseSeries,
baseSeries = (defined(baseSeriesOptions) &&
(chart.series[baseSeriesOptions] ||
chart.get(baseSeriesOptions)));
this.baseSeries = baseSeries || null;
},
/**
* Adds events for the series
*
* @private
* @function derivedSeriesMixin.addEvents
* @return {void}
*/
addEvents: function () {
var derivedSeries = this,
chartSeriesLinked;
chartSeriesLinked = addEvent(this.chart, 'afterLinkSeries', function () {
derivedSeries.setBaseSeries();
if (derivedSeries.baseSeries && !derivedSeries.initialised) {
derivedSeries.setDerivedData();
derivedSeries.addBaseSeriesEvents();
derivedSeries.initialised = true;
}
});
this.eventRemovers.push(chartSeriesLinked);
},
/**
* Adds events to the base series - it required for recalculating the data
* in the series if the base series is updated / removed / etc.
*
* @private
* @function derivedSeriesMixin.addBaseSeriesEvents
* @return {void}
*/
addBaseSeriesEvents: function () {
var derivedSeries = this,
updatedDataRemover,
destroyRemover;
updatedDataRemover = addEvent(derivedSeries.baseSeries, 'updatedData', function () {
derivedSeries.setDerivedData();
});
destroyRemover = addEvent(derivedSeries.baseSeries, 'destroy', function () {
derivedSeries.baseSeries = null;
derivedSeries.initialised = false;
});
derivedSeries.eventRemovers.push(updatedDataRemover, destroyRemover);
},
/**
* Destroys the series
*
* @private
* @function derivedSeriesMixin.destroy
*/
destroy: function () {
this.eventRemovers.forEach(function (remover) {
remover();
});
Series.prototype.destroy.apply(this, arguments);
}
/* eslint-disable valid-jsdoc */
};
return derivedSeriesMixin;
});
_registerModule(_modules, 'Series/Histogram/HistogramSeries.js', [_modules['Mixins/DerivedSeries.js'], _modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (DerivedSeriesMixin, SeriesRegistry, U) {
/* *
*
* Copyright (c) 2010-2021 Highsoft AS
* Author: Sebastian Domas
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var ColumnSeries = SeriesRegistry.seriesTypes.column;
var arrayMax = U.arrayMax,
arrayMin = U.arrayMin,
correctFloat = U.correctFloat,
extend = U.extend,
isNumber = U.isNumber,
merge = U.merge,
objectEach = U.objectEach;
/* ************************************************************************** *
* HISTOGRAM
* ************************************************************************** */
/**
* A dictionary with formulas for calculating number of bins based on the
* base series
**/
var binsNumberFormulas = {
'square-root': function (baseSeries) {
return Math.ceil(Math.sqrt(baseSeries.options.data.length));
},
'sturges': function (baseSeries) {
return Math.ceil(Math.log(baseSeries.options.data.length) * Math.LOG2E);
},
'rice': function (baseSeries) {
return Math.ceil(2 * Math.pow(baseSeries.options.data.length, 1 / 3));
}
};
/**
* Returns a function for mapping number to the closed (right opened) bins
* @private
* @param {Array<number>} bins - Width of the bins
* @return {Function}
**/
function fitToBinLeftClosed(bins) {
return function (y) {
var i = 1;
while (bins[i] <= y) {
i++;
}
return bins[--i];
};
}
/* *
*
* Class
*
* */
/**
* Histogram class
* @private
* @class
* @name Highcharts.seriesTypes.histogram
* @augments Highcharts.Series
*/
var HistogramSeries = /** @class */ (function (_super) {
__extends(HistogramSeries, _super);
function HistogramSeries() {
/* *
*
* Static Properties
*
* */
var _this = _super !== null && _super.apply(this,
arguments) || this;
_this.data = void 0;
_this.options = void 0;
_this.points = void 0;
_this.userOptions = void 0;
return _this;
/* eslint-enable valid-jsdoc */
}
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
HistogramSeries.prototype.binsNumber = function () {
var binsNumberOption = this.options.binsNumber;
var binsNumber = binsNumberFormulas[binsNumberOption] ||
// #7457
(typeof binsNumberOption === 'function' && binsNumberOption);
return Math.ceil((binsNumber && binsNumber(this.baseSeries)) ||
(isNumber(binsNumberOption) ?
binsNumberOption :
binsNumberFormulas['square-root'](this.baseSeries)));
};
HistogramSeries.prototype.derivedData = function (baseData, binsNumber, binWidth) {
var series = this,
max = correctFloat(arrayMax(baseData)),
// Float correction needed, because first frequency value is not
// corrected when generating frequencies (within for loop).
min = correctFloat(arrayMin(baseData)),
frequencies = [],
bins = {},
data = [],
x,
fitToBin;
binWidth = series.binWidth = (correctFloat(isNumber(binWidth) ?
(binWidth || 1) :
(max - min) / binsNumber));
// #12077 negative pointRange causes wrong calculations,
// browser hanging.
series.options.pointRange = Math.max(binWidth, 0);
// If binWidth is 0 then max and min are equaled,
// increment the x with some positive value to quit the loop
for (x = min;
// This condition is needed because of the margin of error while
// operating on decimal numbers. Without that, additional bin
// was sometimes noticeable on the graph, because of too small
// precision of float correction.
x < max &&
(series.userOptions.binWidth ||
correctFloat(max - x) >= binWidth ||
// #13069 - Every add and subtract operation should
// be corrected, due to general problems with
// operations on float numbers in JS.
correctFloat(correctFloat(min + (frequencies.length * binWidth)) -
x) <= 0); x = correctFloat(x + binWidth)) {
frequencies.push(x);
bins[x] = 0;
}
if (bins[min] !== 0) {
frequencies.push(min);
bins[min] = 0;
}
fitToBin = fitToBinLeftClosed(frequencies.map(function (elem) {
return parseFloat(elem);
}));
baseData.forEach(function (y) {
var x = correctFloat(fitToBin(y));
bins[x]++;
});
objectEach(bins, function (frequency, x) {
data.push({
x: Number(x),
y: frequency,
x2: correctFloat(Number(x) + binWidth)
});
});
data.sort(function (a, b) {
return a.x - b.x;
});
data[data.length - 1].x2 = max;
return data;
};
HistogramSeries.prototype.setDerivedData = function () {
var yData = this.baseSeries.yData;
if (!yData.length) {
this.setData([]);
return;
}
var data = this.derivedData(yData,
this.binsNumber(),
this.options.binWidth);
this.setData(data, false);
};
/**
* A histogram is a column series which represents the distribution of the
* data set in the base series. Histogram splits data into bins and shows
* their frequencies.
*
* @sample {highcharts} highcharts/demo/histogram/
* Histogram
*
* @extends plotOptions.column
* @excluding boostThreshold, dragDrop, pointInterval, pointIntervalUnit,
* stacking, boostBlending
* @product highcharts
* @since 6.0.0
* @requires modules/histogram
* @optionparent plotOptions.histogram
*/
HistogramSeries.defaultOptions = merge(ColumnSeries.defaultOptions, {
/**
* A preferable number of bins. It is a suggestion, so a histogram may
* have a different number of bins. By default it is set to the square
* root of the base series' data length. Available options are:
* `square-root`, `sturges`, `rice`. You can also define a function
* which takes a `baseSeries` as a parameter and should return a
* positive integer.
*
* @type {"square-root"|"sturges"|"rice"|number|function}
*/
binsNumber: 'square-root',
/**
* Width of each bin. By default the bin's width is calculated as
* `(max - min) / number of bins`. This option takes precedence over
* [binsNumber](#plotOptions.histogram.binsNumber).
*
* @type {number}
*/
binWidth: void 0,
pointPadding: 0,
groupPadding: 0,
grouping: false,
pointPlacement: 'between',
tooltip: {
headerFormat: '',
pointFormat: ('<span style="font-size: 10px">{point.x} - {point.x2}' +
'</span><br/>' +
'<span style="color:{point.color}">\u25CF</span>' +
' {series.name} <b>{point.y}</b><br/>')
}
});
return HistogramSeries;
}(ColumnSeries));
extend(HistogramSeries.prototype, {
addBaseSeriesEvents: DerivedSeriesMixin.addBaseSeriesEvents,
addEvents: DerivedSeriesMixin.addEvents,
destroy: DerivedSeriesMixin.destroy,
hasDerivedData: DerivedSeriesMixin.hasDerivedData,
init: DerivedSeriesMixin.init,
setBaseSeries: DerivedSeriesMixin.setBaseSeries
});
SeriesRegistry.registerSeriesType('histogram', HistogramSeries);
/* *
*
* Default Export
*
* */
/* *
*
* API Options
*
* */
/**
* A `histogram` series. If the [type](#series.histogram.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.histogram
* @excluding data, dataParser, dataURL, boostThreshold, boostBlending
* @product highcharts
* @since 6.0.0
* @requires modules/histogram
* @apioption series.histogram
*/
/**
* An integer identifying the index to use for the base series, or a string
* representing the id of the series.
*
* @type {number|string}
* @apioption series.histogram.baseSeries
*/
''; // adds doclets above to transpiled file
return HistogramSeries;
});
_registerModule(_modules, 'Series/Bellcurve/BellcurveSeries.js', [_modules['Mixins/DerivedSeries.js'], _modules['Core/Series/SeriesRegistry.js'], _modules['Core/Utilities.js']], function (DerivedSeriesMixin, SeriesRegistry, U) {
/* *
*
* (c) 2010-2021 Highsoft AS
*
* Author: Sebastian Domas
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d,
b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d,
b) { d.__proto__ = b; }) ||
function (d,
b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var AreaSplineSeries = SeriesRegistry.seriesTypes.areaspline;
var correctFloat = U.correctFloat,
extend = U.extend,
isNumber = U.isNumber,
merge = U.merge;
/**
* Bell curve class
*
* @private
* @class
* @name Highcharts.seriesTypes.bellcurve
*
* @augments Highcharts.Series
*/
var BellcurveSeries = /** @class */ (function (_super) {
__extends(BellcurveSeries, _super);
function BellcurveSeries() {
/* *
*
* Static Properties
*
* */
var _this = _super !== null && _super.apply(this,
arguments) || this;
/* eslint-enable valid-jsdoc */
/* *
*
* Properties
*
* */
_this.data = void 0;
_this.options = void 0;
_this.points = void 0;
return _this;
/* eslint-enable valid-jsdoc */
}
/* *
*
* Static Functions
*
* */
/* eslint-disable valid-jsdoc */
/**
* @private
*/
BellcurveSeries.mean = function (data) {
var length = data.length,
sum = data.reduce(function (sum,
value) {
return (sum += value);
}, 0);
return length > 0 && sum / length;
};
/**
* @private
*/
BellcurveSeries.standardDeviation = function (data, average) {
var len = data.length,
sum;
average = isNumber(average) ? average : BellcurveSeries.mean(data);
sum = data.reduce(function (sum, value) {
var diff = value - average;
return (sum += diff * diff);
}, 0);
return len > 1 && Math.sqrt(sum / (len - 1));
};
/**
* @private
*/
BellcurveSeries.normalDensity = function (x, mean, standardDeviation) {
var translation = x - mean;
return Math.exp(-(translation * translation) /
(2 * standardDeviation * standardDeviation)) / (standardDeviation * Math.sqrt(2 * Math.PI));
};
/* *
*
* Functions
*
* */
/* eslint-disable valid-jsdoc */
BellcurveSeries.prototype.derivedData = function (mean, standardDeviation) {
var intervals = this.options.intervals,
pointsInInterval = this.options.pointsInInterval,
x = mean - intervals * standardDeviation,
stop = intervals * pointsInInterval * 2 + 1,
increment = standardDeviation / pointsInInterval,
data = [],
i;
for (i = 0; i < stop; i++) {
data.push([x, BellcurveSeries.normalDensity(x, mean, standardDeviation)]);
x += increment;
}
return data;
};
BellcurveSeries.prototype.setDerivedData = function () {
if (this.baseSeries.yData.length > 1) {
this.setMean();
this.setStandardDeviation();
this.setData(this.derivedData(this.mean, this.standardDeviation), false);
}
return (void 0);
};
BellcurveSeries.prototype.setMean = function () {
this.mean = correctFloat(BellcurveSeries.mean(this.baseSeries.yData));
};
BellcurveSeries.prototype.setStandardDeviation = function () {
this.standardDeviation = correctFloat(BellcurveSeries.standardDeviation(this.baseSeries.yData, this.mean));
};
/**
* A bell curve is an areaspline series which represents the probability
* density function of the normal distribution. It calculates mean and
* standard deviation of the base series data and plots the curve according
* to the calculated parameters.
*
* @sample {highcharts} highcharts/demo/bellcurve/
* Bell curve
*
* @extends plotOptions.areaspline
* @since 6.0.0
* @product highcharts
* @excluding boostThreshold, connectNulls, dragDrop, stacking,
* pointInterval, pointIntervalUnit
* @requires modules/bellcurve
* @optionparent plotOptions.bellcurve
*/
BellcurveSeries.defaultOptions = merge(AreaSplineSeries.defaultOptions, {
/**
* @see [fillColor](#plotOptions.bellcurve.fillColor)
* @see [fillOpacity](#plotOptions.bellcurve.fillOpacity)
*
* @apioption plotOptions.bellcurve.color
*/
/**
* @see [color](#plotOptions.bellcurve.color)
* @see [fillOpacity](#plotOptions.bellcurve.fillOpacity)
*
* @apioption plotOptions.bellcurve.fillColor
*/
/**
* @see [color](#plotOptions.bellcurve.color)
* @see [fillColor](#plotOptions.bellcurve.fillColor)
*
* @default {highcharts} 0.75
* @default {highstock} 0.75
* @apioption plotOptions.bellcurve.fillOpacity
*/
/**
* This option allows to define the length of the bell curve. A unit of
* the length of the bell curve is standard deviation.
*
* @sample highcharts/plotoptions/bellcurve-intervals-pointsininterval
* Intervals and points in interval
*/
intervals: 3,
/**
* Defines how many points should be plotted within 1 interval. See
* `plotOptions.bellcurve.intervals`.
*
* @sample highcharts/plotoptions/bellcurve-intervals-pointsininterval
* Intervals and points in interval
*/
pointsInInterval: 3,
marker: {
enabled: false
}
});
return BellcurveSeries;
}(AreaSplineSeries));
extend(BellcurveSeries.prototype, {
addBaseSeriesEvents: DerivedSeriesMixin.addBaseSeriesEvents,
addEvents: DerivedSeriesMixin.addEvents,
destroy: DerivedSeriesMixin.destroy,
init: DerivedSeriesMixin.init,
setBaseSeries: DerivedSeriesMixin.setBaseSeries
});
SeriesRegistry.registerSeriesType('bellcurve', BellcurveSeries);
/* *
*
* Default Export
*
* */
/* *
*
* API Options
*
* */
/**
* A `bellcurve` series. If the [type](#series.bellcurve.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* For options that apply to multiple series, it is recommended to add
* them to the [plotOptions.series](#plotOptions.series) options structure.
* To apply to all series of this specific type, apply it to
* [plotOptions.bellcurve](#plotOptions.bellcurve).
*
* @extends series,plotOptions.bellcurve
* @since 6.0.0
* @product highcharts
* @excluding dataParser, dataURL, data, boostThreshold, boostBlending
* @requires modules/bellcurve
* @apioption series.bellcurve
*/
/**
* An integer identifying the index to use for the base series, or a string
* representing the id of the series.
*
* @type {number|string}
* @apioption series.bellcurve.baseSeries
*/
/**
* @see [fillColor](#series.bellcurve.fillColor)
* @see [fillOpacity](#series.bellcurve.fillOpacity)
*
* @apioption series.bellcurve.color
*/
/**
* @see [color](#series.bellcurve.color)
* @see [fillOpacity](#series.bellcurve.fillOpacity)
*
* @apioption series.bellcurve.fillColor
*/
/**
* @see [color](#series.bellcurve.color)
* @see [fillColor](#series.bellcurve.fillColor)
*
* @default {highcharts} 0.75
* @default {highstock} 0.75
* @apioption series.bellcurve.fillOpacity
*/
''; // adds doclets above to transpiled file
return BellcurveSeries;
});
_registerModule(_modules, 'masters/modules/histogram-bellcurve.src.js', [], function () {
});
})); |
import{W as t}from"./index-4c9d8d14.js";class s extends t{static get formatter(){}static get params(){return{localized:!0}}init(){super.init()}connected(){super.connected(),this.apply()}changed(t,s){super.changed(t,s),t in this.props&&this.isConnected&&this.apply()}apply(){this.locale||this.setLocale(this.lang),this.host.innerHTML=this.constructor.formatter(this.value,this.locale,this)}fromHostValue(t,s){this.value=t,this.apply()}}export{s as F}; |
/*
Highcharts JS v9.0.0 (2021-02-02)
(c) 2009-2019 Sebastian Bochan, Rafal Sebestjanski
License: www.highcharts.com/license
*/
(function(b){"object"===typeof module&&module.exports?(b["default"]=b,module.exports=b):"function"===typeof define&&define.amd?define("highcharts/modules/lollipop",["highcharts"],function(c){b(c);b.Highcharts=c;return b}):b("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(b){function c(b,e,f,c){b.hasOwnProperty(e)||(b[e]=c.apply(null,f))}b=b?b._modules:{};c(b,"Series/Lollipop/LollipopPoint.js",[b["Core/Series/SeriesRegistry.js"],b["Core/Utilities.js"]],function(b,e){var f=this&&this.__extends||
function(){var b=function(d,a){b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,d){b.__proto__=d}||function(b,d){for(var a in d)d.hasOwnProperty(a)&&(b[a]=d[a])};return b(d,a)};return function(d,a){function c(){this.constructor=d}b(d,a);d.prototype=null===a?Object.create(a):(c.prototype=a.prototype,new c)}}(),c=b.series.prototype.pointClass,a=b.seriesTypes;b=a.area.prototype;var g=e.isObject;e=e.extend;a=function(b){function a(){var a=null!==b&&b.apply(this,arguments)||this;a.series=
void 0;a.options=void 0;return a}f(a,b);return a}(a.dumbbell.prototype.pointClass);e(a.prototype,{pointSetState:b.pointClass.prototype.setState,isValid:c.prototype.isValid,init:function(b,a,e){g(a)&&"low"in a&&(a.y=a.low,delete a.low);return c.prototype.init.apply(this,arguments)}});return a});c(b,"Series/Lollipop/LollipopSeries.js",[b["Series/Lollipop/LollipopPoint.js"],b["Core/Series/SeriesRegistry.js"],b["Core/Utilities.js"]],function(b,c,f){var e=this&&this.__extends||function(){var b=function(a,
c){b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,a){b.__proto__=a}||function(b,a){for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c])};return b(a,c)};return function(a,c){function d(){this.constructor=a}b(a,c);a.prototype=null===c?Object.create(c):(d.prototype=c.prototype,new d)}}(),a=c.seriesTypes,g=a.area.prototype,h=a.column.prototype,d=a.dumbbell,k=f.pick,l=f.merge;f=f.extend;a=function(b){function a(){var a=null!==b&&b.apply(this,arguments)||this;a.data=void 0;a.options=void 0;
a.points=void 0;return a}e(a,b);a.prototype.toYData=function(a){return[k(a.y,a.low)]};a.defaultOptions=l(d.defaultOptions,{lowColor:void 0,threshold:0,connectorWidth:1,groupPadding:.2,pointPadding:.1,states:{hover:{lineWidthPlus:0,connectorWidthPlus:1,halo:!1}},tooltip:{pointFormat:'<span style="color:{series.color}">\u25cf</span> {series.name}: <b>{point.y}</b><br/>'}});return a}(d);f(a.prototype,{pointArrayMap:["y"],pointValKey:"y",translatePoint:g.translate,drawPoint:g.drawPoints,drawDataLabels:h.drawDataLabels,
setShapeArgs:h.translate,pointClass:b});c.registerSeriesType("lollipop",a);"";return a});c(b,"masters/modules/lollipop.src.js",[],function(){})});
//# sourceMappingURL=lollipop.js.map |
/*jshint eqeqeq:false */
/*global jQuery, define */
(function( factory ) {
"use strict";
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([
"jquery",
"./grid.base"
], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
/**
* all events and options here are aded anonynous and not in the base grid
* since the array is to big. Here is the order of execution.
* From this point we use jQuery isFunction
* formatCell
* beforeEditCell,
* onCellSelect (used only for noneditable cels)
* afterEditCell,
* beforeSaveCell, (called before validation of values if any)
* beforeSubmitCell (if cellsubmit remote (ajax))
* onSubmitCell
* afterSubmitCell(if cellsubmit remote (ajax)),
* afterSaveCell,
* errorCell,
* validationCell
* serializeCellData - new
* Options
* cellsubmit (remote,clientArray) (added in grid options)
* cellurl
* ajaxCellOptions
* restoreCellonFail
* */
"use strict";
//module begin
$.jgrid.extend({
editCell : function (iRow,iCol, ed, event){
return this.each(function (){
var $t = this, nm, tmp,cc, cm,
highlight = $(this).jqGrid('getStyleUI',$t.p.styleUI+'.common','highlight', true),
hover = $(this).jqGrid('getStyleUI',$t.p.styleUI+'.common','hover', true),
inpclass = $(this).jqGrid('getStyleUI',$t.p.styleUI+".celledit",'inputClass', true);
if (!$t.grid || $t.p.cellEdit !== true) {return;}
iCol = parseInt(iCol,10);
// select the row that can be used for other methods
$t.p.selrow = $t.rows[iRow].id;
if (!$t.p.knv) {$($t).jqGrid("GridNav");}
// check to see if we have already edited cell
if ($t.p.savedRow.length>0) {
// prevent second click on that field and enable selects
if (ed===true ) {
if(iRow == $t.p.iRow && iCol == $t.p.iCol){
return;
}
}
// save the cell
$($t).jqGrid("saveCell",$t.p.savedRow[0].id,$t.p.savedRow[0].ic);
} else {
window.setTimeout(function () { $("#"+$.jgrid.jqID($t.p.knv)).attr("tabindex","-1").focus();},1);
}
cm = $t.p.colModel[iCol];
nm = cm.name;
if (nm==='subgrid' || nm==='cb' || nm==='rn') {return;}
try {
cc = $($t.rows[iRow].cells[iCol]);
} catch(e) {
cc = $("td:eq("+iCol+")",$t.rows[iRow]);
}
if(parseInt($t.p.iCol,10)>=0 && parseInt($t.p.iRow,10)>=0 && $t.p.iRowId !== undefined) {
var therow = $($t).jqGrid('getGridRowById', $t.p.iRowId);
//$("td:eq("+$t.p.iCol+")",$t.rows[$t.p.iRow]).removeClass("edit-cell " + highlight);
$(therow).removeClass("selected-row " + hover).find("td:eq("+$t.p.iCol+")").removeClass("edit-cell " + highlight);
}
cc.addClass("edit-cell " + highlight);
$($t.rows[iRow]).addClass("selected-row " + hover);
if (cm.editable===true && ed===true && !cc.hasClass("not-editable-cell") && (!$.isFunction($t.p.isCellEditable) || $t.p.isCellEditable.call($t,nm,iRow,iCol))) {
try {
tmp = $.unformat.call($t,cc,{rowId: $t.rows[iRow].id, colModel:cm},iCol);
} catch (_) {
tmp = ( cm.edittype && cm.edittype === 'textarea' ) ? cc.text() : cc.html();
}
if($t.p.autoencode) { tmp = $.jgrid.htmlDecode(tmp); }
if (!cm.edittype) {cm.edittype = "text";}
$t.p.savedRow.push({id:iRow, ic:iCol, name:nm, v:tmp, rowId: $t.rows[iRow].id });
if(tmp === " " || tmp === " " || (tmp.length===1 && tmp.charCodeAt(0)===160) ) {tmp='';}
if($.isFunction($t.p.formatCell)) {
var tmp2 = $t.p.formatCell.call($t, $t.rows[iRow].id,nm,tmp,iRow,iCol);
if(tmp2 !== undefined ) {tmp = tmp2;}
}
$($t).triggerHandler("jqGridBeforeEditCell", [$t.rows[iRow].id, nm, tmp, iRow, iCol]);
if ($.isFunction($t.p.beforeEditCell)) {
$t.p.beforeEditCell.call($t, $t.rows[iRow].id,nm,tmp,iRow,iCol);
}
var opt = $.extend({}, cm.editoptions || {} ,{id:iRow+"_"+nm,name:nm,rowId: $t.rows[iRow].id, oper:'edit', module : 'cell'});
var elc = $.jgrid.createEl.call($t,cm.edittype,opt,tmp,true,$.extend({},$.jgrid.ajaxOptions,$t.p.ajaxSelectOptions || {}));
if( $.inArray(cm.edittype, ['text','textarea','password','select']) > -1) {
$(elc).addClass(inpclass);
}
cc.html("").append(elc).attr("tabindex","0");
$.jgrid.bindEv.call($t, elc, opt);
window.setTimeout(function () { $(elc).focus();},1);
$("input, select, textarea",cc).on("keydown",function(e) {
if (e.keyCode === 27) {
if($("input.hasDatepicker",cc).length >0) {
if( $(".ui-datepicker").is(":hidden") ) { $($t).jqGrid("restoreCell",iRow,iCol); }
else { $("input.hasDatepicker",cc).datepicker('hide'); }
} else {
$($t).jqGrid("restoreCell",iRow,iCol);
}
} //ESC
if (e.keyCode === 13 && !e.shiftKey) {
$($t).jqGrid("saveCell",iRow,iCol);
// Prevent default action
return false;
} //Enter
if (e.keyCode === 9) {
if(!$t.grid.hDiv.loading ) {
if (e.shiftKey) { //Shift TAb
var succ2 = $($t).jqGrid("prevCell", iRow, iCol, e);
if(!succ2 && $t.p.editNextRowCell) {
if(iRow-1 > 0 && $t.rows[iRow-1]) {
iRow--;
$($t).jqGrid("prevCell", iRow, $t.p.colModel.length, e);
}
}
} else {
var succ = $($t).jqGrid("nextCell", iRow, iCol, e);
if(!succ && $t.p.editNextRowCell) {
if($t.rows[iRow+1]) {
iRow++;
$($t).jqGrid("nextCell", iRow, 0, e);
}
}
} //Tab
} else {
return false;
}
}
e.stopPropagation();
});
$($t).triggerHandler("jqGridAfterEditCell", [$t.rows[iRow].id, nm, tmp, iRow, iCol]);
if ($.isFunction($t.p.afterEditCell)) {
$t.p.afterEditCell.call($t, $t.rows[iRow].id,nm,tmp,iRow,iCol);
}
} else {
tmp = cc.html().replace(/\ \;/ig,'');
$($t).triggerHandler("jqGridCellSelect", [$t.rows[iRow].id, iCol, tmp, event]);
if ($.isFunction($t.p.onCellSelect)) {
$t.p.onCellSelect.call($t, $t.rows[iRow].id, iCol, tmp, event);
}
}
$t.p.iCol = iCol; $t.p.iRow = iRow; $t.p.iRowId = $t.rows[iRow].id;
});
},
saveCell : function (iRow, iCol){
return this.each(function(){
var $t= this, fr = $t.p.savedRow.length >= 1 ? 0 : null,
errors = $.jgrid.getRegional(this, 'errors'),
edit =$.jgrid.getRegional(this, 'edit');
if (!$t.grid || $t.p.cellEdit !== true) {return;}
if(fr !== null) {
var trow = $($t).jqGrid("getGridRowById", $t.p.savedRow[0].rowId),
cc = $('td:eq('+iCol+')', trow),
cm = $t.p.colModel[iCol], nm = cm.name, nmjq = $.jgrid.jqID(nm), v, v2,
p = $(cc).offset();
switch (cm.edittype) {
case "select":
if(!cm.editoptions.multiple) {
v = $("#"+iRow+"_"+nmjq+" option:selected", trow ).val();
v2 = $("#"+iRow+"_"+nmjq+" option:selected", trow).text();
} else {
var sel = $("#"+iRow+"_"+nmjq, trow), selectedText = [];
v = $(sel).val();
if(v) { v.join(",");} else { v=""; }
$("option:selected",sel).each(
function(i,selected){
selectedText[i] = $(selected).text();
}
);
v2 = selectedText.join(",");
}
if(cm.formatter) { v2 = v; }
break;
case "checkbox":
var cbv = ["Yes","No"];
if(cm.editoptions && cm.editoptions.value){
cbv = cm.editoptions.value.split(":");
}
v = $("#"+iRow+"_"+nmjq, trow).is(":checked") ? cbv[0] : cbv[1];
v2=v;
break;
case "password":
case "text":
case "textarea":
case "button" :
v = $("#"+iRow+"_"+nmjq, trow).val();
v2=v;
break;
case 'custom' :
try {
if(cm.editoptions && $.isFunction(cm.editoptions.custom_value)) {
v = cm.editoptions.custom_value.call($t, $(".customelement",cc),'get');
if (v===undefined) { throw "e2";} else { v2=v; }
} else { throw "e1"; }
} catch (e) {
if (e==="e1") { $.jgrid.info_dialog(errors.errcap, "function 'custom_value' " + edit.msg.nodefined, edit.bClose, {styleUI : $t.p.styleUI }); }
else if (e==="e2") { $.jgrid.info_dialog(errors.errcap, "function 'custom_value' " + edit.msg.novalue, edit.bClose, {styleUI : $t.p.styleUI }); }
else {$.jgrid.info_dialog(errors.errcap, e.message, edit.bClose, {styleUI : $t.p.styleUI }); }
}
break;
}
// The common approach is if nothing changed do not do anything
if (v2 !== $t.p.savedRow[fr].v){
var vvv = $($t).triggerHandler("jqGridBeforeSaveCell", [$t.p.savedRow[fr].rowId, nm, v, iRow, iCol]);
if (vvv) {v = vvv; v2=vvv;}
if ($.isFunction($t.p.beforeSaveCell)) {
var vv = $t.p.beforeSaveCell.call($t, $t.p.savedRow[fr].rowId, nm, v, iRow, iCol);
if (vv) {v = vv; v2=vv;}
}
var cv = $.jgrid.checkValues.call($t, v, iCol), nuem = false;
if(cv[0] === true) {
var addpost = $($t).triggerHandler("jqGridBeforeSubmitCell", [$t.p.savedRow[fr].rowId, nm, v, iRow, iCol]) || {};
if ($.isFunction($t.p.beforeSubmitCell)) {
addpost = $t.p.beforeSubmitCell.call($t, $t.p.savedRow[fr].rowId, nm, v, iRow, iCol);
if (!addpost) {addpost={};}
}
var retsub = $($t).triggerHandler("jqGridOnSubmitCell", [$t.p.savedRow[fr].rowId, nm, v, iRow, iCol]);
if(retsub === undefined) {
retsub = true;
}
if($.isFunction($t.p.onSubmitCell) ) {
retsub = $t.p.onSubmitCell($t.p.savedRow[fr].rowId, nm, v, iRow, iCol);
if( retsub === undefined) {
retsub = true;
}
}
if( retsub === false) {
return;
}
if( $("input.hasDatepicker",cc).length >0) { $("input.hasDatepicker",cc).datepicker('hide'); }
if ($t.p.cellsubmit === 'remote') {
if ($t.p.cellurl) {
var postdata = {};
if($t.p.autoencode) { v = $.jgrid.htmlEncode(v); }
if(cm.editoptions && cm.editoptions.NullIfEmpty && v === "") {
v = 'null';
nuem = true;
}
postdata[nm] = v;
var opers = $t.p.prmNames,
idname = opers.id,
oper = opers.oper;
postdata[idname] = $.jgrid.stripPref($t.p.idPrefix, $t.p.savedRow[fr].rowId);
postdata[oper] = opers.editoper;
postdata = $.extend(addpost,postdata);
$($t).jqGrid("progressBar", {method:"show", loadtype : $t.p.loadui, htmlcontent: $.jgrid.getRegional($t,'defaults.savetext') });
$t.grid.hDiv.loading = true;
$.ajax( $.extend( {
url: $t.p.cellurl,
data :$.isFunction($t.p.serializeCellData) ? $t.p.serializeCellData.call($t, postdata, nm) : postdata,
type: "POST",
complete: function (result, stat) {
$($t).jqGrid("progressBar", {method:"hide", loadtype : $t.p.loadui });
$t.grid.hDiv.loading = false;
if (stat === 'success') {
var ret = $($t).triggerHandler("jqGridAfterSubmitCell", [$t, result, postdata[idname], nm, v, iRow, iCol]) || [true, ''];
if (ret[0] === true && $.isFunction($t.p.afterSubmitCell)) {
ret = $t.p.afterSubmitCell.call($t, result, postdata[idname], nm, v, iRow, iCol);
}
if(ret[0] === true){
if(nuem) {
v = "";
}
$(cc).empty();
$($t).jqGrid("setCell",$t.p.savedRow[fr].rowId, iCol, v2, false, false, true);
$(cc).addClass("dirty-cell");
$(trow).addClass("edited");
$($t).triggerHandler("jqGridAfterSaveCell", [$t.p.savedRow[fr].rowId, nm, v, iRow, iCol]);
if ($.isFunction($t.p.afterSaveCell)) {
$t.p.afterSaveCell.call($t, $t.p.savedRow[fr].rowId, nm, v, iRow,iCol);
}
$t.p.savedRow.splice(0,1);
} else {
$($t).triggerHandler("jqGridErrorCell", [result, stat]);
if ($.isFunction($t.p.errorCell)) {
$t.p.errorCell.call($t, result, stat);
} else {
$.jgrid.info_dialog(errors.errcap, ret[1], edit.bClose, {
styleUI : $t.p.styleUI,
top:p.top+30,
left:p.left ,
onClose : function() {
if(!$t.p.restoreCellonFail) {
$("#"+iRow+"_"+nmjq, trow).focus();
}
}
});
}
if( $t.p.restoreCellonFail) {
$($t).jqGrid("restoreCell",iRow,iCol);
}
}
}
},
error:function(res,stat,err) {
$("#lui_"+$.jgrid.jqID($t.p.id)).hide();
$t.grid.hDiv.loading = false;
$($t).triggerHandler("jqGridErrorCell", [res, stat, err]);
if ($.isFunction($t.p.errorCell)) {
$t.p.errorCell.call($t, res,stat,err);
} else {
$.jgrid.info_dialog(errors.errcap, res.status+" : "+res.statusText+"<br/>"+stat, edit.bClose, {
styleUI : $t.p.styleUI,
top:p.top+30,
left:p.left ,
onClose : function() {
if(!$t.p.restoreCellonFail) {
$("#"+iRow+"_"+nmjq, trow).focus();
}
}
});
}
if( $t.p.restoreCellonFail) {
$($t).jqGrid("restoreCell", iRow, iCol);
}
}
}, $.jgrid.ajaxOptions, $t.p.ajaxCellOptions || {}));
} else {
try {
$.jgrid.info_dialog(errors.errcap,errors.nourl, edit.bClose, {styleUI : $t.p.styleUI });
if( $t.p.restoreCellonFail) {
$($t).jqGrid("restoreCell", iRow, iCol);
}
} catch (e) {}
}
}
if ($t.p.cellsubmit === 'clientArray') {
$(cc).empty();
$($t).jqGrid("setCell", $t.p.savedRow[fr].rowId, iCol, v2, false, false, true);
$(cc).addClass("dirty-cell");
$(trow).addClass("edited");
$($t).triggerHandler("jqGridAfterSaveCell", [$t.p.savedRow[fr].rowId, nm, v, iRow, iCol]);
if ($.isFunction($t.p.afterSaveCell)) {
$t.p.afterSaveCell.call($t, $t.p.savedRow[fr].rowId, nm, v, iRow, iCol);
}
$t.p.savedRow.splice(0,1);
}
} else {
try {
if( $.isFunction($t.p.validationCell) ) {
$t.p.validationCell.call($t, $("#"+iRow+"_"+nmjq, trow), cv[1], iRow, iCol);
} else {
window.setTimeout(function(){
$.jgrid.info_dialog(errors.errcap,v+ " " + cv[1], edit.bClose, {
styleUI : $t.p.styleUI,
top:p.top+30,
left:p.left ,
onClose : function() {
if(!$t.p.restoreCellonFail) {
$("#"+iRow+"_"+nmjq, trow).focus();
}
}
});
},50);
if( $t.p.restoreCellonFail) {
$($t).jqGrid("restoreCell", iRow, iCol);
}
}
} catch (e) {
alert(cv[1]);
}
}
} else {
$($t).jqGrid("restoreCell", iRow, iCol);
}
}
window.setTimeout(function () { $("#"+$.jgrid.jqID($t.p.knv)).attr("tabindex","-1").focus();},0);
});
},
restoreCell : function(iRow, iCol) {
return this.each(function(){
var $t= this, fr = $t.p.savedRow.length >= 1 ? 0 : null;
if (!$t.grid || $t.p.cellEdit !== true ) {return;}
if(fr !== null) {
var trow = $($t).jqGrid("getGridRowById", $t.p.savedRow[fr].rowId),
cc = $('td:eq('+iCol+')', trow);
// datepicker fix
if($.isFunction($.fn.datepicker)) {
try {
$("input.hasDatepicker",cc).datepicker('hide');
} catch (e) {}
}
$(cc).empty().attr("tabindex","-1");
$($t).jqGrid("setCell", $t.p.savedRow[0].rowId, iCol, $t.p.savedRow[fr].v, false, false, true);
$($t).triggerHandler("jqGridAfterRestoreCell", [$t.p.savedRow[fr].rowId, $t.p.savedRow[fr].v, iRow, iCol]);
if ($.isFunction($t.p.afterRestoreCell)) {
$t.p.afterRestoreCell.call($t, $t.p.savedRow[fr].rowId, $t.p.savedRow[fr].v, iRow, iCol);
}
$t.p.savedRow.splice(0,1);
}
window.setTimeout(function () { $("#"+$t.p.knv).attr("tabindex","-1").focus();},0);
});
},
nextCell : function (iRow, iCol, event) {
var ret;
this.each(function (){
var $t = this, nCol=false, i;
if (!$t.grid || $t.p.cellEdit !== true) {return;}
// try to find next editable cell
for (i=iCol+1; i<$t.p.colModel.length; i++) {
if ( $t.p.colModel[i].editable ===true && (!$.isFunction($t.p.isCellEditable) || $t.p.isCellEditable.call($t, $t.p.colModel[i].name,iRow,i))) {
nCol = i; break;
}
}
if(nCol !== false) {
ret = true;
$($t).jqGrid("editCell", iRow, nCol, true, event);
} else {
ret = false;
if ($t.p.savedRow.length >0) {
$($t).jqGrid("saveCell",iRow,iCol);
}
}
});
return ret;
},
prevCell : function (iRow, iCol, event) {
var ret;
this.each(function (){
var $t = this, nCol=false, i;
if (!$t.grid || $t.p.cellEdit !== true) {return false;}
// try to find next editable cell
for (i=iCol-1; i>=0; i--) {
if ( $t.p.colModel[i].editable ===true && (!$.isFunction($t.p.isCellEditable) || $t.p.isCellEditable.call($t, $t.p.colModel[i].name, iRow,i))) {
nCol = i;
break;
}
}
if(nCol !== false) {
ret = true;
$($t).jqGrid("editCell", iRow, nCol, true, event);
} else {
ret = false;
if ($t.p.savedRow.length >0) {
$($t).jqGrid("saveCell",iRow,iCol);
}
}
});
return ret;
},
GridNav : function() {
return this.each(function () {
var $t = this;
if (!$t.grid || $t.p.cellEdit !== true ) {return;}
// trick to process keydown on non input elements
$t.p.knv = $t.p.id + "_kn";
var selection = $("<div style='position:fixed;top:0px;width:1px;height:1px;' tabindex='0'><div tabindex='-1' style='width:1px;height:1px;' id='"+$t.p.knv+"'></div></div>"),
i, kdir;
function scrollGrid(iR, iC, tp){
if (tp.substr(0,1)==='v') {
var ch = $($t.grid.bDiv)[0].clientHeight,
st = $($t.grid.bDiv)[0].scrollTop,
nROT = $t.rows[iR].offsetTop+$t.rows[iR].clientHeight,
pROT = $t.rows[iR].offsetTop;
if(tp === 'vd') {
if(nROT >= ch) {
$($t.grid.bDiv)[0].scrollTop = $($t.grid.bDiv)[0].scrollTop + $t.rows[iR].clientHeight;
}
}
if(tp === 'vu'){
if (pROT < st ) {
$($t.grid.bDiv)[0].scrollTop = $($t.grid.bDiv)[0].scrollTop - $t.rows[iR].clientHeight;
}
}
}
if(tp==='h') {
var cw = $($t.grid.bDiv)[0].clientWidth,
sl = $($t.grid.bDiv)[0].scrollLeft,
nCOL = $t.rows[iR].cells[iC].offsetLeft+$t.rows[iR].cells[iC].clientWidth,
pCOL = $t.rows[iR].cells[iC].offsetLeft;
if(nCOL >= cw+parseInt(sl,10)) {
$($t.grid.bDiv)[0].scrollLeft = $($t.grid.bDiv)[0].scrollLeft + $t.rows[iR].cells[iC].clientWidth;
} else if (pCOL < sl) {
$($t.grid.bDiv)[0].scrollLeft = $($t.grid.bDiv)[0].scrollLeft - $t.rows[iR].cells[iC].clientWidth;
}
}
}
function findNextVisible(iC,act){
var ind, i;
if(act === 'lft') {
ind = iC+1;
for (i=iC;i>=0;i--){
if ($t.p.colModel[i].hidden !== true) {
ind = i;
break;
}
}
}
if(act === 'rgt') {
ind = iC-1;
for (i=iC; i<$t.p.colModel.length;i++){
if ($t.p.colModel[i].hidden !== true) {
ind = i;
break;
}
}
}
return ind;
}
$(selection).insertBefore($t.grid.cDiv);
$("#"+$t.p.knv)
.focus()
.keydown(function (e){
kdir = e.keyCode;
if($t.p.direction === "rtl") {
if(kdir===37) { kdir = 39;}
else if (kdir===39) { kdir = 37; }
}
switch (kdir) {
case 38:
if ($t.p.iRow-1 >0 ) {
scrollGrid($t.p.iRow-1,$t.p.iCol,'vu');
$($t).jqGrid("editCell",$t.p.iRow-1,$t.p.iCol,false,e);
}
break;
case 40 :
if ($t.p.iRow+1 <= $t.rows.length-1) {
scrollGrid($t.p.iRow+1,$t.p.iCol,'vd');
$($t).jqGrid("editCell",$t.p.iRow+1,$t.p.iCol,false,e);
}
break;
case 37 :
if ($t.p.iCol -1 >= 0) {
i = findNextVisible($t.p.iCol-1,'lft');
scrollGrid($t.p.iRow, i,'h');
$($t).jqGrid("editCell",$t.p.iRow, i,false,e);
}
break;
case 39 :
if ($t.p.iCol +1 <= $t.p.colModel.length-1) {
i = findNextVisible($t.p.iCol+1,'rgt');
scrollGrid($t.p.iRow,i,'h');
$($t).jqGrid("editCell",$t.p.iRow,i,false,e);
}
break;
case 13:
if (parseInt($t.p.iCol,10)>=0 && parseInt($t.p.iRow,10)>=0) {
$($t).jqGrid("editCell",$t.p.iRow,$t.p.iCol,true,e);
}
break;
default :
return true;
}
return false;
});
});
},
getChangedCells : function (mthd) {
var ret=[];
if (!mthd) {mthd='all';}
this.each(function(){
var $t= this,nm;
if (!$t.grid || $t.p.cellEdit !== true ) {return;}
$($t.rows).each(function(j){
var res = {};
if ($(this).hasClass("edited")) {
$('td',this).each( function(i) {
nm = $t.p.colModel[i].name;
if ( nm !== 'cb' && nm !== 'subgrid') {
if (mthd==='dirty') {
if ($(this).hasClass('dirty-cell')) {
try {
res[nm] = $.unformat.call($t,this,{rowId:$t.rows[j].id, colModel:$t.p.colModel[i]},i);
} catch (e){
res[nm] = $.jgrid.htmlDecode($(this).html());
}
}
} else {
try {
res[nm] = $.unformat.call($t,this,{rowId:$t.rows[j].id,colModel:$t.p.colModel[i]},i);
} catch (e) {
res[nm] = $.jgrid.htmlDecode($(this).html());
}
}
}
});
res.id = this.id;
ret.push(res);
}
});
});
return ret;
}
/// end cell editing
});
//module end
}));
|
/*! Buefy v0.9.7 | MIT License | github.com/buefy/buefy */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.Navbar = {}));
}(this, function (exports) { 'use strict';
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var script = {
name: 'NavbarBurger',
props: {
isOpened: {
type: Boolean,
default: false
}
}
};
function normalizeComponent(template, style, script, scopeId, isFunctionalTemplate, moduleIdentifier
/* server only */
, shadowMode, createInjector, createInjectorSSR, createInjectorShadow) {
if (typeof shadowMode !== 'boolean') {
createInjectorSSR = createInjector;
createInjector = shadowMode;
shadowMode = false;
} // Vue.extend constructor export interop.
var options = typeof script === 'function' ? script.options : script; // render functions
if (template && template.render) {
options.render = template.render;
options.staticRenderFns = template.staticRenderFns;
options._compiled = true; // functional template
if (isFunctionalTemplate) {
options.functional = true;
}
} // scopedId
if (scopeId) {
options._scopeId = scopeId;
}
var hook;
if (moduleIdentifier) {
// server build
hook = function hook(context) {
// 2.3 injection
context = context || // cached call
this.$vnode && this.$vnode.ssrContext || // stateful
this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext; // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__;
} // inject component styles
if (style) {
style.call(this, createInjectorSSR(context));
} // register component module identifier for async chunk inference
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier);
}
}; // used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook;
} else if (style) {
hook = shadowMode ? function () {
style.call(this, createInjectorShadow(this.$root.$options.shadowRoot));
} : function (context) {
style.call(this, createInjector(context));
};
}
if (hook) {
if (options.functional) {
// register for functional component in vue file
var originalRender = options.render;
options.render = function renderWithStyleInjection(h, context) {
hook.call(context);
return originalRender(h, context);
};
} else {
// inject component registration as beforeCreate hook
var existing = options.beforeCreate;
options.beforeCreate = existing ? [].concat(existing, hook) : [hook];
}
}
return script;
}
var normalizeComponent_1 = normalizeComponent;
/* script */
const __vue_script__ = script;
/* template */
var __vue_render__ = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('a',_vm._g({staticClass:"navbar-burger burger",class:{ 'is-active': _vm.isOpened },attrs:{"role":"button","aria-label":"menu","aria-expanded":_vm.isOpened}},_vm.$listeners),[_c('span',{attrs:{"aria-hidden":"true"}}),_c('span',{attrs:{"aria-hidden":"true"}}),_c('span',{attrs:{"aria-hidden":"true"}})])};
var __vue_staticRenderFns__ = [];
/* style */
const __vue_inject_styles__ = undefined;
/* scoped */
const __vue_scope_id__ = undefined;
/* module identifier */
const __vue_module_identifier__ = undefined;
/* functional template */
const __vue_is_functional_template__ = false;
/* style inject */
/* style inject SSR */
var NavbarBurger = normalizeComponent_1(
{ render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ },
__vue_inject_styles__,
__vue_script__,
__vue_scope_id__,
__vue_is_functional_template__,
__vue_module_identifier__,
undefined,
undefined
);
var isTouch = typeof window !== 'undefined' && ('ontouchstart' in window || navigator.msMaxTouchPoints > 0);
var events = isTouch ? ['touchstart', 'click'] : ['click'];
var instances = [];
function processArgs(bindingValue) {
var isFunction = typeof bindingValue === 'function';
if (!isFunction && _typeof(bindingValue) !== 'object') {
throw new Error("v-click-outside: Binding value should be a function or an object, ".concat(_typeof(bindingValue), " given"));
}
return {
handler: isFunction ? bindingValue : bindingValue.handler,
middleware: bindingValue.middleware || function (isClickOutside) {
return isClickOutside;
},
events: bindingValue.events || events
};
}
function onEvent(_ref) {
var el = _ref.el,
event = _ref.event,
handler = _ref.handler,
middleware = _ref.middleware;
var isClickOutside = event.target !== el && !el.contains(event.target);
if (!isClickOutside || !middleware(event, el)) {
return;
}
handler(event, el);
}
function toggleEventListeners() {
var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
eventHandlers = _ref2.eventHandlers;
var action = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'add';
eventHandlers.forEach(function (_ref3) {
var event = _ref3.event,
handler = _ref3.handler;
document["".concat(action, "EventListener")](event, handler);
});
}
function bind(el, _ref4) {
var value = _ref4.value;
var _processArgs = processArgs(value),
_handler = _processArgs.handler,
middleware = _processArgs.middleware,
events = _processArgs.events;
var instance = {
el: el,
eventHandlers: events.map(function (eventName) {
return {
event: eventName,
handler: function handler(event) {
return onEvent({
event: event,
el: el,
handler: _handler,
middleware: middleware
});
}
};
})
};
toggleEventListeners(instance, 'add');
instances.push(instance);
}
function update(el, _ref5) {
var value = _ref5.value;
var _processArgs2 = processArgs(value),
_handler2 = _processArgs2.handler,
middleware = _processArgs2.middleware,
events = _processArgs2.events; // `filter` instead of `find` for compat with IE
var instance = instances.filter(function (instance) {
return instance.el === el;
})[0];
toggleEventListeners(instance, 'remove');
instance.eventHandlers = events.map(function (eventName) {
return {
event: eventName,
handler: function handler(event) {
return onEvent({
event: event,
el: el,
handler: _handler2,
middleware: middleware
});
}
};
});
toggleEventListeners(instance, 'add');
}
function unbind(el) {
// `filter` instead of `find` for compat with IE
var instance = instances.filter(function (instance) {
return instance.el === el;
})[0];
toggleEventListeners(instance, 'remove');
}
var directive = {
bind: bind,
update: update,
unbind: unbind,
instances: instances
};
var FIXED_TOP_CLASS = 'is-fixed-top';
var BODY_FIXED_TOP_CLASS = 'has-navbar-fixed-top';
var BODY_SPACED_FIXED_TOP_CLASS = 'has-spaced-navbar-fixed-top';
var FIXED_BOTTOM_CLASS = 'is-fixed-bottom';
var BODY_FIXED_BOTTOM_CLASS = 'has-navbar-fixed-bottom';
var BODY_SPACED_FIXED_BOTTOM_CLASS = 'has-spaced-navbar-fixed-bottom';
var BODY_CENTERED_CLASS = 'has-navbar-centered';
var isFilled = function isFilled(str) {
return !!str;
};
var script$1 = {
name: 'BNavbar',
components: {
NavbarBurger: NavbarBurger
},
directives: {
clickOutside: directive
},
// deprecated, to replace with default 'value' in the next breaking change
model: {
prop: 'active',
event: 'update:active'
},
props: {
type: [String, Object],
transparent: {
type: Boolean,
default: false
},
fixedTop: {
type: Boolean,
default: false
},
fixedBottom: {
type: Boolean,
default: false
},
active: {
type: Boolean,
default: false
},
centered: {
type: Boolean,
default: false
},
wrapperClass: {
type: String
},
closeOnClick: {
type: Boolean,
default: true
},
mobileBurger: {
type: Boolean,
default: true
},
spaced: Boolean,
shadow: Boolean
},
data: function data() {
return {
internalIsActive: this.active,
_isNavBar: true // Used internally by NavbarItem
};
},
computed: {
isOpened: function isOpened() {
return this.internalIsActive;
},
computedClasses: function computedClasses() {
var _ref;
return [this.type, (_ref = {}, _defineProperty(_ref, FIXED_TOP_CLASS, this.fixedTop), _defineProperty(_ref, FIXED_BOTTOM_CLASS, this.fixedBottom), _defineProperty(_ref, BODY_CENTERED_CLASS, this.centered), _defineProperty(_ref, 'is-spaced', this.spaced), _defineProperty(_ref, 'has-shadow', this.shadow), _defineProperty(_ref, 'is-transparent', this.transparent), _ref)];
}
},
watch: {
active: {
handler: function handler(active) {
this.internalIsActive = active;
},
immediate: true
},
fixedTop: function fixedTop(isSet) {
// toggle body class only on update to handle multiple navbar
this.setBodyFixedTopClass(isSet);
},
bottomTop: function bottomTop(isSet) {
// toggle body class only on update to handle multiple navbar
this.setBodyFixedBottomClass(isSet);
}
},
methods: {
toggleActive: function toggleActive() {
this.internalIsActive = !this.internalIsActive;
this.emitUpdateParentEvent();
},
closeMenu: function closeMenu() {
if (this.closeOnClick && this.internalIsActive) {
this.internalIsActive = false;
this.emitUpdateParentEvent();
}
},
emitUpdateParentEvent: function emitUpdateParentEvent() {
this.$emit('update:active', this.internalIsActive);
},
setBodyClass: function setBodyClass(className) {
if (typeof window !== 'undefined') {
document.body.classList.add(className);
}
},
removeBodyClass: function removeBodyClass(className) {
if (typeof window !== 'undefined') {
document.body.classList.remove(className);
}
},
checkIfFixedPropertiesAreColliding: function checkIfFixedPropertiesAreColliding() {
var areColliding = this.fixedTop && this.fixedBottom;
if (areColliding) {
throw new Error('You should choose if the BNavbar is fixed bottom or fixed top, but not both');
}
},
genNavbar: function genNavbar(createElement) {
var navBarSlots = [this.genNavbarBrandNode(createElement), this.genNavbarSlotsNode(createElement)];
if (!isFilled(this.wrapperClass)) {
return this.genNavbarSlots(createElement, navBarSlots);
} // It wraps the slots into a div with the provided wrapperClass prop
var navWrapper = createElement('div', {
class: this.wrapperClass
}, navBarSlots);
return this.genNavbarSlots(createElement, [navWrapper]);
},
genNavbarSlots: function genNavbarSlots(createElement, slots) {
return createElement('nav', {
staticClass: 'navbar',
class: this.computedClasses,
attrs: {
role: 'navigation',
'aria-label': 'main navigation'
},
directives: [{
name: 'click-outside',
value: this.closeMenu
}]
}, slots);
},
genNavbarBrandNode: function genNavbarBrandNode(createElement) {
return createElement('div', {
class: 'navbar-brand'
}, [this.$slots.brand, this.genBurgerNode(createElement)]);
},
genBurgerNode: function genBurgerNode(createElement) {
if (this.mobileBurger) {
var defaultBurgerNode = createElement('navbar-burger', {
props: {
isOpened: this.isOpened
},
on: {
click: this.toggleActive
}
});
var hasBurgerSlot = !!this.$scopedSlots.burger;
return hasBurgerSlot ? this.$scopedSlots.burger({
isOpened: this.isOpened,
toggleActive: this.toggleActive
}) : defaultBurgerNode;
}
},
genNavbarSlotsNode: function genNavbarSlotsNode(createElement) {
return createElement('div', {
staticClass: 'navbar-menu',
class: {
'is-active': this.isOpened
}
}, [this.genMenuPosition(createElement, 'start'), this.genMenuPosition(createElement, 'end')]);
},
genMenuPosition: function genMenuPosition(createElement, positionName) {
return createElement('div', {
staticClass: "navbar-".concat(positionName)
}, this.$slots[positionName]);
},
setBodyFixedTopClass: function setBodyFixedTopClass(isSet) {
this.checkIfFixedPropertiesAreColliding();
if (isSet) {
// TODO Apply only one of the classes once PR is merged in Bulma:
// https://github.com/jgthms/bulma/pull/2737
this.setBodyClass(BODY_FIXED_TOP_CLASS);
this.spaced && this.setBodyClass(BODY_SPACED_FIXED_TOP_CLASS);
} else {
this.removeBodyClass(BODY_FIXED_TOP_CLASS);
this.removeBodyClass(BODY_SPACED_FIXED_TOP_CLASS);
}
},
setBodyFixedBottomClass: function setBodyFixedBottomClass(isSet) {
this.checkIfFixedPropertiesAreColliding();
if (isSet) {
// TODO Apply only one of the classes once PR is merged in Bulma:
// https://github.com/jgthms/bulma/pull/2737
this.setBodyClass(BODY_FIXED_BOTTOM_CLASS);
this.spaced && this.setBodyClass(BODY_SPACED_FIXED_BOTTOM_CLASS);
} else {
this.removeBodyClass(BODY_FIXED_BOTTOM_CLASS);
this.removeBodyClass(BODY_SPACED_FIXED_BOTTOM_CLASS);
}
}
},
beforeMount: function beforeMount() {
this.fixedTop && this.setBodyFixedTopClass(true);
this.fixedBottom && this.setBodyFixedBottomClass(true);
},
beforeDestroy: function beforeDestroy() {
if (this.fixedTop) {
var className = this.spaced ? BODY_SPACED_FIXED_TOP_CLASS : BODY_FIXED_TOP_CLASS;
this.removeBodyClass(className);
} else if (this.fixedBottom) {
var _className = this.spaced ? BODY_SPACED_FIXED_BOTTOM_CLASS : BODY_FIXED_BOTTOM_CLASS;
this.removeBodyClass(_className);
}
},
render: function render(createElement, fn) {
return this.genNavbar(createElement);
}
};
/* script */
const __vue_script__$1 = script$1;
/* template */
/* style */
const __vue_inject_styles__$1 = undefined;
/* scoped */
const __vue_scope_id__$1 = undefined;
/* module identifier */
const __vue_module_identifier__$1 = undefined;
/* functional template */
const __vue_is_functional_template__$1 = undefined;
/* style inject */
/* style inject SSR */
var Navbar = normalizeComponent_1(
{},
__vue_inject_styles__$1,
__vue_script__$1,
__vue_scope_id__$1,
__vue_is_functional_template__$1,
__vue_module_identifier__$1,
undefined,
undefined
);
//
//
//
//
//
//
//
//
//
//
//
//
//
var clickableWhiteList = ['div', 'span', 'input'];
var script$2 = {
name: 'BNavbarItem',
inheritAttrs: false,
props: {
tag: {
type: String,
default: 'a'
},
active: Boolean
},
methods: {
/**
* Keypress event that is bound to the document
*/
keyPress: function keyPress(_ref) {
var key = _ref.key;
if (key === 'Escape' || key === 'Esc') {
this.closeMenuRecursive(this, ['NavBar']);
}
},
/**
* Close parent if clicked outside.
*/
handleClickEvent: function handleClickEvent(event) {
var isOnWhiteList = clickableWhiteList.some(function (item) {
return item === event.target.localName;
});
if (!isOnWhiteList) {
var parent = this.closeMenuRecursive(this, ['NavbarDropdown', 'NavBar']);
if (parent && parent.$data._isNavbarDropdown) this.closeMenuRecursive(parent, ['NavBar']);
}
},
/**
* Close parent recursively
*/
closeMenuRecursive: function closeMenuRecursive(current, targetComponents) {
if (!current.$parent) return null;
var foundItem = targetComponents.reduce(function (acc, item) {
if (current.$parent.$data["_is".concat(item)]) {
current.$parent.closeMenu();
return current.$parent;
}
return acc;
}, null);
return foundItem || this.closeMenuRecursive(current.$parent, targetComponents);
}
},
mounted: function mounted() {
if (typeof window !== 'undefined') {
this.$el.addEventListener('click', this.handleClickEvent);
document.addEventListener('keyup', this.keyPress);
}
},
beforeDestroy: function beforeDestroy() {
if (typeof window !== 'undefined') {
this.$el.removeEventListener('click', this.handleClickEvent);
document.removeEventListener('keyup', this.keyPress);
}
}
};
/* script */
const __vue_script__$2 = script$2;
/* template */
var __vue_render__$1 = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c(_vm.tag,_vm._g(_vm._b({tag:"component",staticClass:"navbar-item",class:{
'is-active': _vm.active
}},'component',_vm.$attrs,false),_vm.$listeners),[_vm._t("default")],2)};
var __vue_staticRenderFns__$1 = [];
/* style */
const __vue_inject_styles__$2 = undefined;
/* scoped */
const __vue_scope_id__$2 = undefined;
/* module identifier */
const __vue_module_identifier__$2 = undefined;
/* functional template */
const __vue_is_functional_template__$2 = false;
/* style inject */
/* style inject SSR */
var NavbarItem = normalizeComponent_1(
{ render: __vue_render__$1, staticRenderFns: __vue_staticRenderFns__$1 },
__vue_inject_styles__$2,
__vue_script__$2,
__vue_scope_id__$2,
__vue_is_functional_template__$2,
__vue_module_identifier__$2,
undefined,
undefined
);
//
var script$3 = {
name: 'BNavbarDropdown',
directives: {
clickOutside: directive
},
props: {
label: String,
hoverable: Boolean,
active: Boolean,
right: Boolean,
arrowless: Boolean,
boxed: Boolean,
closeOnClick: {
type: Boolean,
default: true
},
collapsible: Boolean
},
data: function data() {
return {
newActive: this.active,
isHoverable: this.hoverable,
_isNavbarDropdown: true // Used internally by NavbarItem
};
},
watch: {
active: function active(value) {
this.newActive = value;
}
},
methods: {
showMenu: function showMenu() {
this.newActive = true;
},
/**
* See naming convetion of navbaritem
*/
closeMenu: function closeMenu() {
this.newActive = !this.closeOnClick;
if (this.hoverable && this.closeOnClick) {
this.isHoverable = false;
}
},
checkHoverable: function checkHoverable() {
if (this.hoverable) {
this.isHoverable = true;
}
}
}
};
/* script */
const __vue_script__$3 = script$3;
/* template */
var __vue_render__$2 = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{directives:[{name:"click-outside",rawName:"v-click-outside",value:(_vm.closeMenu),expression:"closeMenu"}],staticClass:"navbar-item has-dropdown",class:{
'is-hoverable': _vm.isHoverable,
'is-active': _vm.newActive
},on:{"mouseenter":_vm.checkHoverable}},[_c('a',{staticClass:"navbar-link",class:{
'is-arrowless': _vm.arrowless,
'is-active': _vm.newActive && _vm.collapsible
},attrs:{"role":"menuitem","aria-haspopup":"true","href":"#"},on:{"click":function($event){$event.preventDefault();_vm.newActive = !_vm.newActive;}}},[(_vm.label)?[_vm._v(_vm._s(_vm.label))]:_vm._t("label")],2),_c('div',{directives:[{name:"show",rawName:"v-show",value:(!_vm.collapsible || (_vm.collapsible && _vm.newActive)),expression:"!collapsible || (collapsible && newActive)"}],staticClass:"navbar-dropdown",class:{
'is-right': _vm.right,
'is-boxed': _vm.boxed,
}},[_vm._t("default")],2)])};
var __vue_staticRenderFns__$2 = [];
/* style */
const __vue_inject_styles__$3 = undefined;
/* scoped */
const __vue_scope_id__$3 = undefined;
/* module identifier */
const __vue_module_identifier__$3 = undefined;
/* functional template */
const __vue_is_functional_template__$3 = false;
/* style inject */
/* style inject SSR */
var NavbarDropdown = normalizeComponent_1(
{ render: __vue_render__$2, staticRenderFns: __vue_staticRenderFns__$2 },
__vue_inject_styles__$3,
__vue_script__$3,
__vue_scope_id__$3,
__vue_is_functional_template__$3,
__vue_module_identifier__$3,
undefined,
undefined
);
var use = function use(plugin) {
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(plugin);
}
};
var registerComponent = function registerComponent(Vue, component) {
Vue.component(component.name, component);
};
var Plugin = {
install: function install(Vue) {
registerComponent(Vue, Navbar);
registerComponent(Vue, NavbarItem);
registerComponent(Vue, NavbarDropdown);
}
};
use(Plugin);
exports.BNavbar = Navbar;
exports.BNavbarDropdown = NavbarDropdown;
exports.BNavbarItem = NavbarItem;
exports.default = Plugin;
Object.defineProperty(exports, '__esModule', { value: true });
}));
|
/**
* @license Highcharts JS v9.2.1 (2021-08-19)
* @module highcharts/modules/marker-clusters
* @requires highcharts
*
* Marker clusters module for Highcharts
*
* (c) 2010-2021 Wojciech Chmiel
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../Extensions/MarkerClusters.js';
|
var util = require('util'),
webUtil = require('../util/web'),
Tab = require('../client/tab').Tab,
rewriter = require('../util/jsonrewriter'),
Amount = ripple.Amount;
var HistoryTab = function ()
{
Tab.call(this);
};
util.inherits(HistoryTab, Tab);
HistoryTab.prototype.tabName = 'history';
HistoryTab.prototype.mainMenu = 'wallet';
HistoryTab.prototype.generateHtml = function ()
{
return require('../../templates/tabs/history.jade')();
};
HistoryTab.prototype.angular = function (module) {
module.controller('HistoryCtrl', ['$scope', 'rpId', 'rpNetwork',
function ($scope, $id, $network)
{
if (!$id.loginStatus) $id.goId();
var history = [];
// Latest transaction
var latest;
// History collection
$scope.historyShow = [];
$scope.historyCsv = '';
// History states
$scope.$watch('loadState.transactions',function(){
$scope.historyState = !$scope.loadState.transactions ? 'loading' : 'ready';
});
// Open/close states of individual history items
$scope.details = [];
//$scope.typeUsage = [];
//$scope.currencyUsage = [];
// Currencies from history
var historyCurrencies = [];
$scope.types = {
sent: {
'types': ['sent'],
'checked': true
},
received: {
'types': ['received'],
'checked': true
},
gateways: {
'types': ['trusting','trusted'],
'checked': true
},
trades: {
'types': ['offernew','exchange'],
'checked': true
},
orders: {
'types': ['offernew','offercancel','exchange'],
'checked': true
},
other: {
'types': ['accountset','failed','rippling'],
'checked': true
}
};
$scope.advanced_feature_switch = Options.advanced_feature_switch;
$scope.orderedTypes = ['sent','received','gateways','trades','orders','other'];
if (store.get('ripple_history_type_selections')) {
$scope.types = $.extend(true,$scope.types,store.get('ripple_history_type_selections'));
}
// Filters
if (store.get('ripple_history_filters')) {
$scope.filters = store.get('ripple_history_filters');
} else {
$scope.filters = {
'currencies_is_active': false, // we do the currency filter only if this is true, which happens when at least one currency is off
'currencies': {},
'types': ['sent','received','exchange','trusting','trusted','offernew','offercancel','rippling'],
'minimumAmount': 0.000001
};
}
var getDateRangeHistory = function(dateMin,dateMax,callback)
{
var completed = false;
var history = [];
var params = {
account: $id.account,
ledger_index_min: -1,
limit: 200
};
var getTx = function(){
$network.remote.requestAccountTransactions(params)
.on('success', function(data) {
if (data.transactions.length) {
for(var i=0;i<data.transactions.length;i++) {
var date = ripple.utils.toTimestamp(data.transactions[i].tx.date);
if(date < dateMin.getTime()) {
completed = true;
break;
}
if(date > dateMax.getTime())
continue;
// Push
var tx = rewriter.processTxn(data.transactions[i].tx, data.transactions[i].meta, $id.account);
if (tx) history.push(tx);
}
if (data.marker) {
params.marker = data.marker;
$scope.tx_marker = params.marker;
}
else {
// Received all transactions since a marker was not returned
completed = true;
}
if (completed)
callback(history);
else
getTx();
} else {
callback(history);
}
}).request();
};
getTx(0);
};
// DateRange filter form
$scope.submitDateRangeForm = function() {
$scope.dateMaxView.setDate($scope.dateMaxView.getDate() + 1); // Including last date
changeDateRange($scope.dateMinView,$scope.dateMaxView);
};
$scope.submitMinimumAmountForm = function() {
updateHistory();
};
var changeDateRange = function(dateMin,dateMax) {
history = [];
$scope.historyState = 'loading';
getDateRangeHistory(dateMin,dateMax,function(hist){
$scope.$apply(function () {
history = hist;
$scope.historyState = 'ready';
updateHistory();
})
})
};
// All the currencies
$scope.$watch('balances', function(){
updateCurrencies();
});
// Types filter has been changed
$scope.$watch('types', function(){
var arr = [];
var checked = {};
_.each($scope.types, function(type,index){
if (type.checked) {
arr = arr.concat(type.types);
}
checked[index] = {
checked: !!type.checked
};
});
$scope.filters.types = arr;
if (!store.disabled) {
store.set('ripple_history_type_selections', checked);
}
}, true);
if (!store.disabled) {
$scope.$watch('filters', function(){
store.set('ripple_history_filters', $scope.filters);
}, true);
}
$scope.$watch('filters.types', function(){
updateHistory();
}, true);
// Currency filter has been changed
$scope.$watch('filters.currencies', function(){
updateCurrencies();
updateHistory();
}, true);
// New transactions
$scope.$watchCollection('history',function(){
history = $scope.history;
updateHistory();
// Update currencies
if (history.length)
updateCurrencies();
},true);
// Updates the history collection
var updateHistory = function (){
//$scope.typeUsage = [];
//$scope.currencyUsage = [];
$scope.historyShow = [];
if (history.length) {
var dateMin, dateMax;
$scope.minLedger = 0;
var currencies = _.map($scope.filters.currencies,function(obj,key){return obj.checked ? key : false});
history.forEach(function(event)
{
// Calculate dateMin/dateMax. Used in date filter view
if (!$scope.dateMinView) {
if (!dateMin || dateMin > event.date)
dateMin = event.date;
if (!dateMax || dateMax < event.date)
dateMax = event.date;
}
var affectedCurrencies = _.map(event.affected_currencies, function (currencyCode) {
return ripple.Currency.from_json(currencyCode).to_human();
});
// Update currencies
historyCurrencies = _.union(historyCurrencies, affectedCurrencies); // TODO put in one large array, then union outside of foreach
// Calculate min ledger. Used in "load more"
if (!$scope.minLedger || $scope.minLedger > event.ledger_index)
$scope.minLedger = event.ledger_index;
// Type filter
if (event.transaction && event.transaction.type === 'error') ; // Always show errors
else if (event.transaction && !_.contains($scope.filters.types,event.transaction.type))
return;
// Some events don't have transactions.. this is a temporary fix for filtering offers
else if (!event.transaction && !_.contains($scope.filters.types,'offernew'))
return;
// Currency filter
//if ($scope.filters.currencies_is_active && _.intersection(currencies,event.affected_currencies).length <= 0)
// return;
var effects = [];
var isFundedTrade = false; // Partially/fully funded
var isCancellation = false;
if (event.effects) {
// Show effects
$.each(event.effects, function(){
var effect = this;
switch (effect.type) {
case 'offer_funded':
case 'offer_partially_funded':
case 'offer_bought':
isFundedTrade = true;
/* falls through */
case 'offer_cancelled':
if (effect.type === 'offer_cancelled') {
isCancellation = true;
if (event.transaction && event.transaction.type === 'offercancel')
return;
}
effects.push(effect);
break;
}
});
event.showEffects = effects;
// Trade filter - remove open orders that haven't been filled/partially filled
if (_.contains($scope.filters.types,'exchange') && !_.contains($scope.filters.types,'offercancel')) {
if ((event.transaction && event.transaction.type === 'offernew' && !isFundedTrade) || isCancellation)
return
}
effects = [ ];
var amount, maxAmount;
var minimumAmount = $scope.filters.minimumAmount;
// Balance changer effects
$.each(event.effects, function(){
var effect = this;
switch (effect.type) {
case 'fee':
case 'balance_change':
case 'trust_change_balance':
effects.push(effect);
// Minimum amount filter
if (effect.type === 'balance_change' || effect.type === 'trust_change_balance') {
amount = effect.amount.abs().is_native()
? effect.amount.abs().to_number() / 1000000
: effect.amount.abs().to_number();
if (!maxAmount || amount > maxAmount)
maxAmount = amount;
}
break;
}
});
// Minimum amount filter
if (maxAmount && minimumAmount > maxAmount)
return;
event.balanceEffects = effects;
}
// Don't show sequence update events
if (event.effects && 1 === event.effects.length && event.effects[0].type == 'fee')
return;
// Push events to history collection
$scope.historyShow.push(event);
// Type and currency usages
// TODO offers/trusts
//if (event.transaction)
// $scope.typeUsage[event.transaction.type] = $scope.typeUsage[event.transaction.type] ? $scope.typeUsage[event.transaction.type]+1 : 1;
//event.affected_currencies.forEach(function(currency){
// $scope.currencyUsage[currency] = $scope.currencyUsage[currency]? $scope.currencyUsage[currency]+1 : 1;
//});
});
if ($scope.historyShow.length && !$scope.dateMinView) {
setValidDateOnScopeOrNullify('dateMinView', dateMin);
setValidDateOnScopeOrNullify('dateMaxView', dateMax);
}
}
};
// Update the currency list
var updateCurrencies = function (){
if (!$.isEmptyObject($scope.balances)) {
var currencies = _.union(
['XRP'],
_.map($scope.balances,function(obj,key){return obj.total.currency().to_human();}),
historyCurrencies
);
var objCurrencies = {};
var firstProcess = $.isEmptyObject($scope.filters.currencies);
$scope.filters.currencies_is_active = false;
_.each(currencies, function(currency){
var checked = ($scope.filters.currencies[currency] && $scope.filters.currencies[currency].checked) || firstProcess;
objCurrencies[currency] = {'checked':checked};
if (!checked)
$scope.filters.currencies_is_active = true;
});
$scope.filters.currencies = objCurrencies;
}
};
var setValidDateOnScopeOrNullify = function(key, value) {
if (isNaN(value) || value == null) {
$scope[key] = null;
} else {
$scope[key] = new Date(value);
}
};
$scope.loadMore = function () {
var dateMin = $scope.dateMinView;
var dateMax = $scope.dateMaxView;
$scope.historyState = 'loading';
var limit = 100; // TODO why 100?
var params = {
account: $id.account,
ledger_index_min: -1,
limit: limit,
marker: $scope.tx_marker
};
$network.remote.requestAccountTransactions(params)
.on('success', function(data) {
$scope.$apply(function () {
if (data.transactions.length < limit) {
}
$scope.tx_marker = data.marker;
if (data.transactions) {
var transactions = [];
data.transactions.forEach(function (e) {
var tx = rewriter.processTxn(e.tx, e.meta, $id.account);
if (tx) {
var date = ripple.utils.toTimestamp(tx.date);
if (dateMin && dateMax) {
if (date < dateMin.getTime() || date > dateMax.getTime())
return;
} else if (dateMax && date > dateMax.getTime()) {
return;
} else if (dateMin && date < dateMin.getTime()) {
return;
}
transactions.push(tx);
}
});
var newHistory = _.uniq(history.concat(transactions),false,function(ev){return ev.hash});
$scope.historyState = (history.length === newHistory.length) ? 'full' : 'ready';
history = newHistory;
updateHistory();
}
});
}).request();
}
var exists = function(pty) {
return typeof pty !== 'undefined';
};
// Change first letter of string to uppercase or lowercase
var capFirst = function(str, caps) {
var first = str.charAt(0);
return (caps ? first.toUpperCase() : first.toLowerCase()) + str.slice(1);
};
var issuerToString = function(issuer) {
var iss = issuer.to_json();
return typeof iss === 'number' && isNaN(iss) ? '' : iss;
};
// Convert Amount value to human-readable format
var formatAmount = function(amount) {
var formatted = '';
if (amount instanceof Amount) {
formatted = amount.to_human({group_sep: false, precision: 2});
// If amount is very small and only has zeros (ex. 0.0000), raise precision
if (formatted.length > 1 && 0 === +formatted) {
formatted = amount.to_human({group_sep: false, precision: 20, max_sig_digits: 5});
}
}
return formatted;
};
$scope.exportCsv = function() {
// Header (1st line) of CSV with name of each field
// Ensure that the field values for each row added in addLineToCsvToCsv() correspond in this order
var csv = 'Date,Time,Ledger Number,Transaction Type,Trust address,' +
'Address sent from,Amount sent/sold,Currency sent/sold,Issuer of sent/sold ccy,' +
'Address sent to,Amount received,Currency received,Issuer of received ccy,' +
'Executed Price,Network Fee paid,Transaction Hash\r\n';
var addLineToCsv = function(line) {
// Ensure that the fields match the CSV header initialized in var csv
csv += [ line['Date'], line['Time'], line['LedgerNum'], line['TransType'], line['TrustAddr'],
line['FromAddr'], line['SentAmount'], line['SentCcy'], line['SentIssuer'],
line['ToAddr'], line['RecvAmount'], line['RecvCcy'], line['RecvIssuer'],
line['ExecPrice'], line['Fee'], line['TransHash']
].join(',') + '\r\n';
}
// Convert the fields of interest in buy & sell Amounts to strings in Key/Value pairs
var getOrderDetails = function(keyVal, buy, sell) {
if (buy !== null && buy instanceof Amount) {
keyVal['SentAmount'] = formatAmount(buy);
keyVal['SentCcy'] = buy.currency().get_iso();
keyVal['SentIssuer'] = issuerToString(buy.issuer());
}
if (sell !== null && sell instanceof Amount) {
keyVal['RecvAmount'] = formatAmount(sell);
keyVal['RecvCcy'] = sell.currency().get_iso();
keyVal['RecvIssuer'] = issuerToString(sell.issuer());
}
}
// Construct a CSV string by:
// 1) Iterating over each line item in the *displayed* Transaction History
// 2) If the type of Transaction is in scope, convert the relevant fields to strings in Key/Value pairs
// 3) Concatenate the strings extracted in (2) in a comma-delimited line and append this line to the CSV
for (var i = 0; i < $scope.historyShow.length; i++) {
var histLine = $scope.historyShow[i],
transaction = histLine.transaction,
type = histLine.tx_type,
dateTime = moment(histLine.date),
na = 'NA',
line = {},
lineTemplate = {},
lineTrust = {},
linePayment = {},
lineOffer = {},
sent;
// Unsuccessful transactions are excluded from the export
var transType = exists(transaction) ? transaction.type : null;
if (transType === 'failed' || histLine.tx_result !== 'tesSUCCESS') continue;
// Fields common to all Transaction types
lineTemplate['Date'] = dateTime.format('YYYY-MM-DD');
lineTemplate['Time'] = dateTime.format('HH:mm:ss');
lineTemplate['LedgerNum'] = histLine.ledger_index;
lineTemplate['Fee'] = formatAmount(Amount.from_json(histLine.fee));
lineTemplate['TransHash'] = histLine.hash;
// Default type-specific fields to NA, they will be overridden later if applicable
lineTemplate['TrustAddr'] = lineTemplate['FromAddr'] = lineTemplate['ToAddr'] = na;
lineTemplate['RecvAmount'] = lineTemplate['RecvCcy'] = lineTemplate['ExecPrice'] = na;
// Include if Payment, Trust, Offer. Otherwise Exclude.
if (type === 'TrustSet') {
// Trust Line (Incoming / Outgoing)
var trust = '';
if (transType === 'trusted') trust = 'Incoming ';
else if (transType === 'trusting') trust = 'Outgoing ';
else continue; // unrecognised trust type
lineTrust['TransType'] = trust + 'trust line';
lineTrust['TrustAddr'] = transaction.counterparty;
lineTrust['SentAmount'] = formatAmount(transaction.amount);
lineTrust['SentCcy'] = transaction.currency; //transaction.amount.currency().get_iso();
lineTrust['SentIssuer'] = lineTrust['RecvIssuer'] = na;
line = $.extend({}, lineTemplate, lineTrust);
addLineToCsv(line);
}
else if (type === 'Payment' && transType !== null) {
// Payment (Sent / Received)
if (transType === 'sent') sent = true;
else if (transType === 'received') sent = false;
else continue; // unrecognised payment type
linePayment['TransType'] = capFirst(transType, true) + ' ' + capFirst(type, false);
if (sent) {
// If sent, counterparty is Address To
linePayment['ToAddr'] = transaction.counterparty;
linePayment['FromAddr'] = $id.account;
}
else {
// If received, counterparty is Address From
linePayment['FromAddr'] = transaction.counterparty;
linePayment['ToAddr'] = $id.account;
}
if (exists(transaction.amountSent)) {
amtSent = transaction.amountSent;
linePayment['SentAmount'] = exists(amtSent.value) ? amtSent.value : formatAmount(Amount.from_json(amtSent));
linePayment['SentCcy'] = exists(amtSent.currency) ? amtSent.currency : 'XRP';
if (exists(transaction.sendMax)) linePayment['SentIssuer'] = transaction.sendMax.issuer;
}
linePayment['RecvAmount'] = formatAmount(transaction.amount);
linePayment['RecvCcy'] = transaction.currency;
linePayment['RecvIssuer'] = issuerToString(transaction.amount.issuer());
line = $.extend({}, lineTemplate, linePayment);
addLineToCsv(line);
}
else if (type === 'Payment' || type === 'OfferCreate' || type === 'OfferCancel') {
// Offers (Created / Cancelled / Executed)
var effect;
if (transType === 'offernew') {
getOrderDetails(lineOffer, transaction.gets, transaction.pays);
lineOffer['TransType'] = 'Offer Created';
line = $.extend({}, lineTemplate, lineOffer);
addLineToCsv(line);
}
else if (transType === 'offercancel') {
for (var e = 0; e < histLine.effects.length; e++) {
effect = histLine.effects[e];
if (effect.type === 'offer_cancelled') {
getOrderDetails(lineOffer, effect.gets, effect.pays);
lineOffer['TransType'] = 'Offer Cancelled';
line = $.extend({}, lineTemplate, lineOffer);
addLineToCsv(line);
break;
}
}
}
for (var s = 0; s < histLine.showEffects.length; s++) {
effect = histLine.showEffects[s],
buy = null,
sell = null;
lineOffer = {};
switch (effect.type) {
case 'offer_bought':
case 'offer_funded':
case 'offer_partially_funded':
// Order fills (partial or full)
if (effect.type === 'offer_bought') {
buy = exists(effect.paid) ? effect.paid : effect.pays;
sell = exists(effect.got) ? effect.got : effect.gets;
}
else {
buy = exists(effect.got) ? effect.got : effect.gets;
sell = exists(effect.paid) ? effect.paid : effect.pays;
}
getOrderDetails(lineOffer, buy, sell);
lineOffer['TransType'] = 'Executed offer';
lineOffer['ExecPrice'] = formatAmount(effect.price);
line = $.extend({}, lineTemplate, lineOffer);
if (s > 0) line['Fee'] = ''; // Fee only applies once
addLineToCsv(line);
break; // end case
}
}
}
// else unrecognised Transaction type hence ignored
}
// Ensure that historyCsv is set to empty string if there is nothing to download,
// otherwise the file download will be a single line with header and no data
$scope.historyCsv = $scope.historyShow.length ? csv : '';
};
}]);
};
module.exports = HistoryTab;
|
KonOpas.Stars = function(id, opt) {
opt = opt || {};
this.name = 'konopas.' + id + '.stars';
try { this.store = localStorage || sessionStorage || (new KonOpas.VarStore()); }
catch (e) { this.store = new KonOpas.VarStore(); }
this.tag = opt.tag || 'has_star';
this.server = false;
this.data = this.read();
}
KonOpas.Stars.prototype.read = function() {
return JSON.parse(this.store && this.store.getItem(this.name) || '{}');
}
KonOpas.Stars.prototype.write = function() {
try {
if (this.store) this.store.setItem(this.name, JSON.stringify(this.data));
} catch (e) {
if ((e.code != DOMException.QUOTA_EXCEEDED_ERR) || (this.store.length != 0)) { throw e; }
}
}
KonOpas.Stars.prototype.list = function() {
var list = [];
if (this.data) for (var id in this.data) {
if ((this.data[id].length == 2) && this.data[id][0]) list.push(id);
}
return list;
}
KonOpas.Stars.prototype.add = function(star_list, mtime) {
mtime = mtime || Math.floor(Date.now()/1000);
star_list.forEach(function(id) { this.data[id] = [1, mtime]; }, this);
this.write();
if (this.server) this.server.set_prog(this.list());
}
KonOpas.Stars.prototype.set = function(star_list) {
var mtime = Math.floor(Date.now()/1000);
if (this.data) for (var id in this.data) {
this.data[id] = [0, mtime];
}
this.add(star_list, mtime);
}
KonOpas.Stars.prototype.toggle = function(el, id) {
var add_star = !el.classList.contains(this.tag);
var mtime = Math.floor(Date.now()/1000);
this.data[id] = [add_star ? 1 : 0, mtime];
this.write();
if (this.server) this.server.add_prog(id, add_star);
if (add_star) el.classList.add(this.tag);
else el.classList.remove(this.tag);
}
KonOpas.Stars.prototype.sync = function(new_data) {
var local_mod = [], redraw = false;
for (var id in new_data) {
if (new_data[id].length != 2) {
_log('Stars.sync: invalid input ' + id + ': ' + JSON.stringify(new_data[id]), 'warn');
continue;
}
if (!(id in this.data) || (new_data[id][1] > this.data[id][1])) {
local_mod.push(id);
if (!(id in this.data) || (new_data[id][0] != this.data[id][0])) redraw = true;
this.data[id] = new_data[id];
}
}
if (local_mod.length) {
_log('Stars.sync: local changes: ' + local_mod + (redraw ? ' -> redraw' : ''));
this.write();
if (redraw) konopas.set_view();
}
if (this.server) {
var server_add = [], server_rm = [];
for (var id in this.data) {
if (!(id in new_data) || (new_data[id][1] < this.data[id][1])) {
if (this.data[id][0]) server_add.push(id);
else server_rm.push(id);
}
}
if (server_add.length) {
_log('Stars.sync: server add: ' + server_add);
this.server.add_prog(server_add, true);
}
if (server_rm.length) {
_log('Stars.sync: server rm: ' + server_rm);
this.server.add_prog(server_rm, false);
}
if (!local_mod.length && !server_add.length && !server_rm.length) {
_log('Stars.sync: no changes');
}
}
}
KonOpas.Stars.prototype.show = function() {
var view = _el("star_data"),
hash = window.location.hash.substr(6),
set_raw = (hash && (hash.substr(0,4) == 'set:')) ? hash.substr(4).split(',') : [],
set = konopas.program.list.filter(function(p) { return (set_raw.indexOf(p.id) >= 0); }).map(function(p) { return p.id; }),
set_len = set.length,
html = '',
star_list = this.list(),
stars_len = star_list.length;
if (konopas.store.limit && (!this.server || !this.server.connected)) {
html = '<p>' + i18n.txt('star_no_memory', {'WHY': konopas.store.limit, 'SERVER': !!this.server});
}
if (!stars_len && !set_len) {
_el("prog_ls").innerHTML = '';
view.innerHTML = html + '<p>' + i18n.txt('star_hint');
return;
}
document.body.classList.remove("show_set");
set.sort();
star_list.sort();
var set_link = '#star/set:' + star_list.join(',');
if (set_len) {
if (KonOpas.arrays_equal(set, star_list)) {
html += '<p>' + i18n.txt('star_export_this', { 'THIS':set_link }) + '<p>' +
i18n.txt('star_export_share', {
'SHORT': KonOpas.link_to_short_url(location.href),
'QR': KonOpas.link_to_qr_code(location.href)
});
} else {
document.body.classList.add("show_set");
var n_same = KonOpas.array_overlap(set, star_list);
var n_new = set_len - n_same;
var n_bad = set_raw.length - set_len;
html += '<p>' + i18n.txt('star_import_this', {'THIS':location.href})
+ '<p>' + i18n.txt('star_import_diff', { 'PREV':stars_len, 'NEW':n_new, 'SAME':n_same });
if (n_bad) html += ' ' + i18n.txt('star_import_bad', {'BAD':n_bad});
if (!stars_len || (n_same != stars_len)) {
html += '<p>» <a href="#star" id="star_set_set">' + i18n.txt('star_set') + '</a>';
}
if (stars_len) {
if (n_same != stars_len) {
var d = [];
if (n_new) d.push(i18n.txt('add_n', {'N':n_new}));
d.push(i18n.txt('discard_n', {'N':stars_len - n_same}));
html += ' (' + d.join(', ') + ')';
}
if (n_new) html += '<p>» <a href="#star" id="star_set_add">' + i18n.txt('star_add', {'N':n_new}) + '</a>';
}
}
} else {
html += '<p id="star_links">» ' + i18n.txt('star_export_link', { 'URL':set_link, 'N':stars_len });
}
view.innerHTML = html;
var el_set = _el('star_set_set'); if (el_set) el_set.onclick = function() { konopas.stars.set(set); return true; };
var el_add = _el('star_set_add'); if (el_add) el_add.onclick = function() { konopas.stars.add(set); return true; };
if (this.server) this.server.show_ical_link(view);
var ls = konopas.program.list.filter(function(it) { return (star_list.indexOf(it.id) >= 0) || (set.indexOf(it.id) >= 0); });
KonOpas.Item.show_list(ls, {hide_ended:true});
if (set_len) for (var i = 0; i < set_len; ++i) {
var el = _el('s' + set[i]);
if (el) el.classList.add("in_set");
}
}
|
/**
* 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.
*
* @emails react-core
* @jest-environment node
*/
'use strict';
let React;
let ReactNoop;
let Scheduler;
let ImmediatePriority;
let UserBlockingPriority;
let NormalPriority;
let LowPriority;
let IdlePriority;
let runWithPriority;
describe('ReactSchedulerIntegration', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactNoop = require('react-noop-renderer');
Scheduler = require('scheduler');
ImmediatePriority = Scheduler.unstable_ImmediatePriority;
UserBlockingPriority = Scheduler.unstable_UserBlockingPriority;
NormalPriority = Scheduler.unstable_NormalPriority;
LowPriority = Scheduler.unstable_LowPriority;
IdlePriority = Scheduler.unstable_IdlePriority;
runWithPriority = Scheduler.unstable_runWithPriority;
});
function getCurrentPriorityAsString() {
const priorityLevel = Scheduler.unstable_getCurrentPriorityLevel();
switch (priorityLevel) {
case ImmediatePriority:
return 'Immediate';
case UserBlockingPriority:
return 'UserBlocking';
case NormalPriority:
return 'Normal';
case LowPriority:
return 'Low';
case IdlePriority:
return 'Idle';
default:
throw Error('Unknown priority level: ' + priorityLevel);
}
}
// TODO: Delete this once new API exists in both forks
function LegacyHiddenDiv({hidden, children, ...props}) {
if (gate(flags => flags.new)) {
return (
<div hidden={hidden} {...props}>
<React.unstable_LegacyHidden mode={hidden ? 'hidden' : 'visible'}>
{children}
</React.unstable_LegacyHidden>
</div>
);
} else {
return (
<div hidden={hidden} {...props}>
{children}
</div>
);
}
}
it('flush sync has correct priority', () => {
function ReadPriority() {
Scheduler.unstable_yieldValue(
'Priority: ' + getCurrentPriorityAsString(),
);
return null;
}
ReactNoop.flushSync(() => ReactNoop.render(<ReadPriority />));
expect(Scheduler).toHaveYielded(['Priority: Immediate']);
});
it('has correct priority during rendering', () => {
function ReadPriority() {
Scheduler.unstable_yieldValue(
'Priority: ' + getCurrentPriorityAsString(),
);
return null;
}
ReactNoop.render(<ReadPriority />);
expect(Scheduler).toFlushAndYield(['Priority: Normal']);
runWithPriority(UserBlockingPriority, () => {
ReactNoop.render(<ReadPriority />);
});
expect(Scheduler).toFlushAndYield(['Priority: UserBlocking']);
runWithPriority(IdlePriority, () => {
ReactNoop.render(<ReadPriority />);
});
expect(Scheduler).toFlushAndYield(['Priority: Idle']);
});
it('has correct priority when continuing a render after yielding', () => {
function ReadPriority() {
Scheduler.unstable_yieldValue(
'Priority: ' + getCurrentPriorityAsString(),
);
return null;
}
runWithPriority(UserBlockingPriority, () => {
ReactNoop.render(
<>
<ReadPriority />
<ReadPriority />
<ReadPriority />
</>,
);
});
// Render part of the tree
expect(Scheduler).toFlushAndYieldThrough(['Priority: UserBlocking']);
// Priority is set back to normal when yielding
expect(getCurrentPriorityAsString()).toEqual('Normal');
// Priority is restored to user-blocking when continuing
expect(Scheduler).toFlushAndYield([
'Priority: UserBlocking',
'Priority: UserBlocking',
]);
});
it('layout effects have immediate priority', () => {
const {useLayoutEffect} = React;
function ReadPriority() {
Scheduler.unstable_yieldValue(
'Render priority: ' + getCurrentPriorityAsString(),
);
useLayoutEffect(() => {
Scheduler.unstable_yieldValue(
'Layout priority: ' + getCurrentPriorityAsString(),
);
});
return null;
}
ReactNoop.render(<ReadPriority />);
expect(Scheduler).toFlushAndYield([
'Render priority: Normal',
'Layout priority: Immediate',
]);
});
it('passive effects never have higher than normal priority', async () => {
const {useEffect} = React;
function ReadPriority({step}) {
Scheduler.unstable_yieldValue(
`Render priority: ${getCurrentPriorityAsString()}`,
);
useEffect(() => {
Scheduler.unstable_yieldValue(
`Effect priority: ${getCurrentPriorityAsString()}`,
);
return () => {
Scheduler.unstable_yieldValue(
`Effect clean-up priority: ${getCurrentPriorityAsString()}`,
);
};
});
return null;
}
// High priority renders spawn effects at normal priority
await ReactNoop.act(async () => {
Scheduler.unstable_runWithPriority(ImmediatePriority, () => {
ReactNoop.render(<ReadPriority />);
});
});
expect(Scheduler).toHaveYielded([
'Render priority: Immediate',
'Effect priority: Normal',
]);
await ReactNoop.act(async () => {
Scheduler.unstable_runWithPriority(UserBlockingPriority, () => {
ReactNoop.render(<ReadPriority />);
});
});
expect(Scheduler).toHaveYielded([
'Render priority: UserBlocking',
'Effect clean-up priority: Normal',
'Effect priority: Normal',
]);
// Renders lower than normal priority spawn effects at the same priority
await ReactNoop.act(async () => {
Scheduler.unstable_runWithPriority(IdlePriority, () => {
ReactNoop.render(<ReadPriority />);
});
});
expect(Scheduler).toHaveYielded([
'Render priority: Idle',
'Effect clean-up priority: Idle',
'Effect priority: Idle',
]);
});
it('passive effects have correct priority even if they are flushed early', async () => {
const {useEffect} = React;
function ReadPriority({step}) {
Scheduler.unstable_yieldValue(
`Render priority [step ${step}]: ${getCurrentPriorityAsString()}`,
);
useEffect(() => {
Scheduler.unstable_yieldValue(
`Effect priority [step ${step}]: ${getCurrentPriorityAsString()}`,
);
});
return null;
}
await ReactNoop.act(async () => {
ReactNoop.render(<ReadPriority step={1} />);
Scheduler.unstable_flushUntilNextPaint();
expect(Scheduler).toHaveYielded(['Render priority [step 1]: Normal']);
Scheduler.unstable_runWithPriority(UserBlockingPriority, () => {
ReactNoop.render(<ReadPriority step={2} />);
});
});
expect(Scheduler).toHaveYielded([
'Effect priority [step 1]: Normal',
'Render priority [step 2]: UserBlocking',
'Effect priority [step 2]: Normal',
]);
});
it('passive effect clean-up functions have correct priority even when component is deleted', async () => {
const {useEffect} = React;
function ReadPriority({step}) {
useEffect(() => {
return () => {
Scheduler.unstable_yieldValue(
`Effect clean-up priority: ${getCurrentPriorityAsString()}`,
);
};
});
return null;
}
await ReactNoop.act(async () => {
ReactNoop.render(<ReadPriority />);
});
await ReactNoop.act(async () => {
Scheduler.unstable_runWithPriority(ImmediatePriority, () => {
ReactNoop.render(null);
});
});
expect(Scheduler).toHaveYielded(['Effect clean-up priority: Normal']);
await ReactNoop.act(async () => {
ReactNoop.render(<ReadPriority />);
});
await ReactNoop.act(async () => {
Scheduler.unstable_runWithPriority(UserBlockingPriority, () => {
ReactNoop.render(null);
});
});
expect(Scheduler).toHaveYielded(['Effect clean-up priority: Normal']);
// Renders lower than normal priority spawn effects at the same priority
await ReactNoop.act(async () => {
ReactNoop.render(<ReadPriority />);
});
await ReactNoop.act(async () => {
Scheduler.unstable_runWithPriority(IdlePriority, () => {
ReactNoop.render(null);
});
});
expect(Scheduler).toHaveYielded(['Effect clean-up priority: Idle']);
});
it('passive effects are called before Normal-pri scheduled in layout effects', async () => {
const {useEffect, useLayoutEffect} = React;
function Effects({step}) {
useLayoutEffect(() => {
Scheduler.unstable_yieldValue('Layout Effect');
Scheduler.unstable_scheduleCallback(NormalPriority, () =>
Scheduler.unstable_yieldValue(
'Scheduled Normal Callback from Layout Effect',
),
);
});
useEffect(() => {
Scheduler.unstable_yieldValue('Passive Effect');
});
return null;
}
function CleanupEffect() {
useLayoutEffect(() => () => {
Scheduler.unstable_yieldValue('Cleanup Layout Effect');
Scheduler.unstable_scheduleCallback(NormalPriority, () =>
Scheduler.unstable_yieldValue(
'Scheduled Normal Callback from Cleanup Layout Effect',
),
);
});
return null;
}
await ReactNoop.act(async () => {
ReactNoop.render(<CleanupEffect />);
});
expect(Scheduler).toHaveYielded([]);
await ReactNoop.act(async () => {
ReactNoop.render(<Effects />);
});
expect(Scheduler).toHaveYielded([
'Cleanup Layout Effect',
'Layout Effect',
'Passive Effect',
// These callbacks should be scheduled after the passive effects.
'Scheduled Normal Callback from Cleanup Layout Effect',
'Scheduled Normal Callback from Layout Effect',
]);
});
it('after completing a level of work, infers priority of the next batch based on its expiration time', () => {
function App({label}) {
Scheduler.unstable_yieldValue(
`${label} [${getCurrentPriorityAsString()}]`,
);
return label;
}
// Schedule two separate updates at different priorities
runWithPriority(UserBlockingPriority, () => {
ReactNoop.render(<App label="A" />);
});
ReactNoop.render(<App label="B" />);
// The second update should run at normal priority
expect(Scheduler).toFlushAndYield(['A [UserBlocking]', 'B [Normal]']);
});
it('requests a paint after committing', () => {
const scheduleCallback = Scheduler.unstable_scheduleCallback;
const root = ReactNoop.createRoot();
root.render('Initial');
Scheduler.unstable_flushAll();
scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('A'));
scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('B'));
scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('C'));
// Schedule a React render. React will request a paint after committing it.
root.render('Update');
// Advance time just to be sure the next tasks have lower priority
Scheduler.unstable_advanceTime(2000);
scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('D'));
scheduleCallback(NormalPriority, () => Scheduler.unstable_yieldValue('E'));
// Flush everything up to the next paint. Should yield after the
// React commit.
Scheduler.unstable_flushUntilNextPaint();
expect(Scheduler).toHaveYielded(['A', 'B', 'C']);
});
// @gate enableLegacyHiddenType
it('idle updates are not blocked by offscreen work', async () => {
function Text({text}) {
Scheduler.unstable_yieldValue(text);
return text;
}
function App({label}) {
return (
<>
<Text text={`Visible: ` + label} />
<LegacyHiddenDiv hidden={true}>
<Text text={`Hidden: ` + label} />
</LegacyHiddenDiv>
</>
);
}
const root = ReactNoop.createRoot();
await ReactNoop.act(async () => {
root.render(<App label="A" />);
// Commit the visible content
expect(Scheduler).toFlushUntilNextPaint(['Visible: A']);
expect(root).toMatchRenderedOutput(
<>
Visible: A
<div hidden={true} />
</>,
);
// Before the hidden content has a chance to render, schedule an
// idle update
runWithPriority(IdlePriority, () => {
root.render(<App label="B" />);
});
// The next commit should only include the visible content
expect(Scheduler).toFlushUntilNextPaint(['Visible: B']);
expect(root).toMatchRenderedOutput(
<>
Visible: B
<div hidden={true} />
</>,
);
});
// The hidden content commits later
expect(Scheduler).toHaveYielded(['Hidden: B']);
expect(root).toMatchRenderedOutput(
<>
Visible: B<div hidden={true}>Hidden: B</div>
</>,
);
});
});
describe(
'regression test: does not infinite loop if `shouldYield` returns ' +
'true after a partial tree expires',
() => {
let logDuringShouldYield = false;
beforeEach(() => {
jest.resetModules();
jest.mock('scheduler', () => {
const actual = require.requireActual('scheduler/unstable_mock');
return {
...actual,
unstable_shouldYield() {
if (logDuringShouldYield) {
actual.unstable_yieldValue('shouldYield');
}
return actual.unstable_shouldYield();
},
};
});
React = require('react');
ReactNoop = require('react-noop-renderer');
Scheduler = require('scheduler');
React = require('react');
});
afterEach(() => {
jest.mock('scheduler', () =>
require.requireActual('scheduler/unstable_mock'),
);
});
it('using public APIs to trigger real world scenario', async () => {
// This test reproduces a case where React's Scheduler task timed out but
// the `shouldYield` method returned true. The bug was that React fell
// into an infinite loop, because it would enter the work loop then
// immediately yield back to Scheduler.
//
// (The next test in this suite covers the same case. The difference is
// that this test only uses public APIs, whereas the next test mocks
// `shouldYield` to check when it is called.)
function Text({text}) {
return text;
}
function App({step}) {
return (
<>
<Text text="A" />
<TriggerErstwhileSchedulerBug />
<Text text="B" />
<TriggerErstwhileSchedulerBug />
<Text text="C" />
</>
);
}
function TriggerErstwhileSchedulerBug() {
// This triggers a once-upon-a-time bug in Scheduler that caused
// `shouldYield` to return true even though the current task expired.
Scheduler.unstable_advanceTime(10000);
Scheduler.unstable_requestPaint();
return null;
}
await ReactNoop.act(async () => {
ReactNoop.render(<App />);
expect(Scheduler).toFlushUntilNextPaint([]);
expect(Scheduler).toFlushUntilNextPaint([]);
});
});
it('mock Scheduler module to check if `shouldYield` is called', async () => {
// This test reproduces a bug where React's Scheduler task timed out but
// the `shouldYield` method returned true. Usually we try not to mock
// internal methods, but I've made an exception here since the point is
// specifically to test that React is reslient to the behavior of a
// Scheduler API. That being said, feel free to rewrite or delete this
// test if/when the API changes.
function Text({text}) {
Scheduler.unstable_yieldValue(text);
return text;
}
function App({step}) {
return (
<>
<Text text="A" />
<Text text="B" />
<Text text="C" />
</>
);
}
await ReactNoop.act(async () => {
// Partially render the tree, then yield
ReactNoop.render(<App />);
expect(Scheduler).toFlushAndYieldThrough(['A']);
// Start logging whenever shouldYield is called
logDuringShouldYield = true;
// Let's call it once to confirm the mock actually works
Scheduler.unstable_shouldYield();
expect(Scheduler).toHaveYielded(['shouldYield']);
// Expire the task
Scheduler.unstable_advanceTime(10000);
// Because the render expired, React should finish the tree without
// consulting `shouldYield` again
expect(Scheduler).toFlushExpired(['B', 'C']);
});
});
},
);
|
var wt = require('../index');
var should = require('should');
describe('test/translate.test.js', function() {
describe('valid result', function() {
it('should.be.type.result String', function(done) {
wt.translate('uD67wmZzhi3RFcmTkGoks2Dr', '子曰', function(err, data) {
if (err) {} else {
data.should.be.type('string');
}
done();
});
});
});
describe('valid api err', function() {
it('should.be.type.result String', function(done) {
wt.translate('err api', '子曰', function(err, data) {
err.should.be.an.instanceof(Object);
done();
});
});
});
}); |
/**
* @jsx React.DOM
*/
var FluxBuckets, Immutable;
require('react-raf-batching').inject();
Immutable = require('immutable');
FluxBuckets = require('./components/FluxBuckets');
React.renderComponent( <FluxBuckets />, document.querySelector('#app'));
|
version https://git-lfs.github.com/spec/v1
oid sha256:1d185dfb68e247ba51832743ff441b36f5140720b0d6e9b3e3be963b07a27eca
size 911
|
var chai = require('chai');
var Bot = require('../index.js');
var utils = require('../libs/utils.js');
var bot = new Bot({token: 'token'});
var sinon = require('sinon');
var vow = require('vow');
var sinonChai = require('sinon-chai');
chai.use(sinonChai);
var expect = require('chai').expect;
var request = require('request');
describe('slack-bot-api', function() {
describe('#find', function() {
it('1', function() {
var data = [{a: 1, b: 2}, {b: 3, c: 4}];
expect(utils.find(data, {a: 1})).to.equal(data[0]);
});
it('2', function() {
var data = [{a: 1, b: 2, c: 4}, {b: 3, c: 4}];
expect(utils.find(data, {a: 1, c: 4})).to.equal(data[0]);
});
it('3', function() {
var data = [{a: 1, b: 2}, {b: 3, c: 4}];
expect(utils.find(data, {b: 3})).to.equal(data[1]);
});
it('4', function() {
var data = [{a: 1, b: 2}, {b: 3, c: 4}];
expect(utils.find(data, {a: 1, b: 2, c: 3})).to.not.equal(data[0]);
});
});
describe('#_api', function() {
afterEach(function() {
request.post.restore();
});
it('check url', function(done) {
var r1;
sinon.stub(request, 'post', function(data, cb) {
r1 = data;
cb(null, null, '{}');
});
bot._api('method', {foo: 1, bar: 2, baz: 3}).always(function() {
expect(r1).to.deep.equal(
{
url: 'https://slack.com/api/method',
form: {
foo: 1,
bar: 2,
baz: 3,
token: 'token'
}
}
);
done();
})
});
it('response without error', function(done) {
sinon.stub(request, 'post', function(data, cb) {
cb(null, null, "{\"ok\": true}");
});
bot._api('method', {foo: 1, bar: 2, baz: 3}).then(function(data) {
expect(data.ok).to.equal(true);
done();
})
});
it('response with error', function(done) {
sinon.stub(request, 'post', function(data, cb) {
cb(null, null, "{\"ok\": false}");
});
bot._api('method').fail(function(data) {
expect(data.ok).to.equal(false);
done();
})
});
});
describe('#postTo', function() {
beforeEach(function() {
sinon.stub(bot, 'getChannels');
sinon.stub(bot, 'getUsers');
sinon.stub(bot, 'getGroups');
});
afterEach(function() {
bot.getChannels.restore();
bot.getUsers.restore();
bot.getGroups.restore();
});
it('1', function(cb) {
bot.getChannels.returns(vow.fulfill({channels: [{name: 'name1', is_channel: true}]}));
bot.getUsers.returns(vow.fulfill({members: []}));
bot.getGroups.returns(vow.fulfill({groups: []}));
sinon.stub(bot, 'postMessageToChannel').returns(vow.fulfill());
bot.postTo('name1', 'text').then(function() {
expect(bot.postMessageToChannel).to.have.callCount(1);
expect(bot.postMessageToChannel).to.have.been.calledWith('name1', 'text');
cb();
});
});
it('2', function(cb) {
bot.getChannels.returns(vow.fulfill({channels: []}));
bot.getUsers.returns(vow.fulfill({members: [{name: 'name1'}]}));
bot.getGroups.returns(vow.fulfill({groups: []}));
sinon.stub(bot, 'postMessageToUser').returns(vow.fulfill());
bot.postTo('name1', 'text').then(function() {
expect(bot.postMessageToUser).to.have.callCount(1);
expect(bot.postMessageToUser).to.have.been.calledWith('name1', 'text');
cb();
});
});
it('3', function(cb) {
bot.getChannels.returns(vow.fulfill({channels: []}));
bot.getUsers.returns(vow.fulfill({members: []}));
bot.getGroups.returns(vow.fulfill({groups: [{name: 'name1', is_group: true}]}));
sinon.stub(bot, 'postMessageToGroup').returns(vow.fulfill());
bot.postTo('name1', 'text').then(function() {
expect(bot.postMessageToGroup).to.have.callCount(1);
expect(bot.postMessageToGroup).to.have.been.calledWith('name1', 'text');
cb();
});
});
});
});
|
(function () {
"use strict";
angular.module("dlGallery", ["ngAnimate", "ui.bootstrap", "angular-loading-bar", "ngTouch", "bootstrapLightbox"]);
})();
|
import { StyleSheet } from "aphrodite";
export default StyleSheet.create({
"side-panel": {
position: "fixed",
zIndex: 100,
top: 0,
bottom: 0,
width: "375px",
overflowX: "hidden",
overflowY: "auto",
WebkitOverflowScrolling: "touch",
"@media (max-width: 480px)": {
width: "100%",
},
},
"prompt-panel": {
position: "fixed",
zIndex: 100,
top: "auto",
bottom: 0,
overflowX: "hidden",
overflowY: "auto",
WebkitOverflowScrolling: "touch",
"@media (max-width: 768px)": {
bottom: 0,
top: "auto",
backgroundColor: "transparent",
width: "calc(100% - 20px)",
left: "10px",
// maxWidth: "380px",
},
"@media (min-width: 481px)": {
left: "50%",
marginLeft: "-190px",
maxWidth: "380px",
},
},
interior: {
overflowY: "auto !important",
"@media (max-width: 480px)": {
paddingBottom: "60px",
},
},
});
|
var catchall = require('catchall'),
fs = require('fs'),
outcome = require("outcome");
module.exports = {
"def catchall OR public/catchall": {
"params": {
"input": true,
"output": true
},
"description": "makes ALL errors catchable",
"message": "<%-input %>",
"run": run
}
}
function run(target, next) {
var data = target.get();
catchall.load(data.input, outcome.error(next).success(function(wrappedSource) {
target.set("input", data.output);
fs.witeFile(data.output, wrappedSource, next);
}));
}
|
var class_tempest_1_1_vertex_buffer_base =
[
[ "~VertexBufferBase", "class_tempest_1_1_vertex_buffer_base.html#a4a10f3f20f9bfd80d2e8ba490f79b71f", null ]
]; |
var Example = Example || {};
Example.collisionFiltering = function() {
var Engine = Matter.Engine,
Render = Matter.Render,
Runner = Matter.Runner,
Composite = Matter.Composite,
Composites = Matter.Composites,
Common = Matter.Common,
MouseConstraint = Matter.MouseConstraint,
Mouse = Matter.Mouse,
World = Matter.World,
Bodies = Matter.Bodies;
// create engine
var engine = Engine.create(),
world = engine.world;
// create renderer
var render = Render.create({
element: document.body,
engine: engine,
options: {
width: Math.min(document.documentElement.clientWidth, 800),
height: Math.min(document.documentElement.clientHeight, 600),
wireframes: false,
background: '#111'
}
});
Render.run(render);
// create runner
var runner = Runner.create();
Runner.run(runner, engine);
// define our categories (as bit fields, there are up to 32 available)
var defaultCategory = 0x0001,
redCategory = 0x0002,
greenCategory = 0x0004,
blueCategory = 0x0008;
var redColor = '#C44D58',
blueColor = '#4ECDC4',
greenColor = '#C7F464';
// add floor
World.add(world, Bodies.rectangle(400, 600, 900, 50, {
isStatic: true,
render: {
fillStyle: 'transparent',
lineWidth: 1
}
}));
// create a stack with varying body categories (but these bodies can all collide with each other)
World.add(world,
Composites.stack(275, 100, 5, 9, 10, 10, function(x, y, column, row) {
var category = redCategory,
color = redColor;
if (row > 5) {
category = blueCategory;
color = blueColor;
} else if (row > 2) {
category = greenCategory;
color = greenColor;
}
return Bodies.circle(x, y, 20, {
collisionFilter: {
category: category
},
render: {
strokeStyle: color,
fillStyle: 'transparent',
lineWidth: 1
}
});
})
);
// this body will only collide with the walls and the green bodies
World.add(world,
Bodies.circle(310, 40, 30, {
collisionFilter: {
mask: defaultCategory | greenCategory
},
render: {
strokeStyle: Common.shadeColor(greenColor, -20),
fillStyle: greenColor
}
})
);
// this body will only collide with the walls and the red bodies
World.add(world,
Bodies.circle(400, 40, 30, {
collisionFilter: {
mask: defaultCategory | redCategory
},
render: {
strokeStyle: Common.shadeColor(redColor, -20),
fillStyle: redColor
}
})
);
// this body will only collide with the walls and the blue bodies
World.add(world,
Bodies.circle(480, 40, 30, {
collisionFilter: {
mask: defaultCategory | blueCategory
},
render: {
strokeStyle: Common.shadeColor(blueColor, -20),
fillStyle: blueColor
}
})
);
// add mouse control
var mouse = Mouse.create(render.canvas),
mouseConstraint = MouseConstraint.create(engine, {
mouse: mouse,
constraint: {
stiffness: 0.2,
render: {
visible: false
}
}
});
World.add(world, mouseConstraint);
// keep the mouse in sync with rendering
render.mouse = mouse;
// red category objects should not be draggable with the mouse
mouseConstraint.collisionFilter.mask = defaultCategory | blueCategory | greenCategory;
// fit the render viewport to the scene
Render.lookAt(render, {
min: { x: 0, y: 0 },
max: { x: 800, y: 600 }
});
// context for MatterTools.Demo
return {
engine: engine,
runner: runner,
render: render,
canvas: render.canvas,
stop: function() {
Matter.Render.stop(render);
Matter.Runner.stop(runner);
}
};
}; |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = initStyleNodes;
var _felaUtils = require('fela-utils');
var sheetMap = {
fontFaces: _felaUtils.FONT_TYPE,
statics: _felaUtils.STATIC_TYPE,
keyframes: _felaUtils.KEYFRAME_TYPE,
rules: _felaUtils.RULE_TYPE
};
function initNode(styleNodes, baseNode, css, type) {
var media = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : '';
var node = (0, _felaUtils.getStyleNode)(styleNodes, baseNode, type, media);
// in case that there is a node coming from server already
// but rules are not matchnig
if (node.textContent !== css) {
node.textContent = css;
}
}
function initStyleNodes(renderer) {
renderer.styleNodes = (0, _felaUtils.reflushStyleNodes)();
var baseNode = renderer.styleNodes[_felaUtils.RULE_TYPE];
for (var style in sheetMap) {
if (renderer[style].length > 0) {
initNode(renderer.styleNodes, baseNode, renderer[style], sheetMap[style]);
}
}
for (var media in renderer.mediaRules) {
var mediaCSS = renderer.mediaRules[media];
if (mediaCSS.length > 0) {
initNode(renderer.styleNodes, baseNode, mediaCSS, _felaUtils.RULE_TYPE, media);
}
}
} |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z" />
, 'CheckBoxOutlineBlankOutlined');
|
(function( jQuery ) {
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rselectTextarea = /^(?:select|textarea)/i,
rspacesAjax = /\s+/,
rts = /([?&])_=[^&]*/,
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 = {},
// Document location
ajaxLocation,
// Document location segments
ajaxLocParts;
// #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 = "*";
}
if ( jQuery.isFunction( func ) ) {
var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
i = 0,
length = dataTypes.length,
dataType,
list,
placeBefore;
// For each dataType in the dataTypeExpression
for(; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters ),
selection;
for(; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
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 );
}
}
jQuery.fn.extend({
load: function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf( " " );
if ( off >= 0 ) {
var selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// 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 ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
// Complete callback (responseText is used internally)
complete: function( jqXHR, status, responseText ) {
// Store the response as specified by the jqXHR object
responseText = jqXHR.responseText;
// If successful, inject the HTML into all the matched elements
if ( jqXHR.isResolved() ) {
// #4825: Get the actual response in case
// a dataFilter is present in ajaxSettings
jqXHR.done(function( r ) {
responseText = r;
});
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
responseText );
}
if ( callback ) {
self.each( callback, [ responseText, status, jqXHR ] );
}
}
});
return this;
},
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.bind( o, f );
};
});
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({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// 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 ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": "*/*"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.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: {
context: true,
url: true
}
},
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 // Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery._Deferred(),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// ifModified key
ifModifiedKey,
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// The jqXHR state
state = 0,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// 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 === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || "abort";
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
// 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;
var isSuccess,
success,
error,
statusText = nativeStatusText,
response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
lastModified,
etag;
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
jQuery.lastModified[ ifModifiedKey ] = lastModified;
}
if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
jQuery.etag[ ifModifiedKey ] = etag;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
try {
success = ajaxConvert( s, response );
statusText = "success";
isSuccess = true;
} catch(e) {
// We have a parsererror
statusText = "parsererror";
error = e;
}
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if( !statusText || status ) {
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( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.done;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.then( tmp, tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
// Determine if a cross-domain request is in order
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 prefiler, stop there
if ( state === 2 ) {
return false;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// 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 If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// 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 ] !== "*" ? ", */*; 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
jqXHR.abort();
return false;
}
// 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 {
jQuery.error( e );
}
}
}
return jqXHR;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : value;
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = 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 ( var prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
}
});
function buildParams( prefix, obj, traditional, add ) {
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 {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && obj != null && typeof obj === "object" ) {
// Serialize object item.
for ( var name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields,
ct,
type,
finalDataType,
firstDataType;
// Fill responseXXX fields
for( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// 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
function ajaxConvert( s, response ) {
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
var dataTypes = s.dataTypes,
converters = {},
i,
key,
length = dataTypes.length,
tmp,
// Current and previous dataTypes
current = dataTypes[ 0 ],
prev,
// Conversion expression
conversion,
// Conversion function
conv,
// Conversion functions (transitive conversion)
conv1,
conv2;
// For each dataType in the chain
for( i = 1; i < length; i++ ) {
// Create converters map
// with lowercased keys
if ( i === 1 ) {
for( key in s.converters ) {
if( typeof key === "string" ) {
converters[ key.toLowerCase() ] = s.converters[ key ];
}
}
}
// Get the dataTypes
prev = current;
current = dataTypes[ i ];
// If current is auto dataType, update it to prev
if( current === "*" ) {
current = prev;
// If no auto and dataTypes are actually different
} else if ( prev !== "*" && prev !== current ) {
// Get the converter
conversion = prev + " " + current;
conv = converters[ conversion ] || converters[ "* " + current ];
// If there is no direct converter, search transitively
if ( !conv ) {
conv2 = undefined;
for( conv1 in converters ) {
tmp = conv1.split( " " );
if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
conv2 = converters[ tmp[1] + " " + current ];
if ( conv2 ) {
conv1 = converters[ conv1 ];
if ( conv1 === true ) {
conv = conv2;
} else if ( conv2 === true ) {
conv = conv1;
}
break;
}
}
}
}
// If we found no converter, dispatch an error
if ( !( conv || conv2 ) ) {
jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
}
// If found converter is not an equivalence
if ( conv !== true ) {
// Convert with 1 or 2 converters accordingly
response = conv ? conv( response ) : conv2( conv1(response) );
}
}
}
return response;
}
})( jQuery );
|
function DeepCopy(obj) {
if (typeof(obj) !== 'object') {
return obj;
}
var cloned = {};
for (var i in obj) {
cloned[i] = DeepCopy(obj[i]);
}
return cloned;
}
var andy = { age: 21, family: "mitev"};
var cloning = DeepCopy(andy);
andy.i = 22;
console.log(andy);
console.log(cloning); |
requirejs(['require',
'/scripts/svg4everybody.js',
'/scripts/flickity.pkgd.js',
'/scripts/fontfaceobserver.js',
'/scripts/respimage.js',
'/scripts/ls.parent-fit.js',
'/scripts/lazysizes-umd.js'
],
function(require, Flickity) {
'use strict';
var font = new FontFaceObserver('Open Sans');
font.load().then(function () {
document.documentElement.className += " app-fonts--loaded";
});
// SVG Sprite polyfill
svg4everybody();
// Choices select
let choicesSelector = document.querySelector('.js-choices-selector');
if (choicesSelector !== null) {
const choices = new Choices('.js-choices-selector', {
itemSelectText: 'auswählen',
});
}
// Static navigation drawer
var navBarIsActive = false;
function navigationToggleHandler(element, options) {
var $navBar = document.querySelector(options.navBar);
// Handle navigation states
if (navBarIsActive) {
element.classList.remove(options.navBarToggleActiveClass);
$navBar.classList.remove(options.navBarVisible);
$navBar.classList.add(options.navBarHidden);
} else {
element.classList.add(options.navBarToggleActiveClass);
$navBar.classList.add(options.navBarVisible);
$navBar.classList.remove(options.navBarHidden);
}
navBarIsActive = !navBarIsActive;
}
var navBarToggle = Array.prototype.slice.call(document.querySelectorAll('.js-nav-toggle'));
// Nav bar toggle
navBarToggle.forEach(function(el) {
el.addEventListener("click", function(event) {
event.preventDefault();
event.stopPropagation();
navigationToggleHandler(el,
{
navBar: ".c-nav-bar",
navBarHidden: "c-nav-bar--hidden",
navBarVisible: "c-nav-bar--visible",
navBarToggleActiveClass: "js-nav-toggle--active",
navBarToggleCloseClass: "js-nav-toggle--close"
}
);
})
});
var $bannerBar = document.querySelector('.app-js-carousel'),
$galleryContainer = document.querySelector('.js-gallery');
if ($bannerBar !== null) {
var bannerflkty = new Flickity('.app-js-carousel', {
pauseAutoPlayOnHover: false,
autoPlay: 7000,
contain: true,
wrapAround: true,
imagesLoaded: true,
cellSelector: '.app-banner-item',
cellAlign: 'left',
selectedAttraction: 0.025,
friction: 0.28
});
$bannerBar.classList.add('app-banner--loaded');
}
// Content image galleries
if ($galleryContainer !== null) {
var flkty = new Flickity('.js-gallery', {
autoPlay: true,
contain: true,
wrapAround: true,
imagesLoaded: true,
cellSelector: '.app-gallery-cell',
cellAlign: 'left'
});
$galleryContainer.classList.add('app-banner--loaded');
}
// Initialize scripts
// Load Slider Resize
window.addEventListener('load', function() {
var sliders = Array.prototype.slice.call(document.querySelectorAll('.js-slider-resize'));
if (sliders) {
sliders.forEach(function(slider) {
var flkty = Flickity.data(slider);
flkty.resize()
});
}
});
});
|
import Component from '@glimmer/component';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
export default class DraggableColumnComponent extends Component {
/**
* Injected `layout` service. Used to broadcast
* changes the layout of the app.
*
* @property layoutService
* @type {Service}
*/
@service('layout') layoutService;
@tracked minWidth = 60;
/**
* Trigger that the application dimensions have changed due to
* something being dragged/resized such as the main nav or the
* object inspector.
*
* @method triggerResize
*/
@action
triggerResize() {
this.layoutService.trigger('resize', { source: 'draggable-column' });
}
}
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text,
Image,
TouchableHighlight,
PixelRatio
} from 'react-native';
import HeaderView from './HeaderCell.js';
import MeItemCell from './MeItemCell.js';
export default class HomeCell extends Component {
static defaultProps = {
name: '详情'
}
constructor(props) {
super(props);
this.state = {
obj: this.props.obj,
onSelect:this.props.onSelect,
headerClick:this.props.headerClick,
};
}
render(){
if (this.props.sectionID == 'header') {
// return null;
return (<HeaderView headerClick={this.state.headerClick}/>);
}
return (<MeItemCell isBottom={this.props.isBottom} rowID={this.props.rowID} sectionID={this.props.sectionID} obj={this.state.obj} onSelect={this.state.onSelect}/>);
}
}
const styles = StyleSheet.create({
}); |
$(function () {
var optsDate = {
format: 'Y-m-d', // รูปแบบวันที่
formatDate: 'Y-m-d',
timepicker: false,
closeOnDateSelect: true,
}
var optsTime = {
format: 'H:i', // รูปแบบเวลา
step: 30, // step เวลาของนาที แสดงค่าทุก 30 นาที
formatTime: 'H:i',
datepicker: false,
}
var setDateFunc = function (ct, obj) {
var minDateSet = $("#startDate_Soon").val();
var maxDateSet = $("#endDate_Soon").val();
if ($(obj).attr("id") == "startDate_Soon") {
this.setOptions({
minDate: false,
maxDate: maxDateSet ? maxDateSet : false
})
}
if ($(obj).attr("id") == "endDate_Soon") {
this.setOptions({
maxDate: false,
minDate: minDateSet ? minDateSet : false
})
}
}
var setTimeFunc = function (ct, obj) {
var minDateSet = $("#startDate_Soon").val();
var maxDateSet = $("#endDate_Soon").val();
var minTimeSet = $("#startTime_Soon").val();
var maxTimeSet = $("#endTime_Soon").val();
if (minDateSet != maxDateSet) {
minTimeSet = false;
maxTime = false;
}
if ($(obj).attr("id") == "startTime_Soon") {
this.setOptions({
maxDate: maxDateSet ? maxDateSet : false,
minTime: false,
maxTime: maxTimeSet ? maxTimeSet : false
})
}
if ($(obj).attr("id") == "endTime_Soon") {
this.setOptions({
minDate: minDateSet ? minDateSet : false,
maxTime: false,
minTime: minTimeSet ? minTimeSet : false
})
}
}
$("#startDate_Soon,#endDate_Soon").datetimepicker($.extend(optsDate, {
onShow: setDateFunc,
onSelectDate: setDateFunc,
}));
$("#startTime_Soon,#endTime_Soon").datetimepicker($.extend(optsTime, {
onShow: setTimeFunc,
onSelectTime: setTimeFunc,
}));
}); |
var mysql = require('mysql'),
sqlconfig = require('../conf/config.json'),
conn = {},
dbinteraction = {};
dbinteraction.rGoodClassMenu = function(callback) {
var query = 'SELECT * FROM goodsclass ORDER BY gclasscode DESC;';
var result = [];
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("查询出错:" + err);
return;
}
if (rows.length > 0) {
rows.forEach(function(item, i) {
var goodsclass = {
"name": item.gclassname,
"code": item.gclasscode
};
result.push(goodsclass);
});
} else {
result = false;
}
// console.log(result);
conn.end();
callback(result);
});
}
dbinteraction.gcUni = function(gclassname, callback) {
var query = 'SELECT * FROM goodsclass WHERE gclassname="' + gclassname + '";';
var result = false;
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("查询出错:" + err);
result = "查询出错!";
callback(result);
return;
}
if (rows.length == 0) {
result = 200;
} else {
result = "商品分类已存在!";
}
conn.end();
callback(result);
return;
});
}
dbinteraction.addGclass = function(gclassname, callback) {
dbinteraction.gcUni(gclassname, function(mark) {
if (mark == 200) {
var query = 'INSERT INTO goodsclass(gclassname)VALUE("' + gclassname + '");';
var result = false;
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("查询出错:" + err);
result = "插入出错!";
callback(result);
return;
}
if (rows) {
console.log("查询结果!" + rows);
console.log(rows);
result = "Ye";
}
conn.end();
callback(result);
return;
});
} else {
callback(mark);
return;
}
});
}
dbinteraction.getGcode = function(gclassname, callback) {
var query = 'SELECT gclasscode FROM goodsclass WHERE gclassname="' + gclassname + '";';
var result = false;
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("查询出错:" + err);
err = "插入出错!";
callback(err, null);
return;
}
if (rows) {
result = rows[0].gclasscode;
console.log("查询结果-code!" + result);
}
conn.end();
callback(null, result);
return;
});
}
dbinteraction.deleteGclass = function(code, callback) {
var query = 'DELETE FROM goodsclass WHERE gclasscode=' + code + ';';
var result = false;
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("删除出错:" + err);
err = "删除出错!";
callback(err, null);
return;
}
result = code;
conn.end();
callback(null, result);
return;
});
}
dbinteraction.pushGoods = function(msg, callback) {
var query = 'INSERT INTO goods(gclasscode,gname,gdescription,price,img,path)VALUE';
query += '(' + msg.code + ',"' + msg.name + '","' + msg.description + '",' + msg.price + ',"' + msg.filename + '","' + msg.path + '");';
var result = false;
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("插入商品数据出错:" + err);
err = "插入商品数据出错!";
callback(err, null);
return;
}
result = 200;
conn.end();
callback(null, result);
return;
});
}
dbinteraction.getGoods = function(code, callback) {
var query = "",
result = [];
if (!code) {
console.log("查询全部");
query = 'SELECT * FROM goods;';
} else {
query = 'SELECT * FROM goods WHERE gclasscode=' + code + ';'
console.log("查询部分1");
}
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("查询商品数据出错:" + err);
err = "查询商品数据出错!";
callback(err, null);
return;
}
if (rows.length > 0) {
rows.forEach(function(item, i) {
var goods = {
"name": item.gname,
"code": item.gcode,
"description": item.gdescription,
"price": item.price,
"imgurl": item.path + item.img
};
result.push(goods);
});
}
callback(null, result);
return;
});
}
dbinteraction.getGood = function(code, callback) {
var query = 'SELECT CONCAT(path,img) AS imgurl FROM goods WHERE gcode=' + code + ';';
var result = false;
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("删除出错:" + err);
err = "删除出错!";
callback(err, null);
return;
}
if (rows.length == 1) {
result = rows[0].imgurl;
}
conn.end();
callback(null, result);
return;
});
}
dbinteraction.deleteGoods = function(code, callback) {
var query = 'DELETE FROM goods WHERE gcode=' + code + ';';
var result = false;
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("删除出错:" + err);
err = "删除出错!";
callback(err, null);
return;
}
result = code;
conn.end();
callback(null, result);
return;
});
}
dbinteraction.getGoodsKey = function(key, callback) {
var query = 'SELECT gcode,gname,gdescription,price,CONCAT(path,img) AS imgurl FROM goods WHERE gname ';
query += 'LIKE "%' + key + '%" OR gdescription LIKE "%' + key + '%";';
var result = [];
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("查询商品数据出错:" + err);
err = "查询商品数据出错!";
callback(err, null);
return;
}
if (rows.length > 0) {
rows.forEach(function(item, i) {
var goods = {
"name": item.gname,
"code": item.gcode,
"description": item.gdescription,
"price": item.price,
"imgurl": item.imgurl
};
result.push(goods);
});
}
callback(null, result);
return;
});
}
dbinteraction.getMenu = function(use, callback) {
var query = 'SELECT * FROM CMenu ORDER BY mcode DESC;';;
var result = [];
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("查询一级文化块出错:" + err);
err = "查询一级文化块出错!";
callback(err, null);
return;
}
if (rows.length > 0) {
var len = rows.length;
(function pushResult(i) {
var item = rows[i];
var temp = {
"code": item.mcode,
"name": item.cname,
"description": item.description
};
if (use) {
query = 'SELECT CONCAT(path,img) AS imgurl FROM ctmenu WHERE mmcode=' + item.mcode + ';';
conn.query(query, function(err, rows, fields) {
if (err) {
console.log(err);
return;
}
var rlen = rows.length;
if (rlen > 0) {
var rone = rows[Math.floor(Math.random() * rows.length)];
temp["imgurl"] = rone.imgurl;
result.push(temp);
}
if (++i >= len) {
conn.end();
callback(null, result);
return;
}
pushResult(i);
});
} else {
result.push(temp);
if (++i >= len) {
conn.end();
callback(null, result);
return;
}
pushResult(i);
}
})(0);
}
});
}
dbinteraction.pushMenu = function(name, description, callback) {
var query = 'INSERT INTO CMenu(cname,description)VALUE("' + name + '","' + description + '");';
var result = "";
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("插入一级文化块出错:" + err);
err = "插入一级文化块出错!";
callback(err, null);
return;
}
query = 'SELECT * FROM CMenu WHERE cname="' + name + '";';
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("查询一级文化块code出错:" + err);
err = "查询一级文化块code出错!";
callback(err, null);
return;
}
result = rows[rows.length - 1].mcode;
conn.end();
callback(null, result);
return;
})
});
}
dbinteraction.deleteMenu = function(code, callback) {
var query = 'DELETE FROM CMenu WHERE mcode=' + code + ';';
var result = "";
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("删除一级文化块出错:" + err);
err = "删除一级文化块出错!";
callback(err, null);
return;
}
result = code;
callback(null, result);
return;
});
}
dbinteraction.getSMenu = function(code, use, callback) {
var query = 'SELECT * FROM csmenu WHERE mcode=' + code + ' ORDER BY cod DESC;';
var result = [];
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("查询二级级文化块出错:" + err);
err = "查询二级级文化块出错!";
callback(err, null);
return;
}
if (rows.length > 0) {
var rowsLen = rows.length;
(function pushResult(i) {
var item = rows[i],
cod = item.cod;
var temp = {
"code": cod,
"name": item.cname,
"description": item.description
};
if (use) {
query = 'SELECT CONCAT(path,img) AS imgurl FROM ctmenu WHERE mcode=' + cod + ';';
conn.query(query, function(err, rows, fields) {
if (err) {
console.log(err);
return;
}
var rlen = rows.length;
if (rlen > 0) {
var rone = rows[Math.floor(Math.random() * rlen)];
temp["imgurl"] = rone.imgurl;
result.push(temp);
}
if (++i < rowsLen) {
pushResult(i);
} else {
conn.end();
callback(null, result);
return;
}
});
} else {
result.push(temp);
if (++i < rowsLen) {
pushResult(i);
} else {
conn.end();
callback(null, result);
return;
}
}
})(0);
} else {
callback(null, result);
return;
}
});
}
dbinteraction.pushSMenu = function(mcode, name, description, callback) {
var query = 'INSERT INTO csmenu(mcode,cname,description)VALUE(' + mcode + ',"' + name + '","' + description + '");';
var result = "";
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("插入二级级文化块出错:" + err);
err = "插入二级级文化块出错!";
callback(err, null);
return;
}
result = 200;
callback(null, result);
return;
});
}
dbinteraction.deleteSMenu = function(code, callback) {
var query = 'DELETE FROM csmenu WHERE cod=' + code + ';';
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("删除一级文化块出错:" + err);
err = "删除一级文化块出错!";
callback(err, null);
return;
}
callback(null, "Ye");
return;
});
}
dbinteraction.getTMenu = function(code, callback) {
var query = 'SELECT * FROM ctmenu WHERE mcode=' + code + ' ORDER BY cod DESC;';
var result = [];
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("插叙三级级文化块出错:" + err);
err = "插叙三级级文化块出错!";
conn.end();
callback(err, null);
return;
}
if (rows.length > 0) {
rows.forEach(function(item, i) {
var temp = {
"code": item.cod,
"name": item.cname,
"description": item.description,
"imgurl": item.path + item.img
}
result.push(temp);
})
}
conn.end();
callback(null, result);
return;
});
};
dbinteraction.getTMenuOne = function(code, callback) {
var query = 'SELECT CONCAT(path,img) AS imgurl FROM ctmenu WHERE cod=' + code + ';';
var result = false;
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("插查询imgurl出错:" + err);
err = "查询imgurl出错!";
callback(err, null);
return;
}
if (rows.length == 1) {
result = rows[0].imgurl;
}
conn.end();
callback(null, result);
return;
});
}
dbinteraction.pushTMenu = function(msg, callback) {
var query = 'INSERT INTO ctmenu(mmcode,mcode,cname,description,img,path)VALUE';
query += '(' + msg.mmcode + ',' + msg.mcode + ',"' + msg.name + '","' + msg.description + '","' + msg.filename + '","' + msg.path + '");'
var result = "";
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("插入一级文化块出错:" + err);
err = "插入一级文化块出错!";
callback(err, null);
return;
}
result = 200;
console.log("目录图片推送成功!");
callback(null, result);
conn.end();
return;
});
}
dbinteraction.deleteTMenu = function(code, callback) {
var query = 'DELETE FROM ctmenu WHERE cod=' + code+';';
conn = mysql.createConnection(sqlconfig);
conn.connect();
conn.query(query, function(err, rows, fields) {
if (err) {
console.log("删除一级文化块出错:" + err);
err = "删除一级文化块出错!";
callback(err, null);
return;
}
conn.end();
callback(null, code);
return;
});
}
module.exports = dbinteraction;
|
/* Kriteria.js */
(function(cxt, global) {
"use strict";
var getProperty = require("./lib/getProperty.js").getProperty,
matchPrefix = require("./lib/matchPrefix.js").matchPrefix,
Condition = require("./lib/Condition.js").Condition,
evaluation = require("./lib/evaluation.js").evaluation,
kref = require("./lib/keys_reference.js").keysReference;
/**
* @public
* @class
*/
var Kriteria = function Kriteria() {
this._conditionAnd = [];
this._conditionOr = [];
this._not_flg = false;
};
Kriteria._name_ = "Kriteria";
/**
* @public
* @function
* @returns {Condition[]}
*/
Kriteria.prototype.getConditionAnd = function getConditionAnd() {
return this._conditionAnd;
};
/**
* @public
* @function
* @returns {Condition[]}
*/
Kriteria.prototype.getConditionOr = function getConditionAOr() {
return this._conditionOr;
};
/**
* @private
* @property
* @description
*/
Kriteria._JS_OPERATOR = {
eq: "===",
ne: "!==",
lt: "<",
le: "<=",
gt: ">",
ge: ">="
};
/**
* @public
* @function
* @param {Condition} condition -
* @returns {void}
* @description
*/
Kriteria.prototype.addAnd = function addAnd(condition) {
this._conditionAnd[this._conditionAnd.length] = condition;
};
/**
* @public
* @function
* @param {Condition} condition -
* @returns {void}
* @description
*/
Kriteria.prototype.addOr = function addOr(condition) {
this._conditionOr[this._conditionOr.length] = condition;
};
/**
* @public
* @function
* @param {Mixed(String|Kriteria|Function)} key - key name or Kriteria instance or Kriteria reqired function
* @returns {Function} evaluation || {Kriteria}
* @description
*/
Kriteria.prototype.and = function and(key) {
var key_type = typeof key,
cri = null;
if(
key_type === "string" ||
key instanceof String ||
key_type === "number" ||
key instanceof Number
) {
return evaluation("and", key, this);
} else if(key instanceof Kriteria) {
cri = key;
this.addAnd(new Condition("", "", [], "", cri));
return this;
} else if(typeof key === "function") {
cri = new Kriteria();
key(cri);
this.addAnd(new Condition("", "", [], "", cri));
return this;
} else {
throw new Error("invalid type of argument. (" + key_type + ")");
}
};
/**
* @public
* @function
* @param {Mixed(String|Kriteria|Function)} key - key name or Kriteria instance or Kriteria reqired function
* @returns {Mixed(Function|Kriteria)}
* @description
*/
Kriteria.prototype.or = function or(key) {
var key_type = typeof key,
cri = null;
if(key_type === "string" ||
key instanceof String ||
key_type === "number" ||
key instanceof Number
) {
return evaluation("or", key, this);
} else if(key instanceof Kriteria) {
cri = key;
this.addOr(new Condition("", "", [], "", cri));
return this;
} else if(typeof key === "function") {
cri = new Kriteria();
key(cri);
this.addOr(new Condition("", "", [], "", cri));
return this;
} else {
throw new Error("invalid type of argument. (" + key_type + ")");
}
};
/**
* @public
* @function
* @returns {Kriteria}
* @description
*/
Kriteria.prototype.not = function not() {
this._not_flg = !this._not_flg;
return this;
};
/**
* @public
* @static
* @function
* @param {Object} conditions -
* {Condition[]} conditions.and -
* {Condition[]} conditions.or -
* @returns {Kriteria}
* @description
*/
Kriteria.parse = function parse(conditions) {
var ret = new Kriteria(),
i = "";
for(i in conditions.and) {
ret.addAnd(conditions.and[i]);
}
for(i in conditions.or) {
ret.andOr(conditions.or[i]);
}
if(conditions.not) {
ret.not();
}
return ret;
};
/**
* @public
* @function
* @param {Object} data -
* @returns {Boolean}
* @description
*/
Kriteria.prototype.match = function match(data) {
var i = 0, l = 0,
j = 0, l2 = 0,
left_key = "",
operator = "",
right_key = [],
key_type = "",
left_value = null,
right_value = [],
result = false,
condition = null,
tmp_right_value = null;
for(i = 0, l = this._conditionAnd.length; i < l; i = i + 1) {
condition = this._conditionAnd[i];
if(condition.criteria instanceof Kriteria) {
result = condition.criteria.match(data);
// and条件は1つでもfalseがあったら、結果はfalse
if(!result) {
break;
}
} else {
left_key = condition.left_key;
operator = condition.operator;
right_key = condition.right_key;
key_type = condition.key_type;
left_value = getProperty(data, left_key);
if(key_type === "value") {
right_value = right_key;
} else if(key_type === "key") {
tmp_right_value = getProperty(data, right_key[0]);
if(Array.isArray(tmp_right_value)) {
if(operator === "match" || operator === "not_match") {
right_value = [];
for(j = 0, l2 = tmp_right_value.length; j < l2; j = j + 1) {
if(tmp_right_value[j] === null
|| tmp_right_value[j] === void 0
|| tmp_right_value[j] === "") {
right_value[j] = tmp_right_value[j];
} else {
right_value[j] = new RegExp(tmp_right_value[j]);
}
}
} else {
right_value = tmp_right_value;
}
} else {
if(operator === "match" || operator === "not_match") {
if(tmp_right_value === null
|| tmp_right_value === void 0
|| tmp_right_value === "") {
right_value = tmp_right_value;
} else {
right_value = [new RegExp(tmp_right_value)];
}
} else {
right_value = [tmp_right_value];
}
}
}
if(
right_value === void 0
|| !!~right_value.indexOf(void 0)
|| left_value === void 0
) {
// valueがundefinedの場合はfalse
result = false;
} else {
// 上記以外は比較演算
result = this._compare(left_value, operator, right_value);
}
// and条件は1つでもfalseがあったら、結果はfalse
if(!result) {
break;
}
}
}
// and条件ですべて一致した場合
if(result) {
return !!(true ^ this._not_flg);
}
for(i = 0, l = this._conditionOr.length; i < l; i = i + 1) {
condition = this._conditionOr[i];
if(condition.criteria instanceof Kriteria) {
result = condition.criteria.match(data);
if(result) {
return !!(true ^ this._not_flg);
}
} else {
left_key = condition.left_key;
operator = condition.operator;
right_key = condition.right_key;
key_type = condition.key_type;
left_value = getProperty(data, left_key);
if(key_type === "value") {
right_value = right_key;
} else if(key_type === "key") {
tmp_right_value = getProperty(data, right_key[0]);
if(Array.isArray(tmp_right_value)) {
if(operator === "match" || operator === "not_match") {
right_value = [];
for(j = 0, l2 = tmp_right_value.length; j < l2; j = j + 1) {
if(tmp_right_value[j] === null
|| tmp_right_value[j] === void 0
|| tmp_right_value[j] === "") {
right_value[j] = tmp_right_value[j];
} else {
right_value[j] = new RegExp(tmp_right_value[j]);
}
}
} else {
right_value = tmp_right_value;
}
} else {
if(operator === "match" || operator === "not_match") {
if(tmp_right_value === null
|| tmp_right_value === void 0
|| tmp_right_value !== "") {
right_value = tmp_right_value;
} else {
right_value = [new RegExp(tmp_right_value)];
}
} else {
right_value = [tmp_right_value];
}
}
}
if(
right_value === void 0
|| !!~right_value.indexOf(void 0)
|| left_value === void 0
) {
// valueがundefinedの場合はfalse
result = false;
} else {
// 上記以外は比較演算
result = this._compare(left_value, operator, right_value);
}
// or条件は1つでもtrueがあったら、結果はtrue
if(result) {
return !!(true ^ this._not_flg);
}
}
}
// 上記以外はfalse
return !!(false ^ this._not_flg);
};
/**
* @private
* @function
* @param {Mixed(String|Number)} value1 -
* @param {String} operator -
* @param {Array} value2 -
* @returns {Boolean}
* @description
*/
Kriteria.prototype._compare = function _compare(value1, operator, value2) {
var result = false;
switch(operator) {
case "eq":
result = (value2[0] === value1);
break;
case "ne":
result = (value2[0] !== value1);
break;
case "lt":
result = (value2[0] > value1);
break;
case "le":
result = (value2[0] >= value1);
break;
case "gt":
result = (value2[0] < value1);
break;
case "ge":
result = (value2[0] <= value1);
break;
case "in":
result = !!~value2.indexOf(value1);
break;
case "not_in":
result = !~value2.indexOf(value1);
break;
case "between":
result = (value2[0] <= value1 && value2[1] >= value1);
break;
case "not_between":
result = (value2[0] > value1 || value2[1] < value1);
break;
case "match":
if(value2[0] === null) {
if(value1 === null || value1 === void 0) {
result = true;
} else {
result = false;
}
} else if(value1 === null) {
result = false;
} else if(value2[0] === "") {
result = value1 === "" ? true : false;
} else {
result = value2[0].test(value1);
}
break;
case "not_match":
if(value2[0] === null) {
if(value1 === null || value1 === void 0) {
result = false;
} else {
result = true;
}
} else if(value1 === null) {
result = true;
} else if(value2[0] === "") {
result = value1 === "" ? false : true;
} else {
result = !value2[0].test(value1);
}
break;
}
return result;
};
/**
* @public
* @function
* @returns {Function}
* @description
*/
Kriteria.prototype.matcher = function matcher() {
/* eslint no-new-func: 0 */
return new Function("$", "return " + this._createMatchingExpression());
};
/**
* @private
* @function
* @returns {String}
* @description
*/
Kriteria.prototype._createMatchingExpression = function _createMatchingExpression() {
var i = 0, l = 0,
expAnd = [],
expOr = [],
retAnd = "",
retOr = "",
condition = null,
ret = "";
for(i = 0, l = this._conditionAnd.length; i < l; i = i + 1) {
condition = this._conditionAnd[i];
if(condition.criteria instanceof Kriteria) {
expAnd[expAnd.length] = "(" + condition.criteria._createMatchingExpression() + ")";
} else {
expAnd[expAnd.length] = this._createExpression(condition);
}
}
for(i = 0, l = this._conditionOr.length; i < l; i = i + 1) {
condition = this._conditionOr[i];
if(condition.criteria instanceof Kriteria) {
expOr[expOr.length] = "(" + condition.criteria._createMatchingExpression() + ")";
} else {
expOr[expOr.length] = this._createExpression(condition);
}
}
retAnd = expAnd.join(" && ");
retOr = expOr.join(" || ");
if(retAnd && retOr) {
ret = retAnd + " || " + retOr + " ";
} else if(!retOr) {
ret = retAnd;
} else if(!retAnd) {
ret = retOr;
}
if(this._not_flg) {
ret = "!(" + ret + ")";
}
return ret;
};
/**
* @private
* @function
* @param {Condition} condition -
* @returns {String}
* @description
*/
Kriteria.prototype._createExpression = function _createExpression(condition) {
return "(" +
this._createJsExpressionOfKeyIsNotUndefined(condition.left_key) +
" && " +
(
condition.key_type === "key" ?
this._createJsExpressionOfKeyIsNotUndefined(condition.right_key[0]) + " && " :
""
) +
this._createJsExpression(condition) +
")";
};
/**
* @private
* @function
* @param {Condition}
* @returns {String}
* @description
*/
Kriteria.prototype._createJsExpression = function _createJsExpression(condition) {
var left_key = kref("$", condition.left_key.split(".")),
operator = condition.operator,
right_key = condition.right_key,
key_type = condition.key_type,
_operator = Kriteria._JS_OPERATOR[operator],
$_right_key = kref("$", right_key[0]).toString();
if(_operator) {
/* 演算子が eq, ne, lt, le, gt, ge のいずれか
[left_key] [operator] "[right_key]"
[left_key] [operator] $.[right_key]
*/
return left_key + " " + _operator + " " +
this._toStringExpressionFromValue(right_key[0], key_type);
} else if(operator === "in") {
/* in 演算子
!!~[[right_key]].indexOf([left_key])
(Array.isArray($.[right_key]) ? !!~$.[right_key].indexOf([left_key]) : $.[right_key] === [left_key])
*/
if(key_type === "value") {
return "!!~" + this._toStringExpressionFromArray(right_key) + ".indexOf(" + left_key + ")";
} else {
return "(Array.isArray(" + $_right_key + ") ? " +
"!!~" + $_right_key + ".indexOf(" + left_key + "): " +
$_right_key + " === " + left_key + ")";
}
} else if(operator === "not_in") {
/* not_in 演算子
*/
if(key_type === "value") {
return "!~" + this._toStringExpressionFromArray(right_key) + ".indexOf(" + left_key + ")";
} else {
return "(Array.isArray(" + $_right_key + ") ? " +
"!~" + $_right_key + ".indexOf(" + left_key + "): " +
$_right_key + " !== " + left_key + ")";
}
} else if(operator === "between") {
/* between 演算子
*/
return left_key + " >= " + this._toStringExpressionFromValue(right_key[0], key_type) +
" && " +
left_key + " <= " + this._toStringExpressionFromValue(right_key[1], key_type);
} else if(operator === "not_between") {
/* not_between 演算子
*/
return left_key + " < " + this._toStringExpressionFromValue(right_key[0], key_type) +
" || " +
left_key + " > " + this._toStringExpressionFromValue(right_key[1], key_type);
} else if(operator === "match") {
/* match 演算子
*/
if(right_key[0] === void 0) {
return false;
} else if(right_key[0] === null) {
return "(" + left_key + " === null ? true : false)";
} else if(right_key[0] === "") {
return "(" + left_key + " === '' ? true : false)";
} else {
//return "(" + left_key + " !== null && " + right_key[0] + ".test(" + left_key + "))";
return "(" + right_key[0] + ".test(" + left_key + "))";
}
} else if(operator === "not_match") {
/* not_match 演算子
*/
if(right_key[0] === void 0) {
return false;
} else if(right_key[0] === null) {
return "(" + left_key + " === null ? false : true)";
} else if(right_key[0] === "") {
return "(" + left_key + " === '' ? false : true)";
} else {
//return "(" + left_key + " !== null && !" + right_key[0] + ".test(" + left_key + "))";
return "(!" + right_key[0] + ".test(" + left_key + "))";
}
} else {
return null;
}
};
/**
* @private
* @function
* @param {String} key -
* @returns {String}
* @description
*/
Kriteria.prototype._createJsExpressionOfKeyIsNotUndefined =
function _createJsExpressionOfKeyIsNotUndefined(key) {
var keys = key.split("."),
work_keys = [],
ret = [];
for(var i = 0, l = keys.length; i < l; i = i + 1) {
work_keys[work_keys.length] = keys[i];
ret[ret.length] = kref("$", work_keys).toString() + " !== void 0";
}
return ret.join(" && ");
};
/**
* @private
* @function
* @param {String} key -
* @returns {String}
* @description
*/
Kriteria.prototype._createJSExpressionOfKeyIsUndefined =
function _createJSExpressionOfKeyIsUndefined(key) {
var keys = key.split("."),
work_keys = [],
ret = [];
for(var i = 0, l = keys.length; i < l; i = i + 1) {
work_keys[work_keys.length] = keys[i];
var $_work_keys = kref("$", work_keys);
ret[ret.length] = $_work_keys + " === void 0";
ret[ret.length] = $_work_keys + " === null";
}
return ret.join(" || ");
};
/**
* @private
* @function
* @param {Array} arr -
* @returns {String}
* @description
*/
Kriteria.prototype._toStringExpressionFromArray = function _toStringExpressionFromArray(arr) {
var ret = [];
for(var i = 0, l = arr.length; i < l; i = i + 1) {
ret[ret.length] = this._toStringExpressionFromValue(arr[i], "value");
}
return "[" + ret.join(", ") + "]";
};
/**
* @private
* @function
* @param {Mixed(String|Number)} value -
* @param {String} type -
* @returns {String}
* @description
*/
Kriteria.prototype._toStringExpressionFromValue =
function _toStringExpressionFromValue(value, type) {
if(type === "value" && (typeof value === "string" || value instanceof String)) {
return '"' + value + '"';
} else if(type === "key") {
return kref("$", value.split(".")).toString();
} else {
return value + '';
}
};
/**
* @public
* @function
* @param {String[]} prefixes -
* @returns {Object.<Kriteria>}
*/
Kriteria.prototype.splitByKeyPrefixes = function splitByKeyPrefixes(prefixes) {
if(!Array.isArray(prefixes) || prefixes.length === 0) {
return null;
}
var ret = {},
condition = null,
splited_criteria = null,
matchPrefixes = [],
left_key = "",
right_key = "",
key_type = "",
match1 = true,
match2 = true,
added = true,
key = "",
i = 0, l = 0,
j = 0, l2 = 0;
for(i = 0, l = prefixes.length; i < l; i = i + 1) {
ret[prefixes[i]] = new Kriteria();
}
ret.else = new Kriteria();
for(i = 0, l = this._conditionAnd.length; i < l; i = i + 1) {
condition = this._conditionAnd[i];
if(condition.criteria instanceof Kriteria) {
splited_criteria = condition.criteria.splitByKeyPrefixes(prefixes);
for(key in splited_criteria) {
if(splited_criteria[key] !== null) {
ret[key].and(splited_criteria[key]);
}
}
} else {
matchPrefixes = [];
left_key = condition.left_key;
right_key = condition.right_key[0];
key_type = condition.key_type;
added = false;
for(j = 0, l2 = prefixes.length; j < l2; j = j + 1) {
matchPrefixes[matchPrefixes.length] = prefixes[j];
match1 = matchPrefix(left_key, matchPrefixes);
if(key_type === "key") {
match2 = matchPrefix(right_key, matchPrefixes);
}
if(
(key_type === "value" && match1) ||
(key_type === "key" && match1 && match2)
) {
ret[prefixes[j]].addAnd(condition);
added = true;
break;
}
}
if(!added) {
ret.else.addAnd(condition);
}
}
}
for(i = 0, l = this._conditionOr.length; i < l; i = i + 1) {
condition = this._conditionOr[i];
if(condition.criteria instanceof Kriteria) {
splited_criteria = condition.criteria.splitByKeyPrefixes(prefixes);
for(key in splited_criteria) {
if(splited_criteria[key] !== null) {
ret[key].or(splited_criteria[key]);
}
}
} else {
matchPrefixes = [];
left_key = condition.left_key;
right_key = condition.right_key[0];
key_type = condition.key_type;
added = false;
for(j = 0, l2 = prefixes.length; j < l2; j = j + 1) {
matchPrefixes[matchPrefixes.length] = prefixes[j];
match1 = matchPrefix(left_key, matchPrefixes);
if(key_type === "key") {
match2 = matchPrefix(right_key, matchPrefixes);
}
if(
(key_type === "value" && match1) ||
(key_type === "key" && match1 && match2)
) {
ret[prefixes[j]].addOr(condition);
added = true;
break;
}
}
if(!added) {
ret.else.addOr(condition);
}
}
}
for(key in ret) {
if(ret[key].getConditionAnd().length > 0 || ret[key].getConditionOr().length > 0) {
ret[key]._not_flg = this._not_flg;
} else {
ret[key] = null;
}
}
return ret;
};
/**
* @public
* @function
* @param {Kriteria} kri -
* @param {Boolean} unique -
* @returns {Kriteria}
*/
Kriteria.prototype.merge = function merge(kri, unique) {
var new_kriteria = new Kriteria(),
kri_cond_and = kri.getConditionAnd(),
kri_cond_or = kri.getConditionOr(),
cond1 = null,
match = false,
i = 0, l = 0,
j = 0, l2 = 0;
if(this._not_flg !== kri._not_flg) {
throw new Error("Kriteria#merge - collision to not flag.");
}
for(i = 0, l = this._conditionAnd.length; i < l; i = i + 1) {
new_kriteria.addAnd(this._conditionAnd[i]);
}
for(i = 0, l = this._conditionOr.length; i < l; i = i + 1) {
new_kriteria.addOr(this._conditionOr[i]);
}
if(!unique) {
for(i = 0, l = kri_cond_and.length; i < l; i = i + 1) {
new_kriteria.addAnd(kri_cond_and[i]);
}
for(i = 0, l = kri_cond_or.length; i < l; i = i + 1) {
new_kriteria.addOr(kri_cond_or[i]);
}
} else {
for(i = 0, l = kri_cond_and.length; i < l; i = i + 1) {
cond1 = kri_cond_and[i];
match = false;
for(j = 0, l2 = this._conditionAnd.length; j < l2; j = j + 1) {
if(cond1.compareTo(this._conditionAnd[j]) === 0) {
match = true;
break;
}
}
if(!match) {
new_kriteria.addAnd(cond1);
}
}
for(i = 0, l = kri_cond_or.length; i < l; i = i + 1) {
cond1 = kri_cond_or[i];
match = false;
for(j = 0, l2 = this._conditionOr.length; j < l2; j = j + 1) {
if(cond1.compareTo(this._conditionOr[j]) === 0) {
match = true;
break;
}
}
if(!match) {
new_kriteria.addOr(cond1);
}
}
}
return new_kriteria;
};
/**
* @public
* @function
* @param {Kriteria} kri -
* @returns {Number}
* 0 - equal
* 1 - greater
* -1 - less
*/
Kriteria.prototype.compareTo = function compareTo(kri) {
var sort_func = function(a, b) {
return a.compareTo(b);
},
kri_cond_and = kri.getConditionAnd(),
kri_cond_or = kri.getConditionOr(),
cond1 = null,
cond2 = null,
compared = true,
len1 = 0, len2 = 0,
i = 0, l = 0;
this._conditionAnd.sort(sort_func);
kri_cond_and.sort(sort_func);
this._conditionOr.sort(sort_func);
kri_cond_or.sort(sort_func);
if(this._not_flg && !kri._not_flg) {
return -1;
} else if(!this._not_flg && kri._not_flg) {
return 1;
}
len1 = this._conditionAnd.length;
len2 = kri_cond_and.length;
l = len1 > len2 ? len1 : len2;
for(i = 0; i < l; i = i + 1) {
cond1 = this._conditionAnd[i];
cond2 = kri_cond_and[i];
if(!cond1) {
return -1;
} else if(!cond2) {
return 1;
}
compared = cond1.compareTo(cond2);
if(compared !== 0) {
return compared;
}
}
len1 = this._conditionOr.length;
len2 = kri_cond_or.length;
l = len1 > len2 ? len1 : len2;
for(i = 0; i < l; i = i + 1) {
cond1 = this._conditionOr[i];
cond2 = kri_cond_or[i];
if(!cond1) {
return -1;
} else if(!cond2) {
return 1;
}
compared = cond1.compareTo(cond2);
if(compared !== 0) {
return compared;
}
}
return 0;
};
/**
* @public
* @function
* @param {String[]} prefixes -
* @returns {Kriteria}
*/
Kriteria.prototype.removePrefixes = function removePrefixes(prefixes) {
var rex = null,
condition = null,
i = 0, l = 0;
if(prefixes === null || prefixes === void 0 || !Array.isArray(prefixes) || prefixes.length === 0) {
return this;
}
rex = new RegExp("^(" + prefixes.join("|") + ").");
for(i = 0, l = this._conditionAnd.length; i < l; i = i + 1) {
condition = this._conditionAnd[i];
if(condition.criteria instanceof Kriteria) {
condition.criteria.removePrefixes(prefixes);
} else {
condition.left_key = condition.left_key.replace(rex, "");
if(condition.key_type === "key") {
condition.right_key[0] = condition.right_key[0].replace(rex, "");
}
}
}
for(i = 0, l = this._conditionOr.length; i < l; i = i + 1) {
condition = this._conditionOr[i];
if(condition.criteria instanceof Kriteria) {
condition.criteria.removePrefixes(prefixes);
} else {
condition.left_key = condition.left_key.replace(rex, "");
if(condition.key_type === "key") {
condition.right_key[0] = condition.right_key[0].replace(rex, "");
}
}
}
return this;
};
cxt.Kriteria = Kriteria;
global.Kriteria = Kriteria;
}(this, (0, eval)("this").window || this));
|
import * as tslib_1 from "tslib";
import * as React from 'react';
import { css } from '@microsoft/office-ui-fabric-react-bundle';
import styles from './MobilePreviewDeviceView.module.scss';
import { DeviceOrientation, DeviceType } from '../mobilePreview/MobilePreview';
var MobilePreviewDeviceView = /** @class */ (function (_super) {
tslib_1.__extends(MobilePreviewDeviceView, _super);
function MobilePreviewDeviceView(props) {
return _super.call(this, props) || this;
}
MobilePreviewDeviceView.prototype.render = function () {
var formStyle = {
width: this.props.currentDevice.width,
height: this.props.currentDevice.height
};
var mobilePreviewClassName = css(styles.mobilePreviewDevice, this.props.deviceType === DeviceType.Tablet ? styles.mobilePreviewTablet :
this.props.currentOrientation === DeviceOrientation.Portrait ? styles.mobilePreviewPortrait :
styles.mobilePreviewLandscape);
if (this.props.deviceType === DeviceType.Phone) {
if (this.props.currentOrientation === DeviceOrientation.Landscape) {
formStyle.width = this.props.currentDevice.height;
formStyle.height = this.props.currentDevice.width;
}
}
if (this.props.deviceType === DeviceType.Tablet) {
if (this.props.currentOrientation === DeviceOrientation.Portrait) {
formStyle.width = this.props.currentDevice.height;
formStyle.height = this.props.currentDevice.width;
}
}
return (React.createElement("div", { className: mobilePreviewClassName, style: formStyle },
React.createElement("iframe", { className: styles.mobilePreviewIframe, src: this.props.url })));
};
return MobilePreviewDeviceView;
}(React.Component));
export default MobilePreviewDeviceView;
//# sourceMappingURL=MobilePreviewDeviceView.js.map |
var urllib = require("urllib");
exports.generateTempQR = generateTempQR;
exports.generateEternalQR = generateEternalQR;
exports.getQR = getQR;
exports.qrcodeURL = qrcodeURL;
exports.generateEternalQrBySceneStr = generateEternalQrBySceneStr;
// expire_seconds should less than 604800
// scene_id should be an integer
// callback(err, result)
function generateTempQR(access_token, expire_seconds, scene_id, callback){
var url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + access_token;
var opts = {
dataType: 'json',
type: 'POST',
headers: {
'Content-Type': 'application/json'
},
data: {
expire_seconds: expire_seconds,
action_name: "QR_SCENE",
action_info: {
scene: {
scene_id: scene_id
}
}
}
};
urllib.request(url, opts, function(err, body, resp){
if(err){
callback(err);
return;
}
if(body.errcode){
callback(body);
return;
}
callback(null, body);
});
}
// scene_id should be 1-100000
// callback(err, result)
function generateEternalQR(access_token, scene_id, callback){
var url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + access_token;
var opts = {
dataType: 'json',
type: 'POST',
headers: {
'Content-Type': 'application/json'
},
data: {
action_name: "QR_LIMIT_SCENE",
action_info: {
scene: {
scene_id: scene_id
}
}
}
};
urllib.request(url, opts, function(err, body, resp){
if(err){
callback(err);
return;
}
if(body.errcode){
callback(body);
return;
}
callback(null, body);
});
}
function generateEternalQrBySceneStr(access_token, scene_id, callback){
var url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + access_token;
var opts = {
dataType: 'json',
type: 'POST',
headers: {
'Content-Type': 'application/json'
},
data: {
action_name: "QR_LIMIT_STR_SCENE",
action_info: {
scene: {
scene_str: scene_id
}
}
}
};
console.log(opts);
urllib.request(url, opts, function(err, body, resp){
if(err){
callback(err);
return;
}
if(body.errcode){
callback(body);
return;
}
callback(null, body);
});
}
// callback(err, body)
function getQR(ticket, callback){
var url = qrcodeURL(ticket);
var options = {
method: "GET"
};
urllib.request(url, options, function(err, body, resp){
if(err){
callback(err);
return;
}
if(resp.status === 404){
callback({code: 404, msg: "qrcode not found"});
return;
}
callback(null, body);
});
}
// the qrcode url, could be displayed by img tag
function qrcodeURL(ticket){
return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;
} |
/* globals angular */
;(function() {
"use strict";
angular.module('WaypointServiceTest', ['ngMock', 'zumba.angular-waypoints']);
/**
* Util/Waypoint Service Test Suite
*/
describe('Waypoint Service', function() {
beforeEach(module('WaypointServiceTest'));
describe('getHandlerSync', function() {
it('returns a function', inject(function(WaypointService) {
expect(WaypointService.getHandlerSync()).toEqual(jasmine.any(Function));
}));
describe('handler function', function() {
it('will do nothing if the scope does not contain a valid property', function() {
inject(function(WaypointService, $timeout) {
var callback = jasmine.createSpy('callback');
var handler = WaypointService.getHandlerSync({}, callback);
handler('down');
$timeout.verifyNoPendingTasks();
expect(callback).not.toHaveBeenCalled();
});
});
it('executes the callback on the next tick', function() {
inject(function(WaypointService, $timeout) {
var callback = jasmine.createSpy('callback');
var handler = WaypointService.getHandlerSync({ down : 'test' }, callback);
handler('down');
$timeout.flush();
expect(callback).toHaveBeenCalledWith('test');
});
});
it('will not execute the callback imedeately', function() {
inject(function(WaypointService) {
var callback = jasmine.createSpy('callback');
var handler = WaypointService.getHandlerSync({ down : 'test' }, callback);
handler('down');
expect(callback).not.toHaveBeenCalled();
});
});
});
});
});
}());
|
// @flow
import path from 'path'
import { createFileTransformer, loadLocalFromContext } from '@pundle/api'
import manifest from '../package.json'
function createComponent({ extensions = ['.gql', '.graphql'] }: { extensions?: Array<string> } = {}) {
return createFileTransformer({
name: manifest.name,
version: manifest.version,
priority: 1500,
async callback({ file, context }) {
const extName = path.extname(file.filePath)
if (!extensions.includes(extName) || file.format !== 'js') {
return null
}
const exported = await loadLocalFromContext(context, 'graphql-tag')
const parsed = exported(typeof file.contents === 'string' ? file.contents : file.contents.toString())
return {
contents: `module.exports = ${JSON.stringify(parsed)}`,
sourceMap: {
version: 3,
sources: [file.filePath],
names: ['$'],
mappings: 'AAAAA',
},
}
},
})
}
module.exports = createComponent
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.