code
stringlengths 2
1.05M
|
---|
'use strict';
/* App Module */
var realtyApp = angular.module('realtyApp', [
'ngRoute',
'angularUtils.directives.dirPagination',
'realtyControllers',
'realtyFilters',
'realtyServices'
]);
realtyApp.config(function(paginationTemplateProvider) {
paginationTemplateProvider.setPath('/bower_components/angular-utils-pagination/dirPagination.tpl.html');
});
realtyApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/properties', {
templateUrl: 'partials/properties/list.html',
controller: 'PropertyListCtrl',
activetab: 'home'
}).
when('/properties/advertise', {
templateUrl: 'partials/properties/form.html',
controller: 'PropertyAdvertisementCtrl',
activetab: 'advertise'
}).
when('/properties/:propertyId', {
templateUrl: 'partials/properties/detail.html',
controller: 'PropertyDetailCtrl',
activetab: ''
}).
when('/properties/:propertyId/edit', {
templateUrl: 'partials/properties/form.html',
controller: 'PropertyEditCtrl',
activetab: 'edit'
}).
otherwise({
templateUrl: 'partials/properties/list.html',
controller: 'PropertyListCtrl',
activetab: 'home'
});
}
]);
'use strict';
/* Controllers */
var realtyControllers = angular.module('realtyControllers', []);
realtyControllers.controller('PropertyListCtrl', ['$scope', 'Property', 'propertyImage', 'propertyData',
function($scope, Property, propertyImage, propertyData) {
// $scope.properties = Property.query();
// console.log($scope.properties);
$scope.beds = propertyData.beds();
$scope.bathrooms = propertyData.bathrooms();
$scope.garageSpaces = propertyData.garageSpaces();
// Paginate properties
$scope.totalProperties = 0;
$scope.propertiesPerPage = 10; // this should match however many results your API puts on one page
$scope.pagination = {
current: 1
};
$scope.getResultsPage = function getResultsPage(pageNumber) {
// The following will generate :
// http://realty.dev/api/properties?page=1
Property.get({page:pageNumber}, function(result) {
$scope.properties = result.data;
$scope.totalProperties = result.total;
});
}
$scope.getResultsPage(1);
$scope.pageChanged = function(newPage) {
$scope.getResultsPage(newPage);
};
$scope.isCarSpaceAvailable = function(carSpace) {
if (carSpace != 0) {
return true;
}
return false;
}
$scope.getPropertyImage = function(photo) {
return propertyImage.jpg(photo.name);
}
$scope.clearFilters = function() {
$scope.filter = {};
}
}]);
realtyControllers.controller('PropertyDetailCtrl', ['$scope', '$routeParams', '$location', 'Page', 'Property', 'propertyImage',
function($scope, $routeParams, $location, Page, Property, propertyImage) {
$scope.property = Property.get({propertyId: $routeParams.propertyId}, function(property) {
$scope.mainImageUrl = propertyImage.jpg(property.photos[0].name);
// set page title
Page.setTitle(property.address);
});
$scope.setImage = function(image) {
$scope.mainImageUrl = propertyImage.jpg(image);
}
$scope.deleteProperty = function() {
$scope.property.$delete({propertyId: $routeParams.propertyId}, function(result) {
if (result.success) {
// redirect to home page
$location.path('/');
}
});
}
}
]);
realtyControllers.controller('PropertyAdvertisementCtrl', ['$scope', '$location', 'Page', 'Property', 'propertyData',
function($scope, $location, Page, Property, propertyData) {
Page.setTitle("List your property");
$scope.title = "List your property";
$scope.submitButtonTitle = "List property";
$scope.propertyTypes = propertyData.propertyTypes();
$scope.beds = propertyData.beds();
$scope.bathrooms = propertyData.bathrooms();
$scope.garageSpaces = propertyData.garageSpaces();
$scope.property = new Property();
// Pre-selected items
$scope.property.beds = $scope.beds[0].number;
$scope.property.bathrooms = $scope.bathrooms[0].number;
$scope.processForm = function() {
$scope.property.$save(function(result) {
if (result.success) {
// redirect to home page
$location.path('/');
}
});
}
}]);
realtyControllers.controller('PropertyEditCtrl', ['$scope', '$routeParams', '$location', 'Page', 'Property', 'propertyData',
function($scope, $routeParams, $location, Page, Property, propertyData) {
Page.setTitle("Edit your property");
$scope.title = "Edit your property";
$scope.submitButtonTitle = "Update property";
$scope.propertyTypes = propertyData.propertyTypes();
$scope.beds = propertyData.beds();
$scope.bathrooms = propertyData.bathrooms();
$scope.garageSpaces = propertyData.garageSpaces();
$scope.property = Property.get({propertyId: $routeParams.propertyId}, function (property) {
if (property.smoking_allowed == 1) {
$scope.property.smoking_allowed = true;
}
if (property.pets_allowed == 1) {
$scope.property.pets_allowed = true;
}
});
$scope.processForm = function() {
$scope.property.$update({ propertyId:$routeParams.propertyId }, function(result) {
if (result.success) {
// redirect to home page
$location.path('/');
}
});
}
}]);
realtyControllers.controller('LayoutsCtrl', ['$scope', 'Page',
function($scope, Page) {
$scope.Page = Page;
}]);
realtyControllers.controller('WidgetsCtrl', ['$scope', '$route',
function($scope, $route) {
$scope.$route = $route;
}]);
'use strict';
/* Filters */
var realtyFilters = angular.module('realtyFilters', []);
realtyFilters.filter('ucfirst', function() {
return function(input) {
if (! input) return;
return input.charAt(0).toUpperCase() + input.slice(1);
};
});
realtyFilters.filter('strLimit', ['$filter', function($filter) {
return function(input, limit) {
if (input.length <= limit) {
return input;
}
return $filter('limitTo')(input, limit) + '...';
};
}]);
realtyFilters.filter('nl2br', function($sce) {
return function(msg,is_xhtml) {
var is_xhtml = is_xhtml || true;
var breakTag = (is_xhtml) ? '<br />' : '<br>';
var msg = (msg + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
return $sce.trustAsHtml(msg);
}
});
'use strict';
/* Services */
var realtyServices = angular.module('realtyServices', ['ngResource']);
realtyServices.factory('Property', ['$resource',
function($resource) {
return $resource('/api/properties/:propertyId', {},
{
'update': { method:'PUT' }
});
}
]);
realtyServices.factory('Page', function() {
var title = 'Realty';
return {
title: function() { return title; },
setTitle: function(newTitle) {
title = newTitle + " - Realty";
}
};
});
realtyServices.service('propertyData', function() {
return {
propertyTypes: function() {
return [
{ value: 'unit', name: 'Unit' },
{ value: 'house', name: 'House' },
{ value: 'apartment', name: 'Apartment' },
];
},
beds: function() {
return [
{ value: "1", number: "1" },
{ value: "2", number: "2" },
{ value: "3", number: "3" },
{ value: "4", number: "4" },
{ value: "5", number: "5" },
{ value: "6", number: "6" },
{ value: "7", number: "7" },
{ value: "8", number: "8" },
{ value: "9", number: "9" },
{ value: "10", number: "10" }
];
},
bathrooms: function() {
return [
{ value: "1", number: "1" },
{ value: "2", number: "2" },
{ value: "3", number: "3" },
{ value: "4", number: "4" },
{ value: "5", number: "5" }
];
},
garageSpaces: function() {
return [
{ value: "1", number: "1" },
{ value: "2", number: "2" },
{ value: "3", number: "3" },
{ value: "4", number: "4" },
{ value: "5", number: "5" }
];
}
};
});
realtyServices.service('propertyImage', function() {
var dir = "images/";
return {
jpg : function(name) {
return dir + name + ".jpg";
},
png : function(name) {
return dir + name + ".png";
}
};
});
|
var assert = require('assert'),
http = require('http'),
util = require('../lib/util');
module.exports = {
'ReconnectingClient tolerates connection failures': function(beforeExit) {
// TODO: Clean this test up using the new http client and server implementation
// var PORT = 9010,
// simpleResponse = function (req, res) { res.writeHead(200); res.end(); },
// svr = http.createServer(simpleResponse),
// client = util.createReconnectingClient(PORT, 'localhost'),
// numResponses = 0,
// clientErrorsDetected = 0,
// req, testTimeout;
//
// // reconnecting client should work like a normal client and get a response from our server
// svr.listen(PORT);
// req = client.request('GET', '/');
// assert.isNotNull(req);
// req.on('response', function(res) {
// numResponses++;
// res.on('end', function() {
// // once the server is terminated, request() should cause a clientError event (below)
// svr = svr.close();
// req = client.request('GET','/');
//
// client.once('reconnect', function() {
// // restart server, and request() should work again
// svr = http.createServer(simpleResponse);
// svr.listen(PORT);
//
// req = client.request('GET','/');
// req.end();
// req.on('response', function(res) {
// clearTimeout(testTimeout);
//
// numResponses++;
// svr = svr.close();
// });
// });
// });
// });
// client.on('error', function(err) { clientErrorsDetected++; });
// req.end();
//
// // Maximum timeout for this test is 1 second
// testTimeout = setTimeout(function() { if (svr) { svr.close(); } }, 2000);
beforeExit(function() {
// assert.equal(clientErrorsDetected, 1);
// assert.equal(numResponses, 2);
});
},
};
|
'use strict';var _path;
function _load_path() {return _path = _interopRequireDefault(require('path'));}var _jestRegexUtil;
function _load_jestRegexUtil() {return _jestRegexUtil = require('jest-regex-util');}var _micromatch;
function _load_micromatch() {return _micromatch = _interopRequireDefault(require('micromatch'));}function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}
const MOCKS_PATTERN = new RegExp(
(0, (_jestRegexUtil || _load_jestRegexUtil()).escapePathForRegex)((_path || _load_path()).default.sep + '__mocks__' + (_path || _load_path()).default.sep)); /**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/const shouldInstrument = (filename, options, config) => {if (!options.collectCoverage) {
return false;
}
if (config.testRegex && filename.match(config.testRegex)) {
return false;
}
if (
config.testMatch &&
config.testMatch.length &&
(_micromatch || _load_micromatch()).default.any(filename, config.testMatch))
{
return false;
}
if (
// This configuration field contains an object in the form of:
// {'path/to/file.js': true}
options.collectCoverageOnlyFrom &&
!options.collectCoverageOnlyFrom[filename])
{
return false;
}
if (
// still cover if `only` is specified
!options.collectCoverageOnlyFrom &&
options.collectCoverageFrom &&
!(0, (_micromatch || _load_micromatch()).default)(
[(_path || _load_path()).default.relative(config.rootDir, filename)],
options.collectCoverageFrom).
length)
{
return false;
}
if (
config.coveragePathIgnorePatterns &&
config.coveragePathIgnorePatterns.some(pattern => filename.match(pattern)))
{
return false;
}
if (MOCKS_PATTERN.test(filename)) {
return false;
}
return true;
};
module.exports = shouldInstrument;
|
'use strict';
const store = new WeakMap();
module.exports = function(obj) {
if (!store.has(obj)) {
store.set(obj, {});
}
return store.get(obj);
};
|
"use strict";
var types = {
resize: function (image, options) {
return image.resize(options.width, options.height);
},
resizeAndCrop: function (image, options) {
return image.geometry(options.width, options.height, "^")
.gravity(options.gravity || "center")
.crop(options.width, options.height);
},
quality: function (image, value) {
return image.quality(value);
}
};
module.exports = function (type, options, image) {
if (!(type in types)) throw "No method " + type + " defined";
return types[type](image, options);
};
|
define({
"addTaskTip": "Lisää yksi tai useampia suodattimia pienoisohjelmaan ja määritä kunkin niistä parametrit.",
"enableMapFilter": "Poista esiasetettu karttatason suodatin kartasta.",
"newFilter": "Uusi suodatin",
"filterExpression": "Suodatinlauseke",
"layerDefaultSymbolTip": "Käytä karttatason oletussymbolia",
"uploadImage": "Lataa kuva",
"selectLayerTip": "Valitse karttataso.",
"setTitleTip": "Määritä otsikko.",
"noTasksTip": "Suodattimia ei ole määritetty. Lisää uusi suodatin valitsemalla ${newFilter}.",
"collapseFiltersTip": "Tiivistä mahdolliset suodatinlausekkeet, kun pienoisohjelma avataan",
"zoomtoTip": "Lähennä jäljellä oleviin kohteisiin, kun suodatinta on käytetty",
"groupByLayerTip": "Ryhmittele suodattimet karttatason perusteella",
"autoApplyWhenValueInput": "Käytä tätä suodatinta automaattisesti, kun arvo on syötetty",
"autoApplyWhenWidgetOpen": "Käytä tätä suodatinta, kun pienoisohjelma on avattu",
"info": "Tiedot",
"expressions": "Ehtolauseke",
"allowCustom": "Salli mukautettujen suodattimien luonti",
"filterActions": "Mukautetut suodatustoimet",
"custom": "Ota mukautetut suodattimet käyttöön",
"resetAll": "Ota Nollaa kaikki -toiminto käyttöön",
"turnOffAll": "Ota Poista kaikki käytöstä -toiminto käyttöön",
"matchMsgSetAll": "Näytä kohteet, jotka vastaavat kaikkia suodattimia",
"matchMsgSetAny": "Näytä kohteet, jotka vastaavat mitä tahansa suodatinta"
});
|
module.exports = {
input: {
_key: 'R5FvMrjo',
_type: 'block',
children: [
{
_key: 'cZUQGmh4',
_type: 'span',
marks: [],
text: 'Dat heading'
}
],
markDefs: [],
style: 'h2'
},
output: '<h2>Dat heading</h2>'
}
|
ns.HTMLElements.CTable = (function(){
var EClassNames = {
Base: 'cjw-table'
};
function fn(oData)
{
fn.Parent.call(this, oData);
this.m_html = document.createElement('TABLE');
this.m_html.cellSpacing = 0;
this.m_html.cellPadding = 0;
ns.DOM.AddClassNames(this.m_html, [
EClassNames.Base,
oData ? oData.ClassName : ''
]);
this.m_htmlColGroup = document.createElement('COLGROUP');
this.m_html.appendChild(this.m_htmlColGroup);
this.m_htmlBody = document.createElement('TBODY');
this.m_html.appendChild(this.m_htmlBody);
};
ns.Class.Derive(fn, ns.HTMLElements.CHTMLElement);
fn.prototype.AddColumns = function(asColumnWidths)
{
var nColCursor,
nColCount = asColumnWidths.length;
for(nColCursor = 0; nColCursor < nColCount; nColCursor++)
{
var sColumnWidth = asColumnWidths[nColCursor],
col = document.createElement('COL');
col.style.width = sColumnWidth;
this.m_htmlColGroup.appendChild(col);
}
};
fn.prototype.AddHTMLItems = function(aahtmlItems)
{
var nRowCursor,
nRowCount = aahtmlItems.length;
for(nRowCursor = 0; nRowCursor < nRowCount; nRowCursor++)
{
var ahtmlItems = aahtmlItems[nRowCursor],
nColCursor,
nColCount = ahtmlItems.length,
tr = document.createElement('TR');
for(nColCursor = 0; nColCursor < nColCount; nColCursor++)
{
var td = document.createElement('TD');
td.appendChild(ahtmlItems[nColCursor]);
tr.appendChild(td);
}
this.m_htmlBody.appendChild(tr);
}
};
return fn;
})();
|
// sqlite3 database test
// for now unused in this project, but left here for
// future versions.
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(':memory:');
db.serialize(function() {
db.run("CREATE TABLE lorem (info TEXT)");
var stmt = db.prepare("INSERT INTO lorem VALUES (?)");
for (var i = 0; i < 10; i++) {
stmt.run("Ipsum " + i);
}
stmt.finalize();
db.each("SELECT rowid AS id, info FROM lorem", function(err, row) {
console.log(row.id + ": " + row.info);
});
});
db.close();
|
define([], function() {
function run(group, bite) {
var content = bite.session.getValue();
if (content) {
var result = group.container.querySelector('.bite-container-result'),
resultDocument = result.contentDocument,
resultWindow = result.contentWindow,
scriptTagES6 = resultDocument.createElement('script'),
scriptTag = resultDocument.createElement('script');
scriptTagES6.src = 'lib/runners/6to5.js';
resultDocument.head.appendChild(scriptTagES6);
scriptTagES6.addEventListener('load', function() {
scriptTag.innerHTML = 'try { ' + resultWindow.to5.transform(content).code + ' }catch(e){ console.log(e.name + ": " + e.message); window.top.console.error(e) }';
resultDocument.body.appendChild(scriptTag);
});
}
}
return run;
});
|
'use strict';
const isValidHex = require('../isValidHex');
it('isValidHex', () => {
expect(isValidHex('#333')).toBeTruthy();
expect(isValidHex('#a3b')).toBeTruthy();
expect(isValidHex('#333a')).toBeTruthy();
expect(isValidHex('#333afe')).toBeTruthy();
expect(isValidHex('#333afeaa')).toBeTruthy();
expect(isValidHex('a')).toBeFalsy();
expect(isValidHex('aaa')).toBeFalsy();
expect(isValidHex('$aaa')).toBeFalsy();
expect(isValidHex('@aaa')).toBeFalsy();
expect(isValidHex('var(aaa)')).toBeFalsy();
expect(isValidHex('#z1')).toBeFalsy();
expect(isValidHex('#00000')).toBeFalsy();
expect(isValidHex('#000000000')).toBeFalsy();
expect(isValidHex('#33z')).toBeFalsy();
});
|
const webpack = require('webpack'); // eslint-disable-line import/no-unresolved
const webpackConfig = {
module: {
loaders: [{
test: /\.ts$/,
loader: 'ts-loader',
exclude: /node_modules/
}],
postLoaders: [{
test: /src\/.+\.ts$/,
exclude: /(node_modules|\.spec\.ts$)/,
loader: 'sourcemap-istanbul-instrumenter-loader?force-sourcemap=true'
}]
},
plugins: [
new webpack.SourceMapDevToolPlugin({
filename: null,
test: /\.(ts|js)($|\?)/i
})
],
resolve: {
extensions: ['', '.ts', '.js']
}
};
module.exports = config => {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha'],
// list of files / patterns to load in the browser
files: [
'test/test.spec.ts'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/test.spec.ts': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
remapIstanbulReporter: {
reports: {
html: 'coverage/html',
'text-summary': null
}
},
phantomjsLauncher: {
// Have phantomjs exit if a ResourceError is encountered (useful if karma exits without killing phantom)
exitOnResourceError: true
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['dots', 'karma-remap-istanbul'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
});
};
|
const path = require('path')
const fs = require('fs')
const webpack = require('webpack')
const { CheckerPlugin } = require('awesome-typescript-loader')
const NODE_ENV = process.env.NODE_ENV || 'development'
const sourcePath = path.join(__dirname, './src')
const env = {
'process.env.NODE_ENV': JSON.stringify(NODE_ENV)
}
const config = {
devtool: 'inline-source-map',
entry: ['./src/index.ts'],
output: {
path: __dirname,
filename: 'cockpit-download-addon.user.js',
publicPath: '/'
},
target: 'web',
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx']
},
module: {
rules: [
{ parser: { requireEnsure: false } },
{
test: /\.tsx?$/,
include: sourcePath,
loader: 'awesome-typescript-loader'
}
]
},
plugins: [
new webpack.NamedModulesPlugin(),
new webpack.DefinePlugin(env),
new CheckerPlugin()
],
stats: { colors: true },
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
},
performance: {
hints: false
}
}
if (NODE_ENV === 'production') {
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const template = require('lodash/template')
const pkg = require('./package.json')
const banner = template(fs.readFileSync('./src/banner', 'utf-8'))(pkg)
config.devtool = false
config.plugins = [
...config.plugins,
new UglifyJsPlugin({
uglifyOptions: {
ecma: 8,
compress: {
comparisons: false,
warnings: false
},
output: {
comments: false,
ascii_only: true
}
}
}),
new webpack.BannerPlugin({ banner, raw: true })
]
}
module.exports = config
|
'use strict';
var MrtBot = require('./lib/mrtbot');
var botInstance = new MrtBot({
token: '_bot_token_here',
name: 'mr.t',
dbPath: 'data/mrtbot.db',
joinChannel: '_chat_channel_here_',
cronSchedule: '0 * 0,4,8,12,16,20 * * *',
printToLog: false
});
botInstance.run();
|
#!/usr/bin/env node
/*
* node-cordova-tools
* https://github.com/CoHyper/node-cordova-tools
*
* Copyright (c) 2017 Sven Hedström-Lang
* Licensed under the MIT license.
*/
let exec = require('child_process').exec;
let fs = require('fs');
let CONFIG = require('./../lib/config');
/**
* @author Sven Hedström-Lang
*
* @requires npm install -g cordova
*/
let projectPath = CONFIG.getKey('projectPath');
let platforms = CONFIG.getKey('platforms');
let platform = 'browser';
fs.stat(`${projectPath}/platforms/${platform}`, function (err, stats) {
if (err) {
return console.warn(err);
}
if (stats && stats.isDirectory()) {
exec(
[
`cd ${projectPath}`,
`cordova run ${platform}`
].join(' && '),
CONFIG.onCallback
);
}
});
|
var m = 0;
var canvas; //for affecting position of canvas or other things
var h2;
function setup() {
h2 = createElement('h2', "This is a dynamic header!");
canvas = createCanvas(300,300);
canvas.position(0,0); //absolute positioning relative to the page, not the canvas coordinate system!
createP("My favorite color is purple!!!!");
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
createButton('button!');
}
createElement('br');
}
}
function draw() {
clear(); //set background to transparent over the DOM
// background(150,20,200);
ellipse(100,100,100,100);
h2.position(m*10,m*10);
}
function mousePressed() {
m++;
createP("I've clicked the mouse " + m + " times!");
h2.html("Hey I clicked the page, wOW");
}
//THE DOM: "document-object-model"
//basically the rendering of your HTML file and its structure,
//but unlike your HTML, it can change as you interact with the rendered page.
//creating html elements with javascript
//createCanvas() --> makes a canvas appear on the page
//createP()
//createDiv()
//createButton()
//createImg()
//and...
//createElement('tag', content);
//.html()
//.position()
//.style()
|
// Generated on 2016-09-07 using generator-angular 0.15.1
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Automatically load required Grunt tasks
require('jit-grunt')(grunt, {
useminPrepare: 'grunt-usemin',
ngtemplates: 'grunt-angular-templates',
cdnify: 'grunt-google-cdn'
});
// Configurable paths for the application
var appConfig = {
app: require('./bower.json').appPath || 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
yeoman: appConfig,
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
tasks: ['newer:jshint:all', 'newer:jscs:all'],
options: {
livereload: '<%= connect.options.livereload %>'
}
},
jsTest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['newer:jshint:test', 'newer:jscs:test', 'karma']
},
styles: {
files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'postcss']
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= yeoman.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost',
livereload: 35729
},
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect().use(
'/app/styles',
connect.static('./app/styles')
),
connect.static(appConfig.app)
];
}
}
},
test: {
options: {
port: 9001,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
dist: {
options: {
open: true,
base: '<%= yeoman.dist %>'
}
}
},
// Make sure there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: {
src: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js'
]
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/spec/{,*/}*.js']
}
},
// Make sure code styles are up to par
jscs: {
options: {
config: '.jscsrc',
verbose: true
},
all: {
src: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js'
]
},
test: {
src: ['test/spec/{,*/}*.js']
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/{,*/}*',
'!<%= yeoman.dist %>/.git{,*/}*'
]
}]
},
server: '.tmp'
},
// Add vendor prefixed styles
postcss: {
options: {
processors: [
require('autoprefixer-core')({browsers: ['last 1 version']})
]
},
server: {
options: {
map: true
},
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the app
wiredep: {
app: {
src: ['<%= yeoman.app %>/index.html'],
ignorePath: /\.\.\//
},
test: {
devDependencies: true,
src: '<%= karma.unit.configFile %>',
ignorePath: /\.\.\//,
fileTypes:{
js: {
block: /(([\s\t]*)\/{2}\s*?bower:\s*?(\S*))(\n|\r|.)*?(\/{2}\s*endbower)/gi,
detect: {
js: /'(.*\.js)'/gi
},
replace: {
js: '\'{{filePath}}\','
}
}
}
}
},
// Renames files for browser caching purposes
filerev: {
dist: {
src: [
'<%= yeoman.dist %>/scripts/{,*/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist %>/styles/fonts/*'
]
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
html: '<%= yeoman.app %>/index.html',
options: {
dest: '<%= yeoman.dist %>',
flow: {
html: {
steps: {
js: ['concat', 'uglifyjs'],
css: ['cssmin']
},
post: {}
}
}
}
},
// Performs rewrites based on filerev and the useminPrepare configuration
usemin: {
html: ['<%= yeoman.dist %>/{,*/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
js: ['<%= yeoman.dist %>/scripts/{,*/}*.js'],
options: {
assetsDirs: [
'<%= yeoman.dist %>',
'<%= yeoman.dist %>/images',
'<%= yeoman.dist %>/styles'
],
patterns: {
js: [[/(images\/[^''""]*\.(png|jpg|jpeg|gif|webp|svg))/g, 'Replacing references to images']]
}
}
},
// The following *-min tasks will produce minified files in the dist folder
// By default, your `index.html`'s <!-- Usemin block --> will take care of
// minification. These next options are pre-configured if you do not wish
// to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= yeoman.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= yeoman.dist %>/scripts/scripts.js': [
// '<%= yeoman.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseWhitespace: true,
conservativeCollapse: true,
collapseBooleanAttributes: true,
removeCommentsFromCDATA: true
},
files: [{
expand: true,
cwd: '<%= yeoman.dist %>',
src: ['*.html'],
dest: '<%= yeoman.dist %>'
}]
}
},
ngtemplates: {
dist: {
options: {
module: 'angularZadanieApp',
htmlmin: '<%= htmlmin.dist.options %>',
usemin: 'scripts/scripts.js'
},
cwd: '<%= yeoman.app %>',
src: 'views/{,*/}*.html',
dest: '.tmp/templateCache.js'
}
},
// ng-annotate tries to make the code safe for minification automatically
// by using the Angular long form for dependency injection.
ngAnnotate: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat/scripts',
src: '*.js',
dest: '.tmp/concat/scripts'
}]
}
},
// Replace Google CDN references
cdnify: {
dist: {
html: ['<%= yeoman.dist %>/*.html']
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,png,txt}',
'*.html',
'images/{,*/}*.{webp}',
'styles/fonts/{,*/}*.*'
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/images',
src: ['generated/*']
}, {
expand: true,
cwd: 'bower_components/bootstrap/dist',
src: 'fonts/*',
dest: '<%= yeoman.dist %>'
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Run some tasks in parallel to speed up the build process
concurrent: {
server: [
'copy:styles'
],
test: [
'copy:styles'
],
dist: [
'copy:styles',
'imagemin',
'svgmin'
]
},
// Test settings
karma: {
unit: {
configFile: 'test/karma.conf.js',
singleRun: true
}
}
});
grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'postcss:server',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run(['serve:' + target]);
});
grunt.registerTask('test', [
'clean:server',
'wiredep',
'concurrent:test',
'postcss',
'connect:test',
'karma'
]);
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'postcss',
'ngtemplates',
'concat',
'ngAnnotate',
'copy:dist',
'cdnify',
'cssmin',
'uglify',
'filerev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:jshint',
'newer:jscs',
'test',
'build'
]);
};
|
/*
DO NOT USE OR REFERENCE THIS FILE!!! Switch back to 1130g
THIS was an attempt to add a json global vars for special handlers, like price and inventory. BUT these cases are going to be so unique per user that it makes more sense to handle it on a case-by-case basis in their layout and not bloat this js file unnecessarily.
Change Log
2010-02-16 big adds
- added support for JSON_actions, which included inventory checks.
2009-11-30
- added basic support for 'flags' !!!!!!!!!!!!!! need to upgrade this from boolean to bitwise in handlePogPrice() function
- updated text inputs so maxlength wouldn't be set in form unless set on option (setting to blank caused browser to default to maxlength = 0)
- updated validation script so type='attribs' would not be validated. better handling of forms with blank value.
- better handling of blank values for text inputs (IE was showing as 'undefined' - literally).
2009-11-18 - changed price display so it used a function. That'll make it easier for later updates. handlePogPrice();
2009-11-17 - added missing $ to price modifiers.
2009-10-14 - new json saves as 10-15. changed var pogErrors to JSONpogErrors in validate function.
2009-10-14 - IE wasn't supporting maxlength on text inputs. JS function added.
2009-10-14 - added change log. :)
2009-10-04 - Updated to max placement of pogs more flexible. 2 divs now required:
JSONPogDisplay - will update this div with the pog content.
JSONpogErrors - will update this div with errors for pog validation
##### Things to know about sogs:
sku = product id + inventory-able options
stid = product id + sku + non inventoriable options
there can be only three! 3 inventory able options per product.
price modifiers/setters are handled in order, so if sog 1-3 modify, but sog 4 sets, sog 4 wins.
all non-text entry options can be set up as inventory-able
##### Where I left off on 02/16
price modifiers work on select lists. Radio buttons, text entry, etc are a whole can of worms. ouch.
latency - this shouldn't be too hard to build in EXCEPT that the select list onChange for both latency and price is going to be a pain.
not sure how to do it. Started with the assoc_array_sum so I could determine how many JSON_action features are enabled and perhaps compile the list of functions into a var and then run an eval on it. suicide? Perhaps only one action is allows? hhmmm..
maybe there's a 'perform_action' function and IT looks at what other functions need to be performed.
function perform_action(any,var,needed,for,functions) {
if(JSON_action[0]['price_update'] == 1)
price_update();
if(JSON_action[0]['latency_display'] == 1)
latency_display();
}
that might work...
COuld even name the perform_SELECT_actions and perform_TEXTBOX_actions. a little more versatile or a lot more code? something to think about.
*/
/*
JSON_actions object.
var JSON_actions = [{"check_inventory":"1","price_update":"1","latency_display"}];
The key/value pairs in the actions array determine if extra 'steps' should occur anywhere in the sog handlers
check_inventory = boolean. defaults to 0. If set to 1, it will do an inventory check against the SKU to see if inventory is available.
-> this check occurs AFTER all the error handling for sogs selection has occured. All sogs must be set for a STID to be generated.
price_update = boolean. defaults to false. If set to true, the price div will update as price-modifying options are added/removed.
-> make sure div with id JSONPogDisplay is present and base_price var is set.
-> currently works only on select lists
latency_display = will display the sog-specific shipping latency if enabled.
-> will be displayed under the sog, once a selection is made.
-> works ONLY if there is a single inventory-able option on a given product.
-> currently works on select lists only
*/
//default all the actions to OFF
if(!JSON_actions[0]['inventory_check'])
JSON_actions[0]['inventory_check'] == 0;
if(!JSON_actions[0]['price_update'])
JSON_actions[0]['price_update'] == 0;
if(!JSON_actions[0]['latency_display'])
JSON_actions[0]['latency_display'] == 0
//used to sum up the values of an associative array.
//specifically, this is used to determine how many JSON_actions are enabled
function assoc_array_sum(A) {
sum = 0
for (key in A)
sum += A[key];
return sum;
}
/*
a function to update a div with the price in it.
-> needs to 'know' if a sog has already been selected (ie a change is occuring) and take into account what modified value, if any, was already applied to sog_price and handle this accordingly.
-> requires sog_price var to be set from start.
-> needs to take into account whether the options is a set price or modify price.
NOTE - currently, this only works on SELECT options
*/
function price_update(sogid,sogvalue,sogArray) {
//P is used to sum up the prices/modifiers
P = 0;
//obtain the price modifier from the json array.
for(i = 0; i < sogArray['options'].length; i++) {
if(sogArray['options'][i]['v'] == sogvalue) {
sog_price[sogid] = (sogArray['options'][i]['p'] == undefined) ? "0.00" : sogArray['options'][i]['p'];
}
}
//loop through sog_price array and sum up modifiers/setters.
for(key in sog_price) {
if(sog_price[key][0] == '+')
P = Number(sog_price[key].substr(1)) + P;
else if(sog_price[key][0] == '-')
P = Number(sog_price[key].substr(1)) - P;
else if(sog_price[key][0] == '$')
P = Number(sog_price[key].substr(1)); //sets the price to this pogs value.
}
P = Number(base_price)+P;
$('JSONprice').innerHTML = '$'+P.toFixed(2); //sets two decimals after the number.
}
/*
A very simple validation script for making sure that 'non-optional' options have a value.
a div with the id 'pogErrors' must be present in the layout for this to work properly.
*/
function validate_pogs (){
valid = true;
var inventoryPrompts = ''; //used to store the prompts for inventory-able skus (used in error handling)
var focusSku = $('product_id').value; //gets used in a json pointer for inventory checking.
var thisSTID = focusSku; //the option id/values get added to this to compile the STID
$('JSONpogErrors').innerHTML = "";
//if the pog var is set, loop through it and validate.
if(MYADD2CART_pogs) {
for(i = 0; i < MYADD2CART_pogs.length; i++) {
pogid = MYADD2CART_pogs[i]['id']; //the id is used multiple times so a var is created to reduce number of lookups needed.
//for attribs (finders) set the value to something so the if statement for displaying the error doesn't barf
if(MYADD2CART_pogs[i]['type'] == 'attribs') {
pogValue = "0";
}
//The value of a radio button is obtained slightly differently than any other form input type.
else if(MYADD2CART_pogs[i]['type'] == 'radio' || MYADD2CART_pogs[i]['type'] == 'imggrid') {
pogValue = $$('input:checked[type="radio"][name="pog_"+pogid]').pluck('value'); //prototype method for getting radio button value
// alert(MYADD2CART_pogs[i]['optional']+" and pogvalue = "+pogValue);
}
else {
//was orinally just setting pogvalue to the form value, but if .value is blank, a js error was geing generated sometimes.
pogValue = (document.addToCartFrm['pog_'+pogid].value == "") ? "" : document.addToCartFrm['pog_'+pogid].value;
// alert(pogid+" = "+pogValue);
}
//compose the STID
if(MYADD2CART_pogs[i]['inv'] == 1) {
thisSTID += ':'+pogid+pogValue;
inventoryPrompts += MYADD2CART_pogs[i]['prompt'];
}
//If the option IS required (not set to optional) AND the option value is blank, AND the option type is not attribs (finder) record an error
if(MYADD2CART_pogs[i]['optional'] != 1 && pogValue == "" && MYADD2CART_pogs[i]['type'] != 'attribs') {
valid = false;
$('JSONpogErrors').innerHTML += "The choice for '"+MYADD2CART_pogs[i]['prompt']+"' is required. Please make a selection <!-- id: "+pogid+" --><br>";
}
}
}
//if all options are selected AND checkinventory is on, do inventory check.
if(valid == true && JSON_actions[0]["check_inventory"] >= 1) {
if(MYADD2CART_sku[thisSTID]['inv'] == 0) {
$('JSONpogErrors').innerHTML = "We're sorry, but the combination of selections you've made is not available. Try changing the "+inventoryPrompts;
valid = false;
}
//the else is here for during testing. when valid = false is uncommented, so should this alert so we can easily determine when a successful submit occurs.
else {
// alert('inventory available! form would submit.');
}
}
// valid = false; //here for testing (to keep the form from submitting)
return valid;
}
//Used to limit the number of characters in an input or textarea. IE doesn't support MAXLENGTH.
function textCounter(field, maxlimit) {
if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
}
//used to load a script IF that script hasn't already been loaded. Uses the id attribute of a script tag to determine if the script has already been loaded.
function loadScript(url,scriptTagId) {
if(!$(scriptTagId)) {
var e = document.createElement("script");
e.src = url;
e.id = scriptTagId;
e.type="text/javascript";
document.getElementsByTagName("head")[0].appendChild(e);
// alert("loaded "+url);
}
}
//there's a lot of logic with how price should be displayed. This is a dumbed down version but here for future compatibility.
function handlePogPrice(P,flags) {
//no price is displayed if the price bitwise is set to 1 - !!!!!!!!!!!!!!!!!!! UPGRADE THIS TO SUPPORT BITWISE
if(flags >= 1 || P == undefined || P == "") {
price = "";
}
//Puts the + sign, if present, in the correct spot
else if(P.charAt(0) == '+') {
price = " +$"+P.substr(1);
}
//Puts the - sign, if present, in the correct spot
else if (P.charAt(0) == "-")
price = " -$"+P.substr(1);
//If a $ is already present, do not add one.
else if (P.charAt(0) == "$")
price = " "+P;
else
price = " $"+P;
return price;
}
// Function for creating radio button input
function createRadio(pogid,pogvalue) {
/*
IE once again blows. you can use a createElement for radio buttons, but it won't be selectable. Why would we want it selectable anyway?
*/
try {
radioInput = document.createElement('<input name="pog_'+pogid+'" type="radio" />');
}
catch(err){
radioInput = document.createElement('input');
}
// the place I got this script didn't specifically state why the name is duplicated outside the 'catch' above, but I think it's for Opera support
radioInput.setAttribute('type','radio');
radioInput.setAttribute('name',"pog_"+pogid);
radioInput.className = "zform_radio";
radioInput.setAttribute("value", pogvalue);
radioInput.setAttribute("id","pog_id_"+pogid+"_value_"+pogvalue);
return radioInput;
}
//if the group hint (ghint) is present, add a ? to the end of the option and then put a hidden div below the option for display when the ? is clicked.
function gHintQmark(pogid,pogHint) {
var ghintQMarkSpan = document.createElement("span");
with(ghintQMarkSpan) {
innerHTML = " <a href='#div_"+pogid+"' onclick='$(\"ghint_"+pogid+"\").toggle(); return false;' class='ghint_qmark'><strong>?<\/strong><\/a> ";
}
$("div_"+pogid).appendChild(ghintQMarkSpan);
var ghintDiv = document.createElement("div");
with(ghintDiv) {
setAttribute("id",'ghint_'+pogid);
className = "zhint";
style.display="none"; // IE sucks and doesn't support style for setAttribute.
innerHTML = pogHint;
}
$("div_"+pogid).appendChild(ghintDiv);
}
//image functions
//This function will generate an image url. no src or anything else, just the url.
function zoovyImageUrl(IMGID,W,H,B) { //if you have to ask JT what these parameters are, you have no business being here.
return(image_base_url+"/W"+W+"-H"+H+"-B"+B+"/"+IMGID); // need to add support for M and P?
}
/*
used with image select lists to change out the image for the selected index.
In the standard image select, it uses the id attribute of the select list to store the image filename.
In some cases, a different file name may be needed, so the IMAGENAME var can be passed to handle this (needed if biglist is customized for image support).
*/
function updateThumb(POGID,W,H,IMAGENAME) {
var imgID = '';
//if IMAGENAME is set, use that for the image file name. If not, retrieve image filename from the id of the option itself
if(IMAGENAME)
imgID = IMAGENAME.toLowerCase();
else {
var select_list_field = $('pog_'+POGID);
imgID = select_list_field.options[select_list_field.selectedIndex].id;
}
// alert(imgID);
$('imgSelect_'+POGID+'_img' ).innerHTML = "<a href='#' onClick='zoom(""+zoovyImageUrl(imgID,'','','FFFFFF')+";")'><img src='"+zoovyImageUrl(imgID,W,H,'FFFFFF')+"' height='"+H+"' width='"+W+"' alt='' border='0'></a>";
}
function zoom (url) {
z = window.open('','zoom_popUp','status=0,directories=0,toolbar=0,menubar=0,resizable=1,scrollbars=1,location=0');
z.document.write('<html>\n<head>\n<title>Picture Zoom</title>\n</head>\n<body>\n<div align="center">\n<img src="' + url + '"><br>\n<form><input type="button" value="Close Window" onClick="self.close(true)"></form>\n</div>\n</body>\n</html>\n');
z.document.close();
z.focus(true);
}
// ###################### JSON class
// NOTES - make sure you don't have a comma after the last class function or it breaks IE.
var ZoovyPOGs = Class.create({
addHandler: function(key,value,f) {
// adds a new entry to the this.handlers e.g.:
this.handlers[ key+"." + value ] = f;
},
initialize: function(pogs) {
this.pogs = pogs;
this.handlers = {};
this.addHandler("type","text","renderOptionTEXT");
this.addHandler("type","radio","renderOptionRADIO");
this.addHandler("type","select","renderOptionSELECT");
this.addHandler("type","imgselect","renderOptionIMGSELECT");
this.addHandler("type","number","renderOptionNUMBER");
this.addHandler("type","cb","renderOptionCB");
this.addHandler("type","attribs","renderOptionATTRIBS");
this.addHandler("type","readonly","renderOptionREADONLY");
this.addHandler("type","hidden","renderOptionHIDDEN");
this.addHandler("type","assembly","renderOptionHIDDEN");
this.addHandler("type","textarea","renderOptionTEXTAREA");
this.addHandler("type","imggrid","renderOptionIMGGRID");
this.addHandler("type","calendar","renderOptionCALENDAR");
this.addHandler("type","biglist","renderOptionBIGLIST");
this.addHandler("unknown","","renderOptionUNKNOWN");
},
listOptionIDs: function() {
// return an array of option id's
var r = Array();
for ( var i=0, len=this.pogs.length; i<len; ++i ) {
r.push(this.pogs[i].id);
}
return(r);
},
getOptionByID: function(id) {
// returns the structure of a specific option group.
var r = null;
for ( var i=0, len=this.pogs.length; i<len; ++i ) {
if (this.pogs[i].id == id) {
r = this.pogs[i];
}
}
return(r);
},
renderOptionSELECT: function(pog) {
var pogid = pog.id;
var selectList = document.createElement("select");
with(selectList) {
setAttribute("id", "pog_"+pogid);
setAttribute("name", "pog_"+pogid);
className = "zform_select"; // IE friendly way to set class
}
var i = 0;
var len = pog.options.length;
//if the option is 'optional' AND has more than one option, add blank prompt. If required, add a please choose prompt first.
if(len > 0) {
selOption = document.createElement("option");
selOption.innerHTML = (pog['optional'] == 1) ? "" : "Please choose (required)";
// sets the required option as disabled. must then set it as selected AFTER disabling it (otherwise it auto-selects the first option)
with(selOption) {
setAttribute('value', "");
setAttribute('disabled', true);
setAttribute('selected', true);
}
selectList.appendChild(selOption);
}
//adds options to the select list.
while (i < len) {
selOption = document.createElement("option");
selOption.setAttribute("value", pog['options'][i]['v']);
selOption.innerHTML = pog['options'][i]['prompt'];
if(pog['options'][i]['p'])
selOption.innerHTML += handlePogPrice(pog['options'][i]['p'],pog.flags); //' '+pog['options'][i]['p'][0]+'$'+pog['options'][i]['p'].substr(1);
selectList.appendChild(selOption);
i++;
}
//if price_update is enabled, add a function to modify the displayed price based on the option price modifier.
if(JSON_actions[0]['price_update'] == 1)
selectList.onchange= function(){price_update(pogid,this.value,pogs.getOptionByID(pogid));};
//if update latency is enabled, update latency onchange. currently, only one JSON_action is supported.
$("div_"+pogid).appendChild(selectList);
// $("div_"+pogid).innerHTML += "<div class='zhint'>usually ships in X days</div>";
//output ? with hint in hidden div IF ghint is set
if(pog['ghint'])
gHintQmark(pogid,pog['ghint']);
},
renderOptionBIGLIST: function(pog) {
//loadscript adds an id to the script tag when it loads the js. If that id exists, then the script is loaded and doesn't need to be loaded again.
//this isn't working in chrome, IE or safari.
// if(!$('bigListScript'))
// loadScript('%GRAPHICS_URL%/DynamicOptionList-20090819.js','bigListScript');
var pogid = pog.id;
// this select list isn't used for the pog value. it's here purely for usability. it contains the 'first' set of choices.
/* var selectListSkip = document.createElement("select");
with(selectListSkip) {
setAttribute("id", "pog_"+pogid+"skip");
setAttribute("name", "pog_"+pogid+"skip");
className = 'zform_select';
// setAttribute("class", "zform_select zform_biglist zform_biglist0");
}
*/
// this is the select list that will contain the 'second' set of choices. It is the one that is actually used on POST.
selectListSkip = "<select id='pog_"+pogid+"skip' name='pog_"+pogid+"skip' class='zform_select zform_biglist zform_biglist1' style='margin-right:5px;'></select>";
var selectList = document.createElement("select");
with(selectList) {
setAttribute("id", "pog_"+pogid);
setAttribute("name", "pog_"+pogid);
className = "zform_select";
// setAttribute("class", "zform_select zform_biglist zform_biglist2");
}
/*
the two select lists get added to the dom prior to the options getting inserted into them because:
as we loop through the array, the options are added each time.
An id is assigned to the options in the first/skip select list.
The Id's are used to see if the option already exists so that the same option isn't created twice.
note - moving the appendChilds to the bottom doesn't fix the IE issue.
*/
parentDiv = $("div_"+pogid);
with(parentDiv) {
innerHTML += selectListSkip;
}
$("div_"+pogid).appendChild(selectList);
//output ? with hint in hidden div IF ghint is set
if(pog['ghint'])
gHintQmark(pogid,pog['ghint']);
// 'i' was blowing chunks, so inc is used to increment through the loop.
var inc = 0;
var len = pog.options.length;
// !!!!!!!!! this is part of the dual-level function. don't know it well.
// originally (default) pog_biglist was pog_AQ (where AQ = SOG id) but since we in a class, no need to make the var pog specific... right???
var pog_biglist = new DynamicOptionList();
pog_biglist.addDependentFields("pog_"+pogid+"skip","pog_"+pogid);
//pog_biglist[pogid].selectFirstOption = false;
//adds options to the select list. the prompt is stored as "list1prompt|list2prompt". selValues 0 and 1 equate to list1prompt and list2prompt, respectively.
while (inc < len) {
selValues = pog['options'][inc]['prompt'].split('|');
/*
defaultList is used to build the displayed 'second' list when the options initially load.
That list is based upon all the items in the array where selValue0 (or first prompt) is equal to defaultList, which is set to the first selValue0 of the array.
A variable was created for this instead of doing an indexOf or another split because it seemed like it would be faster.
*/
if(inc < 1) {
defaultList = selValues[0];
}
//builds the 'first' list of options. id is used to see if focus option has already been created so that each first option (first|second) is only added once
if(!$('biglist_'+pogid+selValues[0])) {
selOption = document.createElement("option");
selOption.setAttribute("value", selValues[0]);
selOption.setAttribute("id", 'biglist_'+pogid+selValues[0]);
selOption.innerHTML = selValues[0];
$('pog_'+pogid+'skip').appendChild(selOption);
}
//put together the default list of choices for the 'second' list.
/* if(defaultList == selValues[0]) {
selOptions = document.createElement("option");
selOptions.setAttribute("value", pog['options'][inc]['v']);
selOptions.setAttribute("id", pog['options'][inc]['v']);
selOptions.innerHTML = selValues[1];
selectList.appendChild(selOptions);
}
*/
//this is something to for the DynamicOptionList. I think it's in chinese.
pog_biglist.forValue(selValues[0]).addOptionsTextValue(selValues[1],pog['options'][inc]['v']);
inc++; // keep inc outside that if statement or you'll blow everything to shiat.
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1 add ghint code here...
// this initializes the dynamic select menu
initDynamicOptionLists();
},
renderOptionIMGSELECT: function(pog) {
var pogid = pog.id;
var selectList = document.createElement("select");
with(selectList) {
setAttribute("id", "pog_"+pogid);
setAttribute("name", "pog_"+pogid);
className = "zform_select";
}
// selectList.setAttribute("onchange","updateThumb('"+pogid+"','"+pog.width+"','"+pog.height+"');");
selectList.onchange= function(){updateThumb(pogid,pog.width,pog.height);};
var i = 0;
var len = pog.options.length;
//if the option is 'optional' AND has more than one option, add blank prompt. If required, add a please choose prompt first.
if(len > 0) {
selOption = document.createElement("option");
selOption.innerHTML = (pog['optional'] == 1) ? "" : "Please choose (required)";
// sets the required option as disabled. must then set it as selected AFTER disabling it (otherwise it auto-selects the first option)
with(selOption) {
setAttribute('value', "");
setAttribute('disabled', true);
setAttribute('selected', true);
}
selectList.appendChild(selOption);
}
//adds options to the select list.
while (i < len) {
selOption = document.createElement("option");
selOption.setAttribute("value", pog['options'][i]['v']);
selOption.innerHTML = pog['options'][i]['prompt'];
selOption.setAttribute("id", pog['options'][i]['img']);
if(pog['options'][i]['p'])
selOption.innerHTML += handlePogPrice(pog['options'][i]['p'],pog.flags);
selectList.appendChild(selOption);
i++;
}
$("div_"+pogid).appendChild(selectList);
//output ? with hint in hidden div IF ghint is set
if(pog['ghint'])
gHintQmark(pogid,pog['ghint']);
imageDiv = document.createElement('div');
with(imageDiv) {
id = "imgSelect_"+pogid+"_img";
className = 'imageselect_image';
innerHTML += "<img src='"+zoovyImageUrl('blank.gif',pog.width,pog.height,'FFFFFF')+"' alt='' border='0' height='"+pog.height+"' width='"+pog.width+"' name='selectImg_"+pogid+"' id='selectImg_"+pogid+"'>";
}
$("div_"+pogid).appendChild(imageDiv);
},
renderOptionRADIO: function(pog) {
var pogid = pog.id;
//display ? with hint in hidden div IF ghint is set
if(pog['ghint'])
gHintQmark(pogid,pog['ghint']);
var radioInput; //used to create the radio button element.
var radioLabel; //used to create the radio button label.
var i = 0;
var len = pog['options'].length;
while (i < len) {
$("div_"+pogid).innerHTML += "<div class='zform_radio_input'>";
//creates the radio input and assigns attributes
$("div_"+pogid).appendChild(createRadio(pogid,pog['options'][i]['v'])); //add radio button to dom.
radioLabel = document.createElement('label');
with(radioLabel) {
className = "zhint";
setAttribute("for", "pog_id_"+pogid+"_value_"+pog['options'][i]['v']);
setAttribute("title", (pog['options'][i]['html']) ? pog['options'][i]['html'] : pog['options'][i]['prompt']);
}
radioLabel.appendChild(document.createTextNode(pog['options'][i]['prompt'])); // puts the prompt between the label tags.
// puts the price, if set, after the prompt.
//the price gets passed as +5.00 or -5.00 but needs to be displayed at +$5.00 or -$5.00, hence then [0] and substr crap below.
if(pog['options'][i]['p'])
radioLabel.appendChild(document.createTextNode(handlePogPrice(pog['options'][i]['p'],pog.flags)));
$("div_"+pogid).appendChild(radioLabel); //add label to dom.
$("div_"+pogid).innerHTML += "<\/div>";
i++
}
},
renderOptionCB: function(pog) {
var pogid = pog.id;
var cb = document.createElement('input');
with(cb) {
setAttribute("type","checkbox");
setAttribute("id", "pog_"+pogid);
setAttribute("value", "ON");
setAttribute("name", "pog_"+pogid);
className = "zform_checkbox";
}
$("div_"+pogid).appendChild(cb);
/*
Creates the 'hidden input' form field in the DOM which is used to let the cart know that the
checkbox element was present and it's absense in the form post means it wasn't checked.
*/
var hidden = document.createElement("input");
with(hidden) {
setAttribute("id", "pog_"+pogid+"_cb");
setAttribute("value", "1");
setAttribute("name", "pog_"+pogid+"_cb");
setAttribute("type", "hidden");
}
$("div_"+pogid).appendChild(hidden);
},
renderOptionHIDDEN: function(pog) {
var pogid = pog.id;
//hidden attributes don't need a label.
$("pog_"+pogid+"_id").style.display = 'none';
//Creates the 'hidden input' form field in the DOM.
var textbox = document.createElement("input");
with(textbox) {
setAttribute("id", "pog_"+pogid);
//cant set the value to null in IE because it will literally write out 'undefined'. this statement should handle undefined, defined and blank just fine.
if(pog['default'])
defaultValue = (pog['default'] == "") ? "" : pog['default'];
else
defaultValue = "";
setAttribute("value",defaultValue);
setAttribute("name", "pog_"+pogid);
setAttribute("type", "hidden");
//can't set maxlength attribute if there is no value (browser treats blank as 0)
if(pog['maxlength'])
setAttribute("maxlength", pog['maxlength']);
}
//make input a new child of the div with the label. should this be a child of the label? I don't think so....
$("div_"+pogid).appendChild(textbox);
},
renderOptionATTRIBS: function(pog) {
//attributes are used with finders. They don't do anything and they don't require a form element in the add to cart.. BUT we may want to do something merchant specific, so here it is.... to overide...
$("div_"+pog.id).style.display = 'none';
},
renderOptionTEXT: function(pog) {
var pogid = pog.id;
//Creates the 'text input' form field in the DOM.
var textbox = document.createElement("input");
with(textbox) {
setAttribute("id", "pog_"+pogid);
//cant set the value to null in IE because it will literally write out 'undefined'. this statement should handle undefined, defined and blank just fine.
if(pog['default'])
defaultValue = (pog['default'] == "") ? "" : pog['default'];
else
defaultValue = "";
setAttribute("value",defaultValue);
setAttribute("name", "pog_"+pogid);
className = "zform_textbox";
setAttribute("type", "text");
}
//can't set maxlength attribute if there is no value (browser treats blank as 0)
// maxlength doesn't work in IE... so there's a js function added to each onkeypress
if(pog['maxlength']) {
textbox.maxlength = pog['maxlength'];
textbox.onkeyup = function(){textCounter(this,pog['maxlength']);};
textbox.onkeydown = function(){textCounter(this,pog['maxlength']);};
}
//make input a new child of the div with the label. should this be a child of the label? I don't think so....
$("div_"+pogid).appendChild(textbox);
//output ? with hint in hidden div IF ghint is set
if(pog['ghint'])
gHintQmark(pogid,pog['ghint']);
},
renderOptionCALENDAR: function(pog) {
//load the calendar script, if it hasn't already been loaded.
loadScript(graphics_url+'/calendarPopup-20090812.js','calendarScript');
var pogid = pog.id;
var pogid = pog.id;
//Creates the 'text input' form field in the DOM.
var textbox = document.createElement("input");
with(textbox) {
setAttribute("id", "pog_"+pogid);
//cant set the value to null in IE because it will literally write out 'undefined'. this statement should handle undefined, defined and blank just fine.
if(pog['default'])
defaultValue = (pog['default'] == "") ? "" : pog['default'];
else
defaultValue = "";
setAttribute("name", "pog_"+pogid);
className = "zform_textbox";
setAttribute("type", "text");
}
//can't set maxlength attribute if there is no value (browser treats blank as 0)
// maxlength doesn't work in IE... so there's a js function added to each onkeypress
if(pog['maxlength']) {
textbox.maxlength = pog['maxlength'];
textbox.onkeyup = function(){textCounter(this,pog['maxlength']);};
textbox.onkeydown = function(){textCounter(this,pog['maxlength']);};
}
//make input a new child of the div with the label. should this be a child of the label? I don't think so....
$("div_"+pogid).appendChild(textbox);
var calendarLink = document.createElement("div");
with(calendarLink) {
style.display = 'inline';
innerHTML = " <a href='#' name='pog"+pogid+"AnCh0R' id='pog"+pogid+"AnCh0R' onclick=\"var pog"+pogid+" = new CalendarPopup(); pog"+pogid+".select($('pog_"+pogid+"'),'pog"+pogid+"AnCh0R','MM/dd/yyyy'); return false;\">Calendar</a>";
}
$("div_"+pogid).appendChild(calendarLink);
//output ? with hint in hidden div IF ghint is set
if(pog['ghint'])
gHintQmark(pogid,pog['ghint']);
//if the rush prompt is set, display it under the form.
if(pog.rush_prompt) {
var rush_promptDiv = document.createElement("div");
with(rush_promptDiv) {
setAttribute("id",'rush_prompt_'+pogid);
className = "zhint";
}
rush_promptDiv.innerHTML = pog['rush_prompt'];
$("div_"+pogid).appendChild(rush_promptDiv);
}
},
renderOptionNUMBER: function(pog) {
var pogid = pog.id;
//Creates the 'text input' form field in the DOM.
var textbox = document.createElement("input");
with(textbox) {
setAttribute("id", "pog_"+pogid);
//cant set the value to null in IE because it will literally write out 'undefined'. this statement should handle undefined, defined and blank just fine.
if(pog['default'])
defaultValue = (pog['default'] == "") ? "" : pog['default'];
else
defaultValue = "";
setAttribute("name", "pog_"+pogid);
className = "zform_textbox";
setAttribute("type", "text");
}
//can't set maxlength attribute if there is no value (browser treats blank as 0)
// maxlength doesn't work in IE... so there's a js function added to each onkeypress
if(pog['maxlength']) {
textbox.maxlength = pog['maxlength'];
textbox.onkeyup = function(){textCounter(this,pog['maxlength']);};
textbox.onkeydown = function(){textCounter(this,pog['maxlength']);};
}
//make input a new child of the div with the label. should this be a child of the label? I don't think so....
$("div_"+pogid).appendChild(textbox);
},
renderOptionTEXTAREA: function(pog) {
var pogid = pog.id;
//output ? with hint in hidden div IF ghint is set
if(pog['ghint'])
gHintQmark(pogid,pog['ghint']);
var textarea = document.createElement('textarea');
with(textarea) {
setAttribute("id", "pog_"+pogid);
setAttribute("name", "pog_"+pogid);
className = "zform_textarea";
setAttribute("cols",pog['cols']);
setAttribute("rows",pog['rows']);
style.display = 'block';
// setAttribute("wrap","PHYSICAL");
// setAttribute('ondblclick',foo);
}
$("div_"+pogid).appendChild(textarea);
},
renderOptionREADONLY: function(pog) {
var pogid = pog.id;
$("div_"+pogid).innerHTML += "<span class='zsmall'>"+pog['default']+"<\/span>";
},
renderOptionIMGGRID: function(pog) {
var pogid = pog.id;
//display ? with hint in hidden div IF ghint is set
if(pog['ghint'])
gHintQmark(pogid,pog['ghint']);
var pogcols = pog.cols; //number of columns. user defined, defaults to 8 in json.
myTable = document.createElement("table");
with(myTable) {
setAttribute("id","imggrid_table_"+pogid);
// className = "ztable_row_head";
}
myTableBody = document.createElement("tbody");
myTableBody.setAttribute("id","imggrid_tbody_"+pogid);
myTable.appendChild(myTableBody);
// Need to know how many rows are present for the first 'for' loop, which creates the rows.
// if there are more columns alloted than options, default to 1.
var totalRows = (pog['options']['length'] < pogcols) ? 1: pog.options.length / pogcols;
// Need to know how many total columns are present for the second 'for' loop, which creates each td (with image, label, radio, etc).
var totalCols = (pog['options']['length'] < pogcols) ? pog.options.length : pogcols;
// Can't use i to increment becuase it makes everything go whacky.
// This is used to increment the pog through the loop below so we can access the individual pog data.
var inc = 0;
var radioInput; //used to create the radio button element.
var radioLabel; //used to create the radio button label.
// alert(" pog id = "+pogid+"\n pogcols = "+pogcols+"\n totalRows "+totalRows+"\n total columns = "+totalCols+"\n number of pogs = "+pog['options']['length']);
for (r=0; r<totalRows; r++) { // controls the number of rows that will appear.
oRow = myTableBody.insertRow(-1); //adds a row to the table.
for (c=0; c<totalCols; c++) { // ################## Set 3 to the number of columns.
// safety catch for rows that don't populate all columns.
if(pog.options[inc]) {
oCell = oRow.insertCell(-1);
oCell.setAttribute("id","imggrid_row"+r+"_col"+c+"_"+pogid);
oCell.className = "ztable_row";
oCell.innerHTML = "<div><label for='pog_id_"+pogid+"_value_"+pog.options[inc].v+"'><img src='"+zoovyImageUrl(pog.options[inc].img,pog.width,pog.height,'FFFFFF')+"' alt='' border='0' height='"+pog.height+"' width='"+pog.width+"'><\/a><\/label><\/div>";
oCell.appendChild(createRadio(pogid,pog.options[inc].v)); //adds the radio button into the DOM
//Creates the radio label and assigns necessary attributes.
radioLabel = document.createElement('label');
with(radioLabel) {
className = "zhint";
setAttribute("for", "pog_id_"+pogid+"_value_"+pog.options[inc].v);
}
radioLabel.appendChild(document.createTextNode(pog.options[inc].prompt)); // puts the prompt between the label tags.
oCell.appendChild(radioLabel); //puts the label tag into the table.
} //ends safety catch.
inc++; //pog inc is still incremented outside the catch so we don't get stuck in an infinite loop.
}
}
$("div_"+pogid).appendChild(myTable); //add table to dom.
},
renderOptionUNKNOWN: function(pog) {
return("UNKNOWN "+pog.type+": "+pog.prompt+" / "+pog.id);
},
renderOption: function(pog) {
var pogid = pog.id;
//add a div to the dom that surrounds the pog
var formFieldDiv = document.createElement("div");
with(formFieldDiv) {
setAttribute("id",'div_'+pogid);
className = "zform_div";
}
//create the label (prompt) for the form input and make it a child of the newly created div.
formFieldLabel = document.createElement('label');
with(formFieldLabel) {
setAttribute("for", "pog_"+pogid);
setAttribute("id", "pog_"+pogid+"_id");
setAttribute("style", "vertical-align:top;");
//if ghint is set, use that as the title attribute, otherwise use the prompt.
(pog.ghint) ? setAttribute("title",pog.ghint) : setAttribute("title",pog.prompt);
}
formFieldLabel.appendChild(document.createTextNode(pog.prompt+": "));
formFieldDiv.appendChild(formFieldLabel);
//Push the new div into a div with id JSONPogDisplay as a new child.
// note - originally, i pushed this onto the add to cart form, but that wasn't very flexible in terms of location.
$("JSONPogDisplay").appendChild(formFieldDiv); /// NOTE the form ID on this should probably be auto-generated from the element ID.
if (this.handlers["pogid."+pogid]) {
return(eval("this."+this.handlers["pogid."+pogid]+"(pog)"));
}
else if (this.handlers["type."+pog.type]) {
return(eval("this."+this.handlers["type."+pog.type]+"(pog)"));
}
else {
return(eval("this."+this.handlers["unknown."]+"(pog)"));
}
}});
|
import React from 'react'
const ExtPage = props =>{
return(
<div>这就是一个为了静态看的页面</div>
)
}
module.exports = ExtPage
module.exports.default = module.exports
|
export default {
getLocation() {
return window && window.location;
}
};
|
/*globals importScripts:true, self:true */
importScripts("/dist/papergirl.js");
self.onmessage = function(messageEvent) {
return papergirl
.setDriver(messageEvent.data.driver)
.then(function() {
return papergirl.setItem('service worker', messageEvent.data.value);
})
.then(function() {
return papergirl.getItem('service worker');
})
.then(function(value) {
messageEvent
.ports[0]
.postMessage({
body: value + ' using ' + papergirl.driver()
});
})
.catch(function(error) {
messageEvent
.ports[0]
.postMessage({
error: JSON.stringify(error),
body: error,
fail: true
});
});
};
self.oninstall = function(event) {
event.waitUntil(
papergirl
.setItem('service worker registration', 'serviceworker present')
.then(function(value) {
console.log(value);
})
);
};
|
/*
Author : John Weis
Plugin : Tweeze
Purpose: Uses the Search API at Twitter - https://dev.twitter.com/docs/using-search
Version: 0.1
TODO:
implement a since_id store via $.data
handle error messaging
handle rate limiting (via a cookie, so the user doesn't Ctrl + R and freak out
*/
;(function ($) {
$.fn.tweeze = function (options) {
var settings = {
base_url : "http://search.twitter.com/search.json?q=",
count : '15',
hashtag_filter : null,
linkify : true,
max_attempts : 3,
min_size : 0,
show_senders : false,
show_faces : false, // does nothing yet
search_term : null,
rpp : null,
usernames : {
'from' : [],
'to' : []
},
on_complete : null
};
var _wrapper = null;
var attempts = 0;
var data_collection = {
results : []
};
// courtesy of Jeremy Parrish (rrish.org)
function _linkify(text) {
return text.replace(/(https?:\/\/\S+)/gi, '<a target="_blank" href="$1">$1</a>').replace(/(^|\s)@(\w+)/g, '$1<a target="_blank" href="http://twitter.com/$2">@$2</a>').replace(/(^|\s)#(\w+)/g, ' <a target="_blank" href="http://search.twitter.com/search?q=%23$2">#$2</a>');
};
/*
* Copyright (c) 2008 John Resig (jquery.com)
* Licensed under the MIT license.
*
*
* based on the JavaScript Pretty Date from John Resig
* http://ejohn.org/blog/javascript-pretty-date/
* his code used ISO 8601, I modified it to use RFC 822 dates
*
* ISO 8601 - 2008-01-28T20:24:17Z
* RFC 822 -
*
*/
function _prettyDate(time) {
// var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
var date = new Date(time),
diff = (((new Date()).getTime() - date.getTime()) / 1000),
day_diff = Math.floor(diff / 86400);
if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) return "undefined";
return day_diff == 0 && ( diff < 60 && "just now" ||
diff < 120 && "1 minute ago" || diff < 3600 && Math.floor(diff / 60) + " minutes ago" ||
diff < 7200 && "1 hour ago" || diff < 86400 && Math.floor(diff / 3600) + " hours ago") ||
day_diff == 1 && "Yesterday" || day_diff < 7 && day_diff + " days ago" ||
day_diff < 31 && Math.ceil(day_diff / 7) + " weeks ago";
}
function _build_request_url() {
var url = "";
var query_string = "";
// if from or to are < 3, then the results are only filtered after the fact
// as the Search API has simplicity requirements
// this is also probably one of the DRYest pieces of code i have written in a long time...
// loop through and build the @from and @to params
$.each(settings.usernames, function(k, set) {
if (set.length < 4) {
$.each(set , function(i, name){
if (i > 0 ) { query_string += "OR+"; }
query_string += k + ":" + name + "+";
});
}
});
if (settings.usernames.length < 3){
$.each( settings.from_usernames, function(i, val){
if (i > 0 ) {
query_string += "OR+";
}
query_string += "from:" + val + "+";
});
}
if (typeof settings.hashtag_filter == 'string') {
query_string += "#" + settings.hashtag_filter + '+';
}
if (typeof settings.search_term == 'string') {
query_string += settings.search_term + '+';
}
url = settings.base_url + escape(query_string);
if (typeof settings.rpp == 'number') {
url += '&rpp=' + settings.rpp;
}
return url;
}
// in logic filter to avoid the complexity requirements from the Twitter Search API
function _filter_from(tweet) {
var matches = false;
if (settings.usernames['from'].length > 0) {
$.each(settings.usernames['from'], function(i, name) {
if (tweet.from_user.toLowerCase() == name.toLowerCase()) {
matches = true;
}
});
} else {
matches = true;
}
return matches;
}
function _push_tweet(tweet) {
var duplicate = false;
$.each(data_collection.results, function(i, t){
if (tweet.id_str == t.id_str) {
duplicate = true;
}
});
if (!duplicate) {
data_collection.results.push(tweet);
}
}
// this retrieves the data from the Twitter Search API
function _retrieve_data(search_string) {
attempts++;
$.ajax({
url : search_string,
dataType : 'jsonp',
statusCode : {
404 : function() { console.log('file not found'); },
420 : function() { console.log('increase the chill'); } // TODO: do something with this
},
success : function(data) {
if (data['results']) {
console.dir(data['results']);
$.each(data['results'], function(i, tweet) {
// if this tweet is in the list of from users,
// or the list of from users isn't specified
// then we'll add it to the collection
if (_filter_from(tweet)) {
// TODO: make sure we're not duplicating the tweet in the list
_push_tweet(tweet);
}
});
// if we still need more, let's call again, going further back in time
if ((data_collection.results.length < settings.min_size) && (attempts < settings.max_attempts)) {
// TODO: go grab more tweets
console.log('i need more tweets!');
_retrieve_data(search_string);
} else {
// if we have an adequate # of tweets, let's render
_render_data();
}
} else {
// for some reason, the response from twitter didn't have any ['results']
// so let's call render just in case
_render_data();
}
}
});
}
// this handles the DOM manipulation
function _render_data() {
$.each(data_collection.results, function(i, tweet) {
// only show the number that we need to see
if (i < settings.count) {
// build and attach the tweet to the list
var t = $("<li></li>");
// add the sender to the li
if (settings.show_senders) {
$("<a></a>")
.addClass('user')
.attr('target', '_blank')
.attr('href', 'http://twitter.com/' + tweet.from_user)
.html(tweet.from_user)
.appendTo(t);
}
// add the text to the li
$("<span></span>")
.addClass('text')
.html( _linkify(tweet.text) )
.appendTo(t);
// add the time to the li
$("<a></a>")
.addClass('time')
.attr('target', '_blank')
.attr('href', 'http://twitter.com/' + tweet.from_user + '/statuses/' + tweet.id_str)
.html( _prettyDate(tweet.created_at) )
.appendTo(t);
t.appendTo(_wrapper);
}
});
if (typeof settings.on_complete == 'function') {
settings.on_complete();
}
}
// TODO: create functions such as update and destroy - http://docs.jquery.com/Plugins/Authoring#Events
//// returning a function with the .each maintains chainability - http://docs.jquery.com/Plugins/Authoring#Maintaining_Chainability
return this.each(function () {
if (options) {
$.extend(settings, options);
}
// TODO: eventually build in the ability to register and just update, keeping a copy of the current tweets
// set the reference for later
_wrapper = $(this).addClass('tweeze');
// grab the data with the default request URL
// once the data has been retrieved, the retriever calls the renderer
_retrieve_data(_build_request_url());
//// we already have a copy of this - http://docs.jquery.com/Plugins/Authoring#Context
});
};
})(jQuery);
|
'use strict';
function getError(validateInfo, field) {
if (validateInfo && validateInfo[field] && validateInfo[field].length > 0) {
return validateInfo[field][0];
}
return '';
}
module.exports = getError;
|
/*global describe, it, expect, before */
/*jshint expr:true */
var chai = require('chai'),
Strategy = require('..').Strategy;
describe('Strategy', function() {
describe('failing authentication', function() {
var strategy = new Strategy(function(creds, done) {
return done(null, false);
});
var info;
before(function(done) {
chai.passport.use(strategy)
.fail(function(i) {
info = i;
done();
})
.req(function(req) {
req.headers['content-type'] = 'application/json';
req.body = {};
req.body.username = 'johndoe';
req.body.password = 'secret';
req.body.mfaCode = '123456';
})
.authenticate();
});
it('should fail', function() {
expect(info).to.be.undefined;
});
});
describe('failing authentication with info', function() {
var strategy = new Strategy(function(creds, done) {
return done(null, false, { message: 'authentication failed' });
});
var info;
before(function(done) {
chai.passport.use(strategy)
.fail(function(i) {
info = i;
done();
})
.req(function(req) {
req.headers['content-type'] = 'application/json';
req.body = {};
req.body.username = 'johndoe';
req.body.password = 'secret';
req.body.mfaCode = '123456';
})
.authenticate();
});
it('should fail', function() {
expect(info).to.be.an('object');
expect(info.message).to.equal('authentication failed');
});
});
});
|
'use strict';
const Post = require('../models/post');
class IndexController {
index(req, res) {
res.render('index', {
session: req.session
});
}
}
module.exports = new IndexController();
|
const gulp = require('gulp');
const eslint = require('gulp-eslint');
const clear = require('clear');
const {rollup} = require('rollup');
const vue = require('rollup-plugin-vue2');
const babel = require('rollup-plugin-babel');
const uglify = require('rollup-plugin-uglify');
const moduleName = 'VueXdraggable';
const destName = 'vue-xdraggable';
// 检测代码风格
gulp.task('lint', () => {
clear();
return gulp.src(['src/**/*.js', 'src/**/*.vue', '!node_modules/**', '!dist/**'])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
// 编译开发版本
gulp.task('build:dev', ['lint'], () => {
return rollup({
entry: 'src/index.js',
plugins: [vue(), babel()],
external: ['vue-xdraggable']
})
.then((bundle) => {
bundle.write({
moduleName,
format: 'umd',
dest: `dist/${destName}.js`,
sourceMap: true,
globals: {
'vue-xdraggable': 'VueXdraggable'
}
});
});
});
// 编译生产版本
gulp.task('build:prod', ['lint'], () => {
return rollup({
entry: 'src/index.js',
plugins: [vue(), babel(), uglify()],
external: ['vue-xdraggable']
})
.then((bundle) => {
bundle.write({
moduleName,
format: 'umd',
dest: `dist/${destName}.min.js`,
sourceMap: true,
globals: {
'vue-xdraggable': 'VueXdraggable'
}
});
});
});
gulp.task('default', ['lint', 'build:dev', 'build:prod']);
|
'use strict';
/**
* Module dependencies.
*/
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
User = require('mongoose').model('User');
module.exports = function() {
// Use local strategy
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
},
function(username, password, done) {
User.findOne({
username: username
}, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, {
message: 'Benutzer unbekannt / Passwort falsch!'
});
}
if (!user.authenticate(password)) {
return done(null, false, {
message: 'Benutzer unbekannt / Passwort falsch!'
});
}
return done(null, user);
});
}
));
};
|
import { between } from '../../utils/format.js'
import { position } from '../../utils/event.js'
import FormMixin from '../../mixins/form.js'
import DarkMixin from '../../mixins/dark.js'
import TouchPan from '../../directives/TouchPan.js'
// PGDOWN, LEFT, DOWN, PGUP, RIGHT, UP
export const keyCodes = [ 34, 37, 40, 33, 39, 38 ]
export function getRatio (evt, dragging, reverse, vertical) {
const
pos = position(evt),
val = vertical === true
? between((pos.top - dragging.top) / dragging.height, 0, 1)
: between((pos.left - dragging.left) / dragging.width, 0, 1)
return reverse === true ? 1.0 - val : val
}
export function getModel (ratio, min, max, step, decimals) {
let model = min + ratio * (max - min)
if (step > 0) {
const modulo = (model - min) % step
model += (Math.abs(modulo) >= step / 2 ? (modulo < 0 ? -1 : 1) * step : 0) - modulo
}
if (decimals > 0) {
model = parseFloat(model.toFixed(decimals))
}
return between(model, min, max)
}
export const SliderMixin = {
mixins: [ DarkMixin, FormMixin ],
directives: {
TouchPan
},
props: {
min: {
type: Number,
default: 0
},
max: {
type: Number,
default: 100
},
step: {
type: Number,
default: 1,
validator: v => v >= 0
},
color: String,
labelColor: String,
labelTextColor: String,
dense: Boolean,
label: Boolean,
labelAlways: Boolean,
markers: Boolean,
snap: Boolean,
vertical: Boolean,
reverse: Boolean,
disable: Boolean,
readonly: Boolean,
tabindex: [ String, Number ],
thumbPath: {
type: String,
default: 'M 4, 10 a 6,6 0 1,0 12,0 a 6,6 0 1,0 -12,0'
}
},
data () {
return {
active: false,
preventFocus: false,
focus: false
}
},
computed: {
axis () {
return this.vertical === true ? '--v' : '--h'
},
classes () {
return `q-slider q-slider${this.axis} q-slider--${this.active === true ? '' : 'in'}active` +
(this.isReversed === true ? ' q-slider--reversed' : '') +
(this.color !== void 0 ? ` text-${this.color}` : '') +
(this.disable === true ? ' disabled' : ' q-slider--enabled' + (this.editable === true ? ' q-slider--editable' : '')) +
(this.focus === 'both' ? ' q-slider--focus' : '') +
(this.label || this.labelAlways === true ? ' q-slider--label' : '') +
(this.labelAlways === true ? ' q-slider--label-always' : '') +
(this.isDark === true ? ' q-slider--dark' : '') +
(this.dense === true ? ' q-slider--dense q-slider--dense' + this.axis : '')
},
editable () {
return this.disable !== true && this.readonly !== true
},
decimals () {
return (String(this.step).trim('0').split('.')[1] || '').length
},
computedStep () {
return this.step === 0 ? 1 : this.step
},
markerStyle () {
return {
backgroundSize: this.vertical === true
? '2px ' + (100 * this.computedStep / (this.max - this.min)) + '%'
: (100 * this.computedStep / (this.max - this.min)) + '% 2px'
}
},
computedTabindex () {
return this.editable === true ? this.tabindex || 0 : -1
},
isReversed () {
return this.vertical === true
? this.reverse === true
: this.reverse !== (this.$q.lang.rtl === true)
},
positionProp () {
if (this.vertical === true) {
return this.isReversed === true ? 'bottom' : 'top'
}
return this.isReversed === true ? 'right' : 'left'
},
sizeProp () {
return this.vertical === true ? 'height' : 'width'
},
orientation () {
return this.vertical === true ? 'vertical' : 'horizontal'
},
attrs () {
const attrs = {
role: 'slider',
'aria-valuemin': this.min,
'aria-valuemax': this.max,
'aria-orientation': this.orientation,
'data-step': this.step
}
if (this.disable === true) {
attrs['aria-disabled'] = 'true'
}
else if (this.readonly === true) {
attrs['aria-readonly'] = 'true'
}
return attrs
},
panDirectives () {
return this.editable === true
? [{
name: 'touch-pan',
value: this.__pan,
modifiers: {
[ this.orientation ]: true,
prevent: true,
stop: true,
mouse: true,
mouseAllDir: true
}
}]
: null
}
},
methods: {
__getThumbSvg (h) {
return h('svg', {
staticClass: 'q-slider__thumb absolute',
attrs: {
focusable: 'false', /* needed for IE11 */
viewBox: '0 0 20 20',
width: '20',
height: '20',
'aria-hidden': 'true'
}
}, [
h('path', {
attrs: {
d: this.thumbPath
}
})
])
},
__getPinStyle (percent, ratio) {
if (this.vertical === true) {
return {}
}
const offset = `${Math.ceil(20 * Math.abs(0.5 - ratio))}px`
return {
pin: {
transformOrigin: `${this.$q.lang.rtl === true ? offset : (this.$q.platform.is.ie === true ? '100%' : `calc(100% - ${offset})`)} 50%`
},
pinTextContainer: {
[this.$q.lang.rtl === true ? 'left' : 'right']: `${percent * 100}%`,
transform: `translateX(${Math.ceil((this.$q.lang.rtl === true ? -1 : 1) * 20 * percent)}px)`
}
}
},
__pan (event) {
if (event.isFinal) {
if (this.dragging !== void 0) {
this.__updatePosition(event.evt)
// only if touch, because we also have mousedown/up:
event.touch === true && this.__updateValue(true)
this.dragging = void 0
this.$emit('pan', 'end')
}
this.active = false
}
else if (event.isFirst) {
this.dragging = this.__getDragging(event.evt)
this.__updatePosition(event.evt)
this.__updateValue()
this.active = true
this.$emit('pan', 'start')
}
else {
this.__updatePosition(event.evt)
this.__updateValue()
}
},
__blur () {
this.focus = false
},
__activate (evt) {
this.__updatePosition(evt, this.__getDragging(evt))
this.__updateValue()
this.preventFocus = true
this.active = true
document.addEventListener('mouseup', this.__deactivate, true)
},
__deactivate () {
this.preventFocus = false
if (this.dragging === void 0) {
this.active = false
}
this.__updateValue(true)
this.__blur()
document.removeEventListener('mouseup', this.__deactivate, true)
},
__mobileClick (evt) {
this.__updatePosition(evt, this.__getDragging(evt))
this.__updateValue(true)
},
__keyup (evt) {
if (keyCodes.includes(evt.keyCode)) {
this.__updateValue(true)
}
}
},
beforeDestroy () {
document.removeEventListener('mouseup', this.__deactivate, true)
}
}
|
/* Usage:
*
* --exec: specify which test(s) to run
* --iter: how many iterations each test should run (default: 1e6)
* --slow: toggle use of slow buffer
*
* Example:
*
* node buffer_write_string.js --exec 'write - 1e1' --iter 1e5 --slow
*
* Defaults are 'fast' and '1e6'.
*/
var oc = require('../templates/_buffer').oncomplete;
var Timer = require('../../lib/node-timer');
var params = Timer.parse(process.argv);
var Buff = params.slow ? require('buffer').SlowBuffer : Buffer;
var ITER = params.iter || 1e6;
var buff = Buff(1e4);
var str1e1 = createString(1e1);
var str1e2 = createString(1e2);
var str1e3 = createString(1e3);
var oc_args = [ITER];
Timer('write - 1e1', function() {
for (var i = 0; i < ITER; i++)
buff.write(str1e1);
}).oncomplete(oc, oc_args);
Timer('write - 1e1@1e3', function() {
for (var i = 0; i < ITER; i++)
buff.write(str1e1, 1e3);
}).oncomplete(oc, oc_args);
Timer('write - 1e2', function() {
for (var i = 0; i < ITER; i++)
buff.write(str1e2);
}).oncomplete(oc, oc_args);
Timer('write - 1e2@1e3', function() {
for (var i = 0; i < ITER; i++)
buff.write(str1e2, 1e3);
}).oncomplete(oc, oc_args);
Timer('write - 1e3', function() {
for (var i = 0; i < ITER; i++)
buff.write(str1e3);
}).oncomplete(oc, oc_args);
Timer('write - 1e3@1e3', function() {
for (var i = 0; i < ITER; i++)
buff.write(str1e3, 1e3);
}).oncomplete(oc, oc_args);
function createString(len) {
var str = 'a';
while (str.length * 2 <= len)
str += str;
str += str.substr(0, len - str.length);
return str;
}
oc_args.push(Timer.maxNameLength());
|
test('.prototype.divide()', 12, function () {
// integer
equal((new MathLib.Integer('+10000000')).divide(new MathLib.Integer('+10')).toString(), '1000000');
equal((new MathLib.Integer('+10000000')).divide(new MathLib.Integer('-10')).toString(), '-1000000');
equal((new MathLib.Integer('-10000000')).divide(new MathLib.Integer('+10')).toString(), '-1000000');
equal((new MathLib.Integer('-10000000')).divide(new MathLib.Integer('-10')).toString(), '1000000');
equal((new MathLib.Integer('+10000001')).divide(new MathLib.Integer('+10')).toString(), '10000001/10');
equal((new MathLib.Integer('+10000001')).divide(new MathLib.Integer('-10')).toString(), '-10000001/10');
equal((new MathLib.Integer('-10000001')).divide(new MathLib.Integer('+10')).toString(), '-10000001/10');
equal((new MathLib.Integer('-10000001')).divide(new MathLib.Integer('-10')).toString(), '10000001/10');
// number
equal((new MathLib.Integer('+100')).divide(10), 10);
equal((new MathLib.Integer('+100')).divide(-10), -10);
equal((new MathLib.Integer('-100')).divide(10), -10);
equal((new MathLib.Integer('-100')).divide(-10), 10);
});
|
var app = angular.module('JSONedit', ['ui']);
// fix ui-multi-sortable to y-axis
app.value('ui.config', {
"sortable": {
"axis": "y",
"placeholder": "sortable-placeholder"
}
});
// override the default input to update on blur
// from http://jsfiddle.net/cn8VF/
app.directive('ngModelOnblur', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elm, attr, ngModelCtrl) {
if (attr.type === 'radio' || attr.type === 'checkbox') return;
elm.unbind('input').unbind('keydown').unbind('change');
elm.bind('blur', function() {
scope.$apply(function() {
ngModelCtrl.$setViewValue(elm.val());
});
});
}
};
});
// directive to focus an input element
// usage: <input type="text" focus />
//app.directive('focus', function() {
// return {
// restrict: 'A',
// link: function(scope, element, attributes) {
// element[0].focus();
// }
// }
//});
app.directive('json', function($compile, $timeout) {
return {
restrict: 'E',
scope: {
child: '=',
type: '='
},
link: function(scope, element, attributes) {
var stringName = "Value";
var objectName = "Object"; // or technically more correct: Map
var arrayName = "List";
var refName = "Reference";
scope.valueTypes = [stringName, objectName, arrayName];
//////
// Helper functions
//////
var getType = function(obj) {
var type = Object.prototype.toString.call(obj);
if (type === "[object Object]") {
return "Object";
} else if(type === "[object Array]"){
return "Array";
} else {
return "Literal";
}
};
var isNumber = function(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
scope.getType = function(obj) {
return getType(obj);
};
scope.toggleCollapse = function() {
if (scope.collapsed) {
scope.collapsed = false;
scope.chevron = "icon-chevron-down";
} else {
scope.collapsed = true;
scope.chevron = "icon-chevron-right";
}
};
scope.moveKey = function(obj, key, newkey) {
//moves key to newkey in obj
obj[newkey] = obj[key];
delete obj[key];
};
scope.deleteKey = function(obj, key) {
if (getType(obj) == "Object") {
if( confirm('Delete "'+key+'" and all it contains?') ) {
delete obj[key];
}
} else if (getType(obj) == "Array") {
if( confirm('Delete "'+obj[key]+'"?') ) {
obj.splice(key, 1);
}
} else {
console.error("object to delete from was " + obj);
}
};
scope.addItem = function(obj) {
if (getType(obj) == "Object") {
// check input for key
if (scope.keyName == undefined || scope.keyName.length == 0){
alert("Please fill in a name");
} else if (scope.keyName.indexOf("$") == 0){
alert("The name may not start with $ (the dollar sign)");
} else if (scope.keyName.indexOf("_") == 0){
alert("The name may not start with _ (the underscore)");
} else {
if (obj[scope.keyName]) {
if( !confirm('An item with the name "'+scope.keyName
+'" exists already. Do you really want to replace it?') ) {
return;
}
}
// add item to object
switch(scope.valueType) {
case stringName: obj[scope.keyName] = scope.valueName ? scope.possibleNumber(scope.valueName) : "";
break;
case objectName: obj[scope.keyName] = {};
break;
case arrayName: obj[scope.keyName] = [];
break;
case refName: obj[scope.keyName] = {"Reference!!!!": "todo"};
break;
}
//clean-up
scope.keyName = "";
scope.valueName = "";
scope.showAddKey = false;
}
} else if (getType(obj) == "Array") {
// add item to array
switch(scope.valueType) {
case stringName: obj.push(scope.valueName ? scope.valueName : "");
break;
case objectName: obj.push({});
break;
case arrayName: obj.push([]);
break;
case refName: obj.push({"Reference!!!!": "todo"});
break;
}
scope.valueName = "";
scope.showAddKey = false;
} else {
console.error("object to add to was " + obj);
}
};
scope.possibleNumber = function(val) {
return isNumber(val) ? parseFloat(val) : val;
};
//////
// Template Generation
//////
// Note:
// sometimes having a different ng-model and then saving it on ng-change
// into the object or array is necesarry for all updates to work
// recursion
var switchTemplate =
'<span ng-switch on="getType(val)" >'
+ '<json ng-switch-when="Object" child="val" type="\'object\'"></json>'
+ '<json ng-switch-when="Array" child="val" type="\'array\'"></json>'
+ '<span ng-switch-default class="jsonLiteral"><input type="text" ng-model="val" '
+ 'placeholder="Empty" ng-model-onblur ng-change="child[key] = possibleNumber(val)"/>'
+ '</span>'
+ '</span>';
// display either "plus button" or "key-value inputs"
var addItemTemplate =
'<div ng-switch on="showAddKey" class="block" >'
+ '<span ng-switch-when="true">';
if (scope.type == "object"){
// input key
addItemTemplate += '<input placeholder="Name" type="text" ui-keyup="{\'enter\':\'addItem(child)\'}" '
+ 'class="input-small addItemKeyInput" ng-model="$parent.keyName" />';
}
addItemTemplate +=
// value type dropdown
'<select ng-model="$parent.valueType" ng-options="option for option in valueTypes"'
+ 'ng-init="$parent.valueType=\''+stringName+'\'" ui-keydown="{\'enter\':\'addItem(child)\'}"></select>'
// input value
+ '<span ng-show="$parent.valueType == \''+stringName+'\'"> : <input type="text" placeholder="Value" '
+ 'class="input-medium addItemValueInput" ng-model="$parent.valueName" ui-keyup="{\'enter\':\'addItem(child)\'}"/></span> '
// Add button
+ '<button class="btn btn-primary" ng-click="addItem(child)">Add</button> '
+ '<button class="btn" ng-click="$parent.showAddKey=false">Cancel</button>'
+ '</span>'
+ '<span ng-switch-default>'
// plus button
+ '<button class="addObjectItemBtn" ng-click="$parent.showAddKey = true"><i class="icon-plus"></i></button>'
+ '</span>'
+ '</div>';
// start template
if (scope.type == "object"){
var template = '<i ng-click="toggleCollapse()" ng-class="chevron"'
+ ' ng-init="chevron = \'icon-chevron-down\'"></i>'
+ '<span class="jsonItemDesc">'+objectName+'</span>'
+ '<div class="jsonContents" ng-hide="collapsed">'
// repeat
+ '<span class="block" ng-hide="key.indexOf(\'_\') == 0" ng-repeat="(key, val) in child">'
// object key
+ '<span class="jsonObjectKey">'
+ '<input class="keyinput" type="text" ng-model="newkey" ng-init="newkey=key" '
+ 'ng-change="moveKey(child, key, newkey)"/>'
// delete button
+ '<i class="deleteKeyBtn icon-trash" ng-click="deleteKey(child, key)"></i>'
+ '</span>'
// object value
+ '<span class="jsonObjectValue">' + switchTemplate + '</span>'
+ '</span>'
// repeat end
+ addItemTemplate
+ '</div>';
} else if (scope.type == "array") {
var template = '<i ng-click="toggleCollapse()" ng-class="chevron" ng-init="chevron = \'icon-chevron-down\'"></i>'
+ '<span class="jsonItemDesc">'+arrayName+'</span>'
+ '<div class="jsonContents" ng-hide="collapsed">'
+ '<ol class="arrayOl" ui-multi-sortable ng-model="child">'
// repeat
+ '<li class="arrayItem" ng-repeat="val in child">'
// delete button
+ '<i class="deleteKeyBtn icon-trash" ng-click="deleteKey(child, $index)"></i>'
+ '<i class="moveArrayItemBtn icon-align-justify"></i>'
+ '<span>' + switchTemplate + '</span>'
+ '</li>'
// repeat end
+ '</ol>'
+ addItemTemplate
+ '</div>';
} else {
console.error("scope.type was "+ scope.type);
}
var newElement = angular.element(template);
$compile(newElement)(scope);
element.replaceWith(newElement);
}
};
});
|
/*!
* jQuery JavaScript Library v1.11.3
* 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:19Z
*/
(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 inherently posses a window with a document
// (such as Node.js), expose a jQuery-making 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 ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//
var deletedIds = [];
var slice = deletedIds.slice;
var concat = deletedIds.concat;
var push = deletedIds.push;
var indexOf = deletedIds.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var support = {};
var
version = "1.11.3",
// 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, IE<9
// 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: deletedIds.sort,
splice: deletedIds.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// 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() {},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
// 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;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
isPlainObject: function( obj ) {
var key;
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( support.ownLast ) {
for ( key in obj ) {
return hasOwn.call( obj, key );
}
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Support: Android<4.1, IE<9
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 ) {
var len;
if ( arr ) {
if ( indexOf ) {
return indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
while ( j < len ) {
first[ i++ ] = second[ j++ ];
}
// Support: IE<9
// Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)
if ( len !== len ) {
while ( second[j] !== undefined ) {
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 args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = 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: function() {
return +( new Date() );
},
// 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 ( jQuery.inArray( elem, qualifier ) >= 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,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
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,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
// 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.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
// 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] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return 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 = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
jQuery.fn.extend({
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
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 matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
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 ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
ret = jQuery.unique( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
ret = ret.reverse();
}
}
return this.pushStack( ret );
};
});
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 // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var 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;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.triggerHandler ) {
jQuery( document ).triggerHandler( "ready" );
jQuery( document ).off( "ready" );
}
}
});
/**
* Clean-up method for dom ready events
*/
function detach() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
}
/**
* The ready event handler and self cleanup method
*/
function completed() {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
var strundefined = typeof undefined;
// Support: IE<9
// Iteration over object's inherited properties before its own
var i;
for ( i in jQuery( support ) ) {
break;
}
support.ownLast = i !== "0";
// Note: most support tests are defined in their respective modules.
// false until the test is run
support.inlineBlockNeedsLayout = false;
// Execute ASAP in case we need to set body.style.zoom
jQuery(function() {
// Minified: var a,b,c,d
var val, div, body, container;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Return for frameset docs that don't have a body
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
if ( typeof div.style.zoom !== strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";
support.inlineBlockNeedsLayout = val = div.offsetWidth === 3;
if ( val ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
});
(function() {
var div = document.createElement( "div" );
// Execute the test only if not already executed in another module.
if (support.deleteExpando == null) {
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
}
// Null elements to avoid leaks in IE.
div = null;
})();
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function( elem ) {
var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ],
nodeType = +elem.nodeType || 1;
// Do not set data on non-element DOM nodes because it will not be cleared (#8335).
return nodeType !== 1 && nodeType !== 9 ?
false :
// Nodes accept data unless otherwise specified; rejection can be conditional
!noData || noData !== true && elem.getAttribute("classid") === noData;
};
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function internalData( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var ret, thisCache,
internalKey = jQuery.expando,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
// Avoid exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( typeof name === "string" ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
i = name.length;
while ( i-- ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
/* jshint eqeqeq: false */
} else if ( support.deleteExpando || cache != cache.window ) {
/* jshint eqeqeq: true */
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// The following elements (space-suffixed to avoid Object.prototype collisions)
// throw uncatchable exceptions if you attempt to set expando properties
noData: {
"applet ": true,
"embed ": true,
// ...but Flash objects (which have this classid) *can* handle expandos
"object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var i, name, data,
elem = this[0],
attrs = elem && elem.attributes;
// Special expections of .data basically thwart jQuery.access,
// so implement the relevant behavior ourselves
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
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 ] );
}
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return arguments.length > 1 ?
// Sets one value
this.each(function() {
jQuery.data( this, key, value );
}) :
// Gets one value
// Try to fetch any internally stored data first
elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined;
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var 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 );
};
// 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,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
};
var rcheckableType = (/^(?:checkbox|radio)$/i);
(function() {
// Minified: var a,b,c
var input = document.createElement( "input" ),
div = document.createElement( "div" ),
fragment = document.createDocumentFragment();
// Setup
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// IE strips leading whitespace when .innerHTML is used
support.leadingWhitespace = div.firstChild.nodeType === 3;
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
support.tbody = !div.getElementsByTagName( "tbody" ).length;
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
support.htmlSerialize = !!div.getElementsByTagName( "link" ).length;
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
support.html5Clone =
document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>";
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
input.type = "checkbox";
input.checked = true;
fragment.appendChild( input );
support.appendChecked = input.checked;
// Make sure textarea (and checkbox) defaultValue is properly cloned
// Support: IE6-IE11+
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
// #11217 - WebKit loses check when the name is after the checked attribute
fragment.appendChild( div );
div.innerHTML = "<input type='radio' checked='checked' name='t'/>";
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
support.noCloneEvent = true;
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Execute the test only if not already executed in another module.
if (support.deleteExpando == null) {
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
}
})();
(function() {
var i, eventName,
div = document.createElement( "div" );
// Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event)
for ( i in { submit: true, change: true, focusin: true }) {
eventName = "on" + i;
if ( !(support[ i + "Bubbles" ] = eventName in window) ) {
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
div.setAttribute( eventName, "t" );
support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false;
}
}
// Null elements to avoid leaks in IE.
div = null;
})();
var rformElems = /^(?:input|select|textarea)$/i,
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 tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = 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 = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( 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.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// 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 = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined &&
// Support: IE < 9, 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 ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
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
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;
}
};
});
// IE submit delegation
if ( !support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !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 = jQuery._data( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
jQuery._data( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = jQuery._data( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
jQuery._removeData( doc, fix );
} else {
jQuery._data( doc, fix, attaches );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
// Support: IE<8
// 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 = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!support.noCloneEvent || !support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
deletedIds.push( id );
}
}
}
}
}
});
jQuery.fn.extend({
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
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++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map(function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var 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 first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction ||
( l > 1 && typeof value === "string" &&
!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 ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[i], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
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 optmization) 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 ].contentWindow || iframe[ 0 ].contentDocument ).document;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
(function() {
var shrinkWrapBlocksVal;
support.shrinkWrapBlocks = function() {
if ( shrinkWrapBlocksVal != null ) {
return shrinkWrapBlocksVal;
}
// Will be changed later if needed.
shrinkWrapBlocksVal = false;
// Minified: var b,c,d
var div, body, container;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
// Support: IE6
// Check if elements with layout shrink-wrap their children
if ( typeof div.style.zoom !== strundefined ) {
// Reset CSS: box-sizing; display; margin; border
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:1px;width:1px;zoom:1";
div.appendChild( document.createElement( "div" ) ).style.width = "5px";
shrinkWrapBlocksVal = div.offsetWidth !== 3;
}
body.removeChild( container );
return shrinkWrapBlocksVal;
};
})();
var rmargin = (/^margin/);
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles, curCSS,
rposition = /^(top|right|bottom|left)$/;
if ( window.getComputedStyle ) {
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 );
};
curCSS = function( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "";
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, computed ) {
var left, rs, rsLeft, ret,
style = elem.style;
computed = computed || getStyles( elem );
ret = computed ? computed[ name ] : undefined;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
// Support: IE
// IE returns zIndex value as an integer.
return ret === undefined ?
ret :
ret + "" || "auto";
};
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
var condition = conditionFn();
if ( condition == null ) {
// The test was not ready at this point; screw the hook this time
// but check again when needed next time.
return;
}
if ( condition ) {
// Hook not needed (or it's not possible to use it due to missing dependency),
// remove it.
// Since there are no other hooks for marginRight, remove the whole object.
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() {
// Minified: var b,c,d,e,f,g, h,i
var div, style, a, pixelPositionVal, boxSizingReliableVal,
reliableHiddenOffsetsVal, reliableMarginRightVal;
// Setup
div = document.createElement( "div" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName( "a" )[ 0 ];
style = a && a.style;
// Finish early in limited (non-browser) environments
if ( !style ) {
return;
}
style.cssText = "float:left;opacity:.5";
// Support: IE<9
// Make sure that element opacity exists (as opposed to filter)
support.opacity = style.opacity === "0.5";
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!style.cssFloat;
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
support.boxSizing = style.boxSizing === "" || style.MozBoxSizing === "" ||
style.WebkitBoxSizing === "";
jQuery.extend(support, {
reliableHiddenOffsets: function() {
if ( reliableHiddenOffsetsVal == null ) {
computeStyleTests();
}
return reliableHiddenOffsetsVal;
},
boxSizingReliable: function() {
if ( boxSizingReliableVal == null ) {
computeStyleTests();
}
return boxSizingReliableVal;
},
pixelPosition: function() {
if ( pixelPositionVal == null ) {
computeStyleTests();
}
return pixelPositionVal;
},
// Support: Android 2.3
reliableMarginRight: function() {
if ( reliableMarginRightVal == null ) {
computeStyleTests();
}
return reliableMarginRightVal;
}
});
function computeStyleTests() {
// Minified: var b,c,d,j
var div, body, container, contents;
body = document.getElementsByTagName( "body" )[ 0 ];
if ( !body || !body.style ) {
// Test fired too early or in an unsupported environment, exit.
return;
}
// Setup
div = document.createElement( "div" );
container = document.createElement( "div" );
container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
body.appendChild( container ).appendChild( div );
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";
// Support: IE<9
// Assume reasonable values in the absence of getComputedStyle
pixelPositionVal = boxSizingReliableVal = false;
reliableMarginRightVal = true;
// Check for getComputedStyle so that this code is not run in IE<9.
if ( window.getComputedStyle ) {
pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
boxSizingReliableVal =
( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Support: Android 2.3
// 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
contents = div.appendChild( document.createElement( "div" ) );
// Reset CSS: box-sizing; display; margin; border; padding
contents.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";
contents.style.marginRight = contents.style.width = "0";
div.style.width = "1px";
reliableMarginRightVal =
!parseFloat( ( window.getComputedStyle( contents, null ) || {} ).marginRight );
div.removeChild( contents );
}
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
contents = div.getElementsByTagName( "td" );
contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none";
reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
if ( reliableHiddenOffsetsVal ) {
contents[ 0 ].style.display = "";
contents[ 1 ].style.display = "none";
reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
}
body.removeChild( container );
}
})();
// 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
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
// 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.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
} else {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
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 = support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( 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";
}
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: {
// normalize float css property
"float": support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set. See: #7116
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !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 ) {
// Support: IE
// Swallow errors from 'invalid' CSS values (#5509)
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return 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,
support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
// 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
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.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 a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
} ]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
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 = jQuery._data( elem, "fxshow" );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
display = jQuery.css( elem, "display" );
// Test default display if display is currently "none"
checkDisplay = display === "none" ?
jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !support.shrinkWrapBlocks() ) {
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// 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 = jQuery._data( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
// 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 wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
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 || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = jQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
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,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
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() {
// Minified: var a,b,c,d,e
var input, div, select, a, opt;
// Setup
div = document.createElement( "div" );
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
a = div.getElementsByTagName("a")[ 0 ];
// First batch of tests.
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px";
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
support.getSetAttribute = div.className !== "t";
// Get the style information from getAttribute
// (IE uses .cssText instead)
support.style = /top/.test( a.getAttribute("style") );
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
support.hrefNormalized = a.getAttribute("href") === "/a";
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
support.checkOn = !!input.value;
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
support.optSelected = opt.selected;
// Tests for enctype support on a form (#6743)
support.enctype = !!document.createElement("form").enctype;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE8 only
// Check if we can trust getAttribute("value")
input = document.createElement( "input" );
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
})();
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 ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( 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 ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) {
// Support: IE6
// When new option element is added to select box we need to
// force reflow of newly added node in order to workaround delay
// of initialization properties
try {
option.selected = optionSet = true;
} catch ( _ ) {
// Will be executed only in IE6
option.scrollHeight;
}
} else {
option.selected = false;
}
}
// Force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return options;
}
}
}
});
// 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 ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = support.getSetAttribute,
getSetInput = support.input;
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
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
}
});
// Hook for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
// Retrieve booleans specially
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( 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;
} :
function( elem, name, isXML ) {
if ( !isXML ) {
return elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
}
};
});
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
if ( name === "value" || value === elem.getAttribute( name ) ) {
return value;
}
}
};
// Some attributes are constructed with empty-string values when not defined
attrHandle.id = attrHandle.name = attrHandle.coords =
function( elem, name, isXML ) {
var ret;
if ( !isXML ) {
return (ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
}
};
// Fixing value retrieval on a button requires this module
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
if ( ret && ret.specified ) {
return ret.value;
}
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
});
}
if ( !support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
var rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i;
jQuery.fn.extend({
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
}
});
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 ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
}
});
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
// Support: Safari, IE9+
// mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// IE6/7 call enctype encoding
if ( !support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
addClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( 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,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( 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
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
}
});
// 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 = (/\?/);
var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;
jQuery.parseJSON = function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
// Support: Android 2.3
// Workaround failure to string-cast null input
return window.JSON.parse( data + "" );
}
var requireNonComma,
depth = null,
str = jQuery.trim( data + "" );
// Guard against invalid (and possibly dangerous) input by ensuring that nothing remains
// after removing valid tokens
return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) {
// Force termination if we see a misplaced comma
if ( requireNonComma && comma ) {
depth = 0;
}
// Perform no more replacements after returning to outermost depth
if ( depth === 0 ) {
return token;
}
// Commas must not follow "[", "{", or ","
requireNonComma = open || comma;
// Determine new depth
// array/object open ("[" or "{"): depth += true - false (increment)
// array/object close ("]" or "}"): depth += false - true (decrement)
// other cases ("," or primitive): depth += true - true (numeric cast)
depth += !close - !open;
// Remove this token
return "";
}) ) ?
( Function( "return " + str ) )() :
jQuery.error( "Invalid JSON: " + data );
};
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data, "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType.charAt( 0 ) === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while ( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s[ "throws" ] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( 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 {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
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 ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
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 ||
(!support.reliableHiddenOffsets() &&
((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
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();
}
});
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ?
// Support: IE6+
function() {
// XHR cannot access local files, always use ActiveX for that case
return !this.isLocal &&
// Support: IE7-8
// oldIE XHR does not support non-RFC2616 methods (#13240)
// See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx
// and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9
// Although this check for six methods instead of eight
// since IE also does not support "trace" and "connect"
/^(get|post|head|put|delete|options)$/i.test( this.type ) &&
createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
var xhrId = 0,
xhrCallbacks = {},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE<10
// 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 ]( undefined, true );
}
});
}
// Determine support properties
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport(function( options ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !options.crossDomain || support.cors ) {
var callback;
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr(),
id = ++xhrId;
// Open the socket
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 ) {
// Support: IE<9
// IE's ActiveXObject throws a 'Type Mismatch' exception when setting
// request header to a null-value.
//
// To keep consistent with other XHR implementations, cast the value
// to string and ignore `undefined`.
if ( headers[ i ] !== undefined ) {
xhr.setRequestHeader( i, headers[ i ] + "" );
}
}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( options.hasContent && options.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, statusText, responses;
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Clean up
delete xhrCallbacks[ id ];
callback = undefined;
xhr.onreadystatechange = jQuery.noop;
// Abort manually if needed
if ( isAbort ) {
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
// Support: IE<10
// Accessing binary-data responseText throws an exception
// (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && options.isLocal && !options.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, xhr.getAllResponseHeaders() );
}
};
if ( !options.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback );
} else {
// Add to the list of active xhr callbacks
xhr.onreadystatechange = xhrCallbacks[ id ] = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
});
}
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || jQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( 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, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = jQuery.trim( url.slice( off, url.length ) );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) {
jQuery.fn[ type ] = function( fn ) {
return this.on( type, fn );
};
});
jQuery.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 || elem.parentWindow :
false;
}
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" ) &&
jQuery.inArray("auto", [ curCSSTop, curCSSLeft ] ) > -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,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 0 ];
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
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
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// 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;
}));
|
var Phaser = require('phaser');
var self = {}
self.ang = {
to:{
rad:function(a){
return a*(180/Math.PI)
},
deg:function(a){
return a*(Math.PI/180);
}
}
}
self.randInRange = function(point,range){
var a = (Math.random()*360) * (Math.PI / 180);
var d = Math.random()*range*0.5;
return {
x:point.x + Math.cos(a) * d,
y:point.y + Math.sin(a) * d
}
}
self.elipsePos = function(point,angle,size){
var a = angle * (Math.PI / 180);
return {
x: point.x + Math.cos(a) * size.width/2,
y: point.y + Math.sin(a) * size.height/2
};
}
self.mod = function(n,a){
return ((n % a) + a) % a;
}
self.getPorInRange = function (min, max, current) {
if (current >= max) return 1;
if (current <= min) return 0;
return (current - min) / (max - min);
};
self.pointAngleIntersection = function(point1,angle1,point2,angle2) {
// get any point on the line1
var line1 = {
start:point1,
end:self.radPos(point1,angle1,50),
}
// get any point on the line2
var line2 = {
start:point2,
end:self.radPos(point2,angle2,50)
}
var denominator = (((line2.end.y - line2.start.y) * (line1.end.x - line1.start.x)) - ((line2.end.x - line2.start.x) * (line1.end.y - line1.start.y)));
// if is parallel return null;
if(denominator===0) return null;
var a = (((line2.end.x - line2.start.x) * (line1.start.y - line2.start.y)) - ((line2.end.y - line2.start.y) * (line1.start.x - line2.start.x))) / denominator;
return {
x:line1.start.x + (a * (line1.end.x - line1.start.x)),
y:line1.start.y + (a * (line1.end.y - line1.start.y))
};
}
self.getCenter = function(obj){
return {
x:obj.x+(obj.width*0.5),
y:obj.y+(obj.height*0.5),
}
}
self.time = function(){
return Math.floor(+new Date()/1000);
}
self.porBetween = function(min,max,curent,por,fixed){
if(por===undefined) por = 100;
if(fixed===undefined) fixed = 2;
return Number(((curent-min)*por/(max-min)).toFixed(fixed))
}
self.hitDotBox = function(dot,box){
return dot.x>box.x &&
dot.x<box.x+box.width &&
dot.y>box.y &&
dot.y<box.y+box.height;
}
self.hitBoxBox = function(box1,box2){
return box1.x+box1.width>box2.x &&
box1.x<box2.x+box2.width &&
box1.y+box1.height>box2.y &&
box1.y<box2.y+box2.height;
}
self.dotsBetween = function(point1,point2,amount){
if(amount===undefined) amount = 1;
var resp = [];
var dist = self.dist(point1,point2);
var a = self.angleBetween(point1,point2);
return Array.apply(null, {length: 10}).map((val,i)=> i).map(function(i){
var currentPos = (dist/(amount+1))*(i+1);
return {
x:point1.x + Math.cos(a)*currentPos,
y:point1.y + Math.sin(a)*currentPos
}
});
}
self.dotLine = function(point1,point2,amount){
return [point1].concat(self.dotsBetween(point1,point2,amount-2)).concat([point2]);
}
self.angleBetween = function(point1,point2){
return Math.atan2(point2.y-point1.y, point2.x-point1.x);
}
self.angleBetweenRad = function(point1,point2){
return Math.atan2(point2.y-point1.y, point2.x-point1.x)*(180/Math.PI);
}
self.pointBetweenPorcent = function(point1,point2,por){
return self.radPos(
point1,
self.angleBetweenRad(point1,point2),
self.dist(point1,point2)*por
);
}
self.randomPointBetween = function(point1,point2){
return self.pointBetweenPorcent(point1,point2,Math.random());
}
self.radPos = function(point,angle,range){
var a = angle * (Math.PI / 180);
return {
x:point.x + (Math.cos(a) * range),
y:point.y + (Math.sin(a) * range)
}
}
self.getRangeIndexByValue = function(length,current,modes,ASC){
if(ASC===undefined) ASC=true;
if(current>=length) current=length-1;
if(current<=0) current=0;
return ~~(modes*(current/length));
}
self.getModeByValue = function(length,current,modes,ASC){
if(ASC===undefined) ASC=true;
return modes[self.getRangeIndexByValue(length,current,modes.length,ASC)];
}
self.randPorRange = function(val,por){
var part = Math.ceil(val*por/100);
return self.rand(val-part,val+part);
}
self.loadAssets = function(game,assets){
var i;
for(i in assets.atlas) {
game.load.atlasJSONHash(i, assets.atlas[i].image, assets.atlas[i].jsonUrl, assets.atlas[i].json);
}
for(i in assets.images) game.load.image(i, assets.images[i]);
for(i in assets.sprites) game.load.spritesheet(i, assets.sprites[i].image, assets.sprites[i].width, assets.sprites[i].height, assets.sprites[i].frames);
for(i in assets.audio) game.load.audio(i, assets.audio[i]);
}
self.por = function(val,por,plus,fix){
if(plus===undefined) plus=true;
if(fix===undefined) fix=0;
return Number(((val * por / 100)*(plus ? 1 : -1)+val).toFixed(fix));
}
self.dist = function(obj1,obj2){
return Math.sqrt(Math.pow(obj1.x-obj2.x,2)+Math.pow(obj1.y-obj2.y,2));
}
self.setBtn = function(obj,callback){
if(callback===undefined) callback=null;
if(!obj) return;
if(!obj.inputEnabled) obj.inputEnabled = true;
if(!obj.input) return;
obj.input.useHandCursor = true;
if(callback){
obj.events.onInputUp.add(function(e){
callback(e);
});
}
return obj;
}
self.setBtnHold = function(obj,callback,callback2){
if(callback===undefined) callback=null;
if(!obj) return;
if(!obj.inputEnabled) obj.inputEnabled = true;
if(!obj.input) return;
obj.input.useHandCursor = true;
if(callback){
obj.events.onInputDown.add(function(e){
callback(e);
});
}
if(callback2){
obj.events.onInputUp.add(function(e){
callback2(e);
});
}
return obj;
}
self.setHover = function(obj,callback,callback2){
if(callback===undefined) callback=null;
if(callback2===undefined) callback2=null;
if(!obj) return;
if(!obj.inputEnabled) obj.inputEnabled = true;
if(!obj.input) return;
obj.input.useHandCursor = true;
if(callback){
obj.events.onInputOver.add(function(e){
callback(e);
});
}
if(callback2){
obj.events.onInputOut.add(function(e){
callback2(e);
});
}
return obj;
}
module.exports = self;
|
#!/usr/bin/env node
/*
*
* poloniex-unofficial
* https://git.io/polonode
*
* Yet another unofficial Node.js wrapper for the Poloniex cryptocurrency
* exchange APIs.
*
* Copyright (c) 2016 Tyler Filla
*
* This software may be modified and distributed under the terms of the MIT
* license. See the LICENSE file for details.
*
*/
"use strict";
// Import main module
const polo = require("./../../../");
// Obtain API credentials from environment
const apiKey = process.env.POLONIEX_API_TEST_NOP_KEY;
const apiSecret = process.env.POLONIEX_API_TEST_NOP_SECRET;
// Create authenticated trading API wrapper
const poloTrading = new polo.TradingWrapper(apiKey, apiSecret, () => 55);
// Demonstrate the returnActiveLoans command (callback-style)
poloTrading.returnActiveLoans((err, response) => {
if (err) {
throw err.msg;
}
console.log("Using callback:");
console.log(response);
});
// Demonstrate the returnActiveLoans command (promise-style)
poloTrading.returnActiveLoans().then(res => {
console.log("Using promise:");
console.log(res);
}).catch(err => {
console.error(err);
});
|
var jsConsole,
i,
currentCount,
maxCount= 0,
sequenceStart,
arr = [2, 1, 1, 2, 3, 3, 2, 2, 2, 1];
for (i = 1, len = arr.length; i < len; i+=1) {
if (arr[i] === arr[i - 1]) {
currentCount += 1;
} else {
currentCount = 1;
}
if (currentCount > maxCount) {
maxCount = currentCount;
sequenceStart = i + 1 - maxCount;
}
}
jsConsole.writeLine('The maximal sequence of equals is: ');
for (i = sequenceStart; i < sequenceStart + maxCount; i+=1) {
jsConsole.write(arr[i]);
if (!(i === sequenceStart + maxCount - 1)) {
jsConsole.write(', ')
}
}
|
/* ========================================================================= */
/* Preloader
/* ========================================================================= */
jQuery(window).load(function(){
$("#preloader").fadeOut("slow");
});
/* ========================================================================= */
/* Welcome Section Slider
/* ========================================================================= */
$(function() {
var Page = (function() {
var $navArrows = $( '#nav-arrows' ),
$nav = $( '#nav-dots > span' ),
slitslider = $( '#slider' ).slitslider( {
onBeforeChange : function( slide, pos ) {
$nav.removeClass( 'nav-dot-current' );
$nav.eq( pos ).addClass( 'nav-dot-current' );
}
} ),
init = function() {
initEvents();
},
initEvents = function() {
// add navigation events
$navArrows.children( ':last' ).on( 'click', function() {
slitslider.next();
return false;
} );
$navArrows.children( ':first' ).on( 'click', function() {
slitslider.previous();
return false;
} );
$nav.each( function( i ) {
$( this ).on( 'click', function( event ) {
var $dot = $( this );
if( !slitslider.isActive() ) {
$nav.removeClass( 'nav-dot-current' );
$dot.addClass( 'nav-dot-current' );
}
slitslider.jump( i + 1 );
return false;
} );
} );
};
return { init : init };
})();
Page.init();
});
$(document).ready(function(){
/*Prodecimiento de carga de proyectos en otra página del sitio web */
$("#pro1").click(function(){
$(this).attr("href","index.php/proyectos/proy/proyecto1");
});
$("#pro2").click(function(){
$(this).attr("href","index.php/proyectos/proy/proyecto2");
});
$("#pro3").click(function(){
$(this).attr("href","index.php/proyectos/proy/proyecto3");
});
$("#pro4").click(function(){
$(this).attr("href","index.php/proyectos/proy/proyecto4");
});
$("#pro5").click(function(){
$(this).attr("href","index.php/proyectos/proy/proyecto5");
});
$("#pro6").click(function(){
$(this).attr("href","index.php/proyectos/proy/proyecto6");
});
/* ========================================================================= */
/* Menu item highlighting
/* ========================================================================= */
jQuery('#nav').singlePageNav({
offset: jQuery('#nav').outerHeight(),
filter: ':not(.external)',
speed: 2000,
currentClass: 'current',
easing: 'easeInOutExpo',
updateHash: true,
beforeStart: function() {
console.log('begin scrolling');
},
onComplete: function() {
console.log('done scrolling');
}
});
$(window).scroll(function () {
if ($(window).scrollTop() > 400) {
$(".navbar-brand a").css("color","#fff");
$("#navigation").removeClass("animated-header");
} else {
$(".navbar-brand a").css("color","inherit");
$("#navigation").addClass("animated-header");
}
});
/* ========================================================================= */
/* Fix Slider Height
/* ========================================================================= */
// Slider Height
var slideHeight = $(window).height();
$('#home-slider, #slider, .sl-slider, .sl-content-wrapper').css('height',slideHeight);
$(window).resize(function(){'use strict',
$('#home-slider, #slider, .sl-slider, .sl-content-wrapper').css('height',slideHeight);
});
$("#works, #testimonial").owlCarousel({
navigation : true,
pagination : false,
slideSpeed : 700,
paginationSpeed : 400,
singleItem:true,
navigationText: ["<i class='fa fa-angle-left fa-lg'></i>","<i class='fa fa-angle-right fa-lg'></i>"]
});
/* ========================================================================= */
/* Featured Project Lightbox
/* ========================================================================= */
$(".fancybox").fancybox({
padding: 0,
openEffect : 'elastic',
openSpeed : 650,
closeEffect : 'elastic',
closeSpeed : 550,
closeClick : true,
beforeShow: function () {
this.title = $(this.element).attr('title');
this.title = '<h3>' + this.title + '</h3>' + '<p>' + $(this.element).parents('.portfolio-item').find('img').attr('alt') + '</p>';
},
helpers : {
title : {
type: 'inside'
},
overlay : {
css : {
'background' : 'rgba(0,0,0,0.8)'
}
}
}
});
});
/* ========== START GOOGLE MAP ========== */
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);
function init() {
// Basic options for a simple Google Map
// For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
var myLatLng = new google.maps.LatLng(13.974861, -89.706174);
var mapOptions = {
zoom: 15,
center: myLatLng,
disableDefaultUI: true,
scrollwheel: false,
navigationControl: true,
mapTypeControl: false,
scaleControl: false,
draggable: true,
// How you would like to style the map.
// This is where you would paste any style found on Snazzy Maps.
styles: [{
featureType: 'water',
stylers: [{
color: '#46bcec'
}, {
visibility: 'on'
}]
}, {
featureType: 'landscape',
stylers: [{
color: '#f2f2f2'
}]
}, {
featureType: 'road',
stylers: [{
saturation: -100
}, {
lightness: 45
}]
}, {
featureType: 'road.highway',
stylers: [{
visibility: 'simplified'
}]
}, {
featureType: 'road.arterial',
elementType: 'labels.icon',
stylers: [{
visibility: 'off'
}]
}, {
featureType: 'administrative',
elementType: 'labels.text.fill',
stylers: [{
color: '#444444'
}]
}, {
featureType: 'transit',
stylers: [{
visibility: 'off'
}]
}, {
featureType: 'poi',
stylers: [{
visibility: 'off'
}]
}]
};
// Get the HTML DOM element that will contain your map
// We are using a div with id="map" seen below in the <body>
var mapElement = document.getElementById('map-canvas');
// Create the Google Map using our element and options defined above
var map = new google.maps.Map(mapElement, mapOptions);
// Let's also add a marker while we're at it
var marker = new google.maps.Marker({
position: new google.maps.LatLng(13.974861, -89.706174),
map: map,
icon: 'img/icons/map-marker.png',
});
}
// ========== END GOOGLE MAP ========== //
var wow = new WOW ({
offset: 75, // distance to the element when triggering the animation (default is 0)
mobile: false, // trigger animations on mobile devices (default is true)
});
wow.init();
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = '5.0.0-pre.9';
//# sourceMappingURL=version.js.map
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.2.3.6-3-86
description: >
Object.defineProperty - 'Attributes' is a Function object which
implements its own [[Get]] method to access the 'configurable'
property (8.10.5 step 4.a)
includes: [runTestCase.js]
---*/
function testcase() {
var obj = {};
var funObj = function (a, b) {
return a + b;
};
funObj.configurable = true;
Object.defineProperty(obj, "property", funObj);
var beforeDeleted = obj.hasOwnProperty("property");
delete obj.property;
var afterDeleted = obj.hasOwnProperty("property");
return beforeDeleted === true && afterDeleted === false;
}
runTestCase(testcase);
|
define([
'jquery',
'underscore',
'backbone',
], function($, _, Backbone) {
var ItemView = Backbone.Marionette.View.extend({
className : 'row',
/**
*
*/
template : _.template('<li><div class="col-lg-8 text-left"><%=common.truncateString (title, 25, "..") %></div><div class="col-lg-4"><label class="label app-hand label-default" id="on">Oui</label><label class="label app-hand label-danger" id="off">Non</label></div>'),
/**
*
*/
events : {
'click #on' : 'selectMe',
'click #off' : 'deselectMe',
},
initialize: function() {
},
/**
*
*/
render: function() {
this.$el.html(this.template(_.extend(this.model.toJSON())));
return this;
},
/**
*
*/
selectMe : function (e){
this.$el.find('label#on').removeClass('label-default').addClass('label-success');
this.$el.find('label#off').removeClass('label-danger').addClass('label-default');
e.stopImmediatePropagation();
},
/**
*
*/
deselectMe : function (e){
this.$el.find('label#on').removeClass('label-success').addClass('label-default');
this.$el.find('label#off').addClass('label-danger').removeClass('label-default');
e.stopImmediatePropagation();
},
});
var CourseListView = Backbone.Marionette.CompositeView.extend({
/**
*
*/
template : _.template(""),
/**
*
*/
className : '',
/**
*
* @param {Object} collectionView
* @param {Object} itemView
*/
initialize: function(options){
this.$el = options.$container ;
},
/**
*
*/
itemView : ItemView,
/**
*
* @param {Object} collectionView
* @param {Object} itemView
*/
appendHtml: function(collectionView, itemView, index){
this.$el.append(itemView.el);
},
/**
*
*/
close : function (){
this.remove ();
}
});
return CourseListView;
});
|
/** @flow */
import type { Evaluator } from './evaluator';
import type { BodyEntries } from '../target';
import * as Syntax from '../syntax';
import { NodeEvaluator } from './evaluator';
export class ConditionalEvaluator extends NodeEvaluator {
static tags = ['conditional'];
node: Syntax.ConditionalOperator;
constructor(parent: Evaluator, node: Syntax.ConditionalOperator) {
super(parent);
this.node = node;
}
evaluate(...args: any[]) {
this.coder.conditional(
this.defer(this.node.condition),
this.defer(this.node.trueResult),
this.defer(this.node.falseResult),
);
}
}
class IfGeneratingEvaluator extends NodeEvaluator {
generateIf(condition: Function, thenStatements: Syntax.Statements,
elseStatements: Syntax.Statements) {
const thens = thenStatements.isEmpty() ? null : thenStatements;
const elses = elseStatements.isEmpty() ? null : elseStatements;
this.coder.ifStatement(
condition,
thens ? () => { this.dispatch(thens); } : null,
elses ? () => { this.dispatch(elses); } : null,
);
}
}
export class IfEvaluator extends IfGeneratingEvaluator {
static tags = ['if'];
node: Syntax.IfStatement;
constructor(parent: Evaluator, node: Syntax.IfStatement) {
super(parent);
this.node = node;
}
evaluate(...args: any[]) {
this.generateIf(
this.defer(this.node.condition),
this.node.thenStatements,
this.node.elseStatements,
);
}
}
export class IfLetEvaluator extends IfGeneratingEvaluator {
static tags = ['ifLet'];
node: Syntax.IfLetStatement;
constructor(parent: Evaluator, node: Syntax.IfLetStatement) {
super(parent);
this.node = node;
}
evaluate(...args: any[]) {
const some = this.coder.runtimeImport('isSomething');
const letStatement = this.node.condition;
this.dispatch(letStatement);
const { assignments } = letStatement;
const conditions: BodyEntries = [];
assignments.forEach((assignment) => {
assignment.getIdentifiers().forEach((id) => {
conditions.push(
this.coder.code(() => {
this.coder.call(some, [
() => {
this.coder.getter(id.value);
},
]);
}),
);
});
});
this.generateIf(
() => {
this.coder.writeAndGroup(conditions);
},
this.node.thenStatements,
this.node.elseStatements,
);
}
}
|
import mapStateToProps from '../map-state-to-props';
function getDefault(first) {
// coercive equality used to test for null as well.
// noinspection EqualityComparisonWithCoercionJS
return first == undefined ? [] : first;
}
export function discardNullOrEmpty(first, second) {
first = getDefault(first);
second = getDefault(second);
if (first.length + second.length === 0) {
return undefined;
}
if (first.length) {
if (second.length) {
return false;
}
return first;
}
return second;
}
export default function (stateDefs, curry) {
stateDefs = getDefault(stateDefs);
curry = getDefault(curry);
if (!(typeof stateDefs === 'string' || Array.isArray(stateDefs))) {
throw new TypeError(`"stateDefs" must be an array or a string, instead got ${typeof stateDefs}`);
}
if (!(typeof curry === 'string' || Array.isArray(curry))) {
throw new TypeError(`"curry" must be an array or a string, instead got ${typeof curry}`);
}
if (stateDefs.length + curry.length === 0) {
return mapStateToProps;
}
return function (state, props) {
let remnant = discardNullOrEmpty(stateDefs, props.getFromState);
props.getFromState = remnant !== false ? remnant : [].concat(props.getFromState).concat(stateDefs);
remnant = discardNullOrEmpty(curry, props.curryActionsWith);
props.curryActionsWith = remnant !== false ? remnant : [...props.curryActionsWith, ...curry];
return mapStateToProps(state, props);
};
}
|
import React, { Component } from 'react';
import {scaleLinear} from 'd3-scale';
import {
Crosshair,
HorizontalGridLines,
MarkSeries,
VerticalGridLines,
XAxis,
XYPlot,
YAxis,
Voronoi
} from 'react-vis';
export default class DynamicCrosshairScatterplot extends Component {
state = {
data: this.props.datas,
selectedPointId: null,
showVoronoi: false,
x: scaleLinear().domain(this.props.xDomain).range(this.props.xRange),
y: scaleLinear().domain(this.props.yDomain).range(this.props.yRange),
}
_onNearestXY = (value, {index}) => {
this.setState({selectedPointId: index});
}
_onMouseLeave = () => {
this.setState({selectedPointId: null});
}
render() {
const {data, selectedPointId, showVoronoi, x, y} = this.state;
const { width, height, extent, sizeRange } = this.props;
return (
<div className="isoChartWrapper">
<div className="isoChartControl">
<label style={{display: 'block'}}>
<input type="checkbox"
checked={showVoronoi}
onChange={e => this.setState({showVoronoi: !showVoronoi})}
style={{marginRight: '5px'}}
/>
Show Voronoi
</label>
</div>
<XYPlot
onMouseLeave={this._onMouseLeave}
width={width}
height={height}>
<VerticalGridLines />
<HorizontalGridLines />
<XAxis />
<YAxis />
<MarkSeries
className="mark-series-example"
colorType="literal"
data={data.map((point, index) =>
({...point, color: selectedPointId === index ? '#FF9833' : '#12939A'}))}
onNearestXY={this._onNearestXY}
sizeRange={sizeRange} />
<Crosshair values={this.state.crosshairValues}/>
<Voronoi
extent={extent}
nodes={data}
polygonStyle={{stroke: showVoronoi ? 'rgba(0, 0, 0, .2)' : null}}
x={d => x(d.x)}
y={d => y(d.y)}
/>
</XYPlot>
</div>
);
}
}
|
'@mixin'['MixinInReq'] = {
'1.First step': function () {
act.click(function () {
return '#test'
}, {
alt: true,
ctrl: false
});
},
'2.Check': inIFrame('#frame', function () {
notEq(document.getElementById('#yo'), 1);
ok(true);
})
};
function someMethod() {
notEq(this.prevCssClass, getRoundPanel().attr("class"));
eq(dx.checkBox("chkNoHeaderViewSwitch").inst.GetChecked(), isRoundPanelHeaderVisible());
}
|
module.exports = {
title: 'React Hooks'
}
|
angular.module('PetAppUI').factory('PetFactory', function($http, ServerUrl, $routeParams) {
var pets = [];
var fetch = function() {
$http.get(ServerUrl + '/pets').success(function(response) {
angular.copy(response, pets);
});
};
return {
pets: pets,
fetch: fetch
};
var getPet = function() {
$http.get(ServerUrl + '/pets/' + $routeParams.petId).success(function(response) {
$scope.pet = response;
});
};
});
|
import React, { Component, PropTypes} from 'react';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
export default class LoginError extends Component{
componentDidMount = () => {
setTimeout( () => this.props.clearLoginError(), 2000)
}
render(){
return(
<ReactCSSTransitionGroup transitionName='example' transitionAppear={true} transitionEnterTimeout={500} transitionLeaveTimeout={300}>
<div className= 'text-center expanded' style={{backgroundColor:'#ffb3b3'}}>
{this.props.loginError}
</div>
</ReactCSSTransitionGroup>
)
}
}
LoginError.PropTypes ={
loginError: PropTypes.string.isRequired,
clearLoginError: PropTypes.func.isRequired
}
|
import * as actions from './actions'
export default actions
export reducer from './reducer'
export withNotifications from './components/withNotifications'
export Notifications from './components/Notifications'
export * as actionTypes from './actionTypes'
|
// a.js includes b.js and c.js
// b.js includes c.js
function Annie() {
return 'A';
}
// This comment is added to test an issue
INCLUDE('b');
function Caitlyn() {
var c = INCLUDE('c');
return INCLUDE('c') + c;
}
exports.ABC = Annie() + Blitzcrank() + Caitlyn();
|
OnlineStatusModel = new Mongo.Collection('fisOnlineStatus');
OrbitActivitiesModel = new Mongo.Collection('fisOrbitActivities');
//security policies
if (Meteor.isServer) {
OnlineStatusModel.allow({
insert: function () {
return false;
},
update: function () {
return false;
},
remove: function () {
return false;
}
});
OrbitActivitiesModel.allow({
insert: function () {
return false;
},
update: function () {
return false;
},
remove: function () {
return false;
}
});
//TODO REMOVE IF NOT NECESSARY
Meteor.publish('fisOnlineStatus', function () {
return OnlineStatusModel.find();
});
Meteor.publish('fisOrbitActivities', function () {
if (this.userId) {
return OrbitActivitiesModel.find();
} else {
return [];
}
});
Meteor.methods({
getActivitiesPerOrbit: function (start, end) {
var orbit = OrbitsModel.findOne({start:{$gte:(start-1000*60*10)}, end:{$lte:(end+1000*60*10)}});
if (orbit != null) {
var orbitData = OrbitActivitiesModel.find({orbitId: orbit.orbitId}).fetch();
return orbitData;
} else {
console.error("Can't find orbit between %s and %s", start, end);
return [];
}
}
})
}
|
/**
* Created by Daniel on 2017-04-13.
*/
const jwt = require('jsonwebtoken');
const User = require('mongoose').model('User');
import config from '../config';
/**
* The Auth Checker middleware function.
*/
module.exports = (req, res, next) => {
if (!req.headers.authorization) {
return res.status(401).end();
}
// get the last part from a authorization header string like "bearer token-value"
const token = req.headers.authorization.split(' ')[1];
// decode the token using a secret key-phrase
return jwt.verify(token, config.jwtSecret, (err, decoded) => {
// the 401 code is for unauthorized status
if (err) {
return res.status(401).end();
}
const userId = decoded.sub;
// check if a user exists
return User.findById(userId, (userErr, user) => {
if (userErr || !user) {
return res.status(401).end();
} else {
req.session.currentUserID = user._id;
req.session.currentUserName = user.name;
req.session.currentUserEmail = user.email;
return next();
}
});
});
};
|
import React from 'react';
import * as RB from 'react-bootstrap';
export default class Topic extends React.Component {
static propTypes = {
}
render() {
return (
<div>
<RB.Input type='text' value={this.props.topicName} onChange={this.props.handleTopicChange} />
<RB.Button onClick={this.props.handleResetVotes}>Reset Votes</RB.Button>
</div>
);
}
}
|
import map from 'lodash/map'
import React, { Component } from 'react'
import { Helmet } from 'react-helmet'
import LetterheadCard from '../components/LetterheadCard'
import letterheadData from '../data/letterheadData'
import { logPageView } from '../utils/analytics'
class Letterhead extends Component {
componentDidMount = () => {
logPageView()
}
render () {
return (
<div className='container'>
<Helmet>
<title>Letterhead | Resource Center</title>
</Helmet>
<div className='row flow-text'>
<div className='col s12'>
<h2 style={{ marginBottom: 0 }}>Letterhead</h2>
</div>
<div className='col s12'>
<p>
Father Sean Sheridan, TOR, has approved an official Franciscan
University letter-writing style he would like all departments to
adopt when writing University correspondence on electronic or
printed University letterhead. Please review the sample letter and
letter-writing instructions provided here for assistance.
</p>
<p>
We have provided an electronic letterhead template for your use.
For print correspondence, we ask that you order official
University letterhead on quality paper stock from Victoria Bell,
Print Services Manager, Mail and Print Services Office (<a href='mailto:vbell@franciscan.edu'>vbell@franciscan.edu</a>/<a href='tel:17402846354'>740-283-6354</a>).
</p>
</div>
</div>
<div className='row'>
{map(letterheadData, ({ image, title, url, actionText }, key) => {
return (
<LetterheadCard
key={key}
title={title}
actionText={actionText}
image={image}
url={url}
/>
)
})}
</div>
</div>
)
}
}
export default Letterhead
|
import {
default as expect,
} from "expect";
import * as event from "./google.maps.event.mock";
export class Map {
constructor (domEl, options) {
}
setOptions (nextOptions) {
}
setZoom (nextZoom) {
}
}
export {event};
|
var chating_enabled = false;
var drawing_enabled = false;
// Connect to the Node.js Server
io = io.connect('/office');
io.on('connect',function(data){
console.log("I guess that connection worked!");
/* Check if you can initialize the ChatingManager */
if(typeof ChatingManager == 'function')
{
cm = new ChatingManager();
if(cm.init_manager)
{
chating_enabled = true;
}
}
else
{
console.error("Chating Manager is not enabled, chat function is going to be disabled for the Office.");
}
/* Check if you can initialize the DrawingManager */
if(paper !== undefined && typeof DrawingManager == 'function')
{
var canvas = document.getElementById("draw");
paper.setup(canvas);
dm = new DrawingManager();
if(dm.init_manager)
{
drawing_enabled = true;
}
}
else
{
console.error("Drawing Manager is not enabled or paper.js is not found, drawing function is going to be disabled for the Office.");
}
});
io.socket.of("/office").on('connect_failed',function(reason)
{
/* Should redirect to the login page */
console.error("Connect Failed event: "+reason);
window.location.replace("/");
});
io.socket.of("/office").on('error',function(reason)
{
/* Should redirect to the login page */
console.error("Error event: "+reason);
window.location.replace("/");
});
io.on('error', function (error)
{
showStartPage();
cm.clearText();
dm.clearCanvas();
console.log('Error: '+error.error);
});
// console log a message and the events data
io.on('office', function (data, callback)
{
switch(data.type)
{
case "General":
if(data.phase == "register_ok")
{
showMainPage();
}
else if(data.phase == "register_nok")
{
alert(data.message);
showStartPage();
}else if(data.phase == "not_allowed")
{
alert(data.message);
dm.clearCanvas();
clearTextHistory();
showStartPage();
}
else if(data.phase == "announcement")
{
cm.writeGeneralMessages("<em>"+data.message+"</em>");
}
else if(data.phase == "user_data")
{
alert("Hello "+data.user);
console.log("Hello "+data.user);
}
break;
case "Options":
if(data.phase == "get_opts")
{
if(data.breadcrumb != undefined && data.items != undefined)
{
clearTextOptions();
jQuery(".opt_panel#options").html(data.breadcrumb+loadOptions(data.items));
}
}
break;
case "Room_List":
if(data.phase == "update_list")
{
console.log("The list of offices:");
console.log(data.list);
jQuery("#select_room").children().not("[value=create]").remove();
for(var i = 0; i < data.list.length; i++)
{
var temp_room = data.list[i];
var option = document.createElement("option");
jQuery(option).val(temp_room.id).text(temp_room.name);
jQuery("#select_room").append(option);
}
}
break;
case "Chat":
if(chating_enabled)
{
textarea = document.getElementById("text_history");
if(textarea)
{
cm.writeUserMessage(data);
}
}
break;
case "Draw":
if(drawing_enabled)
{
dm.manageDrawing(data, callback);
}
break;
}
});
// Ask for the menu
io.emit("menu", {phase: "main"});
// Actions
function tryRegister()
{
var password_input = jQuery("input#register_password");
var office = jQuery("select#select_room");
if(password_input && office)
{
var data = {
pass: password_input.val(),
office_num: office.val()
};
console.log(data);
io.emit("register", data);
}
jQuery("input#register_password").val("");
}
function logout()
{
io.emit("logout",{});
}
function clearTextOptions()
{
jQuery(".opt_panel#options").html("");
}
function showStartPage()
{
jQuery("div#register").show();
jQuery("div#room_list").show();
jQuery("div#drawing").hide();
jQuery("div#chatting").hide();
}
function showMainPage()
{
jQuery("div#register").hide();
jQuery("div#room_list").hide();
jQuery("div#drawing").show();
jQuery("div#chatting").show();
}
function loadOptions(data)
{
var html = "";
for(var i = 0; i < data.length; i++)
{
html += data[i]+ "<br/><br/>";
}
return html;
}
function kickUser(user)
{
io.emit('kick', {user: jQuery(user).val()});
}
|
// -----------------------------------------
// Backbone Multi-router
// Enables multiple independent routers which
// each match one or more routes.
//
// Author: Tim Griesser
// License: MIT
// -----------------------------------------
(function(root, factory) {
// Set up Backbone appropriately for the environment. Start with AMD.
if (typeof define === 'function' && define.amd) {
define(['backbone', 'underscore'], factory);
// Next for Node.js or CommonJS. jQuery may not be needed as a module.
} else if (typeof exports !== 'undefined') {
factory(require('backbone'), require('underscore'));
// Finally, as a browser global.
} else {
factory(root.Backbone, root._);
}
}(this, function(Backbone, _) {
Backbone.history.handlers = {};
var Router = Backbone.Router;
Backbone.Router = Backbone.Router.extend({
constructor: function() {
this.cid = _.uniqueId('c');
Router.apply(this, arguments);
}
});
Backbone.Router.prototype.route = function() {
Backbone.history.cid = this.cid;
Router.prototype.route.apply(this, arguments);
Backbone.history.cid = null;
return this;
};
Backbone.history.route = function(route, callback) {
if (!this.cid) throw new Error('The history route method must be called from the router.');
(this.handlers[this.cid] || (this.handlers[this.cid] = [])).unshift({route: route, callback: callback});
};
Backbone.history.loadUrl = function(fragmentOverride) {
var fragment = this.fragment = this.getFragment(fragmentOverride);
return _.any(_.map(this.handlers, function(handlers) {
return _.any(handlers, function(handler) {
if (handler.route.test(fragment)) {
handler.callback(fragment);
return true;
}
});
}));
};
return Backbone.Router;
}));
|
var grunt = require("grunt");
var loader = require("../lib/loader");
module.exports.loader = {
load: function (test) {
test.expect(8);
var part1 = loader.load("part1", "tests/parts/", grunt, {}),
part2 = loader.load("part2", "tests/parts/", grunt, {});
test.equal(part1.concat.styles.src.length, 4, "After load with dependencies, part1 must contain 4 files in concat styles src array");
test.equal(part1.concat.scripts.src.length, 6, "After load with dependencies, part1 must contain 6 files in concat scripts src array");
test.equal(part1.concat.libs.src.length, 3, "After load with dependencies, part1 must contain 3 files in libs src array");
test.equal(part1.build.default.length, 3, "After load with dependencies, part1 must contain 3 sub tasks in build default task");
test.equal(part2.concat.styles.src.length, 6, "After load with dependencies, part2 must contain 6 files in concat styles src array");
test.equal(part2.concat.scripts.src.length, 7, "After load with dependencies, part2 must contain 7 files in concat scripts src array");
test.equal(part2.concat.libs.src.length, 4, "After load with dependencies, part2 must contain 4 files in libs src array");
test.equal(part2.build.default.length, 4, "After load with dependencies, part2 must contain 4 sub tasks in lbuild default task");
test.done();
}
};
|
//document.getElementById('wrap').style.height = (window.innerHeight) + "px";
$(document).ready(function() {
$('select').material_select();
$('.tooltipped').tooltip({delay: 50});
$('textarea#description, textarea#method').characterCounter();
$('.carousel').carousel();
});
$('.recipes').dropdown();
$('.dropdown-button').dropdown();
(function($){
$(function(){
$('.button-collapse').sideNav();
$('.parallax').parallax();
}); // end of document ready
})(jQuery); // end of jQuery name space
/* $(function() {
$('textarea').froalaEditor({
// Set custom buttons with separator between them.
toolbarButtons: ['fullscreen','undo', 'redo' , '|', 'bold', 'italic', 'underline', 'formatOL', 'formatUL', 'clearFormatting', '|', 'help', '|', 'html'],
// toolbarButtonsXS: ['undo', 'redo' , 'bold', 'italic', 'underline']
});
}); */
|
function layout() {
var menu = $('#layout_menu'),
menuToggle = $('#layout_menu_toggle'),
nav = $('body > main > nav'),
article = $('body > main > article'),
main = $('body > main'),
dropdowns = $('.dropdown');
menuToggle.click(function() {
menu.toggleClass('showing');
menuToggle.toggleClass('icon-close');
});
nav.click(function() {
main.toggleClass('nav-showing');
});
article.click(function() {
main.removeClass('nav-showing');
})
dropdowns.click(function(event) {
var dropdown = $(this);
var isOpen = dropdown.hasClass('dropdown-open');
dropdowns.removeClass('dropdown-open');
if (!isOpen) {
dropdown.addClass('dropdown-open');
event.stopPropagation();
$(document).click(function() {
dropdown.removeClass('dropdown-open');
});
}
});
dropdowns.children('ul').click(function() {
var dropdown = $(this);
dropdown.removeClass('dropdown-open');
});
dropdowns.children('ul').children('li').click(function() {
var dropdownItem = $(this);
dropdownItem.siblings().removeClass('dropdown-selected');
dropdownItem.addClass('dropdown-selected');
});
}
layout();
|
import welcomeRequest from './welcome'
export {
welcomeRequest
}
|
(function(insight) {
/**
* The BarSeries is an abstract base class for columns and rows.
* @constructor
* @extends insight.Series
* @param {String} name - A uniquely identifying name for this series
* @param {insight.DataProvider | Object[]} data - An object which contains this series' data
* @param {insight.Axis} x - The x axis
* @param {insight.Axis} y - The y axis
*/
insight.BarSeries = function BarSeries(name, data, x, y) {
insight.Series.call(this, name, data, x, y);
// Private variables ------------------------------------------------------------------------------------------
var self = this;
// Internal variables -------------------------------------------------------------------------------------------
self.valueAxis = undefined;
self.keyAxis = undefined;
self.classValues = [insight.constants.BarGroupClass];
// Private functions ------------------------------------------------------------------------------------------
function tooltipFunction(d) {
return self.tooltipFormat()(self.valueFunction()(d));
}
function duration(d, i) {
return 200 + (i * 20);
}
function opacity() {
// If we are using selected/notSelected, then make selected more opaque than notSelected
if (d3.select(this).classed('notselected')) {
return 0.5;
}
//If not using selected/notSelected, make everything opaque
return 1;
}
function seriesSpecificClassName(d) {
var additionalClass = ' ' + self.name + 'class';
var baseClassName = self.itemClassName(d);
var itemClassName = baseClassName + additionalClass;
return itemClassName;
}
// Internal functions -----------------------------------------------------------------------------------------
self.isHorizontal = function() {
return undefined;
};
self.barLength = function(d, plotHeight) {
return undefined;
};
self.valuePosition = function(d) {
return undefined;
};
self.draw = function(chart) {
self.tooltip = chart.tooltip;
self.selectedItems = chart.selectedItems;
var groupSelector = 'g.' + self.name + '.' + insight.constants.BarGroupClass,
barSelector = 'rect.' + self.shortClassName();
var data = self.dataset();
var visibleBars = self.keyAxis.domain();
data = data.filter(function(d) {
var key = self.keyFunction()(d);
return insight.utils.arrayContains(visibleBars, key);
});
var groups = chart.plotArea
.selectAll(groupSelector)
.data(data, self.keyFunction());
var newGroups = groups.enter()
.append('g')
.classed(self.name, true)
.classed(insight.constants.BarGroupClass, true);
var newBars = newGroups.selectAll(barSelector);
newGroups.append('rect')
.attr('class', self.itemClassName)
.attr('in_series', self.name)
.attr('fill', self.color)
.attr('clip-path', 'url(#' + chart.clipPath() + ')')
.on('mouseover', self.mouseOver)
.on('mouseout', self.mouseOut)
.on('click', self.click);
var seriesTypeCount = chart.countSeriesOfType(self);
var seriesIndex = chart.seriesIndexByType(self);
var groupIndex = 0;
var height = (self.isHorizontal()) ? barBreadth : barLength;
var width = (self.isHorizontal()) ? barLength : barBreadth;
var xPosition = (self.isHorizontal()) ? self.valuePosition : keyPosition;
var yPosition = (self.isHorizontal()) ? keyPosition : self.valuePosition;
// Select and update all bars
var allBars = groups.selectAll(barSelector);
allBars.attr('class', self.itemClassName);
allBars.transition()
.duration(duration)
.attr('x', xPosition)
.attr('y', yPosition)
.attr('height', height)
.attr('width', width)
.style('opacity', opacity);
groups.exit().remove();
// draw helper functions ------------------------------------
function groupHeight(d) {
return self.keyAxis.scale.rangeBand(d);
}
function barBreadth(d) {
var heightOfGroup = groupHeight(d);
var breadth = heightOfGroup / seriesTypeCount;
return breadth;
}
function barLength(d) {
var plotHeight = (chart.height() - chart.margin().top - chart.margin().bottom);
return self.barLength(d, plotHeight);
}
function keyPosition(d) {
var groupPositions = self.keyAxis.scale.range();
var groupPos = groupPositions[groupIndex];
var barWidth = width(d);
var position = groupPos + (barWidth * (seriesTypeCount - seriesIndex - 1));
groupIndex++;
return position;
}
};
};
insight.BarSeries.prototype = Object.create(insight.Series.prototype);
insight.BarSeries.prototype.constructor = insight.BarSeries;
})(insight);
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.2.3.7-6-a-273
description: >
Object.defineProperties - 'O' is an Array, 'P' is generic own data
property of 'O', test TypeError is thrown when updating the
[[Configurable]] attribute value of 'P' which is defined as
non-configurable (15.4.5.1 step 5)
includes: [propertyHelper.js]
---*/
var arr = [];
Object.defineProperty(arr, "property", {
value: 12
});
try {
Object.defineProperties(arr, {
"property": {
configurable: true
}
});
$ERROR("Expected an exception.");
} catch (e) {
verifyEqualTo(arr, "property", 12);
verifyNotWritable(arr, "property");
verifyNotEnumerable(arr, "property");
verifyNotConfigurable(arr, "property");
if (!(e instanceof TypeError)) {
$ERROR("Expected TypeError, got " + e);
}
}
|
var request = require('request'),
fs = require('fs'),
filePath = 'articles.json',
previousMaxItem = JSON.parse(fs.readFileSync(filePath, 'utf8')).maxItem || 8453151,
maxItem;
request('https://hacker-news.firebaseio.com/v0/maxitem.json?print=pretty', function (error, response, body) {
if (!error && response.statusCode == 200) {
maxItem = parseInt(body, 10);
fs.writeFileSync(filePath, JSON.stringify({maxItem: maxItem}, null, 2));
if(previousMaxItem < maxItem) {
makeRequest(previousMaxItem + 1, maxItem);
}
}
});
function makeRequest(currentItem, maxItem) {
var url = 'https://hacker-news.firebaseio.com/v0/item/' + currentItem + '.json?print=pretty';
request(url, (function(currentItem) {
return function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(JSON.parse(body).type);
}
console.log(currentItem);
if (currentItem < maxItem) {
makeRequest(currentItem + 1, maxItem);
}
}
} )(currentItem));
}
|
let john = "john";
console.log(john);
let bruh = "bruh";
console.log(bruh);
let singleton = num => num+1;
|
// --------- This code has been automatically generated !!! 2015-08-18T22:56:50.737Z
require("requirish")._(module);
var registerObject = require("lib/misc/factories").registerObject;
registerObject('SessionDiagnostics');
var SessionDiagnostics = require("_generated_/_auto_generated_SessionDiagnostics").SessionDiagnostics;
exports.SessionDiagnostics = SessionDiagnostics;
|
/* jshint expr:true */
import {expect} from 'chai'
import hbs from 'htmlbars-inline-precompile'
import {describe, it} from 'mocha'
import {integration} from 'dummy/tests/helpers/ember-test-utils/setup-component-test'
const test = integration('frost-viz/plot/element/symbol/star')
describe(test.label, function () {
test.setup()
it('renders', function () {
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
// Template block usage:
// this.render(hbs`
// {{#frost-viz/plot/element/symbol/star}}
// template content
// {{/frost-viz/plot/element/symbol/star}}
// `);
this.render(hbs`{{frost-viz/plot/element/symbol/star}}`)
expect(this.$()).to.have.length(1)
})
})
|
'use strict';
var utils = exports;
var BN = require('../../../BN/bn');
utils.assert = function (condition, errorMessage) {
if (!condition) {
throw new Error(errorMessage)
}
};
// Represent num in a w-NAF form
function getNAF(num, w) {
var naf = [];
var ws = 1 << (w + 1);
var k = num.clone();
while (k.cmpn(1) >= 0) {
var z;
if (k.isOdd()) {
var mod = k.andln(ws - 1);
if (mod > (ws >> 1) - 1)
z = (ws >> 1) - mod;
else
z = mod;
k.isubn(z);
} else {
z = 0;
}
naf.push(z);
// Optimization, shift by word if possible
var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
for (var i = 1; i < shift; i++)
naf.push(0);
k.iushrn(shift);
}
return naf;
}
utils.getNAF = getNAF;
// Represent k1, k2 in a Joint Sparse Form
function getJSF(k1, k2) {
var jsf = [
[],
[]
];
k1 = k1.clone();
k2 = k2.clone();
var d1 = 0;
var d2 = 0;
while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
// First phase
var m14 = (k1.andln(3) + d1) & 3;
var m24 = (k2.andln(3) + d2) & 3;
if (m14 === 3)
m14 = -1;
if (m24 === 3)
m24 = -1;
var u1;
if ((m14 & 1) === 0) {
u1 = 0;
} else {
var m8 = (k1.andln(7) + d1) & 7;
if ((m8 === 3 || m8 === 5) && m24 === 2)
u1 = -m14;
else
u1 = m14;
}
jsf[0].push(u1);
var u2;
if ((m24 & 1) === 0) {
u2 = 0;
} else {
var m8 = (k2.andln(7) + d2) & 7;
if ((m8 === 3 || m8 === 5) && m14 === 2)
u2 = -m24;
else
u2 = m24;
}
jsf[1].push(u2);
// Second phase
if (2 * d1 === u1 + 1)
d1 = 1 - d1;
if (2 * d2 === u2 + 1)
d2 = 1 - d2;
k1.iushrn(1);
k2.iushrn(1);
}
return jsf;
}
utils.getJSF = getJSF;
function cachedProperty(obj, name, computer) {
var key = '_' + name;
obj.prototype[name] = function cachedProperty() {
return this[key] !== undefined ? this[key] :
this[key] = computer.call(this);
};
}
utils.cachedProperty = cachedProperty;
function parseBytes(bytes) {
return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
bytes;
}
utils.parseBytes = parseBytes;
function intFromLE(bytes) {
return new BN(bytes, 'hex', 'le');
}
utils.intFromLE = intFromLE;
// used to convert `CryptoJS` wordArrays into `crypto` hex buffers
function wordToByteArray(word, length) {
var ba = [],
xFF = 0xFF;
if (length > 0)
ba.push(word >>> 24);
if (length > 1)
ba.push((word >>> 16) & xFF);
if (length > 2)
ba.push((word >>> 8) & xFF);
if (length > 3)
ba.push(word & xFF);
return ba;
}
function wordArrayToBuffer(wordArray) {
let length = undefined;
if (wordArray.hasOwnProperty("sigBytes") && wordArray.hasOwnProperty("words")) {
length = wordArray.sigBytes;
wordArray = wordArray.words;
} else {
throw Error('Argument not a wordArray')
}
const result = []
let bytes = []
let i = 0;
while (length > 0) {
bytes = wordToByteArray(wordArray[i], Math.min(4, length));
length -= bytes.length;
result.push(bytes);
i++;
}
return [].concat.apply([], result)
}
utils.wordArrayToBuffer = wordArrayToBuffer;
// https://github.com/indutny/minimalistic-crypto-utils/blob/master/lib/utils.js
// moved here to remove the dep
function toArray(msg, enc) {
if (Array.isArray(msg))
return msg.slice();
if (!msg)
return [];
var res = [];
if (typeof msg !== 'string') {
for (var i = 0; i < msg.length; i++)
res[i] = msg[i] | 0;
return res;
}
if (enc === 'hex') {
msg = msg.replace(/[^a-z0-9]+/ig, '');
if (msg.length % 2 !== 0)
msg = '0' + msg;
for (var i = 0; i < msg.length; i += 2)
res.push(parseInt(msg[i] + msg[i + 1], 16));
} else {
for (var i = 0; i < msg.length; i++) {
var c = msg.charCodeAt(i);
var hi = c >> 8;
var lo = c & 0xff;
if (hi)
res.push(hi, lo);
else
res.push(lo);
}
}
return res;
}
utils.toArray = toArray;
function zero2(word) {
if (word.length === 1)
return '0' + word;
else
return word;
}
utils.zero2 = zero2;
function toHex(msg) {
var res = '';
for (var i = 0; i < msg.length; i++)
res += zero2(msg[i].toString(16));
return res;
}
utils.toHex = toHex;
utils.encode = function encode(arr, enc) {
if (enc === 'hex')
return toHex(arr);
else
return arr;
};
|
var _c = _c || {};
_c.app = _c.app || {};
_c.app.views = _c.app.views || {};
(function(views) {
"use strict";
views.ExplosionView = Backbone.View.extend({
initialize: function(options) {
_.bindAll(this,
'render',
'setConstants',
'initMembers',
'animate',
'getFrames'
);
this.setConstants(options);
this.initMembers(options);
},
render: function() {
this.sprite.update(this.context, new Date()).paint(this.context);
},
setConstants: function(options) {
this.OFFSET = new _c.draw.Vector(-22, -32);
// ms to expire before moving to next image
this.PAGEFLIP_INTERVAL = 100;
this.FUSE_FRAMES = 9;
this.EXPLOSION_FRAMES = 9;
},
initMembers: function(options) {
var _this = this,
params = {
frames: this.getFrames()
};
this.context = this.el.getContext('2d');
this.lastAdvance = new Date();
this.ready = false;
this.sprite = new _c.draw.Sprite({
drawable: new _c.draw.FrameSet(params),
behaviors: [
function(context, time) {
if (time - _this.lastAdvance > _this.PAGEFLIP_INTERVAL) {
this.drawable.advance();
_this.lastAdvance = time;
context.clearRect(0, 0, _this.el.width, _this.el.height);
}
}
]
});
},
animate: function(time) {
var _this = this;
if (this.ready) {
if (this.sprite.drawable.index === this.sprite.drawable.frames.length - 1) {
this.ready = false;
setTimeout(function() {
_this.render();
}, this.PAGEFLIP_INTERVAL * 8);
}
this.render();
requestAnimationFrame(this.animate);
}
},
getFrames: function() {
var _this = this,
frames = [],
paramsArray = [],
_width = 180,
_height = 130,
corner = new _c.draw.Point(this.el.width / 2,
this.el.height / 2).offset({x: -_width / 2, y: -_height / 2});
// initial bomb image
paramsArray.push({ src: 'bomb.png' });
// fuse burning
for (var i = 0; i < this.FUSE_FRAMES; i++) {
paramsArray.push({ src: 'explosion/fuse-0' + i + '.png' });
}
// bomb no fuse
paramsArray.push({ src: 'explosion/bomb-no-fuse.png' });
// post-explosion
for (var i = 0; i < this.EXPLOSION_FRAMES; i++) {
paramsArray.push({ src: 'explosion/explosion-0' + i + '.png' });
}
paramsArray.forEach(function(params) {
params.corner = new _c.draw.Point(corner.x, corner.y),
params.width = _width,
params.height = _height,
params.onload = function(event) {
_this.ready = true;
_this.sprite.paint(_this.context);
}
frames.push(new _c.draw.Image(params));
});
return frames;
}
});
})(_c.app.views);
|
const delayEffect = (delay, effect) => {
return {
key: 'delayEffect',
params: { delay, effect }
};
};
const requireCharacter = (prop, status, effect) => {
return {
key: 'require',
params: { status, effect, prop }
};
};
const requireActorAndTarget = (statuses, effect) => {
return requireCharacter(
'actor',
statuses.actor,
requireCharacter('target', statuses.target, effect)
);
};
const delayAndRequire = (delay, statuses, effect) => {
return delayEffect(delay, requireActorAndTarget(statuses, effect));
};
const publishMessage = (type, effect) => {
return {
key: 'publishMessage',
params: { template: type, effect, type }
};
};
const createHit = ({ delay, accuracy, damage }) => {
return delayAndRequire(delay, {
actor: { isAlive: true },
target: { isAlive: true }
}, publishMessage('attack', {
key: 'attack',
params: {
prop: 'actor',
targetProp: 'target',
accuracy,
hitEffect: [
{
key: 'damage',
params: {
prop: 'actor',
targetProp: 'target',
damage
}
},
{
key: 'tilt',
params: {
targetProp: 'target',
tilt: 1
}
}
]
}
}));
};
const createAttack = ({ abilityId, actorDelay, effect }) => {
return requireActorAndTarget(
{
actor: {
isAlive: true,
isAvailable: true
},
target: { isAlive: true }
},
[
publishMessage('setActivity', {
key: 'setActivity',
params: {
prop: 'actor',
delay: actorDelay,
abilityId
}
}),
effect
]
);
};
const createHeavyPunchAbility = () => {
return {
id: 'heavyPunch',
name: 'Heavy Punch',
effect: createAttack({
abilityId: 'heavyPunch',
actorDelay: 6000,
effect: createHit({
delay: 3000,
accuracy: 100,
damage: {
type: 'physical',
power: 2
}
})
})
};
};
const createComboPunchAbility = () => {
return {
id: 'comboPunch',
name: 'Combo Punch',
effect: createAttack({
abilityId: 'comboPunch',
actorDelay: 6000,
effect: [
createHit({
delay: 2000,
accuracy: 100,
damage: {
type: 'physical',
power: -2
}
}),
createHit({
delay: 3000,
accuracy: 100,
damage: {
type: 'physical',
power: -2
}
}),
createHit({
delay: 4000,
accuracy: 100,
damage: {
type: 'physical',
power: -2
}
})
]
})
};
};
export const registerAbilities = (system) => {
const registerAbility = system.world.abilities.register;
registerAbility(createHeavyPunchAbility());
registerAbility(createComboPunchAbility());
};
|
angular.module("goRemote")
.directive('loadMore', ['', function(){
// Runs during compile
return {
scope: {},
require: '^PositionIndexController', // Array = multiple requires, ? = optional, ^ = check parent elements
restrict: 'A',
link: function($scope, iElm, iAttrs, controller) {
$scope.loadMoreData = function() {
$scope.positions = controller.get();
$('html, body').animate({
scrollTop: $(document).height()
}, 100);
}
}
};
}]);
|
'use strict';
/* Filters */
angular.module('myApp.filters', [])
.filter('interpolate', ['version', function(version) {
return function(text) {
return String(text).replace(/\%VERSION\%/mg, version);
};
}])
.filter('urlSlashEncode', function() { //$window
//return $window.encodeURIComponent; //return function
return function(text) {
var url = encodeURIComponent(text);
return url.replace(/\//g, '%252F').replace(/%2F/gi, '%252F');
}
})
.filter('urlSlashDecode', function() { //$window
return function(text) {
//var url = ''+text;
return text.replace(/%2F/gi, "/");
}
})
.filter('timestamp', function() {
return function(text, datelength) {
if (datelength==undefined) { datelength='short'; }
var response = "";
switch (datelength) {
case 'short': // i.e. 09-12-14 13:45:45
response = date('d-m-y H:i:s', new Date(text));
break;
case 'longer': // i.e. 09-12-2014 13:45:45
response = date('d-m-Y H:i:s', new Date(text));
break;
case 'long': // i.e. 09 dec 2014 13:45:45
response = date('d M Y H:i:s', new Date(text));
break;
case 'full': // i.e. 09 december 2014 13:45:45
response = date('l, d M Y H:i:s', new Date(text));
break;
default:
response = date('Y-m-d', new Date(text));
}
return response;
}
});
|
/**
* @func !help
*
* @desc Help menus for commands & command categories
*/
const settings = require('../../settings.json');
const { getGuildCommandPrefix } = require('../../handlers/GuildSettings');
const splitVal = settings.helpMenu.split_value;
exports.help = {
name: 'help',
description: 'Displays all commands available, separated by category',
usage: (bot, message) => {
const prefix = getGuildCommandPrefix(bot, message);
return [
'help [command/category]',
'\n\n',
`For more information on a specific command use "${prefix}help [command]" or "${prefix}help [category]", `,
'where [command] is any command you want to learn more about, and [category] is the category of commands',
'you want to see a list of.',
].join('');
},
};
exports.conf = {
enabled: true,
visible: true,
guildOnly: false,
textChannelOnly: false,
aliases: [settings.botName, 'commands', 'commandlist'],
permLevel: 0,
};
const checkIfCommandAvailable = (command, guildId, perms, conf) => {
const notGuild = (guildId !== conf.mainGuild && guildId !== conf.testGuild);
if (command.conf.guildOnly && notGuild) return false;
if (perms < command.conf.permLevel) return false;
return true;
};
const checkIfCommandVisible = (command, guildId, perms, conf) => {
if (!checkIfCommandAvailable(command, guildId, perms, conf)) return false;
if (!command.conf.visible) return false;
return true;
};
exports.run = (bot, message, args, perms) => {
// Set all args to lowerCase
args.forEach((arg, index) => {
args[index] = arg.toLowerCase();
});
const arg = args[1];
const dm = (message.channel.type === 'dm');
const gid = (message.channel.type === 'dm') ? 0 : message.guild.id;
const prefix = getGuildCommandPrefix(bot, message);
if (!args[1]) {
/**
* !help (no args)
* Sends main help menu
*/
let str;
const commandGroups = Array.from(bot.commandGroups.keys());
const longest = commandGroups.reduce((long, name) => Math.max(long, name.length), 0);
str = `=== Command List Categories ===\nUse "${prefix}help [category]" for the list of commands in that category\nUse "${prefix}help all" to get a list of every command.\n\n`;
bot.commandGroups.forEach((category) => {
const codeStr = category.code.join('|');
str += `${category.name}${' '.repeat(longest - category.name.length)} :: ${prefix}help ${codeStr}${' '.repeat(longest - codeStr.length)} - ${category.description}\n`;
});
return message.channel.send(str, { code: 'asciidoc' });
} if (arg === 'all') {
/**
* !help all
* Sends all available commands to the user via DM
*/
const helpUsageText = this.help.usage(bot, message);
let str = '=== Showing Every Command ==='
+ `\nFor help & info, use: ${prefix}${helpUsageText.substr(0, helpUsageText.indexOf('\n'))}\n\n`
+ `=== Category List ===\n${settings.commandGroups.map(cat => `${cat.code.join(', ')}`).join(', ')}\n\n`
+ '=== Command List ===\n';
let ac = 0;
let substr;
const substringIndexes = [];
const cmdNames = [];
bot.commands.forEach((c) => {
if (checkIfCommandVisible(c, gid, perms, settings)) {
cmdNames.push(c.help.name);
}
});
const longest = cmdNames.reduce((long, name) => Math.max(long, name.length), 0);
bot.commands.forEach((c) => {
if (checkIfCommandVisible(c, gid, perms, settings)) {
ac += 1;
if (c.conf.permLevel === 2) substr = ' (Admin only!)';
else if (c.conf.permLevel === 3) substr = ' (Server owner only!)';
else if (c.conf.permLevel === 4) substr = ' (Bot owner only!)';
else substr = '';
if (dm && c.conf.textChannelOnly) substr += ' (Doesn\'t work in DMs!)';
if (!c.conf.enabled) substr = ' (DISABLED)';
str += `${prefix}${c.help.name}${' '.repeat(longest - c.help.name.length)} :: ${c.help.description}${substr}\n`;
if (ac % splitVal === 0) {
substringIndexes.push(str.length);
} else if (ac === cmdNames.length) {
substringIndexes.push(str.length);
}
}
});
if (substringIndexes.length === 0) {
message.author.send(str, { code: 'asciidoc' });
} else {
substringIndexes.forEach((i, index) => {
if (index === 0) {
message.author.send(str.substring(0, i), { code: 'asciidoc' });
} else {
message.author.send(`=== Command List (contd.) ===\n${str.substring(substringIndexes[index - 1], i)}`, { code: 'asciidoc' });
}
});
}
return message.reply('The entire list of commands has been sent via DM.');
} if (bot.commandGroupCategories.has(arg)) {
/**
* !help [category]
* Help menu for a category
*/
const category = bot.commandGroups.get(bot.commandGroupCategories.get(arg));
const helpUsageText = this.help.usage(bot, message);
let str = `=== ${category.name} Commands ===\nCategory :: ${category.name}\nDescription :: ${category.description}\nCategory aliases :: ${category.code.join(', ')}`
+ `\n\nFor help & info, use: ${prefix}${helpUsageText.substr(0, helpUsageText.indexOf('\n'))}\n\n=== Command List ===\n`;
let substr;
const cmdsInCat = []; const cmdNames = [];
bot.commands.forEach((c) => {
if (c.conf.category === category.name) {
if (checkIfCommandVisible(c, gid, perms, settings)) {
cmdsInCat.push(c);
cmdNames.push(c.help.name);
}
}
});
const longest = cmdNames.reduce((long, name) => Math.max(long, name.length), 0);
cmdsInCat.forEach((c) => {
if (c.conf.permLevel === 2) substr = ' (ADMIN ONLY)';
else if (c.conf.permLevel === 3) substr = ' (SERVER OWNER ONLY)';
else if (c.conf.permLevel === 4) substr = ' (BOT OWNER ONLY)';
else substr = '';
if (dm && c.conf.textChannelOnly) substr += ' (Doesn\'t work in DMs!)';
if (!c.conf.enabled) substr = ' (DISABLED)';
str += `${prefix}${c.help.name}${' '.repeat(longest - c.help.name.length)} :: ${c.help.description}${substr}\n`;
});
return message.channel.send(str, { code: 'asciidoc' });
} if (bot.commands.has(arg) || bot.aliases.has(arg)) {
/**
* !help [command]
* Help menu for a command
*/
let command = bot.commands.get(arg);
if (!command) command = bot.commands.get(bot.aliases.get(arg));
let usage = '';
if (typeof command.help.usage === 'function') {
usage = command.help.usage(bot, message);
} else if (typeof command.help.usage === 'string') {
({ usage } = command.help);
}
if (checkIfCommandAvailable(command, gid, perms, settings)) {
return message.channel.send(`=== ${prefix}${command.help.name} Help Menu ===\nAliases :: ${command.conf.aliases.map(a => prefix + a).join(', ')}`
+ `\n\nDescription :: ${command.help.description}\n${(command.conf.guildOnly) ? '\n[ This command is exclusive to this server ]' : ''}`
+ `${(command.conf.textChannelOnly) ? '\n[ This command will NOT work in DMs ]' : ''}\n${(command.conf.textChannelOnly || command.conf.guildOnly) ? '\n' : ''}`
+ `How to Use :: ${prefix}${usage}`, { code: 'asciidoc' });
}
return message.reply('Sorry, you do not have permission to view that command\'s help menu.');
}
/** Nothing was found, send alert message */
return message.reply(`No command or command category **${arg}** was found. Use \`${prefix}${this.help.name}\` or ${bot.user} for a proper list of commands & categories!`);
};
|
'use strict';
/**
* Pre defined Device Types
* @see https://github.com/SteelSeries/gamesense-sdk/blob/master/doc/api/standard-zones.md#device-types
* @enum {string}
*/
gamesense.DeviceType = {
/**
* Any connected, supported keyboard. Initially the Apex M800, Apex 300, MSI GE62, and MSI GE72.
*/
KEYBOARD: 'keyboard',
/**
* Any connected, supported mouse. Initially the Rival, Dota 2 Rival, Sensei Wireless, and Sims 4 Mouse.
*/
MOUSE: 'mouse',
/**
* Any connected, supported headset. Initially the Siberia Elite line and Siberia v3 Prism.
*/
HEADSET: 'headset',
/**
* Any connected, supported simple indicator device. Initially the Sims4 Plumbob and Valve Dota 2 indicator.
*/
INDICATOR: 'indicator',
/**
* A generic specifier that applies to any connected, supported RGB device that has a static number of lighting zones.
* This can be used to apply settings to a certain zone on all of the types of devices in the list below at once.
* When using this type, a handler will be created for each type below that has the specified zone.
*/
RGB_ZONED: 'rgb-zoned-device',
/**
* Any connected, supported, single zone RGB device. Initially the Siberia Elite line, Siberia v3 Prism, and Sims 4 line.
*/
RGB_1_ZONE: 'rgb-1-zone',
/**
* Any connected, supported, dual zone RGB device. Initially the Rival mouse.
*/
RGB_2_ZONE: 'rgb-2-zone',
/**
* Any connected, supported, three zone RGB device. Initially the Sensei Wireless mouse, the MSI GE62 keyboard, and the MSI GE72 keyboard.
*/
RGB_3_ZONE: 'rgb-3-zone',
/**
* Any connected, supported, five zone RGB device. Initially the Apex 300 keyboard.
*/
RGB_5_ZONE: 'rgb-5-zone',
/**
* Any connected, supported, eight zone RGB device. Initially the Rival 600 and Rival 650 mice.
*/
RGB_8_ZONE: 'rgb-8-zone',
/**
* Any connected, supported, twelve zone RGB device. Initially the QCK Prism mousepad
*/
RGB_12_ZONE: 'rgb-12-zone',
/**
* Any connected, supported, seventeen zone RGB device. Initially the MSI Z270 Gaming Pro Carbon motherboard.
*/
RGB_17_ZONE: 'rgb-17-zone',
/**
* Any connected, supported, twenty-four zone RGB device. Initially the MSI Mystic Light.
*/
RGB_24_ZONE: 'rgb-24-zone',
/**
* Any connected, supported, one hundred three zone RGB device. Initially the MSI MPG27C and MPG27CQ monitors.
*/
RGB_103_ZONE: 'rgb-103-zone',
/**
* Any connected, supported, keyboard with a lighting zone for each key. Initially the APEX M800 keyboard.
*/
RGB_PER_KEY_ZONES: 'rgb-per-key-zones',
/**
* Any connected, supported device that supports notifications on a single OLED or LCD screen.
* Initially the Rival 700, Rival 710, Arctis Pro Wireless, and GameDAC.
*/
SCREENED: 'screened',
/**
* Currently the only supported tactile feedback device is the Rival 700, which has a single motor for the purpose.
* More zones may be introduced in the future with new devices
*/
TACTILE: 'tactile'
};
|
/*
* grunt-po-json
*
*
* Copyright (c) 2014 Nicky Out
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>',
],
options: {
jshintrc: '.jshintrc',
},
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp']
},
// Configuration to be run (and then tested).
po_json: {
default_options: {
'files': {
'tmp/default_options.json': 'test/test.po'
}
},
custom_options: {
'options': {
'amd': true
},
'files': {
'tmp/custom_options.js': {
'test': 'test/test.po',
'test2': 'test/test2.po'
}
}
},
custom_option_key: {
'options': {
'useMsgctxtAsKey': true
},
'files': {
'tmp/custom_option_key.json': 'test/test3.po'
}
}
},
// Unit tests.
nodeunit: {
tests: ['test/*_test.js']
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['clean', 'po_json', 'nodeunit']);
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint', 'test']);
};
|
/* Remember: https://mochajs.org/#arrow-functions*/
import React from 'react';
import { mount, shallow } from 'enzyme';
import sinon from 'sinon';
import UtilsHelper from "helper/utilsHelper";
import App from 'App';
import Header from 'containers/Header';
import GithubLink from 'containers/GithubLink';
import ButtonBar from 'containers/ButtonBar';
import Hints from 'containers/Hints';
import Inputs from 'containers/Input';
import Nav from 'containers/Nav';
import Sliders from 'containers/Slider';
import Toast from 'containers/Toast';
describe("Tests for app.js", () => {
describe("and we check initial", () => {
it("state object", () => {
const wrapper = shallow(<App />);
expect(wrapper.state()).to.deep.equal({
rgb: '91,50,86',
hex: '5b3256',
hue: 307,
rgbOpacity: 1,
hexOpacity: 1,
saturation: 29,
lightness: 28,
alpha: 1,
variance: 10,
type: '',
theme: 'light',
bgColour: '91,50,86,1.0',
isOpen: false,
isHandheld: false,
isDialogActive: false,
showToast: false,
toastMessage: ''
});
});
it("root element", () => {
const wrapper = shallow(<App />);
expect(wrapper.type()).to.equal('div');
expect(wrapper.prop('style')).to.deep.equal({ backgroundColor: 'rgba(91,50,86,1.0)' });
expect(wrapper.find(ButtonBar)).to.have.lengthOf(0);
expect(wrapper.find(GithubLink)).to.have.lengthOf(1);
expect(wrapper.find(Header)).to.have.lengthOf(1);
expect(wrapper.find(Hints)).to.have.lengthOf(1);
expect(wrapper.find(Inputs)).to.have.lengthOf(1);
expect(wrapper.find(Nav)).to.have.lengthOf(1);
expect(wrapper.find(Sliders)).to.have.lengthOf(1);
expect(wrapper.find(Toast)).to.have.lengthOf(1);
});
});
describe("and we check function", () => {
let wrapper, instance;
beforeEach(() => {
wrapper = shallow(<App />);
instance = wrapper.instance();
sinon.spy(instance, 'handleResizeChange');
sinon.stub(UtilsHelper, 'getScreenSize');
});
afterEach(() => {
UtilsHelper.getScreenSize.restore();
instance.handleResizeChange.restore();
});
it("handleResizeChange - small device", () => {
UtilsHelper.getScreenSize.returns({ isHandheld: true });
instance.handleResizeChange();
expect(instance.handleResizeChange.calledOnce).to.equal(true);
expect(wrapper.state()).to.deep.equal({
rgb: '91,50,86',
hex: '5b3256',
hue: 307,
rgbOpacity: 1,
hexOpacity: 1,
saturation: 29,
lightness: 28,
alpha: 1,
variance: 10,
type: '',
theme: 'light',
bgColour: '91,50,86,1.0',
isOpen: false,
isHandheld: true,
isDialogActive: false,
showToast: false,
toastMessage: ''
});
wrapper.update();
expect(wrapper.find(ButtonBar)).to.have.lengthOf(1);
expect(wrapper.find(Nav)).to.have.lengthOf(0);
});
it("handleResizeChange - large device", () => {
UtilsHelper.getScreenSize.returns({ isHandheld: false });
instance.handleResizeChange();
expect(instance.handleResizeChange.calledOnce).to.equal(true);
expect(wrapper.state()).to.deep.equal({
rgb: '91,50,86',
hex: '5b3256',
hue: 307,
rgbOpacity: 1,
hexOpacity: 1,
saturation: 29,
lightness: 28,
alpha: 1,
variance: 10,
type: '',
theme: 'light',
bgColour: '91,50,86,1.0',
isOpen: false,
isHandheld: false,
isDialogActive: false,
showToast: false,
toastMessage: ''
});
});
});
});
|
if(typeof exports === 'object') {
var assert = require("assert");
var alasql = require('..');
};
describe('Test 43', function() {
// describe('Dates', function(){
var db = new alasql.Database("test43");
it('Create database', function(done) {
// alasql('create database test43');
// alasql('use test43');
db.exec('DROP TABLE IF EXISTS orders');
db.exec('CREATE TABLE orders (orderid INT, orderdate DATE)');
// db = alasql.databases.test43;
var data = db.tables.orders.data;
data.push({orderid:1, orderdate: new Date(2014,1,1)});
data.push({orderid:2, orderdate: new Date(2012,0,5)});
data.push({orderid:3, orderdate: new Date(2014,0,1)});
data.push({orderid:4, orderdate: new Date(2014,0,3)});
data.push({orderid:5, orderdate: new Date(2013,10,12)});
data.push({orderid:6, orderdate: new Date(2014,3,28)});
data.push({orderid:7, orderdate: new Date(2014,7,6)});
data.push({orderid:8, orderdate: new Date(2013,10,12)});
done();
});
it('Order by dates ASC', function(done){
var res = db.queryArray("SELECT orderdate FROM orders ORDER BY orderdate");
var ok = res[0]<=res[1] &&
res[1]<=res[2] &&
res[2]<=res[3] &&
res[3]<=res[4] &&
res[4]<=res[5] &&
res[5]<=res[6] &&
res[6]<=res[7];
assert.equal(true, ok);
done();
});
it('Order by dates DESC', function(done){
var res = db.queryArray("SELECT orderdate FROM orders ORDER BY orderdate DESC");
var ok =
res[0]>=res[1] &&
res[1]>=res[2] &&
res[2]>=res[3] &&
res[3]>=res[4] &&
res[4]>=res[5] &&
res[5]>=res[6] &&
res[6]>=res[7];
assert.equal(true, ok);
done();
});
it('Dates parsing in INSERT', function(done){
db.exec("INSERT INTO orders VALUES (10,'2015-10-20')");
var res = db.queryValue('SELECT orderdate FROM orders WHERE orderid = 10');
assert.equal(res.valueOf(), new Date("2015-10-20").valueOf());
done();
});
/*
it('Dates parsing in SELECT', function(done){
db.exec("SELECT orders VALUES (10,'2015-10-20')");
var res = db.queryValue('SELECT orderdate FROM orders WHERE orderid = 10');
assert.equal(res.valueOf(), new Date("2015-10-20").valueOf());
done();
});
*/
// });
});
|
import PropTypes from 'prop-types';
import React from 'react';
import { Image, ActivityIndicator, Platform } from 'react-native';
import RNFS, { DocumentDirectoryPath } from 'react-native-fs';
import ResponsiveImage from 'react-native-responsive-image';
// support RN 0.60
import NetInfo from "@react-native-community/netinfo";
const SHA1 = require("crypto-js/sha1");
const URL = require('url-parse');
export default
class CacheableImage extends React.Component {
static propTypes = {
activityIndicatorProps: PropTypes.object,
defaultSource: Image.propTypes.source,
useQueryParamsInCacheKey: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.array
]),
checkNetwork: PropTypes.bool,
networkAvailable: PropTypes.bool,
downloadInBackground: PropTypes.bool,
storagePermissionGranted: PropTypes.bool
}
static defaultProps = {
style: { backgroundColor: 'transparent' },
activityIndicatorProps: {
style: { backgroundColor: 'transparent', flex: 1 }
},
useQueryParamsInCacheKey: false, // bc
checkNetwork: true,
networkAvailable: false,
downloadInBackground: (Platform.OS === 'ios') ? false : true,
storagePermissionGranted: true
}
state = {
isRemote: false,
cachedImagePath: null,
cacheable: true
}
networkAvailable = this.props.networkAvailable
downloading = false
jobId = null
setNativeProps(nativeProps) {
if (this._imageComponent) {
this._imageComponent.setNativeProps(nativeProps);
}
}
imageDownloadBegin = info => {
switch (info.statusCode) {
case 404:
case 403:
break;
default:
this.downloading = true;
this.jobId = info.jobId;
}
}
imageDownloadProgress = info => {
if ((info.contentLength / info.bytesWritten) == 1) {
this.downloading = false;
this.jobId = null;
}
}
checkImageCache = (imageUri, cachePath, cacheKey) => {
const dirPath = DocumentDirectoryPath+'/'+cachePath;
const filePath = dirPath+'/'+cacheKey;
RNFS
.stat(filePath)
.then((res) => {
if (res.isFile() && res.size > 0) {
// It's possible the component has already unmounted before setState could be called.
// It happens when the defaultSource and source have both been cached.
// An attempt is made to display the default however it's instantly removed since source is available
// means file exists, ie, cache-hit
this.setState({cacheable: true, cachedImagePath: filePath});
}
else {
throw Error("CacheableImage: Invalid file in checkImageCache()");
}
})
.catch((err) => {
// means file does not exist
// first make sure network is available..
// if (! this.state.networkAvailable) {
if (! this.networkAvailable) {
return;
}
// then make sure directory exists.. then begin download
// The NSURLIsExcludedFromBackupKey property can be provided to set this attribute on iOS platforms.
// Apple will reject apps for storing offline cache data that does not have this attribute.
// https://github.com/johanneslumpe/react-native-fs#mkdirfilepath-string-options-mkdiroptions-promisevoid
RNFS
.mkdir(dirPath, {NSURLIsExcludedFromBackupKey: true})
.then(() => {
// before we change the cachedImagePath.. if the previous cachedImagePath was set.. remove it
if (this.state.cacheable && this.state.cachedImagePath) {
let delImagePath = this.state.cachedImagePath;
this._deleteFilePath(delImagePath);
}
// If already downloading, cancel the job
if (this.jobId) {
this._stopDownload();
}
let downloadOptions = {
fromUrl: imageUri,
toFile: filePath,
background: this.props.downloadInBackground,
begin: this.imageDownloadBegin,
progress: this.imageDownloadProgress
};
// directory exists.. begin download
let download = RNFS
.downloadFile(downloadOptions);
this.downloading = true;
this.jobId = download.jobId;
download.promise
.then((res) => {
this.downloading = false;
this.jobId = null;
switch (res.statusCode) {
case 404:
case 403:
this.setState({cacheable: false, cachedImagePath: null});
break;
default:
this.setState({cacheable: true, cachedImagePath: filePath});
}
})
.catch((err) => {
// error occurred while downloading or download stopped.. remove file if created
this._deleteFilePath(filePath);
// If there was no in-progress job, it may have been cancelled already (and this component may be unmounted)
if (this.downloading) {
this.downloading = false;
this.jobId = null;
this.setState({cacheable: false, cachedImagePath: null});
}
});
})
.catch((err) => {
this._deleteFilePath(filePath);
this.setState({cacheable: false, cachedImagePath: null});
});
});
}
_deleteFilePath = (filePath) => {
RNFS
.exists(filePath)
.then((res) => {
if (res) {
RNFS
.unlink(filePath)
.catch((err) => {});
}
});
}
_processSource = (source, skipSourceCheck) => {
if (this.props.storagePermissionGranted
&& source !== null
&& source != ''
&& typeof source === "object"
&& source.hasOwnProperty('uri')
&& (
skipSourceCheck ||
typeof skipSourceCheck === 'undefined' ||
(!skipSourceCheck && source != this.props.source)
)
)
{ // remote
if (this.jobId) { // sanity
this._stopDownload();
}
const url = new URL(source.uri, null, true);
// handle query params for cache key
let cacheable = url.pathname;
if (Array.isArray(this.props.useQueryParamsInCacheKey)) {
this.props.useQueryParamsInCacheKey.forEach(function(k) {
if (url.query.hasOwnProperty(k)) {
cacheable = cacheable.concat(url.query[k]);
}
});
}
else if (this.props.useQueryParamsInCacheKey) {
cacheable = cacheable.concat(url.query);
}
const type = url.pathname.replace(/.*\.(.*)/, '$1');
const cacheKey = SHA1(cacheable) + (type.length < url.pathname.length ? '.' + type : '');
this.checkImageCache(source.uri, url.host, cacheKey);
this.setState({isRemote: true});
}
else {
this.setState({isRemote: false});
}
}
_stopDownload = () => {
if (!this.jobId) return;
this.downloading = false;
RNFS.stopDownload(this.jobId);
this.jobId = null;
}
_handleConnectivityChange = isConnected => {
this.networkAvailable = isConnected;
if (this.networkAvailable && this.state.isRemote && !this.state.cachedImagePath) {
this._processSource(this.props.source);
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.source != this.props.source || nextProps.networkAvailable != this.networkAvailable) {
this.networkAvailable = nextProps.networkAvailable;
this._processSource(nextProps.source);
}
}
shouldComponentUpdate(nextProps, nextState) {
if (nextState === this.state && nextProps === this.props) {
return false;
}
return true;
}
componentWillMount() {
if (this.props.checkNetwork) {
NetInfo.isConnected.addEventListener('connectionChange', this._handleConnectivityChange);
// componentWillUnmount unsets this._handleConnectivityChange in case the component unmounts before this fetch resolves
NetInfo.isConnected.fetch().done(this._handleConnectivityChange);
}
this._processSource(this.props.source, true);
}
componentWillUnmount() {
if (this.props.checkNetwork) {
NetInfo.isConnected.removeEventListener('connectionChange', this._handleConnectivityChange);
this._handleConnectivityChange = null;
}
if (this.downloading && this.jobId) {
this._stopDownload();
}
}
render() {
if ((!this.state.isRemote && !this.props.defaultSource) || !this.props.storagePermissionGranted) {
return this.renderLocal();
}
if (this.state.cacheable && this.state.cachedImagePath) {
return this.renderCache();
}
if (this.props.defaultSource) {
return this.renderDefaultSource();
}
const { children, defaultSource, checkNetwork, networkAvailable, downloadInBackground, activityIndicatorProps, ...props } = this.props;
const style = [activityIndicatorProps.style, this.props.style];
return (
<ActivityIndicator {...props} {...activityIndicatorProps} style={style} />
);
}
renderCache() {
const { children, defaultSource, checkNetwork, networkAvailable, downloadInBackground, activityIndicatorProps, ...props } = this.props;
return (
<ResponsiveImage {...props} source={{uri: 'file://'+this.state.cachedImagePath}} ref={component => this._imageComponent = component}>
{children}
</ResponsiveImage>
);
}
renderLocal() {
const { children, defaultSource, checkNetwork, networkAvailable, downloadInBackground, activityIndicatorProps, ...props } = this.props;
return (
<ResponsiveImage {...props} ref={component => this._imageComponent = component}>
{children}
</ResponsiveImage>
);
}
renderDefaultSource() {
const { children, defaultSource, checkNetwork, networkAvailable, ...props } = this.props;
return (
<CacheableImage {...props} source={defaultSource} checkNetwork={false} networkAvailable={this.networkAvailable} ref={component => this._imageComponent = component}>
{children}
</CacheableImage>
);
}
}
|
const mongoose = require('mongoose');
let animeSchema = mongoose.Schema({
name: {type: 'string', required: 'true'},
description : {type: 'string', required: 'true'},
watched : {type: 'string', required: 'true'},
rating : {type: 'number', required: 'true'},
});
let Anime = mongoose.model('Anime', animeSchema);
module.exports = Anime;
|
// Karma configuration
// Generated on Thu Aug 21 2014 10:24:39 GMT+0200 (CEST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'chai-jquery', 'jquery-1.8.3', 'sinon-chai'],
plugins: [
'karma-mocha',
'karma-chai',
'karma-sinon-chai',
'karma-chrome-launcher',
'karma-phantomjs-launcher',
'karma-jquery',
'karma-chai-jquery'
],
// list of files / patterns to load in the browser
files: [
'bower/angular/angular.js',
'bower/angular-mocks/angular-mocks.js',
'dist/ionic-settings.js',
'test/unit/**/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
|
/*!
* jQuery JavaScript Library v1.4.4
* http://jquery.com/
*
* Copyright 2010, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2010, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Thu Nov 11 19:04:53 2010 -0500
*/
(function( window, undefined ) {
// Use the correct document accordingly with window argument (sandbox)
var document = window.document;
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// (both of which we optimize for)
quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,
// Is it a simple selector
isSimple = /^.[^:#\[\.,]*$/,
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
rwhite = /\s/,
// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
// Check for non-word characters
rnonword = /\W/,
// Check for digits
rdigit = /\d/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
// Useragent RegExp
rwebkit = /(webkit)[ \/]([\w.]+)/,
ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
rmsie = /(msie) ([\w.]+)/,
rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
// Keep a UserAgent string for use with jQuery.browser
userAgent = navigator.userAgent,
// For matching the engine and version of the browser
browserMatch,
// Has the ready events already been bound?
readyBound = false,
// The functions to execute on DOM ready
readyList = [],
// The ready event handler
DOMContentLoaded,
// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = "body";
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
match = quickExpr.exec( selector );
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
doc = (context ? context.ownerDocument || context : document);
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes;
}
return jQuery.merge( this, selector );
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $("TAG")
} else if ( !context && !rnonword.test( selector ) ) {
this.selector = selector;
this.context = document;
selector = document.getElementsByTagName( selector );
return jQuery.merge( this, selector );
// 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 jQuery( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if (selector.selector !== undefined) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.4.4",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return slice.call( this, 0 );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = jQuery();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
} else {
jQuery.merge( ret, elems );
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + (this.selector ? " " : "") + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// If the DOM is already ready
if ( jQuery.isReady ) {
// Execute the function immediately
fn.call( document, jQuery );
// Otherwise, remember the function for later
} else if ( readyList ) {
// Add the function to the wait list
readyList.push( fn );
}
return this;
},
eq: function( i ) {
return i === -1 ?
this.slice( i ) :
this.slice( i, +i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ),
"slice", slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || jQuery(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var 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;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
window.$ = _$;
if ( deep ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Handle when the DOM is ready
ready: function( wait ) {
// A third-party is pushing the ready event forwards
if ( wait === true ) {
jQuery.readyWait--;
}
// Make sure that the DOM is not already loaded
if ( !jQuery.readyWait || (wait !== true && !jQuery.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// 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
if ( readyList ) {
// Execute all of them
var fn,
i = 0,
ready = readyList;
// Reset the list of functions
readyList = null;
while ( (fn = ready[ i++ ]) ) {
fn.call( document, jQuery );
}
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).unbind( "ready" );
}
}
}
},
bindReady: function() {
if ( readyBound ) {
return;
}
readyBound = true;
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", DOMContentLoaded);
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
// A crude way of determining if an object is a window
isWindow: function( obj ) {
return obj && typeof obj === "object" && "setInterval" in obj;
},
isNaN: function( obj ) {
return obj == null || !rdigit.test( obj ) || isNaN( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw msg;
},
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test(data.replace(rvalidescape, "@")
.replace(rvalidtokens, "]")
.replace(rvalidbraces, "")) ) {
// Try to use the native JSON parser first
return window.JSON && window.JSON.parse ?
window.JSON.parse( data ) :
(new Function("return " + data))();
} else {
jQuery.error( "Invalid JSON: " + data );
}
},
noop: function() {},
// Evalulates a script in a global context
globalEval: function( data ) {
if ( data && rnotwhite.test(data) ) {
// Inspired by code by Andrea Giammarchi
// http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
var head = document.getElementsByTagName("head")[0] || document.documentElement,
script = document.createElement("script");
script.type = "text/javascript";
if ( jQuery.support.scriptEval ) {
script.appendChild( document.createTextNode( data ) );
} else {
script.text = data;
}
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709).
head.insertBefore( script, head.firstChild );
head.removeChild( script );
}
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction(object);
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
}
}
return object;
},
// Use native String.trim function wherever possible
trim: trim ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
},
// results is for internal usage only
makeArray: function( array, results ) {
var ret = results || [];
if ( array != null ) {
// The window, strings (and functions) also have 'length'
// The extra typeof function check is to prevent crashes
// in Safari 2 (See: #3039)
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
var type = jQuery.type(array);
if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
push.call( ret, array );
} else {
jQuery.merge( ret, array );
}
}
return ret;
},
inArray: function( elem, array ) {
if ( array.indexOf ) {
return array.indexOf( elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
},
merge: function( first, second ) {
var i = first.length,
j = 0;
if ( typeof second.length === "number" ) {
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var ret = [], retVal;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var ret = [], value;
// Go through the array, translating each of the items to their
// new value (or values).
for ( var i = 0, length = elems.length; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
proxy: function( fn, proxy, thisObject ) {
if ( arguments.length === 2 ) {
if ( typeof proxy === "string" ) {
thisObject = fn;
fn = thisObject[ proxy ];
proxy = undefined;
} else if ( proxy && !jQuery.isFunction( proxy ) ) {
thisObject = proxy;
proxy = undefined;
}
}
if ( !proxy && fn ) {
proxy = function() {
return fn.apply( thisObject || this, arguments );
};
}
// Set the guid of unique handler to the same of original handler, so it can be removed
if ( fn ) {
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
}
// So proxy can be declared as an argument
return proxy;
},
// Mutifunctional method to get and set values to a collection
// The value/s can be optionally by executed if its a function
access: function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
// Setting many attributes
if ( typeof key === "object" ) {
for ( var k in key ) {
jQuery.access( elems, k, key[k], exec, fn, value );
}
return elems;
}
// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
for ( var i = 0; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
return elems;
}
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
},
now: function() {
return (new Date()).getTime();
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
},
browser: {}
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
jQuery.browser[ browserMatch.browser ] = true;
jQuery.browser.version = browserMatch.version;
}
// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
jQuery.browser.safari = true;
}
if ( indexOf ) {
jQuery.inArray = function( elem, array ) {
return indexOf.call( array, elem );
};
}
// Verify that \s matches non-breaking spaces
// (IE fails on this test)
if ( !rwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
};
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
// Expose jQuery to the global object
return (window.jQuery = window.$ = jQuery);
})();
(function() {
jQuery.support = {};
var root = document.documentElement,
script = document.createElement("script"),
div = document.createElement("div"),
id = "script" + jQuery.now();
div.style.display = "none";
div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
var all = div.getElementsByTagName("*"),
a = div.getElementsByTagName("a")[0],
select = document.createElement("select"),
opt = select.appendChild( document.createElement("option") );
// Can't get basic test support
if ( !all || !all.length || !a ) {
return;
}
jQuery.support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: div.firstChild.nodeType === 3,
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText insted)
style: /red/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: a.getAttribute("href") === "/a",
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.55$/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: div.getElementsByTagName("input")[0].value === "on",
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Will be defined later
deleteExpando: true,
optDisabled: false,
checkClone: false,
scriptEval: false,
noCloneEvent: true,
boxModel: null,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableHiddenOffsets: true
};
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as diabled)
select.disabled = true;
jQuery.support.optDisabled = !opt.disabled;
script.type = "text/javascript";
try {
script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
} catch(e) {}
root.insertBefore( script, root.firstChild );
// Make sure that the execution of code works by injecting a script
// tag with appendChild/createTextNode
// (IE doesn't support this, fails, and uses .text instead)
if ( window[ id ] ) {
jQuery.support.scriptEval = true;
delete window[ id ];
}
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete script.test;
} catch(e) {
jQuery.support.deleteExpando = false;
}
root.removeChild( script );
if ( div.attachEvent && div.fireEvent ) {
div.attachEvent("onclick", function click() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
jQuery.support.noCloneEvent = false;
div.detachEvent("onclick", click);
});
div.cloneNode(true).fireEvent("onclick");
}
div = document.createElement("div");
div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>";
var fragment = document.createDocumentFragment();
fragment.appendChild( div.firstChild );
// WebKit doesn't clone checked state correctly in fragments
jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked;
// Figure out if the W3C box model works as expected
// document.body must exist before we can do this
jQuery(function() {
var div = document.createElement("div");
div.style.width = div.style.paddingLeft = "1px";
document.body.appendChild( div );
jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
if ( "zoom" in div.style ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.style.display = "inline";
div.style.zoom = 1;
jQuery.support.inlineBlockNeedsLayout = div.offsetWidth === 2;
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "";
div.innerHTML = "<div style='width:4px;'></div>";
jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2;
}
div.innerHTML = "<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>";
var tds = div.getElementsByTagName("td");
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
jQuery.support.reliableHiddenOffsets = tds[0].offsetHeight === 0;
tds[0].style.display = "";
tds[1].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE < 8 fail this test)
jQuery.support.reliableHiddenOffsets = jQuery.support.reliableHiddenOffsets && tds[0].offsetHeight === 0;
div.innerHTML = "";
document.body.removeChild( div ).style.display = "none";
div = tds = null;
});
// Technique from Juriy Zaytsev
// http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
var eventSupported = function( eventName ) {
var el = document.createElement("div");
eventName = "on" + eventName;
var isSupported = (eventName in el);
if ( !isSupported ) {
el.setAttribute(eventName, "return;");
isSupported = typeof el[eventName] === "function";
}
el = null;
return isSupported;
};
jQuery.support.submitBubbles = eventSupported("submit");
jQuery.support.changeBubbles = eventSupported("change");
// release memory in IE
root = script = div = all = a = null;
})();
var windowData = {},
rbrace = /^(?:\{.*\}|\[.*\])$/;
jQuery.extend({
cache: {},
// Please use with caution
uuid: 0,
// Unique for each copy of jQuery on the page
expando: "jQuery" + jQuery.now(),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
data: function( elem, name, data ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
elem = elem == window ?
windowData :
elem;
var isNode = elem.nodeType,
id = isNode ? elem[ jQuery.expando ] : null,
cache = jQuery.cache, thisCache;
if ( isNode && !id && typeof name === "string" && data === undefined ) {
return;
}
// Get the data from the object directly
if ( !isNode ) {
cache = elem;
// Compute a unique ID for the element
} else if ( !id ) {
elem[ jQuery.expando ] = id = ++jQuery.uuid;
}
// Avoid generating a new cache unless none exists and we
// want to manipulate it.
if ( typeof name === "object" ) {
if ( isNode ) {
cache[ id ] = jQuery.extend(cache[ id ], name);
} else {
jQuery.extend( cache, name );
}
} else if ( isNode && !cache[ id ] ) {
cache[ id ] = {};
}
thisCache = isNode ? cache[ id ] : cache;
// Prevent overriding the named cache with undefined values
if ( data !== undefined ) {
thisCache[ name ] = data;
}
return typeof name === "string" ? thisCache[ name ] : thisCache;
},
removeData: function( elem, name ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
elem = elem == window ?
windowData :
elem;
var isNode = elem.nodeType,
id = isNode ? elem[ jQuery.expando ] : elem,
cache = jQuery.cache,
thisCache = isNode ? cache[ id ] : id;
// If we want to remove a specific section of the element's data
if ( name ) {
if ( thisCache ) {
// Remove the section of cache data
delete thisCache[ name ];
// If we've removed all the data, remove the element's cache
if ( isNode && jQuery.isEmptyObject(thisCache) ) {
jQuery.removeData( elem );
}
}
// Otherwise, we want to remove all of the element's data
} else {
if ( isNode && jQuery.support.deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
// Completely remove the data cache
} else if ( isNode ) {
delete cache[ id ];
// Remove all fields from the object
} else {
for ( var n in elem ) {
delete elem[ n ];
}
}
}
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
if ( elem.nodeName ) {
var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
if ( match ) {
return !(match === true || elem.getAttribute("classid") !== match);
}
}
return true;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var data = null;
if ( typeof key === "undefined" ) {
if ( this.length ) {
var attr = this[0].attributes, name;
data = jQuery.data( this[0] );
for ( var i = 0, l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = name.substr( 5 );
dataAttr( this[0], name, data[ name ] );
}
}
}
return data;
} else if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
var parts = key.split(".");
parts[1] = parts[1] ? "." + parts[1] : "";
if ( value === undefined ) {
data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
// Try to fetch any internally stored data first
if ( data === undefined && this.length ) {
data = jQuery.data( this[0], key );
data = dataAttr( this[0], key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
} else {
return this.each(function() {
var $this = jQuery( this ),
args = [ parts[0], value ];
$this.triggerHandler( "setData" + parts[1] + "!", args );
jQuery.data( this, key, value );
$this.triggerHandler( "changeData" + parts[1] + "!", args );
});
}
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
data = elem.getAttribute( "data-" + key );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
!jQuery.isNaN( data ) ? parseFloat( data ) :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
queue: function( elem, type, data ) {
if ( !elem ) {
return;
}
type = (type || "fx") + "queue";
var q = jQuery.data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( !data ) {
return q || [];
}
if ( !q || jQuery.isArray(data) ) {
q = jQuery.data( elem, type, jQuery.makeArray(data) );
} else {
q.push( data );
}
return q;
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
fn = queue.shift();
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift("inprogress");
}
fn.call(elem, function() {
jQuery.dequeue(elem, type);
});
}
}
});
jQuery.fn.extend({
queue: function( type, data ) {
if ( typeof type !== "string" ) {
data = type;
type = "fx";
}
if ( data === undefined ) {
return jQuery.queue( this[0], type );
}
return this.each(function( i ) {
var queue = jQuery.queue( this, type, data );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
type = type || "fx";
return this.queue( type, function() {
var elem = this;
setTimeout(function() {
jQuery.dequeue( elem, type );
}, time );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
}
});
var rclass = /[\n\t]/g,
rspaces = /\s+/,
rreturn = /\r/g,
rspecialurl = /^(?:href|src|style)$/,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea)?$/i,
rradiocheck = /^(?:radio|checkbox)$/i;
jQuery.props = {
"for": "htmlFor",
"class": "className",
readonly: "readOnly",
maxlength: "maxLength",
cellspacing: "cellSpacing",
rowspan: "rowSpan",
colspan: "colSpan",
tabindex: "tabIndex",
usemap: "useMap",
frameborder: "frameBorder"
};
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.attr );
},
removeAttr: function( name, fn ) {
return this.each(function(){
jQuery.attr( this, name, "" );
if ( this.nodeType === 1 ) {
this.removeAttribute( name );
}
});
},
addClass: function( value ) {
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
self.addClass( value.call(this, i, self.attr("class")) );
});
}
if ( value && typeof value === "string" ) {
var classNames = (value || "").split( rspaces );
for ( var i = 0, l = this.length; i < l; i++ ) {
var elem = this[i];
if ( elem.nodeType === 1 ) {
if ( !elem.className ) {
elem.className = value;
} else {
var className = " " + elem.className + " ",
setClass = elem.className;
for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
setClass += " " + classNames[c];
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
self.removeClass( value.call(this, i, self.attr("class")) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
var classNames = (value || "").split( rspaces );
for ( var i = 0, l = this.length; i < l; i++ ) {
var elem = this[i];
if ( elem.nodeType === 1 && elem.className ) {
if ( value ) {
var className = (" " + elem.className + " ").replace(rclass, " ");
for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[c] + " ", " ");
}
elem.className = jQuery.trim( className );
} else {
elem.className = "";
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this);
self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( rspaces );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space seperated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery.data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ";
for ( var i = 0, l = this.length; i < l; i++ ) {
if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
return true;
}
}
return false;
},
val: function( value ) {
if ( !arguments.length ) {
var elem = this[0];
if ( elem ) {
if ( jQuery.nodeName( elem, "option" ) ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
// We need to handle select boxes special
if ( jQuery.nodeName( elem, "select" ) ) {
var index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if ( index < 0 ) {
return null;
}
// Loop through all the selected options
for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
var option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option
value = jQuery(option).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
}
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) {
return elem.getAttribute("value") === null ? "on" : elem.value;
}
// Everything else, we just grab the value
return (elem.value || "").replace(rreturn, "");
}
return undefined;
}
var isFunction = jQuery.isFunction(value);
return this.each(function(i) {
var self = jQuery(this), val = value;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call(this, i, self.val());
}
// 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 + "";
});
}
if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) {
this.checked = jQuery.inArray( self.val(), val ) >= 0;
} else if ( jQuery.nodeName( this, "select" ) ) {
var values = jQuery.makeArray(val);
jQuery( "option", this ).each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
this.selectedIndex = -1;
}
} else {
this.value = val;
}
});
}
});
jQuery.extend({
attrFn: {
val: true,
css: true,
html: true,
text: true,
data: true,
width: true,
height: true,
offset: true
},
attr: function( elem, name, value, pass ) {
// don't set attributes on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
return undefined;
}
if ( pass && name in jQuery.attrFn ) {
return jQuery(elem)[name](value);
}
var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ),
// Whether we are setting (or getting)
set = value !== undefined;
// Try to normalize/fix the name
name = notxml && jQuery.props[ name ] || name;
// These attributes require special treatment
var special = rspecialurl.test( name );
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( name === "selected" && !jQuery.support.optSelected ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
}
// If applicable, access the attribute via the DOM 0 way
// 'in' checks fail in Blackberry 4.7 #6931
if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) {
if ( set ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
}
if ( value === null ) {
if ( elem.nodeType === 1 ) {
elem.removeAttribute( name );
}
} else {
elem[ name ] = value;
}
}
// browsers index elements by id/name on forms, give priority to attributes.
if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) {
return elem.getAttributeNode( name ).nodeValue;
}
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
if ( name === "tabIndex" ) {
var attributeNode = elem.getAttributeNode( "tabIndex" );
return attributeNode && attributeNode.specified ?
attributeNode.value :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
return elem[ name ];
}
if ( !jQuery.support.style && notxml && name === "style" ) {
if ( set ) {
elem.style.cssText = "" + value;
}
return elem.style.cssText;
}
if ( set ) {
// convert the value to a string (all browsers do this but IE) see #1070
elem.setAttribute( name, "" + value );
}
// Ensure that missing attributes return undefined
// Blackberry 4.7 returns "" from getAttribute #6938
if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) {
return undefined;
}
var attr = !jQuery.support.hrefNormalized && notxml && special ?
// Some attributes require a special call on IE
elem.getAttribute( name, 2 ) :
elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return attr === null ? undefined : attr;
}
});
var rnamespaces = /\.(.*)$/,
rformElems = /^(?:textarea|input|select)$/i,
rperiod = /\./g,
rspace = / /g,
rescape = /[^\w\s.|`]/g,
fcleanup = function( nm ) {
return nm.replace(rescape, "\\$&");
},
focusCounts = { focusin: 0, focusout: 0 };
/*
* A number of helper functions used for managing events.
* Many of the ideas behind this code originated from
* Dean Edwards' addEvent library.
*/
jQuery.event = {
// Bind an event to an element
// Original by Dean Edwards
add: function( elem, types, handler, data ) {
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// For whatever reason, IE has trouble passing the window object
// around, causing it to be cloned in the process
if ( jQuery.isWindow( elem ) && ( elem !== window && !elem.frameElement ) ) {
elem = window;
}
if ( handler === false ) {
handler = returnFalse;
} else if ( !handler ) {
// Fixes bug #7229. Fix recommended by jdalton
return;
}
var handleObjIn, handleObj;
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
}
// Make sure that the function being executed has a unique ID
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure
var elemData = jQuery.data( elem );
// If no elemData is found then we must be trying to bind to one of the
// banned noData elements
if ( !elemData ) {
return;
}
// Use a key less likely to result in collisions for plain JS objects.
// Fixes bug #7150.
var eventKey = elem.nodeType ? "events" : "__events__",
events = elemData[ eventKey ],
eventHandle = elemData.handle;
if ( typeof events === "function" ) {
// On plain objects events is a fn that holds the the data
// which prevents this data from being JSON serialized
// the function does not need to be called, it just contains the data
eventHandle = events.handle;
events = events.events;
} else if ( !events ) {
if ( !elem.nodeType ) {
// On plain objects, create a fn that acts as the holder
// of the values to avoid JSON serialization of event data
elemData[ eventKey ] = elemData = function(){};
}
elemData.events = events = {};
}
if ( !eventHandle ) {
elemData.handle = eventHandle = function() {
// Handle the second event of a trigger and when
// an event is called after a page has unloaded
return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
jQuery.event.handle.apply( eventHandle.elem, arguments ) :
undefined;
};
}
// Add elem as a property of the handle function
// This is to prevent a memory leak with non-native events in IE.
eventHandle.elem = elem;
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = types.split(" ");
var type, i = 0, namespaces;
while ( (type = types[ i++ ]) ) {
handleObj = handleObjIn ?
jQuery.extend({}, handleObjIn) :
{ handler: handler, data: data };
// Namespaced event handlers
if ( type.indexOf(".") > -1 ) {
namespaces = type.split(".");
type = namespaces.shift();
handleObj.namespace = namespaces.slice(0).sort().join(".");
} else {
namespaces = [];
handleObj.namespace = "";
}
handleObj.type = type;
if ( !handleObj.guid ) {
handleObj.guid = handler.guid;
}
// Get the current list of functions bound to this event
var handlers = events[ type ],
special = jQuery.event.special[ type ] || {};
// Init the event handler queue
if ( !handlers ) {
handlers = events[ type ] = [];
// Check for a special event handler
// Only use addEventListener/attachEvent if the special
// events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add the function to the element's handler list
handlers.push( handleObj );
// Keep track of which events have been used, for global triggering
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, pos ) {
// don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
if ( handler === false ) {
handler = returnFalse;
}
var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
eventKey = elem.nodeType ? "events" : "__events__",
elemData = jQuery.data( elem ),
events = elemData && elemData[ eventKey ];
if ( !elemData || !events ) {
return;
}
if ( typeof events === "function" ) {
elemData = events;
events = events.events;
}
// types is actually an event object here
if ( types && types.type ) {
handler = types.handler;
types = types.type;
}
// Unbind all events for the element
if ( !types || typeof types === "string" && types.charAt(0) === "." ) {
types = types || "";
for ( type in events ) {
jQuery.event.remove( elem, type + types );
}
return;
}
// Handle multiple events separated by a space
// jQuery(...).unbind("mouseover mouseout", fn);
types = types.split(" ");
while ( (type = types[ i++ ]) ) {
origType = type;
handleObj = null;
all = type.indexOf(".") < 0;
namespaces = [];
if ( !all ) {
// Namespaced event handlers
namespaces = type.split(".");
type = namespaces.shift();
namespace = new RegExp("(^|\\.)" +
jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
}
eventType = events[ type ];
if ( !eventType ) {
continue;
}
if ( !handler ) {
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( all || namespace.test( handleObj.namespace ) ) {
jQuery.event.remove( elem, origType, handleObj.handler, j );
eventType.splice( j--, 1 );
}
}
continue;
}
special = jQuery.event.special[ type ] || {};
for ( j = pos || 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( handler.guid === handleObj.guid ) {
// remove the given handler for the given type
if ( all || namespace.test( handleObj.namespace ) ) {
if ( pos == null ) {
eventType.splice( j--, 1 );
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
if ( pos != null ) {
break;
}
}
}
// remove generic event handler if no more handlers exist
if ( eventType.length === 0 || pos != null && eventType.length === 1 ) {
if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
ret = null;
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
var handle = elemData.handle;
if ( handle ) {
handle.elem = null;
}
delete elemData.events;
delete elemData.handle;
if ( typeof elemData === "function" ) {
jQuery.removeData( elem, eventKey );
} else if ( jQuery.isEmptyObject( elemData ) ) {
jQuery.removeData( elem );
}
}
},
// bubbling is internal
trigger: function( event, data, elem /*, bubbling */ ) {
// Event object or event type
var type = event.type || event,
bubbling = arguments[3];
if ( !bubbling ) {
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
jQuery.extend( jQuery.Event(type), event ) :
// Just the event type (string)
jQuery.Event(type);
if ( type.indexOf("!") >= 0 ) {
event.type = type = type.slice(0, -1);
event.exclusive = true;
}
// Handle a global trigger
if ( !elem ) {
// Don't bubble custom events when global (to avoid too much overhead)
event.stopPropagation();
// Only trigger if we've ever bound an event for it
if ( jQuery.event.global[ type ] ) {
jQuery.each( jQuery.cache, function() {
if ( this.events && this.events[type] ) {
jQuery.event.trigger( event, data, this.handle.elem );
}
});
}
}
// Handle triggering a single element
// don't do events on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
return undefined;
}
// Clean up in case it is reused
event.result = undefined;
event.target = elem;
// Clone the incoming data, if any
data = jQuery.makeArray( data );
data.unshift( event );
}
event.currentTarget = elem;
// Trigger the event, it is assumed that "handle" is a function
var handle = elem.nodeType ?
jQuery.data( elem, "handle" ) :
(jQuery.data( elem, "__events__" ) || {}).handle;
if ( handle ) {
handle.apply( elem, data );
}
var parent = elem.parentNode || elem.ownerDocument;
// Trigger an inline bound script
try {
if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) {
if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) {
event.result = false;
event.preventDefault();
}
}
// prevent IE from throwing an error for some elements with some event types, see #3533
} catch (inlineError) {}
if ( !event.isPropagationStopped() && parent ) {
jQuery.event.trigger( event, data, parent, true );
} else if ( !event.isDefaultPrevented() ) {
var old,
target = event.target,
targetType = type.replace( rnamespaces, "" ),
isClick = jQuery.nodeName( target, "a" ) && targetType === "click",
special = jQuery.event.special[ targetType ] || {};
if ( (!special._default || special._default.call( elem, event ) === false) &&
!isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) {
try {
if ( target[ targetType ] ) {
// Make sure that we don't accidentally re-trigger the onFOO events
old = target[ "on" + targetType ];
if ( old ) {
target[ "on" + targetType ] = null;
}
jQuery.event.triggered = true;
target[ targetType ]();
}
// prevent IE from throwing an error for some elements with some event types, see #3533
} catch (triggerError) {}
if ( old ) {
target[ "on" + targetType ] = old;
}
jQuery.event.triggered = false;
}
}
},
handle: function( event ) {
var all, handlers, namespaces, namespace_re, events,
namespace_sort = [],
args = jQuery.makeArray( arguments );
event = args[0] = jQuery.event.fix( event || window.event );
event.currentTarget = this;
// Namespaced event handlers
all = event.type.indexOf(".") < 0 && !event.exclusive;
if ( !all ) {
namespaces = event.type.split(".");
event.type = namespaces.shift();
namespace_sort = namespaces.slice(0).sort();
namespace_re = new RegExp("(^|\\.)" + namespace_sort.join("\\.(?:.*\\.)?") + "(\\.|$)");
}
event.namespace = event.namespace || namespace_sort.join(".");
events = jQuery.data(this, this.nodeType ? "events" : "__events__");
if ( typeof events === "function" ) {
events = events.events;
}
handlers = (events || {})[ event.type ];
if ( events && handlers ) {
// Clone the handlers to prevent manipulation
handlers = handlers.slice(0);
for ( var j = 0, l = handlers.length; j < l; j++ ) {
var handleObj = handlers[ j ];
// Filter the functions by class
if ( all || namespace_re.test( handleObj.namespace ) ) {
// Pass in a reference to the handler function itself
// So that we can later remove it
event.handler = handleObj.handler;
event.data = handleObj.data;
event.handleObj = handleObj;
var ret = handleObj.handler.apply( this, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
if ( event.isImmediatePropagationStopped() ) {
break;
}
}
}
}
return event.result;
},
props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// store a copy of the original event object
// and "clone" to set read-only properties
var originalEvent = event;
event = jQuery.Event( originalEvent );
for ( var i = this.props.length, prop; i; ) {
prop = this.props[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary
if ( !event.target ) {
// Fixes #1925 where srcElement might not be defined either
event.target = event.srcElement || document;
}
// check if target is a textnode (safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && event.fromElement ) {
event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
}
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && event.clientX != null ) {
var doc = document.documentElement,
body = document.body;
event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
}
// Add which for key events
if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
event.which = event.charCode != null ? event.charCode : event.keyCode;
}
// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
if ( !event.metaKey && event.ctrlKey ) {
event.metaKey = event.ctrlKey;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button !== undefined ) {
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
}
return event;
},
// Deprecated, use jQuery.guid instead
guid: 1E8,
// Deprecated, use jQuery.proxy instead
proxy: jQuery.proxy,
special: {
ready: {
// Make sure the ready event is setup
setup: jQuery.bindReady,
teardown: jQuery.noop
},
live: {
add: function( handleObj ) {
jQuery.event.add( this,
liveConvert( handleObj.origType, handleObj.selector ),
jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) );
},
remove: function( handleObj ) {
jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj );
}
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, handle );
}
};
jQuery.Event = function( src ) {
// Allow instantiation without the 'new' keyword
if ( !this.preventDefault ) {
return new jQuery.Event( src );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Event type
} else {
this.type = src;
}
// timeStamp is buggy for some events on Firefox(#3843)
// So we won't rely on the native value
this.timeStamp = jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return 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 = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function( event ) {
// Check if mouse(over|out) are still within the same parent element
var parent = event.relatedTarget;
// Firefox sometimes assigns relatedTarget a XUL element
// which we cannot access the parentNode property of
try {
// Traverse up the tree
while ( parent && parent !== this ) {
parent = parent.parentNode;
}
if ( parent !== this ) {
// set the correct event type
event.type = event.data;
// handle event if we actually just moused on to a non sub-element
jQuery.event.handle.apply( this, arguments );
}
// assuming we've left the element since we most likely mousedover a xul element
} catch(e) { }
},
// In case of event delegation, we only need to rename the event.type,
// liveHandler will take care of the rest.
delegate = function( event ) {
event.type = event.data;
jQuery.event.handle.apply( this, arguments );
};
// Create mouseenter and mouseleave events
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
setup: function( data ) {
jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig );
},
teardown: function( data ) {
jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement );
}
};
});
// submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function( data, namespaces ) {
if ( this.nodeName.toLowerCase() !== "form" ) {
jQuery.event.add(this, "click.specialSubmit", function( e ) {
var elem = e.target,
type = elem.type;
if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
e.liveFired = undefined;
return trigger( "submit", this, arguments );
}
});
jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
var elem = e.target,
type = elem.type;
if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
e.liveFired = undefined;
return trigger( "submit", this, arguments );
}
});
} else {
return false;
}
},
teardown: function( namespaces ) {
jQuery.event.remove( this, ".specialSubmit" );
}
};
}
// change delegation, happens here so we have bind.
if ( !jQuery.support.changeBubbles ) {
var changeFilters,
getVal = function( elem ) {
var type = elem.type, val = elem.value;
if ( type === "radio" || type === "checkbox" ) {
val = elem.checked;
} else if ( type === "select-multiple" ) {
val = elem.selectedIndex > -1 ?
jQuery.map( elem.options, function( elem ) {
return elem.selected;
}).join("-") :
"";
} else if ( elem.nodeName.toLowerCase() === "select" ) {
val = elem.selectedIndex;
}
return val;
},
testChange = function testChange( e ) {
var elem = e.target, data, val;
if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) {
return;
}
data = jQuery.data( elem, "_change_data" );
val = getVal(elem);
// the current data will be also retrieved by beforeactivate
if ( e.type !== "focusout" || elem.type !== "radio" ) {
jQuery.data( elem, "_change_data", val );
}
if ( data === undefined || val === data ) {
return;
}
if ( data != null || val ) {
e.type = "change";
e.liveFired = undefined;
return jQuery.event.trigger( e, arguments[1], elem );
}
};
jQuery.event.special.change = {
filters: {
focusout: testChange,
beforedeactivate: testChange,
click: function( e ) {
var elem = e.target, type = elem.type;
if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) {
return testChange.call( this, e );
}
},
// Change has to be called before submit
// Keydown will be called before keypress, which is used in submit-event delegation
keydown: function( e ) {
var elem = e.target, type = elem.type;
if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") ||
(e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
type === "select-multiple" ) {
return testChange.call( this, e );
}
},
// Beforeactivate happens also before the previous element is blurred
// with this event you can't trigger a change event, but you can store
// information
beforeactivate: function( e ) {
var elem = e.target;
jQuery.data( elem, "_change_data", getVal(elem) );
}
},
setup: function( data, namespaces ) {
if ( this.type === "file" ) {
return false;
}
for ( var type in changeFilters ) {
jQuery.event.add( this, type + ".specialChange", changeFilters[type] );
}
return rformElems.test( this.nodeName );
},
teardown: function( namespaces ) {
jQuery.event.remove( this, ".specialChange" );
return rformElems.test( this.nodeName );
}
};
changeFilters = jQuery.event.special.change.filters;
// Handle when the input is .focus()'d
changeFilters.focus = changeFilters.beforeactivate;
}
function trigger( type, elem, args ) {
args[0].type = type;
return jQuery.event.handle.apply( elem, args );
}
// Create "bubbling" focus and blur events
if ( document.addEventListener ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
jQuery.event.special[ fix ] = {
setup: function() {
if ( focusCounts[fix]++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --focusCounts[fix] === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
function handler( e ) {
e = jQuery.event.fix( e );
e.type = fix;
return jQuery.event.trigger( e, null, e.target );
}
});
}
jQuery.each(["bind", "one"], function( i, name ) {
jQuery.fn[ name ] = function( type, data, fn ) {
// Handle object literals
if ( typeof type === "object" ) {
for ( var key in type ) {
this[ name ](key, data, type[key], fn);
}
return this;
}
if ( jQuery.isFunction( data ) || data === false ) {
fn = data;
data = undefined;
}
var handler = name === "one" ? jQuery.proxy( fn, function( event ) {
jQuery( this ).unbind( event, handler );
return fn.apply( this, arguments );
}) : fn;
if ( type === "unload" && name !== "one" ) {
this.one( type, data, fn );
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.add( this[i], type, handler, data );
}
}
return this;
};
});
jQuery.fn.extend({
unbind: function( type, fn ) {
// Handle object literals
if ( typeof type === "object" && !type.preventDefault ) {
for ( var key in type ) {
this.unbind(key, type[key]);
}
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
jQuery.event.remove( this[i], type, fn );
}
}
return this;
},
delegate: function( selector, types, data, fn ) {
return this.live( types, data, fn, selector );
},
undelegate: function( selector, types, fn ) {
if ( arguments.length === 0 ) {
return this.unbind( "live" );
} else {
return this.die( types, null, fn, selector );
}
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
var event = jQuery.Event( type );
event.preventDefault();
event.stopPropagation();
jQuery.event.trigger( event, data, this[0] );
return event.result;
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
i = 1;
// link all the functions, so any of them can unbind this click handler
while ( i < args.length ) {
jQuery.proxy( fn, args[ i++ ] );
}
return this.click( jQuery.proxy( fn, function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
}));
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
var liveMap = {
focus: "focusin",
blur: "focusout",
mouseenter: "mouseover",
mouseleave: "mouseout"
};
jQuery.each(["live", "die"], function( i, name ) {
jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) {
var type, i = 0, match, namespaces, preType,
selector = origSelector || this.selector,
context = origSelector ? this : jQuery( this.context );
if ( typeof types === "object" && !types.preventDefault ) {
for ( var key in types ) {
context[ name ]( key, data, types[key], selector );
}
return this;
}
if ( jQuery.isFunction( data ) ) {
fn = data;
data = undefined;
}
types = (types || "").split(" ");
while ( (type = types[ i++ ]) != null ) {
match = rnamespaces.exec( type );
namespaces = "";
if ( match ) {
namespaces = match[0];
type = type.replace( rnamespaces, "" );
}
if ( type === "hover" ) {
types.push( "mouseenter" + namespaces, "mouseleave" + namespaces );
continue;
}
preType = type;
if ( type === "focus" || type === "blur" ) {
types.push( liveMap[ type ] + namespaces );
type = type + namespaces;
} else {
type = (liveMap[ type ] || type) + namespaces;
}
if ( name === "live" ) {
// bind live handler
for ( var j = 0, l = context.length; j < l; j++ ) {
jQuery.event.add( context[j], "live." + liveConvert( type, selector ),
{ data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } );
}
} else {
// unbind live handler
context.unbind( "live." + liveConvert( type, selector ), fn );
}
}
return this;
};
});
function liveHandler( event ) {
var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
elems = [],
selectors = [],
events = jQuery.data( this, this.nodeType ? "events" : "__events__" );
if ( typeof events === "function" ) {
events = events.events;
}
// Make sure we avoid non-left-click bubbling in Firefox (#3861)
if ( event.liveFired === this || !events || !events.live || event.button && event.type === "click" ) {
return;
}
if ( event.namespace ) {
namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
}
event.liveFired = this;
var live = events.live.slice(0);
for ( j = 0; j < live.length; j++ ) {
handleObj = live[j];
if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) {
selectors.push( handleObj.selector );
} else {
live.splice( j--, 1 );
}
}
match = jQuery( event.target ).closest( selectors, event.currentTarget );
for ( i = 0, l = match.length; i < l; i++ ) {
close = match[i];
for ( j = 0; j < live.length; j++ ) {
handleObj = live[j];
if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) ) {
elem = close.elem;
related = null;
// Those two events require additional checking
if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) {
event.type = handleObj.preType;
related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0];
}
if ( !related || related !== elem ) {
elems.push({ elem: elem, handleObj: handleObj, level: close.level });
}
}
}
}
for ( i = 0, l = elems.length; i < l; i++ ) {
match = elems[i];
if ( maxLevel && match.level > maxLevel ) {
break;
}
event.currentTarget = match.elem;
event.data = match.handleObj.data;
event.handleObj = match.handleObj;
ret = match.handleObj.origHandler.apply( match.elem, arguments );
if ( ret === false || event.isPropagationStopped() ) {
maxLevel = match.level;
if ( ret === false ) {
stop = false;
}
if ( event.isImmediatePropagationStopped() ) {
break;
}
}
}
return stop;
}
function liveConvert( type, selector ) {
return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspace, "&");
}
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").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.bind( name, data, fn ) :
this.trigger( name );
};
if ( jQuery.attrFn ) {
jQuery.attrFn[ name ] = true;
}
});
// Prevent memory leaks in IE
// Window isn't included so as not to unbind existing unload events
// More info:
// - http://isaacschlueter.com/2006/10/msie-memory-leaks/
if ( window.attachEvent && !window.addEventListener ) {
jQuery(window).bind("unload", function() {
for ( var id in jQuery.cache ) {
if ( jQuery.cache[ id ].handle ) {
// Try/Catch is to handle iframes being unloaded, see #4280
try {
jQuery.event.remove( jQuery.cache[ id ].handle.elem );
} catch(e) {}
}
}
});
}
/*!
* Sizzle CSS Selector Engine - v1.0
* Copyright 2009, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
var Sizzle = function( selector, context, results, seed ) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var m, set, checkSet, extra, ret, cur, pop, i,
prune = true,
contextXML = Sizzle.isXML( context ),
parts = [],
soFar = selector;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec( "" );
m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ?
Sizzle.filter( ret.expr, ret.set )[0] :
ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ?
Sizzle.filter( ret.expr, ret.set ) :
ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray( set );
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function( results ) {
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
Sizzle.matches = function( expr, set ) {
return Sizzle( expr, null, null, set );
};
Sizzle.matchesSelector = function( node, expr ) {
return Sizzle( expr, null, null, [node] ).length > 0;
};
Sizzle.find = function( expr, context, isXML ) {
var set;
if ( !expr ) {
return [];
}
for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
var match,
type = Expr.order[i];
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
var left = match[1];
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace(/\\/g, "");
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = context.getElementsByTagName( "*" );
}
return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
while ( expr && set.length ) {
for ( var type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
var found, item,
filter = Expr.filter[ type ],
left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
var pass = not ^ !!found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw "Syntax error, unrecognized expression: " + msg;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function( elem ) {
return elem.getAttribute( "href" );
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !/\W/.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function( checkSet, part ) {
var elem,
isPartStr = typeof part === "string",
i = 0,
l = checkSet.length;
if ( isPartStr && !/\W/.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !/\W/.test(part) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
},
"~": function( checkSet, part, isXML ) {
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !/\W/.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
}
},
find: {
ID: function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function( match, context ) {
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [],
results = context.getElementsByName( match[1] );
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function( match, context ) {
return context.getElementsByTagName( match[1] );
}
},
preFilter: {
CLASS: function( match, curLoop, inplace, result, not, isXML ) {
match = " " + match[1].replace(/\\/g, "") + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function( match ) {
return match[1].replace(/\\/g, "");
},
TAG: function( match, curLoop ) {
return match[1].toLowerCase();
},
CHILD: function( match ) {
if ( match[1] === "nth" ) {
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
var name = match[1].replace(/\\/g, "");
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function( match, curLoop, inplace, result, not ) {
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function( match ) {
match.unshift( true );
return match;
}
},
filters: {
enabled: function( elem ) {
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function( elem ) {
return elem.disabled === true;
},
checked: function( elem ) {
return elem.checked === true;
},
selected: function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
elem.parentNode.selectedIndex;
return elem.selected === true;
},
parent: function( elem ) {
return !!elem.firstChild;
},
empty: function( elem ) {
return !elem.firstChild;
},
has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
},
header: function( elem ) {
return (/h\d/i).test( elem.nodeName );
},
text: function( elem ) {
return "text" === elem.type;
},
radio: function( elem ) {
return "radio" === elem.type;
},
checkbox: function( elem ) {
return "checkbox" === elem.type;
},
file: function( elem ) {
return "file" === elem.type;
},
password: function( elem ) {
return "password" === elem.type;
},
submit: function( elem ) {
return "submit" === elem.type;
},
image: function( elem ) {
return "image" === elem.type;
},
reset: function( elem ) {
return "reset" === elem.type;
},
button: function( elem ) {
return "button" === elem.type || elem.nodeName.toLowerCase() === "button";
},
input: function( elem ) {
return (/input|select|textarea|button/i).test( elem.nodeName );
}
},
setFilters: {
first: function( elem, i ) {
return i === 0;
},
last: function( elem, i, match, array ) {
return i === array.length - 1;
},
even: function( elem, i ) {
return i % 2 === 0;
},
odd: function( elem, i ) {
return i % 2 === 1;
},
lt: function( elem, i, match ) {
return i < match[3] - 0;
},
gt: function( elem, i, match ) {
return i > match[3] - 0;
},
nth: function( elem, i, match ) {
return match[3] - 0 === i;
},
eq: function( elem, i, match ) {
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function( elem, match, i, array ) {
var name = match[1],
filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( "Syntax error, unrecognized expression: " + name );
}
},
CHILD: function( elem, match ) {
var type = match[1],
node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case "nth":
var first = match[2],
last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
var doneName = match[0],
parent = elem.parentNode;
if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
var count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent.sizcache = doneName;
}
var diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function( elem, match ) {
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function( elem, match ) {
return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
},
CLASS: function( elem, match ) {
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function( elem, match ) {
var name = match[1],
result = Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function( elem, match, i, array ) {
var name = match[2],
filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS,
fescape = function(all, num){
return "\\" + (num - 0 + 1);
};
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
var makeArray = function( array, results ) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch( e ) {
makeArray = function( array, results ) {
var i = 0,
ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// If the nodes are siblings (or identical) we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Utility function for retreiving the text value of an array of DOM nodes
Sizzle.getText = function( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += Sizzle.getText( elem.childNodes );
}
}
return ret;
};
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("div"),
id = "script" + (new Date()).getTime(),
root = document.documentElement;
form.innerHTML = "<a name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( document.getElementById( id ) ) {
Expr.find.ID = function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ?
m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
[m] :
undefined :
[];
}
};
Expr.filter.ID = function( elem, match ) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
// release memory in IE
root = form = null;
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function( match, context ) {
var results = context.getElementsByTagName( match[1] );
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function( elem ) {
return elem.getAttribute( "href", 2 );
};
}
// release memory in IE
div = null;
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle,
div = document.createElement("div"),
id = "__sizzle__";
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function( query, context, extra, seed ) {
context = context || document;
// Make sure that attribute selectors are quoted
query = query.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
if ( context.nodeType === 9 ) {
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
// 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
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var old = context.getAttribute( "id" ),
nid = old || id;
if ( !old ) {
context.setAttribute( "id", nid );
}
try {
return makeArray( context.querySelectorAll( "#" + nid + " " + query ), extra );
} catch(pseudoError) {
} finally {
if ( !old ) {
context.removeAttribute( "id" );
}
}
}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
// release memory in IE
div = null;
})();
}
(function(){
var html = document.documentElement,
matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector,
pseudoWorks = false;
try {
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( document.documentElement, "[test!='']:sizzle" );
} catch( pseudoError ) {
pseudoWorks = true;
}
if ( matches ) {
Sizzle.matchesSelector = function( node, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
if ( !Sizzle.isXML( node ) ) {
try {
if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
return matches.call( node, expr );
}
} catch(e) {}
}
return Sizzle(expr, null, null, [node]).length > 0;
};
}
})();
(function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function( match, context, isXML ) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
// release memory in IE
div = null;
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem.sizcache = doneName;
elem.sizset = i;
}
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem.sizcache = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
if ( document.documentElement.contains ) {
Sizzle.contains = function( a, b ) {
return a !== b && (a.contains ? a.contains(b) : true);
};
} else if ( document.documentElement.compareDocumentPosition ) {
Sizzle.contains = function( a, b ) {
return !!(a.compareDocumentPosition(b) & 16);
};
} else {
Sizzle.contains = function() {
return false;
};
}
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 : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function( selector, context ) {
var match,
tmpSet = [],
later = "",
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})();
var runtil = /Until$/,
rparentsprev = /^(?:parents|prevUntil|prevAll)/,
// Note: This RegExp should be improved, or likely pulled from Sizzle
rmultiselector = /,/,
isSimple = /^.[^:#\[\.,]*$/,
slice = Array.prototype.slice,
POS = jQuery.expr.match.POS;
jQuery.fn.extend({
find: function( selector ) {
var ret = this.pushStack( "", "find", selector ),
length = 0;
for ( var i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( var n = length; n < ret.length; n++ ) {
for ( var r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var targets = jQuery( target );
return this.filter(function() {
for ( var i = 0, l = targets.length; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && jQuery.filter( selector, this ).length > 0;
},
closest: function( selectors, context ) {
var ret = [], i, l, cur = this[0];
if ( jQuery.isArray( selectors ) ) {
var match, selector,
matches = {},
level = 1;
if ( cur && selectors.length ) {
for ( i = 0, l = selectors.length; i < l; i++ ) {
selector = selectors[i];
if ( !matches[selector] ) {
matches[selector] = jQuery.expr.match.POS.test( selector ) ?
jQuery( selector, context || this.context ) :
selector;
}
}
while ( cur && cur.ownerDocument && cur !== context ) {
for ( selector in matches ) {
match = matches[selector];
if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) {
ret.push({ selector: selector, elem: cur, level: level });
}
}
cur = cur.parentNode;
level++;
}
}
return ret;
}
var pos = POS.test( selectors ) ?
jQuery( selectors, context || this.context ) : null;
for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i];
while ( cur ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
} else {
cur = cur.parentNode;
if ( !cur || !cur.ownerDocument || cur === context ) {
break;
}
}
}
}
ret = ret.length > 1 ? jQuery.unique(ret) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
if ( !elem || typeof elem === "string" ) {
return jQuery.inArray( this[0],
// If it receives a string, the selector is used
// If it receives nothing, the siblings are used
elem ? jQuery( elem ) : this.parent().children() );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context || this.context ) :
jQuery.makeArray( selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
andSelf: function() {
return this.add( this.prevObject );
}
});
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
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 jQuery.nth( elem, 2, "nextSibling" );
},
prev: function( elem ) {
return jQuery.nth( elem, 2, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( elem.parentNode.firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.makeArray( elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, slice.call(arguments).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
nth: function( cur, result, dir, elem ) {
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] ) {
if ( cur.nodeType === 1 && ++num === result ) {
break;
}
}
return cur;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return (elem === qualifier) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return (jQuery.inArray( elem, qualifier ) >= 0) === keep;
});
}
var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnocache = /<(?:script|object|embed|option|style)/i,
// checked="checked" or checked (html5)
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
raction = /\=([^="'>\s]+\/)>/g,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
};
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "div<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( text ) {
if ( jQuery.isFunction(text) ) {
return this.each(function(i) {
var self = jQuery( this );
self.text( text.call(this, i, self.text()) );
});
}
if ( typeof text !== "object" && text !== undefined ) {
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
}
return jQuery.text( this );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append(this);
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
return this.each(function() {
jQuery( this ).wrapAll( html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
} else if ( arguments.length ) {
var set = jQuery(arguments[0]);
set.push.apply( set, this.toArray() );
return this.pushStack( set, "before", arguments );
}
},
after: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
} else if ( arguments.length ) {
var set = this.pushStack( this, "after", arguments );
set.push.apply( set, jQuery(arguments[0]).toArray() );
return set;
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( events ) {
// Do the clone
var ret = this.map(function() {
if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
// IE copies events bound via attachEvent when
// using cloneNode. Calling detachEvent on the
// clone will also remove the events from the orignal
// In order to get around this, we use innerHTML.
// Unfortunately, this means some modifications to
// attributes in IE that are actually only stored
// as properties will not be copied (such as the
// the name attribute on an input).
var html = this.outerHTML,
ownerDocument = this.ownerDocument;
if ( !html ) {
var div = ownerDocument.createElement("div");
div.appendChild( this.cloneNode(true) );
html = div.innerHTML;
}
return jQuery.clean([html.replace(rinlinejQuery, "")
// Handle the case in IE 8 where action=/test/> self-closes a tag
.replace(raction, '="$1">')
.replace(rleadingWhitespace, "")], ownerDocument)[0];
} else {
return this.cloneNode(true);
}
});
// Copy the events from the original to the clone
if ( events === true ) {
cloneCopyEvent( this, ret );
cloneCopyEvent( this.find("*"), ret.find("*") );
}
// Return the cloned set
return ret;
},
html: function( value ) {
if ( value === undefined ) {
return this[0] && this[0].nodeType === 1 ?
this[0].innerHTML.replace(rinlinejQuery, "") :
null;
// See if we can take a shortcut and just use innerHTML
} else if ( typeof value === "string" && !rnocache.test( value ) &&
(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
value = value.replace(rxhtmlTag, "<$1></$2>");
try {
for ( var i = 0, l = this.length; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
if ( this[i].nodeType === 1 ) {
jQuery.cleanData( this[i].getElementsByTagName("*") );
this[i].innerHTML = value;
}
}
// If using innerHTML throws an exception, use the fallback method
} catch(e) {
this.empty().append( value );
}
} else if ( jQuery.isFunction( value ) ) {
this.each(function(i){
var self = jQuery( this );
self.html( value.call(this, i, self.html()) );
});
} else {
this.empty().append( value );
}
return this;
},
replaceWith: function( value ) {
if ( this[0] && this[0].parentNode ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
} else {
return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
}
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
var results, first, fragment, parent,
value = args[0],
scripts = [];
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback, true );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call(this, i, table ? self.html() : undefined);
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
parent = value && value.parentNode;
// If we're in a fragment, just use that instead of building a new one
if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
results = { fragment: parent };
} else {
results = jQuery.buildFragment( args, this, scripts );
}
fragment = results.fragment;
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
first = fragment.firstChild;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
for ( var i = 0, l = this.length; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
i > 0 || results.cacheable || this.length > 1 ?
fragment.cloneNode(true) :
fragment
);
}
}
if ( scripts.length ) {
jQuery.each( scripts, evalScript );
}
}
return this;
}
});
function root( elem, cur ) {
return jQuery.nodeName(elem, "table") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
function cloneCopyEvent(orig, ret) {
var i = 0;
ret.each(function() {
if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) {
return;
}
var oldData = jQuery.data( orig[i++] ),
curData = jQuery.data( this, oldData ),
events = oldData && oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( var type in events ) {
for ( var handler in events[ type ] ) {
jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
}
}
}
});
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults,
doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
// Only cache "small" (1/2 KB) strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
!rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ args[0] ];
if ( cacheresults ) {
if ( cacheresults !== 1 ) {
fragment = cacheresults;
}
}
}
if ( !fragment ) {
fragment = doc.createDocumentFragment();
jQuery.clean( args, doc, fragment, scripts );
}
if ( cacheable ) {
jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
jQuery.extend({
clean: function( elems, context, fragment, scripts ) {
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if ( typeof context.createElement === "undefined" ) {
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
}
var ret = [];
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" && !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else if ( typeof elem === "string" ) {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Trim whitespace, otherwise indexOf won't work as expected
var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
wrap = wrapMap[ tag ] || wrapMap._default,
depth = wrap[0],
div = context.createElement("div");
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
var hasBody = rtbody.test(elem),
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( var j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
ret = jQuery.merge( ret, elem );
}
}
if ( fragment ) {
for ( i = 0; ret[i]; i++ ) {
if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
} else {
if ( ret[i].nodeType === 1 ) {
ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
}
fragment.appendChild( ret[i] );
}
}
}
return ret;
},
cleanData: function( elems ) {
var data, id, cache = jQuery.cache,
special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
continue;
}
id = elem[ jQuery.expando ];
if ( id ) {
data = cache[ id ];
if ( data && data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
delete cache[ id ];
}
}
}
});
function evalScript( i, elem ) {
if ( elem.src ) {
jQuery.ajax({
url: elem.src,
async: false,
dataType: "script"
});
} else {
jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
var ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
rdashAlpha = /-([a-z])/ig,
rupper = /([A-Z])/g,
rnumpx = /^-?\d+(?:px)?$/i,
rnum = /^-?\d/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssWidth = [ "Left", "Right" ],
cssHeight = [ "Top", "Bottom" ],
curCSS,
getComputedStyle,
currentStyle,
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn.css = function( name, value ) {
// Setting 'undefined' is a no-op
if ( arguments.length === 2 && value === undefined ) {
return this;
}
return jQuery.access( this, name, value, true, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
});
};
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", "opacity" );
return ret === "" ? "1" : ret;
} else {
return elem.style.opacity;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"zIndex": true,
"fontWeight": true,
"opacity": true,
"zoom": true,
"lineHeight": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, origName = jQuery.camelCase( name ),
style = elem.style, hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// Check if we're setting a value
if ( value !== undefined ) {
// Make sure that NaN and null values aren't set. See: #7116
if ( typeof value === "number" && isNaN( value ) || value == null ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( typeof value === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra ) {
// Make sure that we're working with the right name
var ret, origName = jQuery.camelCase( name ),
hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
return ret;
// Otherwise, if a way to get the computed value exists, use that
} else if ( curCSS ) {
return curCSS( elem, name, origName );
}
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var old = {};
// Remember the old values, and insert the new ones
for ( var name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
},
camelCase: function( string ) {
return string.replace( rdashAlpha, fcamelCase );
}
});
// DEPRECATED, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;
jQuery.each(["height", "width"], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
var val;
if ( computed ) {
if ( elem.offsetWidth !== 0 ) {
val = getWH( elem, name, extra );
} else {
jQuery.swap( elem, cssShow, function() {
val = getWH( elem, name, extra );
});
}
if ( val <= 0 ) {
val = curCSS( elem, name, name );
if ( val === "0px" && currentStyle ) {
val = currentStyle( elem, name, name );
}
if ( val != null ) {
// Should return "auto" instead of 0, use 0 for
// temporary backwards-compat
return val === "" || val === "auto" ? "0px" : val;
}
}
if ( val < 0 || val == null ) {
val = elem.style[ name ];
// Should return "auto" instead of 0, use 0 for
// temporary backwards-compat
return val === "" || val === "auto" ? "0px" : val;
}
return typeof val === "string" ? val : val + "px";
}
},
set: function( elem, value ) {
if ( rnumpx.test( value ) ) {
// ignore negative width and height values #1599
value = parseFloat(value);
if ( value >= 0 ) {
return value + "px";
}
} else {
return value;
}
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ?
(parseFloat(RegExp.$1) / 100) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style;
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// Set the alpha filter to set the opacity
var opacity = jQuery.isNaN(value) ?
"" :
"alpha(opacity=" + value * 100 + ")",
filter = style.filter || "";
style.filter = ralpha.test(filter) ?
filter.replace(ralpha, opacity) :
style.filter + ' ' + opacity;
}
};
}
if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, newName, name ) {
var ret, defaultView, computedStyle;
name = name.replace( rupper, "-$1" ).toLowerCase();
if ( !(defaultView = elem.ownerDocument.defaultView) ) {
return undefined;
}
if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) {
ret = computedStyle.getPropertyValue( name );
if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
ret = jQuery.style( elem, name );
}
}
return ret;
};
}
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
var left, rsLeft,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle.left;
// Put in the new values to get a computed value out
elem.runtimeStyle.left = elem.currentStyle.left;
style.left = name === "fontSize" ? "1em" : (ret || 0);
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
elem.runtimeStyle.left = rsLeft;
}
return ret === "" ? "auto" : ret;
};
}
curCSS = getComputedStyle || currentStyle;
function getWH( elem, name, extra ) {
var which = name === "width" ? cssWidth : cssHeight,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight;
if ( extra === "border" ) {
return val;
}
jQuery.each( which, function() {
if ( !extra ) {
val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0;
}
if ( extra === "margin" ) {
val += parseFloat(jQuery.css( elem, "margin" + this )) || 0;
} else {
val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0;
}
});
return val;
}
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
var width = elem.offsetWidth,
height = elem.offsetHeight;
return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
var jsc = jQuery.now(),
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rselectTextarea = /^(?:select|textarea)/i,
rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rnoContent = /^(?:GET|HEAD)$/,
rbracket = /\[\]$/,
jsre = /\=\?(&|$)/,
rquery = /\?/,
rts = /([?&])_=[^&]*/,
rurl = /^(\w+:)?\/\/([^\/?#]+)/,
r20 = /%20/g,
rhash = /#.*$/,
// Keep a copy of the old load method
_load = jQuery.fn.load;
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 = null;
// 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: function( res, status ) {
// If successful, inject the HTML into all the matched elements
if ( status === "success" || status === "notmodified" ) {
// 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(res.responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
res.responseText );
}
if ( callback ) {
self.each( callback, [res.responseText, status, res] );
}
}
});
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 };
}) :
{ name: elem.name, value: val };
}).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.extend({
get: function( url, data, callback, type ) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = null;
}
return jQuery.ajax({
type: "GET",
url: url,
data: data,
success: callback,
dataType: type
});
},
getScript: function( url, callback ) {
return jQuery.get(url, null, callback, "script");
},
getJSON: function( url, data, callback ) {
return jQuery.get(url, data, callback, "json");
},
post: function( url, data, callback, type ) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
},
ajaxSetup: function( settings ) {
jQuery.extend( jQuery.ajaxSettings, settings );
},
ajaxSettings: {
url: location.href,
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded",
processData: true,
async: true,
/*
timeout: 0,
data: null,
username: null,
password: null,
traditional: false,
*/
// This function can be overriden by calling jQuery.ajaxSetup
xhr: function() {
return new window.XMLHttpRequest();
},
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
script: "text/javascript, application/javascript",
json: "application/json, text/javascript",
text: "text/plain",
_default: "*/*"
}
},
ajax: function( origSettings ) {
var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
jsonp, status, data, type = s.type.toUpperCase(), noContent = rnoContent.test(type);
s.url = s.url.replace( rhash, "" );
// Use original (not extended) context object if it was provided
s.context = origSettings && origSettings.context != null ? origSettings.context : s;
// convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Handle JSONP Parameter Callbacks
if ( s.dataType === "jsonp" ) {
if ( type === "GET" ) {
if ( !jsre.test( s.url ) ) {
s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
}
} else if ( !s.data || !jsre.test(s.data) ) {
s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
}
s.dataType = "json";
}
// Build temporary JSONP function
if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
jsonp = s.jsonpCallback || ("jsonp" + jsc++);
// Replace the =? sequence both in the query string and the data
if ( s.data ) {
s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
}
s.url = s.url.replace(jsre, "=" + jsonp + "$1");
// We need to make sure
// that a JSONP style response is executed properly
s.dataType = "script";
// Handle JSONP-style loading
var customJsonp = window[ jsonp ];
window[ jsonp ] = function( tmp ) {
if ( jQuery.isFunction( customJsonp ) ) {
customJsonp( tmp );
} else {
// Garbage collect
window[ jsonp ] = undefined;
try {
delete window[ jsonp ];
} catch( jsonpError ) {}
}
data = tmp;
jQuery.handleSuccess( s, xhr, status, data );
jQuery.handleComplete( s, xhr, status, data );
if ( head ) {
head.removeChild( script );
}
};
}
if ( s.dataType === "script" && s.cache === null ) {
s.cache = false;
}
if ( s.cache === false && noContent ) {
var ts = jQuery.now();
// try replacing _= if it is there
var 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 : "");
}
// If data is available, append data to url for GET/HEAD requests
if ( s.data && noContent ) {
s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
}
// Watch for a new set of requests
if ( s.global && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// Matches an absolute URL, and saves the domain
var parts = rurl.exec( s.url ),
remote = parts && (parts[1] && parts[1].toLowerCase() !== location.protocol || parts[2].toLowerCase() !== location.host);
// If we're requesting a remote document
// and trying to load JSON or Script with a GET
if ( s.dataType === "script" && type === "GET" && remote ) {
var head = document.getElementsByTagName("head")[0] || document.documentElement;
var script = document.createElement("script");
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Handle Script loading
if ( !jsonp ) {
var done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
if ( !done && (!this.readyState ||
this.readyState === "loaded" || this.readyState === "complete") ) {
done = true;
jQuery.handleSuccess( s, xhr, status, data );
jQuery.handleComplete( s, xhr, status, data );
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
if ( head && script.parentNode ) {
head.removeChild( script );
}
}
};
}
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
// We handle everything using the script element injection
return undefined;
}
var requestDone = false;
// Create the request object
var xhr = s.xhr();
if ( !xhr ) {
return;
}
// Open the socket
// Passing null username, generates a Index popup on Opera (#2865)
if ( s.username ) {
xhr.open(type, s.url, s.async, s.username, s.password);
} else {
xhr.open(type, s.url, s.async);
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
// Set content-type if data specified and content-body is valid for this type
if ( (s.data != null && !noContent) || (origSettings && origSettings.contentType) ) {
xhr.setRequestHeader("Content-Type", s.contentType);
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[s.url] ) {
xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
}
if ( jQuery.etag[s.url] ) {
xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
}
}
// Set header so the called script knows that it's an XMLHttpRequest
// Only send the header if it's not a remote XHR
if ( !remote ) {
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
// Set the Accepts header for the server, depending on the dataType
xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
s.accepts[ s.dataType ] + ", */*; q=0.01" :
s.accepts._default );
} catch( headerError ) {}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
// Handle the global AJAX counter
if ( s.global && jQuery.active-- === 1 ) {
jQuery.event.trigger( "ajaxStop" );
}
// close opended socket
xhr.abort();
return false;
}
if ( s.global ) {
jQuery.triggerGlobal( s, "ajaxSend", [xhr, s] );
}
// Wait for a response to come back
var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
// The request was aborted
if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
// Opera doesn't call onreadystatechange before this point
// so we simulate the call
if ( !requestDone ) {
jQuery.handleComplete( s, xhr, status, data );
}
requestDone = true;
if ( xhr ) {
xhr.onreadystatechange = jQuery.noop;
}
// The transfer is complete and the data is available, or the request timed out
} else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
requestDone = true;
xhr.onreadystatechange = jQuery.noop;
status = isTimeout === "timeout" ?
"timeout" :
!jQuery.httpSuccess( xhr ) ?
"error" :
s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
"notmodified" :
"success";
var errMsg;
if ( status === "success" ) {
// Watch for, and catch, XML document parse errors
try {
// process the data (runs the xml through httpData regardless of callback)
data = jQuery.httpData( xhr, s.dataType, s );
} catch( parserError ) {
status = "parsererror";
errMsg = parserError;
}
}
// Make sure that the request was successful or notmodified
if ( status === "success" || status === "notmodified" ) {
// JSONP handles its own success callback
if ( !jsonp ) {
jQuery.handleSuccess( s, xhr, status, data );
}
} else {
jQuery.handleError( s, xhr, status, errMsg );
}
// Fire the complete handlers
if ( !jsonp ) {
jQuery.handleComplete( s, xhr, status, data );
}
if ( isTimeout === "timeout" ) {
xhr.abort();
}
// Stop memory leaks
if ( s.async ) {
xhr = null;
}
}
};
// Override the abort handler, if we can (IE 6 doesn't allow it, but that's OK)
// Opera doesn't fire onreadystatechange at all on abort
try {
var oldAbort = xhr.abort;
xhr.abort = function() {
if ( xhr ) {
// oldAbort has no call property in IE7 so
// just do it this way, which works in all
// browsers
Function.prototype.call.call( oldAbort, xhr );
}
onreadystatechange( "abort" );
};
} catch( abortError ) {}
// Timeout checker
if ( s.async && s.timeout > 0 ) {
setTimeout(function() {
// Check to see if the request is still happening
if ( xhr && !requestDone ) {
onreadystatechange( "timeout" );
}
}, s.timeout);
}
// Send the data
try {
xhr.send( noContent || s.data == null ? null : s.data );
} catch( sendError ) {
jQuery.handleError( s, xhr, null, sendError );
// Fire the complete handlers
jQuery.handleComplete( s, xhr, status, data );
}
// firefox 1.5 doesn't fire statechange for sync requests
if ( !s.async ) {
onreadystatechange();
}
// return XMLHttpRequest to allow aborting the request etc.
return xhr;
},
// 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 ) {
// 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) && obj.length ) {
// 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" ) {
if ( jQuery.isEmptyObject( obj ) ) {
add( prefix, "" );
// Serialize object item.
} else {
jQuery.each( obj, function( k, v ) {
buildParams( prefix + "[" + k + "]", v, 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: {},
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context, xhr, status, e );
}
// Fire the global callback
if ( s.global ) {
jQuery.triggerGlobal( s, "ajaxError", [xhr, s, e] );
}
},
handleSuccess: function( s, xhr, status, data ) {
// If a local callback was specified, fire it and pass it the data
if ( s.success ) {
s.success.call( s.context, data, status, xhr );
}
// Fire the global callback
if ( s.global ) {
jQuery.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
}
},
handleComplete: function( s, xhr, status ) {
// Process result
if ( s.complete ) {
s.complete.call( s.context, xhr, status );
}
// The request was completed
if ( s.global ) {
jQuery.triggerGlobal( s, "ajaxComplete", [xhr, s] );
}
// Handle the global AJAX counter
if ( s.global && jQuery.active-- === 1 ) {
jQuery.event.trigger( "ajaxStop" );
}
},
triggerGlobal: function( s, type, args ) {
(s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
},
// Determines if an XMLHttpRequest was successful or not
httpSuccess: function( xhr ) {
try {
// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
return !xhr.status && location.protocol === "file:" ||
xhr.status >= 200 && xhr.status < 300 ||
xhr.status === 304 || xhr.status === 1223;
} catch(e) {}
return false;
},
// Determines if an XMLHttpRequest returns NotModified
httpNotModified: function( xhr, url ) {
var lastModified = xhr.getResponseHeader("Last-Modified"),
etag = xhr.getResponseHeader("Etag");
if ( lastModified ) {
jQuery.lastModified[url] = lastModified;
}
if ( etag ) {
jQuery.etag[url] = etag;
}
return xhr.status === 304;
},
httpData: function( xhr, type, s ) {
var ct = xhr.getResponseHeader("content-type") || "",
xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if ( xml && data.documentElement.nodeName === "parsererror" ) {
jQuery.error( "parsererror" );
}
// Allow a pre-filtering function to sanitize the response
// s is checked to keep backwards compatibility
if ( s && s.dataFilter ) {
data = s.dataFilter( data, type );
}
// The filter can actually parse the response
if ( typeof data === "string" ) {
// Get the JavaScript object, if JSON is used.
if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
data = jQuery.parseJSON( data );
// If the type is "script", eval it in global context
} else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
jQuery.globalEval( data );
}
}
return data;
}
});
/*
* Create the request object; Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
if ( window.ActiveXObject ) {
jQuery.ajaxSettings.xhr = function() {
if ( window.location.protocol !== "file:" ) {
try {
return new window.XMLHttpRequest();
} catch(xhrError) {}
}
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch(activeError) {}
};
}
// Does this browser support XHR requests?
jQuery.support.ajax = !!jQuery.ajaxSettings.xhr();
var elemdisplay = {},
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = /^([+\-]=)?([\d+.\-]+)(.*)$/,
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
];
jQuery.fn.extend({
show: function( speed, easing, callback ) {
var elem, display;
if ( speed || speed === 0 ) {
return this.animate( genFx("show", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
elem = this[i];
display = elem.style.display;
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !jQuery.data(elem, "olddisplay") && display === "none" ) {
display = 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 ( display === "" && jQuery.css( elem, "display" ) === "none" ) {
jQuery.data(elem, "olddisplay", defaultDisplay(elem.nodeName));
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
elem = this[i];
display = elem.style.display;
if ( display === "" || display === "none" ) {
elem.style.display = jQuery.data(elem, "olddisplay") || "";
}
}
return this;
}
},
hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
var display = jQuery.css( this[i], "display" );
if ( display !== "none" ) {
jQuery.data( this[i], "olddisplay", display );
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
this[i].style.display = "none";
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2, callback ) {
var bool = typeof fn === "boolean";
if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
this._toggle.apply( this, arguments );
} else if ( fn == null || bool ) {
this.each(function() {
var state = bool ? fn : jQuery(this).is(":hidden");
jQuery(this)[ state ? "show" : "hide" ]();
});
} else {
this.animate(genFx("toggle", 3), fn, fn2, callback);
}
return this;
},
fadeTo: function( speed, to, easing, callback ) {
return this.filter(":hidden").css("opacity", 0).show().end()
.animate({opacity: to}, speed, easing, callback);
},
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed(speed, easing, callback);
if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete );
}
return this[ optall.queue === false ? "each" : "queue" ](function() {
// XXX 'this' does not always have a nodeName when running the
// test suite
var opt = jQuery.extend({}, optall), p,
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
self = this;
for ( p in prop ) {
var name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
p = name;
}
if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) {
return opt.complete.call(this);
}
if ( isElement && ( p === "height" || p === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height
// animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
if ( !jQuery.support.inlineBlockNeedsLayout ) {
this.style.display = "inline-block";
} else {
var display = defaultDisplay(this.nodeName);
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( display === "inline" ) {
this.style.display = "inline-block";
} else {
this.style.display = "inline";
this.style.zoom = 1;
}
}
}
}
if ( jQuery.isArray( prop[p] ) ) {
// Create (if needed) and add to specialEasing
(opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1];
prop[p] = prop[p][0];
}
}
if ( opt.overflow != null ) {
this.style.overflow = "hidden";
}
opt.curAnim = jQuery.extend({}, prop);
jQuery.each( prop, function( name, val ) {
var e = new jQuery.fx( self, opt, name );
if ( rfxtypes.test(val) ) {
e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop );
} else {
var parts = rfxnum.exec(val),
start = e.cur() || 0;
if ( parts ) {
var end = parseFloat( parts[2] ),
unit = parts[3] || "px";
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( self, name, (end || 1) + unit);
start = ((end || 1) / e.cur()) * start;
jQuery.style( self, name, start + unit);
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) {
end = ((parts[1] === "-=" ? -1 : 1) * end) + start;
}
e.custom( start, end, unit );
} else {
e.custom( start, val, "" );
}
}
});
// For JS strict compliance
return true;
});
},
stop: function( clearQueue, gotoEnd ) {
var timers = jQuery.timers;
if ( clearQueue ) {
this.queue([]);
}
this.each(function() {
// go in reverse order so anything added to the queue during the loop is ignored
for ( var i = timers.length - 1; i >= 0; i-- ) {
if ( timers[i].elem === this ) {
if (gotoEnd) {
// force the next step to be the last
timers[i](true);
}
timers.splice(i, 1);
}
}
});
// start the next in the queue if the last step wasn't forced
if ( !gotoEnd ) {
this.dequeue();
}
return this;
}
});
function genFx( type, num ) {
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() {
obj[ this ] = type;
});
return obj;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show", 1),
slideUp: genFx("hide", 1),
slideToggle: genFx("toggle", 1),
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.extend({
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;
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( opt.queue !== false ) {
jQuery(this).dequeue();
}
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
};
return opt;
},
easing: {
linear: function( p, n, firstNum, diff ) {
return firstNum + diff * p;
},
swing: function( p, n, firstNum, diff ) {
return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
}
},
timers: [],
fx: function( elem, options, prop ) {
this.options = options;
this.elem = elem;
this.prop = prop;
if ( !options.orig ) {
options.orig = {};
}
}
});
jQuery.fx.prototype = {
// Simple function for setting a style value
update: function() {
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
(jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
},
// Get the current size
cur: function() {
if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
return this.elem[ this.prop ];
}
var r = parseFloat( jQuery.css( this.elem, this.prop ) );
return r && r > -10000 ? r : 0;
},
// Start an animation from one number to another
custom: function( from, to, unit ) {
var self = this,
fx = jQuery.fx;
this.startTime = jQuery.now();
this.start = from;
this.end = to;
this.unit = unit || this.unit || "px";
this.now = this.start;
this.pos = this.state = 0;
function t( gotoEnd ) {
return self.step(gotoEnd);
}
t.elem = this.elem;
if ( t() && jQuery.timers.push(t) && !timerId ) {
timerId = setInterval(fx.tick, fx.interval);
}
},
// Simple 'show' function
show: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
this.options.show = true;
// Begin the animation
// Make sure that we start at a small width/height to avoid any
// flash of content
this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur());
// Start by showing the element
jQuery( this.elem ).show();
},
// Simple 'hide' function
hide: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
this.options.hide = true;
// Begin the animation
this.custom(this.cur(), 0);
},
// Each step of an animation
step: function( gotoEnd ) {
var t = jQuery.now(), done = true;
if ( gotoEnd || t >= this.options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
this.options.curAnim[ this.prop ] = true;
for ( var i in this.options.curAnim ) {
if ( this.options.curAnim[i] !== true ) {
done = false;
}
}
if ( done ) {
// Reset the overflow
if ( this.options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
var elem = this.elem,
options = this.options;
jQuery.each( [ "", "X", "Y" ], function (index, value) {
elem.style[ "overflow" + value ] = options.overflow[index];
} );
}
// Hide the element if the "hide" operation was done
if ( this.options.hide ) {
jQuery(this.elem).hide();
}
// Reset the properties, if the item has been hidden or shown
if ( this.options.hide || this.options.show ) {
for ( var p in this.options.curAnim ) {
jQuery.style( this.elem, p, this.options.orig[p] );
}
}
// Execute the complete function
this.options.complete.call( this.elem );
}
return false;
} else {
var n = t - this.startTime;
this.state = n / this.options.duration;
// Perform the easing function, defaults to swing
var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop];
var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear");
this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration);
this.now = this.start + ((this.end - this.start) * this.pos);
// Perform the next step of the animation
this.update();
}
return true;
}
};
jQuery.extend( jQuery.fx, {
tick: function() {
var timers = jQuery.timers;
for ( var i = 0; i < timers.length; i++ ) {
if ( !timers[i]() ) {
timers.splice(i--, 1);
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
},
interval: 13,
stop: function() {
clearInterval( timerId );
timerId = null;
},
speeds: {
slow: 600,
fast: 200,
// Default speed
_default: 400
},
step: {
opacity: function( fx ) {
jQuery.style( fx.elem, "opacity", fx.now );
},
_default: function( fx ) {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit;
} else {
fx.elem[ fx.prop ] = fx.now;
}
}
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
function defaultDisplay( nodeName ) {
if ( !elemdisplay[ nodeName ] ) {
var elem = jQuery("<" + nodeName + ">").appendTo("body"),
display = elem.css("display");
elem.remove();
if ( display === "none" || display === "" ) {
display = "block";
}
elemdisplay[ nodeName ] = display;
}
return elemdisplay[ nodeName ];
}
var rtable = /^t(?:able|d|h)$/i,
rroot = /^(?:body|html)$/i;
if ( "getBoundingClientRect" in document.documentElement ) {
jQuery.fn.offset = function( options ) {
var elem = this[0], box;
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
try {
box = elem.getBoundingClientRect();
} catch(e) {}
var doc = elem.ownerDocument,
docElem = doc.documentElement;
// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
return box || { top: 0, left: 0 };
}
var body = doc.body,
win = getWindow(doc),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = (win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ),
scrollLeft = (win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft),
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: top, left: left };
};
} else {
jQuery.fn.offset = function( options ) {
var elem = this[0];
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
jQuery.offset.initialize();
var computedStyle,
offsetParent = elem.offsetParent,
prevOffsetParent = elem,
doc = elem.ownerDocument,
docElem = doc.documentElement,
body = doc.body,
defaultView = doc.defaultView,
prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
top = elem.offsetTop,
left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
break;
}
computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
top -= elem.scrollTop;
left -= elem.scrollLeft;
if ( elem === offsetParent ) {
top += elem.offsetTop;
left += elem.offsetLeft;
if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevOffsetParent = offsetParent;
offsetParent = elem.offsetParent;
}
if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevComputedStyle = computedStyle;
}
if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
top += body.offsetTop;
left += body.offsetLeft;
}
if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
top += Math.max( docElem.scrollTop, body.scrollTop );
left += Math.max( docElem.scrollLeft, body.scrollLeft );
}
return { top: top, left: left };
};
}
jQuery.offset = {
initialize: function() {
var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0,
html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } );
container.innerHTML = html;
body.insertBefore( container, body.firstChild );
innerDiv = container.firstChild;
checkDiv = innerDiv.firstChild;
td = innerDiv.nextSibling.firstChild.firstChild;
this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
this.doesAddBorderForTableAndCells = (td.offsetTop === 5);
checkDiv.style.position = "fixed";
checkDiv.style.top = "20px";
// safari subtracts parent border width here which is 5px
this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15);
checkDiv.style.position = checkDiv.style.top = "";
innerDiv.style.overflow = "hidden";
innerDiv.style.position = "relative";
this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);
this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop);
body.removeChild( container );
body = container = innerDiv = checkDiv = table = td = null;
jQuery.offset.initialize = jQuery.noop;
},
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
jQuery.offset.initialize();
if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = (position === "absolute" && jQuery.inArray('auto', [curCSSTop, curCSSLeft]) > -1),
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is absolute
if ( calculatePosition ) {
curPosition = curElem.position();
}
curTop = calculatePosition ? curPosition.top : parseInt( curCSSTop, 10 ) || 0;
curLeft = calculatePosition ? curPosition.left : parseInt( curCSSLeft, 10 ) || 0;
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if (options.top != null) {
props.top = (options.top - curOffset.top) + curTop;
}
if (options.left != null) {
props.left = (options.left - curOffset.left) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return null;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( ["Left", "Top"], function( i, name ) {
var method = "scroll" + name;
jQuery.fn[ method ] = function(val) {
var elem = this[0], win;
if ( !elem ) {
return null;
}
if ( val !== undefined ) {
// Set the scroll offset
return this.each(function() {
win = getWindow( this );
if ( win ) {
win.scrollTo(
!i ? val : jQuery(win).scrollLeft(),
i ? val : jQuery(win).scrollTop()
);
} else {
this[ method ] = val;
}
});
} else {
win = getWindow( elem );
// Return the scroll offset
return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ method ] :
elem[ method ];
}
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function( i, name ) {
var type = name.toLowerCase();
// innerHeight and innerWidth
jQuery.fn["inner" + name] = function() {
return this[0] ?
parseFloat( jQuery.css( this[0], type, "padding" ) ) :
null;
};
// outerHeight and outerWidth
jQuery.fn["outer" + name] = function( margin ) {
return this[0] ?
parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) :
null;
};
jQuery.fn[ type ] = function( size ) {
// Get window width or height
var elem = this[0];
if ( !elem ) {
return size == null ? null : this;
}
if ( jQuery.isFunction( size ) ) {
return this.each(function( i ) {
var self = jQuery( this );
self[ type ]( size.call( this, i, self[ type ]() ) );
});
}
if ( jQuery.isWindow( elem ) ) {
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
return elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] ||
elem.document.body[ "client" + name ];
// Get document width or height
} else if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
return Math.max(
elem.documentElement["client" + name],
elem.body["scroll" + name], elem.documentElement["scroll" + name],
elem.body["offset" + name], elem.documentElement["offset" + name]
);
// Get or set width or height on the element
} else if ( size === undefined ) {
var orig = jQuery.css( elem, type ),
ret = parseFloat( orig );
return jQuery.isNaN( ret ) ? orig : ret;
// Set the width or height on the element (default to pixels if value is unitless)
} else {
return this.css( type, typeof size === "string" ? size : size + "px" );
}
};
});
})(window);
|
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*
* Version: 5.9.1 (2021-08-27)
*/
!function(){"use strict";var n=tinymce.util.Tools.resolve("tinymce.PluginManager"),r=tinymce.util.Tools.resolve("tinymce.Env");n.add("print",function(n){var t,i;function e(){return i.execCommand("mcePrint")}(t=n).addCommand("mcePrint",function(){r.browser.isIE()?t.getDoc().execCommand("print",!1,null):t.getWin().print()}),(i=n).ui.registry.addButton("print",{icon:"print",tooltip:"Print",onAction:e}),i.ui.registry.addMenuItem("print",{text:"Print...",icon:"print",onAction:e}),n.addShortcut("Meta+P","","mcePrint")})}();
|
let moduleName = 'app.controllers';
import angular from 'angular';
import MenuController from './ui/menu/menu_controller';
import ToolbarController from './ui/toolbar/toolbar_controller';
import SidebarController from './ui/sidebar/sidebar_controller';
import FacebookController from './facebook/facebook_controller';
import DashboardController from './dashboard/dashboard_controller';
import ProxyController from './proxy/proxy_controller';
angular.module(moduleName, [])
.controller('FacebookController', FacebookController)
.controller('DashboardController', DashboardController)
.controller('ProxyController', ProxyController)
.controller('ToolbarController', ToolbarController)
.controller('SidebarController', SidebarController)
.controller('MenuController', MenuController)
;
export default moduleName;
|
/**
* Original code from three.js project. https://github.com/mrdoob/three.js
* Original code published with the following license:
*
* The MIT License
*
* Copyright © 2010-2014 three.js authors
*
* 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.
*/
describe('Zia.Vector3', function() {
var x = 2;
var y = 3;
var z = 4;
it("has a constructor", function() {
var a = new Zia.Vector3();
expect(a.x).toBe(0);
expect(a.y).toBe(0);
expect(a.z).toBe(0);
a = new Zia.Vector3(x, y, z);
expect(a.x).toBe(x);
expect(a.y).toBe(y);
expect(a.z).toBe(z);
});
describe('set method', function() {
it("sets another vector into this vector", function() {
var a = new Zia.Vector3();
expect(a.x).toBe(0);
expect(a.y).toBe(0);
expect(a.z).toBe(0);
a.set(x, y, z);
expect(a.x).toBe(x);
expect(a.y).toBe(y);
expect(a.z).toBe(z);
});
});
it( "x, y, z properties", function() {
var a = new Zia.Vector3();
expect(a.x).toBe(0);
expect(a.y).toBe(0);
expect(a.z).toBe(0);
a.x = x;
a.y = y;
a.z = z;
expect(a.x).toBe(x);
expect(a.y).toBe(y);
expect(a.z).toBe(z);
});
describe('add method and addVector method', function() {
it("adds another vector to this vector", function() {
var a = new Zia.Vector3(x, y, z);
var b = new Zia.Vector3(-x, -y, -z);
Zia.Vector3.add(a, b, a);
expect(a.x).toBe(0);
expect(a.y).toBe(0);
expect(a.z).toBe(0);
var c = Zia.Vector3.add(b, b, new Zia.Vector3());
expect(c.x).toBe(-2*x);
expect(c.y).toBe(-2*y);
expect(c.z).toBe(-2*z);
});
});
it("sub and subVectors", function() {
var a = new Zia.Vector3(x, y, z);
var b = new Zia.Vector3(-x, -y, -z);
Zia.Vector3.subtract(a, b, a);
expect(a.x).toBe(2*x);
expect(a.y).toBe(2*y);
expect(a.z).toBe(2*z);
var c = Zia.Vector3.subtract(a, a, new Zia.Vector3());
expect(c.x).toBe(0);
expect(c.y).toBe(0);
expect(c.z).toBe(0);
});
it("multiply/divide", function() {
var a = new Zia.Vector3(x, y, z);
var b = new Zia.Vector3(-x, -y, -z);
Zia.Vector3.multiplyScalar(a, -2, a);
expect(a.x).toBe(x*-2);
expect(a.y).toBe(y*-2);
expect(a.z).toBe(z*-2);
Zia.Vector3.multiplyScalar(b, -2, b);
expect(b.x).toBe(x*2);
expect(b.y).toBe(y*2);
expect(b.z).toBe(z*2);
Zia.Vector3.divideScalar(a, -2, a);
expect(a.x).toBe(x);
expect(a.y).toBe(y);
expect(a.z).toBe(z);
Zia.Vector3.divideScalar(b, -2, b);
expect(b.x).toBe(-x);
expect(b.y).toBe(-y);
expect(b.z).toBe(-z);
});
it("min/max/clamp", function() {
var a = new Zia.Vector3(x, y, z);
var b = new Zia.Vector3(-x, -y, -z);
var c = new Zia.Vector3();
Zia.Vector3.min(a.clone(c), b, c);
expect(c.x).toBe(-x);
expect(c.y).toBe(-y);
expect(c.z).toBe(-z);
Zia.Vector3.max(a.clone(c), b, c);
expect(c.x).toBe(x);
expect(c.y).toBe(y);
expect(c.z).toBe(z);
c.set(-2*x, 2*y, -2*z);
Zia.Vector3.clamp(c, b, a, c);
expect(c.x).toBe(-x);
expect(c.y).toBe(y);
expect(c.z).toBe(-z);
});
it("negate", function() {
var a = new Zia.Vector3(x, y, z);
Zia.Vector3.negate(a, a);
expect(a.x).toBe(-x);
expect(a.y).toBe(-y);
expect(a.z).toBe(-z);
});
it("dot", function() {
var a = new Zia.Vector3(x, y, z);
var b = new Zia.Vector3(-x, -y, -z);
var c = new Zia.Vector3();
var result = Zia.Vector3.dot(a, b);
expect(result).toBe(-x*x-y*y-z*z);
result = Zia.Vector3.dot(a, c);
expect(result).toBe(0);
});
it("length/lengthSq", function() {
var a = new Zia.Vector3(x, 0, 0);
var b = new Zia.Vector3(0, -y, 0);
var c = new Zia.Vector3(0, 0, z);
var d = new Zia.Vector3();
expect(a.length()).toBe(x);
expect(a.lengthSquared()).toBe(x*x);
expect(b.length()).toBe(y);
expect(b.lengthSquared()).toBe(y*y);
expect(c.length()).toBe(z);
expect(c.lengthSquared()).toBe(z*z);
expect(d.length()).toBe(0);
expect(d.lengthSquared()).toBe(0);
a.set(x, y, z);
expect(a.length()).toBe(Math.sqrt(x*x + y*y + z*z));
expect(a.lengthSquared()).toBe(x*x + y*y + z*z);
});
it("normalize", function() {
var a = new Zia.Vector3(x, 0, 0);
var b = new Zia.Vector3(0, -y, 0);
var c = new Zia.Vector3(0, 0, z);
Zia.Vector3.normalize(a, a);
expect(a.length()).toBe(1);
expect(a.x).toBe(1);
Zia.Vector3.normalize(b, b);
expect(b.length()).toBe(1);
expect(b.y).toBe(-1);
Zia.Vector3.normalize(c, c);
expect(c.length()).toBe(1);
expect(c.z).toBe(1);
});
it("distanceTo/distanceToSquared", function() {
var a = new Zia.Vector3(x, 0, 0);
var b = new Zia.Vector3(0, -y, 0);
var c = new Zia.Vector3(0, 0, z);
var d = new Zia.Vector3();
expect(Zia.Vector3.distance(a, d)).toBe(x);
expect(Zia.Vector3.distanceSquared(a, d)).toBe(x*x);
expect(Zia.Vector3.distance(b, d)).toBe(y);
expect(Zia.Vector3.distanceSquared(b, d)).toBe(y*y);
expect(Zia.Vector3.distance(c, d)).toBe(z);
expect(Zia.Vector3.distanceSquared(c, d)).toBe(z*z);
});
it("reflect", function() {
var a = new Zia.Vector3();
var normal = new Zia.Vector3(0, 1, 0);
var b = new Zia.Vector3();
a.set(0, -1, 0);
expect(Zia.Vector3.reflect(a.clone(b), normal)).toEqual(new Zia.Vector3(0, 1, 0));
a.set(1, -1, 0);
expect(Zia.Vector3.reflect(a.clone(b), normal)).toEqual(new Zia.Vector3(1, 1, 0));
a.set(1, -1, 0);
normal.set(0, -1, 0);
expect(Zia.Vector3.reflect(a.clone(b), normal)).toEqual(new Zia.Vector3(1, 1, 0));
});
it("lerp/clone", function() {
var a = new Zia.Vector3(x, 0, z);
var b = new Zia.Vector3(0, -y, 0);
expect(Zia.Vector3.lerp(a, a, 0)).toEqual(Zia.Vector3.lerp(a, a, 0.5));
expect(Zia.Vector3.lerp(a, a, 0)).toEqual(Zia.Vector3.lerp(a, a, 1));
expect(Zia.Vector3.lerp(a.clone(), b, 0)).toEqual(a);
expect(Zia.Vector3.lerp(a.clone(), b, 0.5).x).toEqual(x*0.5);
expect(Zia.Vector3.lerp(a.clone(), b, 0.5).y).toEqual(-y*0.5);
expect(Zia.Vector3.lerp(a.clone(), b, 0.5).z).toEqual(z*0.5);
expect(Zia.Vector3.lerp(a.clone(), b, 1)).toEqual(b);
});
it("equals", function() {
var a = new Zia.Vector3(x, 0, z);
var b = new Zia.Vector3(0, -y, 0);
expect(a.x).not.toEqual(b.x);
expect(a.y).not.toEqual(b.y);
expect(a.z).not.toEqual(b.z);
expect(a.equals(b)).toBe(false);
expect(b.equals(a)).toBe(false);
b.clone(a);
expect(a.x).toEqual(b.x);
expect(a.y).toEqual(b.y);
expect(a.z).toEqual(b.z);
expect(a.equals(b)).toBe(true);
expect(b.equals(a)).toBe(true);
});
});
|
$(document).on("ready" ,function(){
listaTipologiaInversion();/*llamar a mi datatablet listar funcion*/
//abrir el modal para registrar
//REGISTARAR NUEVA tipologia inversion
$("#form-AddTipologiaInversion").submit(function(event)
{
event.preventDefault();
$.ajax(
{
url : base_url+"index.php/TipologiaInversion/AddTipologiaInversion",
type : $(this).attr('method'),
data :$(this).serialize(),
success : function(resp)
{
if(resp=='1')
{
swal("Se registró...","", "success");
formReset();
}
if(resp=='2')
{
swal("NO se registró...","", "error");
}
$('#dynamic-table-TipologiaInversion').dataTable()._fnAjaxUpdate();//para actualizar mi datatablet datatablet funcion
formReset();
$('#VentanaRegTipologiaInversion').modal('hide');
}
});
});
//limpiar campos
function formReset()
{
document.getElementById("form-AddTipologiaInversion").reset();
document.getElementById("form-EditTipologiaInversion").reset();
}
//formulario para ediotar
$("#form-EditTipologiaInversion").submit(function(event)
{
event.preventDefault();
$.ajax(
{
url : base_url+"index.php/TipologiaInversion/UpdateTipologiaInversion",
type : $(this).attr('method'),
data : $(this).serialize(),
success : function(resp)
{
swal(resp,"", "success");
$('#dynamic-table-TipologiaInversion').dataTable()._fnAjaxUpdate();//para actualizar mi datatablet datatablet funcion
formReset();
$('#VentanaEditTipologiaInversion').modal('hide');
}
});
});
});
/*listra */
var listaTipologiaInversion=function()
{
var myTable=$("#dynamic-table-TipologiaInversion").DataTable({
"processing":true,
"serverSide":false,
destroy:true,
"ajax":{
"url":base_url+"index.php/TipologiaInversion/get_TipologiaInversion",
"method":"POST",
"dataSrc":""
},
"columns":[
{"data":"id_tipologia_inv","visible" : false},
{"data":"nombre_tipologia_inv"},
{"defaultContent":"<button type='button' class='editar btn btn-primary btn-xs' data-toggle='modal' data-target='#VentanaEditTipologiaInversion'><i class='ace-icon fa fa-pencil bigger-120'></i></button><button type='button' class='eliminar btn btn-danger btn-xs' data-toggle='modal' data-target='#'><i class='fa fa-trash-o'></i></button>"}
],
"language":idioma_espanol
});
TipologiaData("#dynamic-table-TipologiaInversion",myTable); //CARGAR LA DATA PARA MOSTRAR EN EL MODAL
EliminarTipologiaData("#dynamic-table-TipologiaInversion",myTable);
}
var TipologiaData=function(tbody,myTable){
$(tbody).on("click","button.editar",function(){
var data=myTable.row( $(this).parents("tr")).data();
var txt_IdTipologiaInversionM=$('#txt_IdTipologiaInversionM').val(data.id_tipologia_inv);
var txt_NombreTipologiaInversionM=$('#txt_NombreTipologiaInversionM').val(data.nombre_tipologia_inv);
});
}
var EliminarTipologiaData=function(tbody,myTable){
$(tbody).on("click","button.eliminar",function(){
var data=myTable.row( $(this).parents("tr")).data();
var id_tipologia_inv=data.id_tipologia_inv;
console.log(data);
swal({
title: "Desea eliminar ?",
text: "",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes,Eliminar",
closeOnConfirm: false
},
function(){
$.ajax({
url:base_url+"index.php/TipologiaInversion/EliminarTipologiaInversion",
type:"POST",
data:{id_tipologia_inv:id_tipologia_inv},
success:function(respuesta){
//alert(respuesta);
swal("Se eliminó corectamente", ".", "success");
$('#dynamic-table-TipologiaInversion').dataTable()._fnAjaxUpdate();//para actualizar mi datatablet datatablet
}
});
});
});
}
/*Idioma de datatablet table-sector */
var idioma_espanol=
{
"sProcessing": "Procesando...",
"sLengthMenu": "Mostrar _MENU_ registros",
"sZeroRecords": "No se encontraron resultados",
"sEmptyTable": "Ningún dato disponible en esta tabla",
"sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
"sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros",
"sInfoFiltered": "(filtrado de un total de _MAX_ registros)",
"sInfoPostFix": "",
"sSearch": "Buscar:",
"sUrl": "",
"sInfoThousands": ",",
"sLoadingRecords": "Cargando...",
"oPaginate": {
"sFirst": "Primero",
"sLast": "Último",
"sNext": "Siguiente",
"sPrevious": "Anterior"
},
"oAria": {
"sSortAscending": ": Activar para ordenar la columna de manera ascendente",
"sSortDescending": ": Activar para ordenar la columna de manera descendente"
}
}
|
/*
This is a debug tool. It checks all revisions for data corruption
*/
if(process.argv.length != 3)
{
console.error("Use: node checkPad.js $PADID");
process.exit(1);
}
//get the padID
var padId = process.argv[2];
//initalize the database
var log4js = require("log4js");
log4js.setGlobalLogLevel("INFO");
var async = require("async");
var db = require('../node/db/DB');
var CommonCode = require('../node/utils/CommonCode');
var Changeset = CommonCode.require("/Changeset");
var padManager;
async.series([
//intallize the database
function (callback)
{
db.init(callback);
},
//get the pad
function (callback)
{
padManager = require('../node/db/PadManager');
padManager.doesPadExists(padId, function(err, exists)
{
if(!exists)
{
console.error("Pad does not exist");
process.exit(1);
}
padManager.getPad(padId, function(err, _pad)
{
pad = _pad;
callback(err);
});
});
},
function (callback)
{
//create an array with key kevisions
//key revisions always save the full pad atext
var head = pad.getHeadRevisionNumber();
var keyRevisions = [];
for(var i=0;i<head;i+=100)
{
keyRevisions.push(i);
}
//run trough all key revisions
async.forEachSeries(keyRevisions, function(keyRev, callback)
{
//create an array of revisions we need till the next keyRevision or the End
var revisionsNeeded = [];
for(var i=keyRev;i<=keyRev+100 && i<=head; i++)
{
revisionsNeeded.push(i);
}
//this array will hold all revision changesets
var revisions = [];
//run trough all needed revisions and get them from the database
async.forEach(revisionsNeeded, function(revNum, callback)
{
db.db.get("pad:"+padId+":revs:" + revNum, function(err, revision)
{
revisions[revNum] = revision;
callback(err);
});
}, function(err)
{
if(err)
{
callback(err);
return;
}
//check if the pad has a pool
if(pad.pool === undefined )
{
console.error("Attribute pool is missing");
process.exit(1);
}
//check if there is a atext in the keyRevisions
if(revisions[keyRev] === undefined || revisions[keyRev].meta === undefined || revisions[keyRev].meta.atext === undefined)
{
console.error("No atext in key revision " + keyRev);
callback();
return;
}
var apool = pad.pool;
var atext = revisions[keyRev].meta.atext;
for(var i=keyRev+1;i<=keyRev+100 && i<=head; i++)
{
try
{
//console.log("check revision " + i);
var cs = revisions[i].changeset;
atext = Changeset.applyToAText(cs, atext, apool);
}
catch(e)
{
console.error("Bad changeset at revision " + i + " - " + e.message);
callback();
return;
}
}
callback();
});
}, callback);
}
], function (err)
{
if(err) throw err;
else
{
console.log("finished");
process.exit(0);
}
});
|
// import React from 'react';
// import ReactDOM from 'react-dom';
//
// import('./index.css')
var React = require('react');
var ReactDOM = require('react-dom');
require('./index.css');
var App = require('./components/App');
ReactDOM.render(
<App />,
document.getElementById('app')
);
|
describe(`Client only paths`, () => {
const routes = [
{
path: `/client-only-paths`,
marker: `index`,
label: `Index route`,
},
{
path: `/client-only-paths/page/profile`,
marker: `profile`,
label: `Dynamic route`,
},
{
path: `/client-only-paths/not-found`,
marker: `NotFound`,
label: `Default route (not found)`,
},
{
path: `/client-only-paths/nested`,
marker: `nested-page/index`,
label: `Index route inside nested router`,
},
{
path: `/client-only-paths/nested/foo`,
marker: `nested-page/foo`,
label: `Dynamic route inside nested router`,
},
{
path: `/client-only-paths/static`,
marker: `static-sibling`,
label: `Static route that is a sibling to client only path`,
},
{
path: `/app`,
marker: `app-index-1`,
label: `Prioritize static page over matchPath page with wildcard (static page created before matchPath page)`,
},
{
path: `/app2`,
marker: `app-index-2`,
label: `Prioritize static page over matchPath page with wildcard (static page created after matchPath page)`,
},
{
path: `/app/foo`,
marker: `app-wildcard-1`,
label: `Can navigate to matchPath page with wildcard #1`,
},
{
path: `/app2/foo`,
marker: `app-wildcard-2`,
label: `Can navigate to matchPath page with wildcard #2`,
},
{
path: `/event/2019/10/26/test-event`,
marker: `static-event-1`,
label: `Prioritize static page over matchPath page with named parameters (static page created before matchPath page)`,
},
{
path: `/event/2019/10/28/test-event`,
marker: `static-event-2`,
label: `Prioritize static page over matchPath page with named parameters (static page created after matchPath page)`,
},
{
path: `/event/2019/10/27/test-event`,
marker: `dynamic-event`,
label: `Prioritize matchPath page with named parameters over matchPath page with wildcard`,
},
{
path: `/event/2019/10/foo`,
marker: `dynamic-and-wildcard`,
label: `Can navigate to matchPath page with mix of named parameters and wildcard`,
},
]
describe(`work on first load`, () => {
routes.forEach(({ path, marker, label, skipTestingExactLocation }) => {
it(label, () => {
cy.visit(path).waitForRouteChange()
cy.getTestElement(`dom-marker`).contains(marker)
// `serve-static` (used by `gatsby serve`) is doing some redirects when
// navigating to static pages to always include trailing slash.
// We want to pass this check if trailing slash is added.
cy.url().should(
`match`,
new RegExp(`^${Cypress.config().baseUrl + path}/?$`)
)
})
})
})
describe(`work on client side navigation`, () => {
beforeEach(() => {
cy.visit(`/`).waitForRouteChange()
})
routes.forEach(({ path, marker, label }) => {
it(label, () => {
cy.navigateAndWaitForRouteChange(path)
cy.getTestElement(`dom-marker`).contains(marker)
cy.url().should(`eq`, Cypress.config().baseUrl + path)
})
})
})
})
|
define([
'jquery',
'underscore',
'backbone',
'app'
], function($, _, Backbone, LessonManager) {
Tile = Backbone.Model.extend({
idAttribute: '_id',
parse: function(response) {
//Server
this.set("_id", response._id);
return response;
},
defaults: {
x: '',
y: '',
a: false
},
clear: function() {
console.log("destroy");
this.destroy();
}
});
LessonManager.reqres.setHandler("tile:entity:new", function(id) {
return new Tile();
});
return Tile;
});
|
define([
'views/view',
'views/track',
'tpl!templates/playlist.html',
'jquery-nestable'
],
function (View, TrackView, template) {
var Playlist = View.extend({
template: template,
initialize: function () {
this.listenTo(this.collection, 'add remove reset sort change:selected', this.render);
},
events: {
'click a.clear': 'onClear',
'click .dd li': 'onClick',
'change': 'onChangeOrder'
},
render: function () {
View.prototype.render.apply(this, arguments);
var ol = this.$el.find('ol').empty();
this.tracks = this.collection.map(function (model, index) {
var track = new TrackView({
model: model,
index: index
});
track.render();
ol.append(track.$el);
return track;
});
this.$el.find('.dd').nestable({
maxDepth: 1
});
},
onClear: function () {
this.collection.reset([]);
},
onClick: function (e) {
e.preventDefault();
e.stopPropagation();
// find out which track was clicked
var index = this.$el.find('li').index($(e.currentTarget));
this.collection.select(index);
},
onChangeOrder: function () {
var order = this.$el.find('li').map(function() {
return parseFloat($(this).data('id')) - 1;
}).get();
var models = _.map(order, function (index) {
return this.collection.at(index);
}, this);
this.collection.reset(models);
}
});
return Playlist;
});
|
// Karma configuration
// Generated on Mon Feb 16 2015 22:26:59 GMT-0500 (Eastern Standard Time)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'../dist/igneous.min.js',
'../spec/**/*[sS]pec.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'dots'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS', 'Chrome', 'IE'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
|
M.block_course_contents={debug:false,init:function(Y){main=this;this.Y=Y;main.log('course_contents block Debug mode active');Y.all('.block_course_contents li.section-item').on('click',function(e){main.log('in onclick handler');if(!e.target.hasClass('expanded')){e.target.addClass('expanded')}else e.target.removeClass('expanded');Y.Event.simulate(document.body,"click",{shiftKey:false})})},log:function(data){if(this.debug)console.log(data)}}
|
'use strict';
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const Promise = require('bluebird');
const del = require('del');
const render = require('../../lib/utils/render');
const { nunjucksEnv } = require('../../lib/utils/templates');
const readFile = Promise.promisify(fs.readFile);
describe('render', () => {
before(function () {
this.dest = `${__dirname}/dest/base.html`;
this.tpl = path.resolve(__dirname, 'fixtures', 'templates', 'base.njk');
});
afterEach(function () {
del.sync(this.dest);
});
it('renders nunjucks tpl as a string', function (done) {
const ctx = { name: 'World' };
render(nunjucksEnv, this.tpl, this.dest, ctx)
.then(() => readFile(this.dest, 'utf-8'))
.then((data) => {
assert.ok(data.includes('<title>Title | Herman Documentation</title>'));
assert.ok(
data.includes(
'<p>I say: Hello<span class="widont"> </span>World!</p>',
),
);
done();
})
.catch(done);
});
it('adds doc data to "rendered" array', function (done) {
const ctx = { name: 'World' };
const rendered = [];
const expected = [
{
filename: 'base.html',
title: 'Title',
contents: 'I say: Hello World!',
},
];
render(nunjucksEnv, this.tpl, this.dest, ctx, rendered)
.then(() => {
assert.deepStrictEqual(rendered, expected);
done();
})
.catch(done);
});
});
|
// 0: 成功
// 1---:参数错误
// 2---:服务错误
var _mokaError = {
//参数类
10100: '帐号格式有误',
10101: '手机格式有误',
10102: '邮箱格式有误',
10103: '密码长度必须大于等于6',
10200: '用户未登陆',
10201: '帐号未注册',
10202: '帐号已注册',
10203: '手机号码未注册',
10204: '手机号码已注册',
10205: '邮箱未注册',
10206: '邮箱已注册',
10207: '验证码错误',
10208: '帐号或密码错误',
10209: '性别格式有误, 1: man, 2: woman',
10300: '活动名字长度须大于2小于50',
10301: '截止日期必须为GMT毫秒数',
10302: '人数上限必须为整数',
10303: '费用必须为整型或者浮点型',
10304: '活动人数已满',
10305: '活动详情不能为空',
10306: '至少要一个标签',
10307: '活动坐标为空',
10400: '上传失败,请从新上传',
//服务类
20000: "服务内部错误",
}
/**
* mokaError
*/
var MokaError = function(code){
this.isMoka = true;
this.name = 'mokaError';
this.mokaError = {code: code, msg: _mokaError[code]};
}
MokaError.prototype = Object.create(Error.prototype);
MokaError.prototype.constructor = MokaError;
MokaError.prototype.toString = function() {
var obj = Object(this);
if (obj !== this) {
throw new TypeError();
}
var name = this.name;
name = (name === undefined) ? 'Error' : String(name);
var msg = this.mokaError.msg;
msg = (msg === undefined) ? '' : String(msg);
if (name === '') {
return msg;
}
if (msg === '') {
return name;
}
return name + ': ' + msg;
}
module.exports = MokaError;
|
'use strict'
var path = require('path')
var test = require('tape')
var noop = require('./util/noop-processor')
var spy = require('./util/spy')
var engine = require('..')
var join = path.join
var fixtures = join(__dirname, 'fixtures')
test('settings', function(t) {
t.plan(2)
t.test('should use `settings`', function(st) {
var stderr = spy()
st.plan(2)
engine(
{
processor: noop().use(attacher),
cwd: join(fixtures, 'one-file'),
streamError: stderr.stream,
files: ['.'],
extensions: ['txt'],
settings: {alpha: true}
},
onrun
)
function onrun(error, code) {
st.deepEqual(
[error, code, stderr()],
[null, 0, 'one.txt: no issues found\n'],
'should report'
)
}
function attacher() {
st.deepEqual(this.data('settings'), {alpha: true}, 'should configure')
this.Parser = parser
}
function parser(doc) {
return {type: 'text', value: doc}
}
})
t.test('should cascade `settings`', function(st) {
var stderr = spy()
st.plan(2)
engine(
{
processor: noop().use(attacher),
cwd: join(fixtures, 'config-settings-cascade'),
streamError: stderr.stream,
files: ['.'],
extensions: ['txt'],
rcName: '.foorc',
settings: {alpha: false, bravo: 'charlie'}
},
onrun
)
function onrun(error, code) {
st.deepEqual(
[error, code, stderr()],
[null, 0, 'one.txt: no issues found\n'],
'should report'
)
}
function attacher() {
st.deepEqual(
this.data('settings'),
{alpha: false, bravo: 'charlie', delta: 1},
'should configure'
)
this.Parser = parser
}
function parser(doc) {
return {type: 'text', value: doc}
}
})
})
test('plugins', function(t) {
t.plan(3)
t.test('should use `plugins` as list of functions', function(st) {
var stderr = spy()
st.plan(3)
engine(
{
processor: noop,
cwd: join(fixtures, 'one-file'),
streamError: stderr.stream,
files: ['.'],
extensions: ['txt'],
plugins: [one, [two, {alpha: true}]]
},
onrun
)
function onrun(error, code) {
st.deepEqual(
[error, code, stderr()],
[null, 0, 'one.txt: no issues found\n'],
'should report'
)
}
function one() {
return transformerOne
}
function transformerOne() {
st.pass('transformer')
}
function two(options) {
return transformerTwo
function transformerTwo() {
st.deepEqual(options, {alpha: true}, 'transformer')
}
}
})
t.test('should use `plugins` as list of strings', function(st) {
var stderr = spy()
st.plan(2)
engine(
{
processor: noop().use(addTest),
cwd: join(fixtures, 'config-plugins-reconfigure'),
streamError: stderr.stream,
files: ['.'],
extensions: ['txt'],
plugins: ['./preset', ['./preset/plugin', {two: false, three: true}]]
},
onrun
)
function onrun(error, code) {
st.deepEqual(
[error, code, stderr()],
[null, 0, 'one.txt: no issues found\n'],
'should report'
)
}
function addTest() {
this.t = st
}
})
t.test('should use `plugins` as list of objects', function(st) {
var stderr = spy()
st.plan(2)
engine(
{
processor: noop().use(addTest),
cwd: join(fixtures, 'config-plugins-reconfigure'),
streamError: stderr.stream,
files: ['.'],
extensions: ['txt'],
plugins: {
'./preset': null,
'./preset/plugin': {two: false, three: true}
}
},
onrun
)
function onrun(error, code) {
st.deepEqual(
[error, code, stderr()],
[null, 0, 'one.txt: no issues found\n'],
'should report'
)
}
function addTest() {
this.t = st
}
})
})
|
/* Tabulator v4.9.1 (c) Oliver Folkerd */
var ReactiveData = function ReactiveData(table) {
this.table = table; //hold Tabulator object
this.data = false;
this.blocked = false; //block reactivity while performing update
this.origFuncs = {}; // hold original data array functions to allow replacement after data is done with
this.currentVersion = 0;
};
ReactiveData.prototype.watchData = function (data) {
var self = this,
pushFunc,
version;
this.currentVersion++;
version = this.currentVersion;
self.unwatchData();
self.data = data;
//override array push function
self.origFuncs.push = data.push;
Object.defineProperty(self.data, "push", {
enumerable: false,
configurable: true,
value: function value() {
var args = Array.from(arguments);
if (!self.blocked && version === self.currentVersion) {
args.forEach(function (arg) {
self.table.rowManager.addRowActual(arg, false);
});
}
return self.origFuncs.push.apply(data, arguments);
}
});
//override array unshift function
self.origFuncs.unshift = data.unshift;
Object.defineProperty(self.data, "unshift", {
enumerable: false,
configurable: true,
value: function value() {
var args = Array.from(arguments);
if (!self.blocked && version === self.currentVersion) {
args.forEach(function (arg) {
self.table.rowManager.addRowActual(arg, true);
});
}
return self.origFuncs.unshift.apply(data, arguments);
}
});
//override array shift function
self.origFuncs.shift = data.shift;
Object.defineProperty(self.data, "shift", {
enumerable: false,
configurable: true,
value: function value() {
var row;
if (!self.blocked && version === self.currentVersion) {
if (self.data.length) {
row = self.table.rowManager.getRowFromDataObject(self.data[0]);
if (row) {
row.deleteActual();
}
}
}
return self.origFuncs.shift.call(data);
}
});
//override array pop function
self.origFuncs.pop = data.pop;
Object.defineProperty(self.data, "pop", {
enumerable: false,
configurable: true,
value: function value() {
var row;
if (!self.blocked && version === self.currentVersion) {
if (self.data.length) {
row = self.table.rowManager.getRowFromDataObject(self.data[self.data.length - 1]);
if (row) {
row.deleteActual();
}
}
}
return self.origFuncs.pop.call(data);
}
});
//override array splice function
self.origFuncs.splice = data.splice;
Object.defineProperty(self.data, "splice", {
enumerable: false,
configurable: true,
value: function value() {
var args = Array.from(arguments),
start = args[0] < 0 ? data.length + args[0] : args[0],
end = args[1],
newRows = args[2] ? args.slice(2) : false,
startRow;
if (!self.blocked && version === self.currentVersion) {
//add new rows
if (newRows) {
startRow = data[start] ? self.table.rowManager.getRowFromDataObject(data[start]) : false;
if (startRow) {
newRows.forEach(function (rowData) {
self.table.rowManager.addRowActual(rowData, true, startRow, true);
});
} else {
newRows = newRows.slice().reverse();
newRows.forEach(function (rowData) {
self.table.rowManager.addRowActual(rowData, true, false, true);
});
}
}
//delete removed rows
if (end !== 0) {
var oldRows = data.slice(start, typeof args[1] === "undefined" ? args[1] : start + end);
oldRows.forEach(function (rowData, i) {
var row = self.table.rowManager.getRowFromDataObject(rowData);
if (row) {
row.deleteActual(i !== oldRows.length - 1);
}
});
}
if (newRows || end !== 0) {
self.table.rowManager.reRenderInPosition();
}
}
return self.origFuncs.splice.apply(data, arguments);
}
});
};
ReactiveData.prototype.unwatchData = function () {
if (this.data !== false) {
for (var key in this.origFuncs) {
Object.defineProperty(this.data, key, {
enumerable: true,
configurable: true,
writable: true,
value: this.origFuncs.key
});
}
}
};
ReactiveData.prototype.watchRow = function (row) {
var data = row.getData();
this.blocked = true;
for (var key in data) {
this.watchKey(row, data, key);
}
if (this.table.options.dataTree) {
this.watchTreeChildren(row);
}
this.blocked = false;
};
ReactiveData.prototype.watchTreeChildren = function (row) {
var self = this,
childField = row.getData()[this.table.options.dataTreeChildField],
origFuncs = {};
function rebuildTree() {
self.table.modules.dataTree.initializeRow(row);
self.table.modules.dataTree.layoutRow(row);
self.table.rowManager.refreshActiveData("tree", false, true);
}
if (childField) {
origFuncs.push = childField.push;
Object.defineProperty(childField, "push", {
enumerable: false,
configurable: true,
value: function value() {
var result = origFuncs.push.apply(childField, arguments);
rebuildTree();
return result;
}
});
origFuncs.unshift = childField.unshift;
Object.defineProperty(childField, "unshift", {
enumerable: false,
configurable: true,
value: function value() {
var result = origFuncs.unshift.apply(childField, arguments);
rebuildTree();
return result;
}
});
origFuncs.shift = childField.shift;
Object.defineProperty(childField, "shift", {
enumerable: false,
configurable: true,
value: function value() {
var result = origFuncs.shift.call(childField);
rebuildTree();
return result;
}
});
origFuncs.pop = childField.pop;
Object.defineProperty(childField, "pop", {
enumerable: false,
configurable: true,
value: function value() {
var result = origFuncs.pop.call(childField);
rebuildTree();
return result;
}
});
origFuncs.splice = childField.splice;
Object.defineProperty(childField, "splice", {
enumerable: false,
configurable: true,
value: function value() {
var result = origFuncs.splice.apply(childField, arguments);
rebuildTree();
return result;
}
});
}
};
ReactiveData.prototype.watchKey = function (row, data, key) {
var self = this,
props = Object.getOwnPropertyDescriptor(data, key),
value = data[key],
version = this.currentVersion;
Object.defineProperty(data, key, {
set: function set(newValue) {
value = newValue;
if (!self.blocked && version === self.currentVersion) {
var update = {};
update[key] = newValue;
row.updateData(update);
}
if (props.set) {
props.set(newValue);
}
},
get: function get() {
if (props.get) {
props.get();
}
return value;
}
});
};
ReactiveData.prototype.unwatchRow = function (row) {
var data = row.getData();
for (var key in data) {
Object.defineProperty(data, key, {
value: data[key]
});
}
};
ReactiveData.prototype.block = function () {
this.blocked = true;
};
ReactiveData.prototype.unblock = function () {
this.blocked = false;
};
Tabulator.prototype.registerModule("reactiveData", ReactiveData);
|
/* @flow */
export const HASH_KEY = 'jfa^7uY(#)'
export const SECRET_KEY = 'nj&H8^0L'
|
const getReadableStream = require('./getReadableStream.js');
const getDuplexStream = require('./getDuplexStream.js');
function runBasicStreamTests(data, objData, runTest) {
if (data) {
it('works with a Readable stream', (done) => {
const readableStream = getReadableStream(data);
runTest(readableStream, false, done);
});
}
it('works with a Readable object stream', (done) => {
const readableStream = getReadableStream(objData, {
objectMode: true
});
runTest(readableStream, true, done);
});
if (data) {
it('works with a Duplex stream', (done) => {
const duplexStream = getDuplexStream(data);
runTest(duplexStream, false, done);
});
}
it('works with a Duplex object stream', (done) => {
const duplexStream = getDuplexStream(objData, {
objectMode: true
});
runTest(duplexStream, true, done);
});
}
module.exports = runBasicStreamTests;
|
/**
* Created by lab on 09/09/15.
*/
"use strict";
var app = angular.module("app", ['ngPapaParse', 'ui.select', 'ngSanitize', 'ngAnimate', 'ui.bootstrap', 'ui.bootstrap.collapse','ngOboe']);
app.service('neo4jQueryBuilder', [function() {
return function(queryObject) {
var api = {
getDomains: getDomains,
getMultiSelectionDomains: getMultiSelectionDomains,
getSelectionDomains: getSelectionDomains
};
var statmentTable = {
sp: "MATCH (sp:SWISSProt)-[r:MAPPED]-(p:PDBChain)-[:MAPPED]-(d:ECODDomain) WHERE sp.id = { id } AND (d)-[:DISTANCE]-() AND ( (({start}+{end})< 0) XOR (r.spStart <= {start} AND r.spEnd >= {end}) ) return id(d)",
pdb: "MATCH MATCH (p:PDBEntry)-[:SUBCHAIN]-(:PDBChain)-[:MAPPED]-(d:ECODDomain) where p.id = { id } return id(d)",
pdbc: "MATCH (c:PDBChain)-[r:MAPPED]-(d:ECODDomain) WHERE c.id = { id } AND (d)-[:DISTANCE]-() AND ( (({start}+{end})< 0) XOR (r.seqidStart <= {start} AND r.seqidEnd >= {end}) ) return id(d)",
ecod: "MATCH (d:ECODDomain) WHERE d.id = {id} return id(d)"
};
return api;
function getDomains() {
var statmentString = "MATCH (d:ECODDomain)-[r:DISTANCE]-()";
statmentString += buildRelationWhere();
var queryString = statmentString + " RETURN DISTINCT r";
var queryCountString = statmentString + " RETURN COUNT(d) AS domainCount, COUNT(DISTINCT r) AS relationshipCount";
var query_data_object = {
"statements": [{
"statement": queryString,
"resultDataContents": ["graph"]
}]
};
var query_count_data_object = {
"statements": [{
"statement": queryCountString,
"resultDataContents": ["row"]
}]
};
return {
queryString: JSON.stringify(query_data_object),
queryCountString: JSON.stringify(query_count_data_object)
};
}
function buildRelationWhere() {
var statmentString = " ";
var whereAdded = false;
var addAnd = false;
angular.forEach(queryObject, function (value, key) {
var lowerAdded = false;
if (value && (value.lower || value.upper)) {
if (!whereAdded) {
statmentString += " WHERE (";
whereAdded = true;
}
if (addAnd) {
statmentString += " AND"
}
statmentString += " (";
if (value.lower) {
statmentString += " " + value.lower + " <= r." + key;
lowerAdded = true;
}
if (value.upper) {
if (lowerAdded) {
statmentString += " AND"
}
statmentString += " r." + key + " <= " + value.upper;
}
statmentString += " )";
addAnd = true;
}
});
if (whereAdded) {
statmentString += " )";
}
return statmentString;
}
/* function getSPDomains(sp) {
var statmentString = "MATCH (sp:SWISSProt)-[r:MAPPED]-(p:PDBChain)-[:MAPPED]-(d:ECODDomain) WHERE sp.id = { spid } AND (d)-[:DISTANCE]-() AND ( (({start}+{end})< 0) XOR (r.spStart <= {start} AND r.spEnd >= {end}) ) return id(d)";
var params = {
"spid": sp.id,
"start": (sp.start ? sp.start : -1),
"end": (sp.end ? sp.end : -1)
};
var query_data_object = {
"statement": statmentString,
"parameters": params,
"resultDataContents": ["row"]
};
return query_data_object;
}
function getMultiSPDomains(sps) {
var statements = [];
angular.forEach(sps, function (sp) {
statements.push(getSPDomains(sp));
});
return statements;
}
function getECODDomain(ecod) {
var statmentString = "MATCH (d:ECODDomain) WHERE d.id = { ecodid } return id(d)";
var params = {
"ecodid": ecod.id
};
var query_data_object = {
"statement": statmentString,
"parameters": params,
"resultDataContents": ["row"]
};
return query_data_object;
}
function getMultiECODDomains(ecods) {
var statements = [];
angular.forEach(ecods, function (ecod) {
statements.push(getECODDomain(ecod));
});
return statements;
}
function getMultiPDBDomains(pdbs) {
var statements = [];
angular.forEach(pdbs, function (pdb) {
statements.push(getPDBDomains(pdb));
});
return statements;
}
function getPDBDomains(pdb) {
var statmentString = "MATCH MATCH (p:PDBEntry)-[:SUBCHAIN]-(:PDBChain)-[:MAPPED]-(d:ECODDomain) where p.id =~ '(?){ pdbid }' return id(d)";
var params = {
"spid": pdb.id,
"start": (pdb.start ? pdb.start : -1),
"end": (pdb.end ? pdb.end : -1)
};
var query_data_object = {
"statement": statmentString,
"parameters": params,
"resultDataContents": ["row"]
};
return query_data_object;
}*/
function getMultiSelectionDomains(ids, type) {
var statements = [];
angular.forEach(ids, function (id) {
statements.push(getSelectionDomains(id, type));
});
return statements;
}
function getSelectionDomains(id, type) {
var statmentString = statmentTable[type];
var params = {
"id": ((type == "pdb" || type == "pdbc") ? normalizePdb(id.id): id.id),
"start": (id.start ? id.start : -1),
"end": (id.end ? id.end : -1)
};
var query_data_object = {
"statement": statmentString,
"parameters": params,
"resultDataContents": ["row"]
};
return query_data_object;
}
function normalizePdb(pdb) {
var res = pdb.split('.');
try {
res[0] = res[0].toLowerCase();
} catch (e) {
return undefined;
}
try {
res[1] = res[1].toUpperCase();
return res[0]+'.'+res[1];
} catch (e) {
return res[0];
}
}
};
}]);
app.factory('vivaGraphFactory', ['$q', 'layoutSettings', 'archColors', function($q, layoutSettings, archColors) {
var vivaGraph = function () {
//var vivaGraph = function ( container, neo4j_graph ) {
this.container = undefined;
var vivaGraph = Viva.Graph.graph();
this.graph = vivaGraph;
//this.layout = Viva.Graph.Layout.forceDirected(this.graph, layoutSettings);
//this.layout = Viva.Graph.Layout.forceDirectedPause(this.graph, layoutSettings);
/*var springForce = function (options) {
//var random = require('ngraph.random').random(42);
/!*options = merge(options, {
springCoeff: 0.0002,
springLength: 80
});*!/
options.springCoeff = (options.springCoeff) ? options.springCoeff : 0.0002;
options.springLength = (options.springLength) ? options.springLength : 80;
var api = {
/!**
* Upsates forces acting on a spring
*!/
update : function (spring) {
var body1 = spring.from,
body2 = spring.to,
length = spring.length < 0 ? options.springLength : spring.length,
dx = body2.pos.x - body1.pos.x,
dy = body2.pos.y - body1.pos.y,
r = Math.sqrt(dx * dx + dy * dy);
//if (r === 0) {
// dx = (random.nextDouble() - 0.5) / 50;
// dy = (random.nextDouble() - 0.5) / 50;
// r = Math.sqrt(dx * dx + dy * dy);
//}
var d = r - length;
var coeff = ((!spring.coeff || spring.coeff < 0) ? options.springCoeff : spring.coeff) *( d / r )* spring.weight;
//var coeff = ((!spring.coeff || spring.coeff < 0) ? options.springCoeff : spring.coeff) *( d/r )* spring.weight;
body1.force.x += coeff * dx;
body1.force.y += coeff * dy;
body2.force.x -= coeff * dx;
body2.force.y -= coeff * dy;
}
};
return api;
};*/
var physicsSettings = {
springLength: 30,
springCoeff: 0.0014,
gravity: -1.0,
theta: 0.8,
dragCoeff: 0.08,
timeStep: 20
//createSpringForce: springForce
};
this.layout = Viva.Graph.Layout.pausableForceDirected(this.graph, physicsSettings);
/* this.layout = Viva.Graph.Layout.forceAtlas2(this.graph,{
gravity: 1,
linLogMode: false,
strongGravityMode: false,
slowDown: 1,
outboundAttractionDistribution: false,
iterationsPerRender: 1,
barnesHutOptimize: false,
barnesHutTheta: 0.5,
worker: false
});*/
var customNode = function (size, color) {
function parseColor(color) {
var parsedColor = 0x009ee8ff;
if (typeof color === 'string' && color) {
if (color.length === 4) { // #rgb
color = color.replace(/([^#])/g, '$1$1'); // duplicate each letter except first #.
}
if (color.length === 9) { // #rrggbbaa
parsedColor = parseInt(color.substr(1), 16);
} else if (color.length === 7) { // or #rrggbb.
parsedColor = (parseInt(color.substr(1), 16) << 8) | 0xff;
} else {
throw 'Color expected in hex format with preceding "#". E.g. #00ff00. Got value: ' + color;
}
} else if (typeof color === 'number') {
parsedColor = color;
}
return parsedColor;
}
return {
/**
* Gets or sets size of the square side.
*/
size: typeof size === 'number' ? size : 10,
/**
* Gets or sets color of the square.
*/
get color () {
try {
if (this.node.data.hide) return parseColor('#D8D8D8');
return parseColor(color);
} catch (e) {
//
}
},
set color (color) {
color = color;
},
get marked () {
var val = this.node.data.marked;
if (val) {
return val;
}
return 0;
},
set marked (val) {
this.node.data.marked = val;
},
get extraParameters () {
return this.marked;
}
/*marked: function() {
var val = this.node.data.marked;
if (val) {
return val;
}
return 0;
}*/
};
};
//var glLinkProg = Viva.Graph.View.webglLinkProgram();
var vGraphics = Viva.Graph.View.webglGraphics();
this.graphics = vGraphics;
/*var renderMingleLinks = function () {
if (this.omitLinksRendering) {
return;
}
var nodes = [];
var toPos = {x: 0, y: 0};
var fromPos = {x: 0, y: 0};
var pos;
/!* for (var i = 0; i < linksCount; ++i) {
var ui = links[i];
var pos = ui.pos.from;
fromPos.x = pos.x;
fromPos.y = -pos.y;
pos = ui.pos.to;
toPos.x = pos.x;
toPos.y = -pos.y;
nodes.push({
id: ui.id,
name: ui.id,
data: {
coords: [fromPos.x, fromPos.y, toPos.x, toPos.y]
}
});
}*!/
//return;
vivaGraph.forEachLink(function(link) {
var ui = vGraphics.getLinkUI(link.id);
//console.log(ui);
pos = ui.pos.from;
fromPos.x = pos.x;
fromPos.y = pos.y;
pos = ui.pos.to;
toPos.x = pos.x;
toPos.y = pos.y;
nodes.push({
id: ui.id,
name: ui.id,
color: ui.color,
data: {
coords: [fromPos.x, fromPos.y, toPos.x, toPos.y]
}
});
});
if (!nodes.length) {
return;
}
var bundle = new Bundler();
bundle.setNodes(nodes);
bundle.buildNearestNeighborGraph();
bundle.MINGLE();
bundle.graph.each(function (node) {
var edges = node.unbundleEdges(1);
for (var i= 0, l = edges.length; i < l; i++) {
var e = edges[i];
for(var j= 1, n = e.length; j<n; j++) {
//var pos = e[j].unbundledPos;
pos = e[j-1].unbundledPos;
fromPos.x = pos[0];
fromPos.y = -pos[1];
pos = e[j].unbundledPos;
toPos.x = pos[0];
toPos.y = -pos[1];
glLinkProg.position({id: node.id, color: 3014898687}, fromPos, toPos);
}
}
});
};*/
//this.graphics.renderLinks = renderMingleLinks;
var nodeProgram = new Viva.Graph.View.customWebglNodeProgram();
this.graphics.setNodeProgram(nodeProgram);
//this.graphics.setLinkProgram(glLinkProg);
this.graphics.node(function (node) {
var img = customNode(10, archColors[node.data.arch]);
img.color = img.color - 255;
return img;
});
this.events = Viva.Graph.webglInputEvents(this.graphics, this.graph);
};
vivaGraph.prototype.dispose = function () {
this.renderer.dispose();
};
vivaGraph.prototype.setContainer = function(container) {
this.container = container;
this.createRenderer();
};
vivaGraph.prototype.createRenderer = function() {
this.renderer = Viva.Graph.View.renderer(this.graph,
{
layout : this.layout,
graphics : this.graphics,
renderLinks : true,
container: this.container
}).run();
/*this.renderer = Viva.Graph.View.pixelRenderer(this.graph,
{
container: this.container,
settings: false,
is3d: false
});*/
};
return vivaGraph;
}]);
app.service('OboeWrapper', ['Oboe', function(Oboe) {
return function(oboeParams, errCallback, notifyCallback) {
Oboe(oboeParams).then(
function() {
// finished loading
},
function(error){
// handle errors
errCallback(error);
},
function(nodeObj) {
// handle pattern found notifictions
notifyCallback(nodeObj);
}
);
};
}]);
app.controller('domainCtrl', ['$scope', '$http','vivaGraphFactory', 'neo4jQueryBuilder', 'OboeWrapper', '$modal', 'layoutSettings', 'Papa',
function( $scope, $http, vivaGraphFactory, neo4jQueryBuilder, OboeWrapper, $modal, layoutSettings, Papa) {
var files = {ecodFile: undefined, pdbfile: undefined, pdbcfile: undefined, spfile: undefined};
$scope.query = {rmsd: undefined, psim: undefined, pid: undefined, length: undefined, ligand: undefined};
$scope.graphData = [];
$scope.ligands = [];
$scope.pauseRendering = true;
$scope.pauseLayout = true;
$scope.nodeData = undefined, $scope.nodeSelected = false;
$scope.selectionInput = undefined;
$scope.vivaGraph = new vivaGraphFactory();
$scope.vivaGraph.events.mouseEnter(function (node) {
//console.log('Mouse entered node: ' + node.id);
if (!$scope.nodeSelected) {
$scope.nodeData = node.data;
$scope.$apply();
}
}).mouseLeave(function (node) {
//console.log('Mouse left node: ' + node.id);
if (!$scope.nodeSelected) {
$scope.nodeData = undefined;
$scope.$apply();
}
}).dblClick(function (node) {
//console.log('Double click on node: ' + node.id);
}).click(function (node) {
//console.log('Single click on node: ' + node.id);
$scope.nodeSelected = !$scope.nodeSelected;
node.data.marked = $scope.nodeSelected? 1 : 0;
});
$scope.reset = function() {
//$scope.vivaGraph.renderer.pause();
$scope.vivaGraph.renderer.reset();
//$scope.vivaGraph.renderer.resume();
};
$scope.pauseGraphLayout = function() {
$scope.vivaGraph.layout.pause();
$scope.pauseLayout = false;
};
$scope.resumeGraphLayout = function() {
$scope.vivaGraph.layout.resume();
$scope.pauseLayout = true;
};
$scope.pauseGraphRendering = function() {
//$scope.vivaGraph.layout.setRunLayout(false);
$scope.vivaGraph.renderer.pause();
$scope.pauseRendering = false;
};
$scope.resumeGraphRendering = function() {
//$scope.vivaGraph.layout.setRunLayout(true);
$scope.vivaGraph.renderer.resume();
$scope.pauseRendering = true;
};
$scope.updateGraph = function(queryObject) {
var graph = $scope.vivaGraph.graph;
var queryStrings = neo4jQueryBuilder(queryObject).getDomains();
var modalInstance;
var countReq = {
method: 'POST',
url: 'http://localhost:7474/db/data/transaction/commit',
headers: {
Accept: "application/json; charset=UTF-8",
'Content-Type': 'application/json'
//'X-Stream': 'true'
},
//data: request_data_string
body: queryStrings.queryCountString
};
countReq.start = function(stream) {
console.log("Count Start");
};
countReq.done = function() {
console.log("Count Done");
$scope.domainCount = 0;
$scope.relationshipCount = 0;
modalInstance = $modal.open({
templateUrl: 'graphLoadingModal.html',
controller: 'graphLoadingModalController',
resolve: {
counters: {
domainTotalCount: function() {
return $scope.domainTotalCount;
},
relationshipTotalCount: function() {
return $scope.relationshipTotalCount;
},
domainCount: function() {
return $scope.domainCount;
},
relationshipCount: function() {
return $scope.relationshipCount;
}
}
}
}
);
var req = {
method: 'POST',
url: 'http://localhost:7474/db/data/transaction/commit',
headers: {
Accept: "application/json; charset=UTF-8",
'Content-Type': 'application/json'
//'X-Stream': 'true'
},
//data: request_data_string
body: queryStrings.queryString,
start: function (stream) {
$scope.pauseGraphRendering();
graph.beginUpdate();
graph.clear();
console.log("Start");
},
done: function() {
console.log("Done");
graph.endUpdate();
/* var layout = Viva.Graph.Layout.forceAtlas2(graph,{
gravity: 9,
scalingRatio: 8,
linLogMode: false,
strongGravityMode: false,
slowDown: 3,
outboundAttractionDistribution: false,
iterationsPerRender: 1,
barnesHutOptimize: true,
edgeWeightInfluence: 0,
barnesHutTheta: 0.8,
worker: true,
adjustSizes: true
});
$scope.vivaGraph.renderer = Viva.Graph.View.renderer(graph,
{
layout : layout,
graphics : $scope.vivaGraph.graphics,
renderLinks : true,
container: $scope.vivaGraph.container
}).run();*/
$scope.resumeGraphRendering();
modalInstance.close();
},
patterns: {'node:graph.nodes.*': function (node) {
graph.addNode(node.id, node.properties);
$scope.domainCount++;
$scope.$apply();
}, 'node:graph.relationships.*': function (node) {
graph.addLink(node.startNode, node.endNode);
$scope.relationshipCount++;
$scope.$apply();
}, 'errors': function (node) {
console.log(node);
}}
};
OboeWrapper(req,
function (error) {
// handle errors
}, function (nodeObj) {
}
);
};
countReq.patterns = {
'node:row': function (node) {
$scope.domainTotalCount = node[0];
$scope.relationshipTotalCount = node[1];
$scope.$apply();
}
};
OboeWrapper(countReq,
function(error){
//handle errors
},
function(nodeObj) {
$scope.domainTotalCount = nodeObj[0];
$scope.relationshipTotalCount = nodeObj[1];
}
);
};
$scope.markDomains = function(selectionInput, type) {
/*if (!selectionInput)
return;
var selectionObj;
if (typeof selectionInput === 'string') {
try {
selectionObj = JSON.parse(selectionInput);
} catch (e) {
console.log(e);
return;
}
} else {
selectionObj = selectionInput;
}*/
var statements = [];
/*try {
statements = statements.concat(neo4jQueryBuilder($scope.query).getMultiSPDomains(selectionObj.sp));
//statements.concat(neo4jQueryBuilder($scope.query).getMultiPDBDomains(selectionObj.pdb));
//statements.concat(neo4jQueryBuilder($scope.query).getMultiPDBCDomains(selectionObj.pdbc));
//statements = statements.concat(neo4jQueryBuilder($scope.query).getMultiECODDomains(selectionObj.ecod));
} catch (e) {
console.log(e);
return;
}*/
statements = neo4jQueryBuilder($scope.query).getMultiSelectionDomains(selectionInput, type);
var req = {
method: 'POST',
url: 'http://localhost:7474/db/data/transaction/commit',
headers: {
Accept: "application/json; charset=UTF-8",
'Content-Type': 'application/json',
'X-Stream': 'true'
},
//data: request_data_string
body: JSON.stringify({"statements": statements}),
start: function (stream) {
console.log("Selection Start");
$scope.vivaGraph.graph.forEachNode(function (node) {
node.data.hide = true;
});
},
done: function() {
console.log("Selection Done");
},
patterns: {'node:row': function (nodeId) {
var node = $scope.vivaGraph.graph.getNode(nodeId);
if (node) {
//node.data.marked = 1;
node.data.hide = false;
}
}, 'errors': function (node) {
console.log(nodeId);
}}
};
OboeWrapper(req,
function (error) {
// handle errors
}, function (nodeObj) {
}
);
};
$scope.clearMarking = function () {
$scope.vivaGraph.graph.forEachNode(function (node) {
//node.data.marked = 0;
node.data.hide = false;
});
};
$scope.setFile = function (element, type) {
files[type] = element.files[0];
};
/* $scope.setECODFile = function (element) {
console.log('files:', element.files);
ecodFile = element.files[0];
};
$scope.setPDBFile = function (element) {
console.log('files:', element.files);
pdbfile = element.files[0];
};*/
function parseFile(file, type) {
var ids = [];
Papa.parse(file, {
worker: true,
header:true,
dynamicTyping: true,
step: function(row) {
//console.log("Row:", row.data);
ids.push(row.data[0]);
},
complete: function() {
console.log("All done!");
$scope.markDomains(ids, type);
}
});
}
$scope.csvMarkDomains = function() {
angular.forEach(files, function (value, key) { //value - file, key - type: ecod, pdbc, pdb or sp
parseFile(value, key);
})
};
}]);
app.controller('graphLoadingModalController',['$scope', '$modalInstance', 'counters', function ($scope, $modalInstance, counters) {
$scope.counters = counters;
$scope.cancel = function() {
//
}
}]);
app.directive('vivagraph', [function () {
return {
restrict: 'E',
scope: {
// data objects to be passed as an attributes - for nodes and edges
//vgData: '=data',
//setVg: '&'
vivaGraph: '=vivaGraph'
},
link: function(scope, element, attrs, fn) {
scope.vivaGraph.setContainer(element[0]);
}
}
}]);
app.value('archColors',{
'alpha arrays': '#FE8900',
'alpha bundles': '#00FF00',
'alpha superhelices': '#0000FF',
'alpha duplicates or obligate multimers': '#FF0000',
'alpha complex topology': '#01FFFE',
'beta barrels': '#FFA6FE',
'beta meanders': '#FFDB66',
'beta sandwiches': '#006401',
'beta duplicates or obligate multimers': '#010067',
'beta complex topology': '#95003A',
'a+b two layers': '#007DB5',
'a+b three layers': '#FF00F6',
'a+b four layers': '#FFEEE8',
'a+b complex topology': '#774D00',
'a+b duplicates or obligate multimers': '#90FB92',
'a/b barrels': '#0076FF',
'a/b three-layered sandwiches': '#D5FF00',
'mixed a+b and a/b': '#FF937E',
'few secondary structure elements': '#6A826C',
'extended segments': '#FF029D'
});
app.value('layoutSettings', {
springLength : 30,
springCoeff : 0.0008,
dragCoeff : 0.01,
gravity : -1.2,
theta : 1
});
|
/**
* React Router DOM v6.0.0
*
* Copyright (c) Remix Software Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE.md file in the root directory of this source tree.
*
* @license MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('history'), require('react-router')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', 'history', 'react-router'], factory) :
(global = global || self, factory(global.ReactRouterDOM = {}, global.React, global.HistoryLibrary, global.ReactRouter));
}(this, (function (exports, React, history, reactRouter) { 'use strict';
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;
}
const _excluded = ["onClick", "replace", "state", "target", "to"],
_excluded2 = ["aria-current", "caseSensitive", "className", "end", "style", "to"];
function warning(cond, message) {
if (!cond) {
// eslint-disable-next-line no-console
if (typeof console !== "undefined") console.warn(message);
try {
// Welcome to debugging React Router!
//
// This error is thrown as a convenience so you can more easily
// find the source for a warning that appears in the console by
// enabling "pause on exceptions" in your JavaScript debugger.
throw new Error(message); // eslint-disable-next-line no-empty
} catch (e) {}
}
} ////////////////////////////////////////////////////////////////////////////////
// COMPONENTS
////////////////////////////////////////////////////////////////////////////////
/**
* A <Router> for use in web browsers. Provides the cleanest URLs.
*/
function BrowserRouter(_ref) {
let {
basename,
children,
window
} = _ref;
let historyRef = React.useRef();
if (historyRef.current == null) {
historyRef.current = history.createBrowserHistory({
window
});
}
let history$1 = historyRef.current;
let [state, setState] = React.useState({
action: history$1.action,
location: history$1.location
});
React.useLayoutEffect(() => history$1.listen(setState), [history$1]);
return /*#__PURE__*/React.createElement(reactRouter.Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history$1
});
}
/**
* A <Router> for use in web browsers. Stores the location in the hash
* portion of the URL so it is not sent to the server.
*/
function HashRouter(_ref2) {
let {
basename,
children,
window
} = _ref2;
let historyRef = React.useRef();
if (historyRef.current == null) {
historyRef.current = history.createHashHistory({
window
});
}
let history$1 = historyRef.current;
let [state, setState] = React.useState({
action: history$1.action,
location: history$1.location
});
React.useLayoutEffect(() => history$1.listen(setState), [history$1]);
return /*#__PURE__*/React.createElement(reactRouter.Router, {
basename: basename,
children: children,
location: state.location,
navigationType: state.action,
navigator: history$1
});
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
/**
* The public API for rendering a history-aware <a>.
*/
const Link = /*#__PURE__*/React.forwardRef(function LinkWithRef(_ref3, ref) {
let {
onClick,
replace = false,
state,
target,
to
} = _ref3,
rest = _objectWithoutPropertiesLoose(_ref3, _excluded);
let href = reactRouter.useHref(to);
let internalOnClick = useLinkClickHandler(to, {
replace,
state,
target
});
function handleClick(event) {
if (onClick) onClick(event);
if (!event.defaultPrevented) {
internalOnClick(event);
}
}
return (
/*#__PURE__*/
// eslint-disable-next-line jsx-a11y/anchor-has-content
React.createElement("a", _extends({}, rest, {
href: href,
onClick: handleClick,
ref: ref,
target: target
}))
);
});
{
Link.displayName = "Link";
}
/**
* A <Link> wrapper that knows if it's "active" or not.
*/
const NavLink = /*#__PURE__*/React.forwardRef(function NavLinkWithRef(_ref4, ref) {
let {
"aria-current": ariaCurrentProp = "page",
caseSensitive = false,
className: classNameProp = "",
end = false,
style: styleProp,
to
} = _ref4,
rest = _objectWithoutPropertiesLoose(_ref4, _excluded2);
let location = reactRouter.useLocation();
let path = reactRouter.useResolvedPath(to);
let locationPathname = location.pathname;
let toPathname = path.pathname;
if (!caseSensitive) {
locationPathname = locationPathname.toLowerCase();
toPathname = toPathname.toLowerCase();
}
let isActive = locationPathname === toPathname || !end && locationPathname.startsWith(toPathname) && locationPathname.charAt(toPathname.length) === "/";
let ariaCurrent = isActive ? ariaCurrentProp : undefined;
let className;
if (typeof classNameProp === "function") {
className = classNameProp({
isActive
});
} else {
// If the className prop is not a function, we use a default `active`
// class for <NavLink />s that are active. In v5 `active` was the default
// value for `activeClassName`, but we are removing that API and can still
// use the old default behavior for a cleaner upgrade path and keep the
// simple styling rules working as they currently do.
className = [classNameProp, isActive ? "active" : null].filter(Boolean).join(" ");
}
let style = typeof styleProp === "function" ? styleProp({
isActive
}) : styleProp;
return /*#__PURE__*/React.createElement(Link, _extends({}, rest, {
"aria-current": ariaCurrent,
className: className,
ref: ref,
style: style,
to: to
}));
});
{
NavLink.displayName = "NavLink";
} ////////////////////////////////////////////////////////////////////////////////
// HOOKS
////////////////////////////////////////////////////////////////////////////////
/**
* Handles the click behavior for router `<Link>` components. This is useful if
* you need to create custom `<Link>` compoments with the same click behavior we
* use in our exported `<Link>`.
*/
function useLinkClickHandler(to, _temp) {
let {
target,
replace: replaceProp,
state
} = _temp === void 0 ? {} : _temp;
let navigate = reactRouter.useNavigate();
let location = reactRouter.useLocation();
let path = reactRouter.useResolvedPath(to);
return React.useCallback(event => {
if (event.button === 0 && ( // Ignore everything but left clicks
!target || target === "_self") && // Let browser handle "target=_blank" etc.
!isModifiedEvent(event) // Ignore clicks with modifier keys
) {
event.preventDefault(); // If the URL hasn't changed, a regular <a> will do a replace instead of
// a push, so do the same here.
let replace = !!replaceProp || history.createPath(location) === history.createPath(path);
navigate(to, {
replace,
state
});
}
}, [location, navigate, path, replaceProp, state, target, to]);
}
/**
* A convenient wrapper for reading and writing search parameters via the
* URLSearchParams interface.
*/
function useSearchParams(defaultInit) {
warning(typeof URLSearchParams !== "undefined", "You cannot use the `useSearchParams` hook in a browser that does not " + "support the URLSearchParams API. If you need to support Internet " + "Explorer 11, we recommend you load a polyfill such as " + "https://github.com/ungap/url-search-params\n\n" + "If you're unsure how to load polyfills, we recommend you check out " + "https://polyfill.io/v3/ which provides some recommendations about how " + "to load polyfills only for users that need them, instead of for every " + "user.") ;
let defaultSearchParamsRef = React.useRef(createSearchParams(defaultInit));
let location = reactRouter.useLocation();
let searchParams = React.useMemo(() => {
let searchParams = createSearchParams(location.search);
for (let key of defaultSearchParamsRef.current.keys()) {
if (!searchParams.has(key)) {
defaultSearchParamsRef.current.getAll(key).forEach(value => {
searchParams.append(key, value);
});
}
}
return searchParams;
}, [location.search]);
let navigate = reactRouter.useNavigate();
let setSearchParams = React.useCallback((nextInit, navigateOptions) => {
navigate("?" + createSearchParams(nextInit), navigateOptions);
}, [navigate]);
return [searchParams, setSearchParams];
}
/**
* Creates a URLSearchParams object using the given initializer.
*
* This is identical to `new URLSearchParams(init)` except it also
* supports arrays as values in the object form of the initializer
* instead of just strings. This is convenient when you need multiple
* values for a given key, but don't want to use an array initializer.
*
* For example, instead of:
*
* let searchParams = new URLSearchParams([
* ['sort', 'name'],
* ['sort', 'price']
* ]);
*
* you can do:
*
* let searchParams = createSearchParams({
* sort: ['name', 'price']
* });
*/
function createSearchParams(init) {
if (init === void 0) {
init = "";
}
return new URLSearchParams(typeof init === "string" || Array.isArray(init) || init instanceof URLSearchParams ? init : Object.keys(init).reduce((memo, key) => {
let value = init[key];
return memo.concat(Array.isArray(value) ? value.map(v => [key, v]) : [[key, value]]);
}, []));
}
Object.defineProperty(exports, 'MemoryRouter', {
enumerable: true,
get: function () {
return reactRouter.MemoryRouter;
}
});
Object.defineProperty(exports, 'Navigate', {
enumerable: true,
get: function () {
return reactRouter.Navigate;
}
});
Object.defineProperty(exports, 'Outlet', {
enumerable: true,
get: function () {
return reactRouter.Outlet;
}
});
Object.defineProperty(exports, 'Route', {
enumerable: true,
get: function () {
return reactRouter.Route;
}
});
Object.defineProperty(exports, 'Router', {
enumerable: true,
get: function () {
return reactRouter.Router;
}
});
Object.defineProperty(exports, 'Routes', {
enumerable: true,
get: function () {
return reactRouter.Routes;
}
});
Object.defineProperty(exports, 'UNSAFE_LocationContext', {
enumerable: true,
get: function () {
return reactRouter.UNSAFE_LocationContext;
}
});
Object.defineProperty(exports, 'UNSAFE_NavigationContext', {
enumerable: true,
get: function () {
return reactRouter.UNSAFE_NavigationContext;
}
});
Object.defineProperty(exports, 'UNSAFE_RouteContext', {
enumerable: true,
get: function () {
return reactRouter.UNSAFE_RouteContext;
}
});
Object.defineProperty(exports, 'createRoutesFromChildren', {
enumerable: true,
get: function () {
return reactRouter.createRoutesFromChildren;
}
});
Object.defineProperty(exports, 'generatePath', {
enumerable: true,
get: function () {
return reactRouter.generatePath;
}
});
Object.defineProperty(exports, 'matchPath', {
enumerable: true,
get: function () {
return reactRouter.matchPath;
}
});
Object.defineProperty(exports, 'matchRoutes', {
enumerable: true,
get: function () {
return reactRouter.matchRoutes;
}
});
Object.defineProperty(exports, 'renderMatches', {
enumerable: true,
get: function () {
return reactRouter.renderMatches;
}
});
Object.defineProperty(exports, 'resolvePath', {
enumerable: true,
get: function () {
return reactRouter.resolvePath;
}
});
Object.defineProperty(exports, 'useHref', {
enumerable: true,
get: function () {
return reactRouter.useHref;
}
});
Object.defineProperty(exports, 'useInRouterContext', {
enumerable: true,
get: function () {
return reactRouter.useInRouterContext;
}
});
Object.defineProperty(exports, 'useLocation', {
enumerable: true,
get: function () {
return reactRouter.useLocation;
}
});
Object.defineProperty(exports, 'useMatch', {
enumerable: true,
get: function () {
return reactRouter.useMatch;
}
});
Object.defineProperty(exports, 'useNavigate', {
enumerable: true,
get: function () {
return reactRouter.useNavigate;
}
});
Object.defineProperty(exports, 'useNavigationType', {
enumerable: true,
get: function () {
return reactRouter.useNavigationType;
}
});
Object.defineProperty(exports, 'useOutlet', {
enumerable: true,
get: function () {
return reactRouter.useOutlet;
}
});
Object.defineProperty(exports, 'useParams', {
enumerable: true,
get: function () {
return reactRouter.useParams;
}
});
Object.defineProperty(exports, 'useResolvedPath', {
enumerable: true,
get: function () {
return reactRouter.useResolvedPath;
}
});
Object.defineProperty(exports, 'useRoutes', {
enumerable: true,
get: function () {
return reactRouter.useRoutes;
}
});
exports.BrowserRouter = BrowserRouter;
exports.HashRouter = HashRouter;
exports.Link = Link;
exports.NavLink = NavLink;
exports.createSearchParams = createSearchParams;
exports.useLinkClickHandler = useLinkClickHandler;
exports.useSearchParams = useSearchParams;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=react-router-dom.development.js.map
|
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*
* Version: 5.8.1 (2021-05-20)
*/
(function () {
'use strict';
var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
var __assign = function () {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var typeOf = function (x) {
var t = typeof x;
if (x === null) {
return 'null';
} else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
return 'array';
} else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
return 'string';
} else {
return t;
}
};
var isType = function (type) {
return function (value) {
return typeOf(value) === type;
};
};
var isSimpleType = function (type) {
return function (value) {
return typeof value === type;
};
};
var eq = function (t) {
return function (a) {
return t === a;
};
};
var isString = isType('string');
var isObject = isType('object');
var isArray = isType('array');
var isNull = eq(null);
var isBoolean = isSimpleType('boolean');
var isNullable = function (a) {
return a === null || a === undefined;
};
var isNonNullable = function (a) {
return !isNullable(a);
};
var isNumber = isSimpleType('number');
var noop = function () {
};
var constant = function (value) {
return function () {
return value;
};
};
var never = constant(false);
var always = constant(true);
var none = function () {
return NONE;
};
var NONE = function () {
var eq = function (o) {
return o.isNone();
};
var call = function (thunk) {
return thunk();
};
var id = function (n) {
return n;
};
var me = {
fold: function (n, _s) {
return n();
},
is: never,
isSome: never,
isNone: always,
getOr: id,
getOrThunk: call,
getOrDie: function (msg) {
throw new Error(msg || 'error: getOrDie called on none.');
},
getOrNull: constant(null),
getOrUndefined: constant(undefined),
or: id,
orThunk: call,
map: none,
each: noop,
bind: none,
exists: never,
forall: always,
filter: none,
equals: eq,
equals_: eq,
toArray: function () {
return [];
},
toString: constant('none()')
};
return me;
}();
var some = function (a) {
var constant_a = constant(a);
var self = function () {
return me;
};
var bind = function (f) {
return f(a);
};
var me = {
fold: function (n, s) {
return s(a);
},
is: function (v) {
return a === v;
},
isSome: always,
isNone: never,
getOr: constant_a,
getOrThunk: constant_a,
getOrDie: constant_a,
getOrNull: constant_a,
getOrUndefined: constant_a,
or: self,
orThunk: self,
map: function (f) {
return some(f(a));
},
each: function (f) {
f(a);
},
bind: bind,
exists: bind,
forall: bind,
filter: function (f) {
return f(a) ? me : NONE;
},
toArray: function () {
return [a];
},
toString: function () {
return 'some(' + a + ')';
},
equals: function (o) {
return o.is(a);
},
equals_: function (o, elementEq) {
return o.fold(never, function (b) {
return elementEq(a, b);
});
}
};
return me;
};
var from = function (value) {
return value === null || value === undefined ? NONE : some(value);
};
var Optional = {
some: some,
none: none,
from: from
};
var keys = Object.keys;
var hasOwnProperty = Object.hasOwnProperty;
var each = function (obj, f) {
var props = keys(obj);
for (var k = 0, len = props.length; k < len; k++) {
var i = props[k];
var x = obj[i];
f(x, i);
}
};
var objAcc = function (r) {
return function (x, i) {
r[i] = x;
};
};
var internalFilter = function (obj, pred, onTrue, onFalse) {
var r = {};
each(obj, function (x, i) {
(pred(x, i) ? onTrue : onFalse)(x, i);
});
return r;
};
var filter = function (obj, pred) {
var t = {};
internalFilter(obj, pred, objAcc(t), noop);
return t;
};
var has = function (obj, key) {
return hasOwnProperty.call(obj, key);
};
var hasNonNullableKey = function (obj, key) {
return has(obj, key) && obj[key] !== undefined && obj[key] !== null;
};
var nativePush = Array.prototype.push;
var flatten = function (xs) {
var r = [];
for (var i = 0, len = xs.length; i < len; ++i) {
if (!isArray(xs[i])) {
throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
}
nativePush.apply(r, xs[i]);
}
return r;
};
var get = function (xs, i) {
return i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
};
var head = function (xs) {
return get(xs, 0);
};
var findMap = function (arr, f) {
for (var i = 0; i < arr.length; i++) {
var r = f(arr[i], i);
if (r.isSome()) {
return r;
}
}
return Optional.none();
};
var Global = typeof window !== 'undefined' ? window : Function('return this;')();
var rawSet = function (dom, key, value) {
if (isString(value) || isBoolean(value) || isNumber(value)) {
dom.setAttribute(key, value + '');
} else {
console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
throw new Error('Attribute value was not simple');
}
};
var set = function (element, key, value) {
rawSet(element.dom, key, value);
};
var remove = function (element, key) {
element.dom.removeAttribute(key);
};
var fromHtml = function (html, scope) {
var doc = scope || document;
var div = doc.createElement('div');
div.innerHTML = html;
if (!div.hasChildNodes() || div.childNodes.length > 1) {
console.error('HTML does not have a single root node', html);
throw new Error('HTML must have a single root node');
}
return fromDom(div.childNodes[0]);
};
var fromTag = function (tag, scope) {
var doc = scope || document;
var node = doc.createElement(tag);
return fromDom(node);
};
var fromText = function (text, scope) {
var doc = scope || document;
var node = doc.createTextNode(text);
return fromDom(node);
};
var fromDom = function (node) {
if (node === null || node === undefined) {
throw new Error('Node cannot be null or undefined');
}
return { dom: node };
};
var fromPoint = function (docElm, x, y) {
return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
};
var SugarElement = {
fromHtml: fromHtml,
fromTag: fromTag,
fromText: fromText,
fromDom: fromDom,
fromPoint: fromPoint
};
var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
var global$2 = tinymce.util.Tools.resolve('tinymce.util.Promise');
var global$3 = tinymce.util.Tools.resolve('tinymce.util.XHR');
var hasDimensions = function (editor) {
return editor.getParam('image_dimensions', true, 'boolean');
};
var hasAdvTab = function (editor) {
return editor.getParam('image_advtab', false, 'boolean');
};
var hasUploadTab = function (editor) {
return editor.getParam('image_uploadtab', true, 'boolean');
};
var getPrependUrl = function (editor) {
return editor.getParam('image_prepend_url', '', 'string');
};
var getClassList = function (editor) {
return editor.getParam('image_class_list');
};
var hasDescription = function (editor) {
return editor.getParam('image_description', true, 'boolean');
};
var hasImageTitle = function (editor) {
return editor.getParam('image_title', false, 'boolean');
};
var hasImageCaption = function (editor) {
return editor.getParam('image_caption', false, 'boolean');
};
var getImageList = function (editor) {
return editor.getParam('image_list', false);
};
var hasUploadUrl = function (editor) {
return isNonNullable(editor.getParam('images_upload_url'));
};
var hasUploadHandler = function (editor) {
return isNonNullable(editor.getParam('images_upload_handler'));
};
var showAccessibilityOptions = function (editor) {
return editor.getParam('a11y_advanced_options', false, 'boolean');
};
var isAutomaticUploadsEnabled = function (editor) {
return editor.getParam('automatic_uploads', true, 'boolean');
};
var parseIntAndGetMax = function (val1, val2) {
return Math.max(parseInt(val1, 10), parseInt(val2, 10));
};
var getImageSize = function (url) {
return new global$2(function (callback) {
var img = document.createElement('img');
var done = function (dimensions) {
if (img.parentNode) {
img.parentNode.removeChild(img);
}
callback(dimensions);
};
img.onload = function () {
var width = parseIntAndGetMax(img.width, img.clientWidth);
var height = parseIntAndGetMax(img.height, img.clientHeight);
var dimensions = {
width: width,
height: height
};
done(global$2.resolve(dimensions));
};
img.onerror = function () {
done(global$2.reject('Failed to get image dimensions for: ' + url));
};
var style = img.style;
style.visibility = 'hidden';
style.position = 'fixed';
style.bottom = style.left = '0px';
style.width = style.height = 'auto';
document.body.appendChild(img);
img.src = url;
});
};
var removePixelSuffix = function (value) {
if (value) {
value = value.replace(/px$/, '');
}
return value;
};
var addPixelSuffix = function (value) {
if (value.length > 0 && /^[0-9]+$/.test(value)) {
value += 'px';
}
return value;
};
var mergeMargins = function (css) {
if (css.margin) {
var splitMargin = String(css.margin).split(' ');
switch (splitMargin.length) {
case 1:
css['margin-top'] = css['margin-top'] || splitMargin[0];
css['margin-right'] = css['margin-right'] || splitMargin[0];
css['margin-bottom'] = css['margin-bottom'] || splitMargin[0];
css['margin-left'] = css['margin-left'] || splitMargin[0];
break;
case 2:
css['margin-top'] = css['margin-top'] || splitMargin[0];
css['margin-right'] = css['margin-right'] || splitMargin[1];
css['margin-bottom'] = css['margin-bottom'] || splitMargin[0];
css['margin-left'] = css['margin-left'] || splitMargin[1];
break;
case 3:
css['margin-top'] = css['margin-top'] || splitMargin[0];
css['margin-right'] = css['margin-right'] || splitMargin[1];
css['margin-bottom'] = css['margin-bottom'] || splitMargin[2];
css['margin-left'] = css['margin-left'] || splitMargin[1];
break;
case 4:
css['margin-top'] = css['margin-top'] || splitMargin[0];
css['margin-right'] = css['margin-right'] || splitMargin[1];
css['margin-bottom'] = css['margin-bottom'] || splitMargin[2];
css['margin-left'] = css['margin-left'] || splitMargin[3];
}
delete css.margin;
}
return css;
};
var createImageList = function (editor, callback) {
var imageList = getImageList(editor);
if (typeof imageList === 'string') {
global$3.send({
url: imageList,
success: function (text) {
callback(JSON.parse(text));
}
});
} else if (typeof imageList === 'function') {
imageList(callback);
} else {
callback(imageList);
}
};
var waitLoadImage = function (editor, data, imgElm) {
var selectImage = function () {
imgElm.onload = imgElm.onerror = null;
if (editor.selection) {
editor.selection.select(imgElm);
editor.nodeChanged();
}
};
imgElm.onload = function () {
if (!data.width && !data.height && hasDimensions(editor)) {
editor.dom.setAttribs(imgElm, {
width: String(imgElm.clientWidth),
height: String(imgElm.clientHeight)
});
}
selectImage();
};
imgElm.onerror = selectImage;
};
var blobToDataUri = function (blob) {
return new global$2(function (resolve, reject) {
var reader = new FileReader();
reader.onload = function () {
resolve(reader.result);
};
reader.onerror = function () {
reject(reader.error.message);
};
reader.readAsDataURL(blob);
});
};
var isPlaceholderImage = function (imgElm) {
return imgElm.nodeName === 'IMG' && (imgElm.hasAttribute('data-mce-object') || imgElm.hasAttribute('data-mce-placeholder'));
};
var DOM = global$1.DOM;
var getHspace = function (image) {
if (image.style.marginLeft && image.style.marginRight && image.style.marginLeft === image.style.marginRight) {
return removePixelSuffix(image.style.marginLeft);
} else {
return '';
}
};
var getVspace = function (image) {
if (image.style.marginTop && image.style.marginBottom && image.style.marginTop === image.style.marginBottom) {
return removePixelSuffix(image.style.marginTop);
} else {
return '';
}
};
var getBorder = function (image) {
if (image.style.borderWidth) {
return removePixelSuffix(image.style.borderWidth);
} else {
return '';
}
};
var getAttrib = function (image, name) {
if (image.hasAttribute(name)) {
return image.getAttribute(name);
} else {
return '';
}
};
var getStyle = function (image, name) {
return image.style[name] ? image.style[name] : '';
};
var hasCaption = function (image) {
return image.parentNode !== null && image.parentNode.nodeName === 'FIGURE';
};
var updateAttrib = function (image, name, value) {
if (value === '') {
image.removeAttribute(name);
} else {
image.setAttribute(name, value);
}
};
var wrapInFigure = function (image) {
var figureElm = DOM.create('figure', { class: 'image' });
DOM.insertAfter(figureElm, image);
figureElm.appendChild(image);
figureElm.appendChild(DOM.create('figcaption', { contentEditable: 'true' }, 'Caption'));
figureElm.contentEditable = 'false';
};
var removeFigure = function (image) {
var figureElm = image.parentNode;
DOM.insertAfter(image, figureElm);
DOM.remove(figureElm);
};
var toggleCaption = function (image) {
if (hasCaption(image)) {
removeFigure(image);
} else {
wrapInFigure(image);
}
};
var normalizeStyle = function (image, normalizeCss) {
var attrValue = image.getAttribute('style');
var value = normalizeCss(attrValue !== null ? attrValue : '');
if (value.length > 0) {
image.setAttribute('style', value);
image.setAttribute('data-mce-style', value);
} else {
image.removeAttribute('style');
}
};
var setSize = function (name, normalizeCss) {
return function (image, name, value) {
if (image.style[name]) {
image.style[name] = addPixelSuffix(value);
normalizeStyle(image, normalizeCss);
} else {
updateAttrib(image, name, value);
}
};
};
var getSize = function (image, name) {
if (image.style[name]) {
return removePixelSuffix(image.style[name]);
} else {
return getAttrib(image, name);
}
};
var setHspace = function (image, value) {
var pxValue = addPixelSuffix(value);
image.style.marginLeft = pxValue;
image.style.marginRight = pxValue;
};
var setVspace = function (image, value) {
var pxValue = addPixelSuffix(value);
image.style.marginTop = pxValue;
image.style.marginBottom = pxValue;
};
var setBorder = function (image, value) {
var pxValue = addPixelSuffix(value);
image.style.borderWidth = pxValue;
};
var setBorderStyle = function (image, value) {
image.style.borderStyle = value;
};
var getBorderStyle = function (image) {
return getStyle(image, 'borderStyle');
};
var isFigure = function (elm) {
return elm.nodeName === 'FIGURE';
};
var isImage = function (elm) {
return elm.nodeName === 'IMG';
};
var getIsDecorative = function (image) {
return DOM.getAttrib(image, 'alt').length === 0 && DOM.getAttrib(image, 'role') === 'presentation';
};
var getAlt = function (image) {
if (getIsDecorative(image)) {
return '';
} else {
return getAttrib(image, 'alt');
}
};
var defaultData = function () {
return {
src: '',
alt: '',
title: '',
width: '',
height: '',
class: '',
style: '',
caption: false,
hspace: '',
vspace: '',
border: '',
borderStyle: '',
isDecorative: false
};
};
var getStyleValue = function (normalizeCss, data) {
var image = document.createElement('img');
updateAttrib(image, 'style', data.style);
if (getHspace(image) || data.hspace !== '') {
setHspace(image, data.hspace);
}
if (getVspace(image) || data.vspace !== '') {
setVspace(image, data.vspace);
}
if (getBorder(image) || data.border !== '') {
setBorder(image, data.border);
}
if (getBorderStyle(image) || data.borderStyle !== '') {
setBorderStyle(image, data.borderStyle);
}
return normalizeCss(image.getAttribute('style'));
};
var create = function (normalizeCss, data) {
var image = document.createElement('img');
write(normalizeCss, __assign(__assign({}, data), { caption: false }), image);
setAlt(image, data.alt, data.isDecorative);
if (data.caption) {
var figure = DOM.create('figure', { class: 'image' });
figure.appendChild(image);
figure.appendChild(DOM.create('figcaption', { contentEditable: 'true' }, 'Caption'));
figure.contentEditable = 'false';
return figure;
} else {
return image;
}
};
var read = function (normalizeCss, image) {
return {
src: getAttrib(image, 'src'),
alt: getAlt(image),
title: getAttrib(image, 'title'),
width: getSize(image, 'width'),
height: getSize(image, 'height'),
class: getAttrib(image, 'class'),
style: normalizeCss(getAttrib(image, 'style')),
caption: hasCaption(image),
hspace: getHspace(image),
vspace: getVspace(image),
border: getBorder(image),
borderStyle: getStyle(image, 'borderStyle'),
isDecorative: getIsDecorative(image)
};
};
var updateProp = function (image, oldData, newData, name, set) {
if (newData[name] !== oldData[name]) {
set(image, name, newData[name]);
}
};
var setAlt = function (image, alt, isDecorative) {
if (isDecorative) {
DOM.setAttrib(image, 'role', 'presentation');
var sugarImage = SugarElement.fromDom(image);
set(sugarImage, 'alt', '');
} else {
if (isNull(alt)) {
var sugarImage = SugarElement.fromDom(image);
remove(sugarImage, 'alt');
} else {
var sugarImage = SugarElement.fromDom(image);
set(sugarImage, 'alt', alt);
}
if (DOM.getAttrib(image, 'role') === 'presentation') {
DOM.setAttrib(image, 'role', '');
}
}
};
var updateAlt = function (image, oldData, newData) {
if (newData.alt !== oldData.alt || newData.isDecorative !== oldData.isDecorative) {
setAlt(image, newData.alt, newData.isDecorative);
}
};
var normalized = function (set, normalizeCss) {
return function (image, name, value) {
set(image, value);
normalizeStyle(image, normalizeCss);
};
};
var write = function (normalizeCss, newData, image) {
var oldData = read(normalizeCss, image);
updateProp(image, oldData, newData, 'caption', function (image, _name, _value) {
return toggleCaption(image);
});
updateProp(image, oldData, newData, 'src', updateAttrib);
updateProp(image, oldData, newData, 'title', updateAttrib);
updateProp(image, oldData, newData, 'width', setSize('width', normalizeCss));
updateProp(image, oldData, newData, 'height', setSize('height', normalizeCss));
updateProp(image, oldData, newData, 'class', updateAttrib);
updateProp(image, oldData, newData, 'style', normalized(function (image, value) {
return updateAttrib(image, 'style', value);
}, normalizeCss));
updateProp(image, oldData, newData, 'hspace', normalized(setHspace, normalizeCss));
updateProp(image, oldData, newData, 'vspace', normalized(setVspace, normalizeCss));
updateProp(image, oldData, newData, 'border', normalized(setBorder, normalizeCss));
updateProp(image, oldData, newData, 'borderStyle', normalized(setBorderStyle, normalizeCss));
updateAlt(image, oldData, newData);
};
var normalizeCss = function (editor, cssText) {
var css = editor.dom.styles.parse(cssText);
var mergedCss = mergeMargins(css);
var compressed = editor.dom.styles.parse(editor.dom.styles.serialize(mergedCss));
return editor.dom.styles.serialize(compressed);
};
var getSelectedImage = function (editor) {
var imgElm = editor.selection.getNode();
var figureElm = editor.dom.getParent(imgElm, 'figure.image');
if (figureElm) {
return editor.dom.select('img', figureElm)[0];
}
if (imgElm && (imgElm.nodeName !== 'IMG' || isPlaceholderImage(imgElm))) {
return null;
}
return imgElm;
};
var splitTextBlock = function (editor, figure) {
var dom = editor.dom;
var textBlockElements = filter(editor.schema.getTextBlockElements(), function (_, parentElm) {
return !editor.schema.isValidChild(parentElm, 'figure');
});
var textBlock = dom.getParent(figure.parentNode, function (node) {
return hasNonNullableKey(textBlockElements, node.nodeName);
}, editor.getBody());
if (textBlock) {
return dom.split(textBlock, figure);
} else {
return figure;
}
};
var readImageDataFromSelection = function (editor) {
var image = getSelectedImage(editor);
return image ? read(function (css) {
return normalizeCss(editor, css);
}, image) : defaultData();
};
var insertImageAtCaret = function (editor, data) {
var elm = create(function (css) {
return normalizeCss(editor, css);
}, data);
editor.dom.setAttrib(elm, 'data-mce-id', '__mcenew');
editor.focus();
editor.selection.setContent(elm.outerHTML);
var insertedElm = editor.dom.select('*[data-mce-id="__mcenew"]')[0];
editor.dom.setAttrib(insertedElm, 'data-mce-id', null);
if (isFigure(insertedElm)) {
var figure = splitTextBlock(editor, insertedElm);
editor.selection.select(figure);
} else {
editor.selection.select(insertedElm);
}
};
var syncSrcAttr = function (editor, image) {
editor.dom.setAttrib(image, 'src', image.getAttribute('src'));
};
var deleteImage = function (editor, image) {
if (image) {
var elm = editor.dom.is(image.parentNode, 'figure.image') ? image.parentNode : image;
editor.dom.remove(elm);
editor.focus();
editor.nodeChanged();
if (editor.dom.isEmpty(editor.getBody())) {
editor.setContent('');
editor.selection.setCursorLocation();
}
}
};
var writeImageDataToSelection = function (editor, data) {
var image = getSelectedImage(editor);
write(function (css) {
return normalizeCss(editor, css);
}, data, image);
syncSrcAttr(editor, image);
if (isFigure(image.parentNode)) {
var figure = image.parentNode;
splitTextBlock(editor, figure);
editor.selection.select(image.parentNode);
} else {
editor.selection.select(image);
waitLoadImage(editor, data, image);
}
};
var insertOrUpdateImage = function (editor, partialData) {
var image = getSelectedImage(editor);
if (image) {
var selectedImageData = read(function (css) {
return normalizeCss(editor, css);
}, image);
var data = __assign(__assign({}, selectedImageData), partialData);
if (data.src) {
writeImageDataToSelection(editor, data);
} else {
deleteImage(editor, image);
}
} else if (partialData.src) {
insertImageAtCaret(editor, __assign(__assign({}, defaultData()), partialData));
}
};
var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
var deep = function (old, nu) {
var bothObjects = isObject(old) && isObject(nu);
return bothObjects ? deepMerge(old, nu) : nu;
};
var baseMerge = function (merger) {
return function () {
var objects = [];
for (var _i = 0; _i < arguments.length; _i++) {
objects[_i] = arguments[_i];
}
if (objects.length === 0) {
throw new Error('Can\'t merge zero objects');
}
var ret = {};
for (var j = 0; j < objects.length; j++) {
var curObject = objects[j];
for (var key in curObject) {
if (hasOwnProperty$1.call(curObject, key)) {
ret[key] = merger(ret[key], curObject[key]);
}
}
}
return ret;
};
};
var deepMerge = baseMerge(deep);
var isNotEmpty = function (s) {
return s.length > 0;
};
var global$4 = tinymce.util.Tools.resolve('tinymce.util.ImageUploader');
var global$5 = tinymce.util.Tools.resolve('tinymce.util.Tools');
var getValue = function (item) {
return isString(item.value) ? item.value : '';
};
var getText = function (item) {
if (isString(item.text)) {
return item.text;
} else if (isString(item.title)) {
return item.title;
} else {
return '';
}
};
var sanitizeList = function (list, extractValue) {
var out = [];
global$5.each(list, function (item) {
var text = getText(item);
if (item.menu !== undefined) {
var items = sanitizeList(item.menu, extractValue);
out.push({
text: text,
items: items
});
} else {
var value = extractValue(item);
out.push({
text: text,
value: value
});
}
});
return out;
};
var sanitizer = function (extracter) {
if (extracter === void 0) {
extracter = getValue;
}
return function (list) {
if (list) {
return Optional.from(list).map(function (list) {
return sanitizeList(list, extracter);
});
} else {
return Optional.none();
}
};
};
var sanitize = function (list) {
return sanitizer(getValue)(list);
};
var isGroup = function (item) {
return Object.prototype.hasOwnProperty.call(item, 'items');
};
var findEntryDelegate = function (list, value) {
return findMap(list, function (item) {
if (isGroup(item)) {
return findEntryDelegate(item.items, value);
} else if (item.value === value) {
return Optional.some(item);
} else {
return Optional.none();
}
});
};
var findEntry = function (optList, value) {
return optList.bind(function (list) {
return findEntryDelegate(list, value);
});
};
var ListUtils = {
sanitizer: sanitizer,
sanitize: sanitize,
findEntry: findEntry
};
var makeTab = function (_info) {
return {
title: 'Advanced',
name: 'advanced',
items: [
{
type: 'input',
label: 'Style',
name: 'style'
},
{
type: 'grid',
columns: 2,
items: [
{
type: 'input',
label: 'Vertical space',
name: 'vspace',
inputMode: 'numeric'
},
{
type: 'input',
label: 'Horizontal space',
name: 'hspace',
inputMode: 'numeric'
},
{
type: 'input',
label: 'Border width',
name: 'border',
inputMode: 'numeric'
},
{
type: 'listbox',
name: 'borderstyle',
label: 'Border style',
items: [
{
text: 'Select...',
value: ''
},
{
text: 'Solid',
value: 'solid'
},
{
text: 'Dotted',
value: 'dotted'
},
{
text: 'Dashed',
value: 'dashed'
},
{
text: 'Double',
value: 'double'
},
{
text: 'Groove',
value: 'groove'
},
{
text: 'Ridge',
value: 'ridge'
},
{
text: 'Inset',
value: 'inset'
},
{
text: 'Outset',
value: 'outset'
},
{
text: 'None',
value: 'none'
},
{
text: 'Hidden',
value: 'hidden'
}
]
}
]
}
]
};
};
var AdvTab = { makeTab: makeTab };
var collect = function (editor) {
var urlListSanitizer = ListUtils.sanitizer(function (item) {
return editor.convertURL(item.value || item.url, 'src');
});
var futureImageList = new global$2(function (completer) {
createImageList(editor, function (imageList) {
completer(urlListSanitizer(imageList).map(function (items) {
return flatten([
[{
text: 'None',
value: ''
}],
items
]);
}));
});
});
var classList = ListUtils.sanitize(getClassList(editor));
var hasAdvTab$1 = hasAdvTab(editor);
var hasUploadTab$1 = hasUploadTab(editor);
var hasUploadUrl$1 = hasUploadUrl(editor);
var hasUploadHandler$1 = hasUploadHandler(editor);
var image = readImageDataFromSelection(editor);
var hasDescription$1 = hasDescription(editor);
var hasImageTitle$1 = hasImageTitle(editor);
var hasDimensions$1 = hasDimensions(editor);
var hasImageCaption$1 = hasImageCaption(editor);
var hasAccessibilityOptions = showAccessibilityOptions(editor);
var automaticUploads = isAutomaticUploadsEnabled(editor);
var prependURL = Optional.some(getPrependUrl(editor)).filter(function (preUrl) {
return isString(preUrl) && preUrl.length > 0;
});
return futureImageList.then(function (imageList) {
return {
image: image,
imageList: imageList,
classList: classList,
hasAdvTab: hasAdvTab$1,
hasUploadTab: hasUploadTab$1,
hasUploadUrl: hasUploadUrl$1,
hasUploadHandler: hasUploadHandler$1,
hasDescription: hasDescription$1,
hasImageTitle: hasImageTitle$1,
hasDimensions: hasDimensions$1,
hasImageCaption: hasImageCaption$1,
prependURL: prependURL,
hasAccessibilityOptions: hasAccessibilityOptions,
automaticUploads: automaticUploads
};
});
};
var makeItems = function (info) {
var imageUrl = {
name: 'src',
type: 'urlinput',
filetype: 'image',
label: 'Source'
};
var imageList = info.imageList.map(function (items) {
return {
name: 'images',
type: 'listbox',
label: 'Image list',
items: items
};
});
var imageDescription = {
name: 'alt',
type: 'input',
label: 'Alternative description',
disabled: info.hasAccessibilityOptions && info.image.isDecorative
};
var imageTitle = {
name: 'title',
type: 'input',
label: 'Image title'
};
var imageDimensions = {
name: 'dimensions',
type: 'sizeinput'
};
var isDecorative = {
type: 'label',
label: 'Accessibility',
items: [{
name: 'isDecorative',
type: 'checkbox',
label: 'Image is decorative'
}]
};
var classList = info.classList.map(function (items) {
return {
name: 'classes',
type: 'listbox',
label: 'Class',
items: items
};
});
var caption = {
type: 'label',
label: 'Caption',
items: [{
type: 'checkbox',
name: 'caption',
label: 'Show caption'
}]
};
var getDialogContainerType = function (useColumns) {
return useColumns ? {
type: 'grid',
columns: 2
} : { type: 'panel' };
};
return flatten([
[imageUrl],
imageList.toArray(),
info.hasAccessibilityOptions && info.hasDescription ? [isDecorative] : [],
info.hasDescription ? [imageDescription] : [],
info.hasImageTitle ? [imageTitle] : [],
info.hasDimensions ? [imageDimensions] : [],
[__assign(__assign({}, getDialogContainerType(info.classList.isSome() && info.hasImageCaption)), {
items: flatten([
classList.toArray(),
info.hasImageCaption ? [caption] : []
])
})]
]);
};
var makeTab$1 = function (info) {
return {
title: 'General',
name: 'general',
items: makeItems(info)
};
};
var MainTab = {
makeTab: makeTab$1,
makeItems: makeItems
};
var makeTab$2 = function (_info) {
var items = [{
type: 'dropzone',
name: 'fileinput'
}];
return {
title: 'Upload',
name: 'upload',
items: items
};
};
var UploadTab = { makeTab: makeTab$2 };
var createState = function (info) {
return {
prevImage: ListUtils.findEntry(info.imageList, info.image.src),
prevAlt: info.image.alt,
open: true
};
};
var fromImageData = function (image) {
return {
src: {
value: image.src,
meta: {}
},
images: image.src,
alt: image.alt,
title: image.title,
dimensions: {
width: image.width,
height: image.height
},
classes: image.class,
caption: image.caption,
style: image.style,
vspace: image.vspace,
border: image.border,
hspace: image.hspace,
borderstyle: image.borderStyle,
fileinput: [],
isDecorative: image.isDecorative
};
};
var toImageData = function (data, removeEmptyAlt) {
return {
src: data.src.value,
alt: data.alt.length === 0 && removeEmptyAlt ? null : data.alt,
title: data.title,
width: data.dimensions.width,
height: data.dimensions.height,
class: data.classes,
style: data.style,
caption: data.caption,
hspace: data.hspace,
vspace: data.vspace,
border: data.border,
borderStyle: data.borderstyle,
isDecorative: data.isDecorative
};
};
var addPrependUrl2 = function (info, srcURL) {
if (!/^(?:[a-zA-Z]+:)?\/\//.test(srcURL)) {
return info.prependURL.bind(function (prependUrl) {
if (srcURL.substring(0, prependUrl.length) !== prependUrl) {
return Optional.some(prependUrl + srcURL);
}
return Optional.none();
});
}
return Optional.none();
};
var addPrependUrl = function (info, api) {
var data = api.getData();
addPrependUrl2(info, data.src.value).each(function (srcURL) {
api.setData({
src: {
value: srcURL,
meta: data.src.meta
}
});
});
};
var formFillFromMeta2 = function (info, data, meta) {
if (info.hasDescription && isString(meta.alt)) {
data.alt = meta.alt;
}
if (info.hasAccessibilityOptions) {
data.isDecorative = meta.isDecorative || data.isDecorative || false;
}
if (info.hasImageTitle && isString(meta.title)) {
data.title = meta.title;
}
if (info.hasDimensions) {
if (isString(meta.width)) {
data.dimensions.width = meta.width;
}
if (isString(meta.height)) {
data.dimensions.height = meta.height;
}
}
if (isString(meta.class)) {
ListUtils.findEntry(info.classList, meta.class).each(function (entry) {
data.classes = entry.value;
});
}
if (info.hasImageCaption) {
if (isBoolean(meta.caption)) {
data.caption = meta.caption;
}
}
if (info.hasAdvTab) {
if (isString(meta.style)) {
data.style = meta.style;
}
if (isString(meta.vspace)) {
data.vspace = meta.vspace;
}
if (isString(meta.border)) {
data.border = meta.border;
}
if (isString(meta.hspace)) {
data.hspace = meta.hspace;
}
if (isString(meta.borderstyle)) {
data.borderstyle = meta.borderstyle;
}
}
};
var formFillFromMeta = function (info, api) {
var data = api.getData();
var meta = data.src.meta;
if (meta !== undefined) {
var newData = deepMerge({}, data);
formFillFromMeta2(info, newData, meta);
api.setData(newData);
}
};
var calculateImageSize = function (helpers, info, state, api) {
var data = api.getData();
var url = data.src.value;
var meta = data.src.meta || {};
if (!meta.width && !meta.height && info.hasDimensions) {
if (isNotEmpty(url)) {
helpers.imageSize(url).then(function (size) {
if (state.open) {
api.setData({ dimensions: size });
}
}).catch(function (e) {
return console.error(e);
});
} else {
api.setData({
dimensions: {
width: '',
height: ''
}
});
}
}
};
var updateImagesDropdown = function (info, state, api) {
var data = api.getData();
var image = ListUtils.findEntry(info.imageList, data.src.value);
state.prevImage = image;
api.setData({
images: image.map(function (entry) {
return entry.value;
}).getOr('')
});
};
var changeSrc = function (helpers, info, state, api) {
addPrependUrl(info, api);
formFillFromMeta(info, api);
calculateImageSize(helpers, info, state, api);
updateImagesDropdown(info, state, api);
};
var changeImages = function (helpers, info, state, api) {
var data = api.getData();
var image = ListUtils.findEntry(info.imageList, data.images);
image.each(function (img) {
var updateAlt = data.alt === '' || state.prevImage.map(function (image) {
return image.text === data.alt;
}).getOr(false);
if (updateAlt) {
if (img.value === '') {
api.setData({
src: img,
alt: state.prevAlt
});
} else {
api.setData({
src: img,
alt: img.text
});
}
} else {
api.setData({ src: img });
}
});
state.prevImage = image;
changeSrc(helpers, info, state, api);
};
var calcVSpace = function (css) {
var matchingTopBottom = css['margin-top'] && css['margin-bottom'] && css['margin-top'] === css['margin-bottom'];
return matchingTopBottom ? removePixelSuffix(String(css['margin-top'])) : '';
};
var calcHSpace = function (css) {
var matchingLeftRight = css['margin-right'] && css['margin-left'] && css['margin-right'] === css['margin-left'];
return matchingLeftRight ? removePixelSuffix(String(css['margin-right'])) : '';
};
var calcBorderWidth = function (css) {
return css['border-width'] ? removePixelSuffix(String(css['border-width'])) : '';
};
var calcBorderStyle = function (css) {
return css['border-style'] ? String(css['border-style']) : '';
};
var calcStyle = function (parseStyle, serializeStyle, css) {
return serializeStyle(parseStyle(serializeStyle(css)));
};
var changeStyle2 = function (parseStyle, serializeStyle, data) {
var css = mergeMargins(parseStyle(data.style));
var dataCopy = deepMerge({}, data);
dataCopy.vspace = calcVSpace(css);
dataCopy.hspace = calcHSpace(css);
dataCopy.border = calcBorderWidth(css);
dataCopy.borderstyle = calcBorderStyle(css);
dataCopy.style = calcStyle(parseStyle, serializeStyle, css);
return dataCopy;
};
var changeStyle = function (helpers, api) {
var data = api.getData();
var newData = changeStyle2(helpers.parseStyle, helpers.serializeStyle, data);
api.setData(newData);
};
var changeAStyle = function (helpers, info, api) {
var data = deepMerge(fromImageData(info.image), api.getData());
var style = getStyleValue(helpers.normalizeCss, toImageData(data, false));
api.setData({ style: style });
};
var changeFileInput = function (helpers, info, state, api) {
var data = api.getData();
api.block('Uploading image');
head(data.fileinput).fold(function () {
api.unblock();
}, function (file) {
var blobUri = URL.createObjectURL(file);
var finalize = function () {
api.unblock();
URL.revokeObjectURL(blobUri);
};
var updateSrcAndSwitchTab = function (url) {
api.setData({
src: {
value: url,
meta: {}
}
});
api.showTab('general');
changeSrc(helpers, info, state, api);
};
blobToDataUri(file).then(function (dataUrl) {
var blobInfo = helpers.createBlobCache(file, blobUri, dataUrl);
if (info.automaticUploads) {
helpers.uploadImage(blobInfo).then(function (result) {
updateSrcAndSwitchTab(result.url);
finalize();
}).catch(function (err) {
finalize();
helpers.alertErr(err);
});
} else {
helpers.addToBlobCache(blobInfo);
updateSrcAndSwitchTab(blobInfo.blobUri());
api.unblock();
}
});
});
};
var changeHandler = function (helpers, info, state) {
return function (api, evt) {
if (evt.name === 'src') {
changeSrc(helpers, info, state, api);
} else if (evt.name === 'images') {
changeImages(helpers, info, state, api);
} else if (evt.name === 'alt') {
state.prevAlt = api.getData().alt;
} else if (evt.name === 'style') {
changeStyle(helpers, api);
} else if (evt.name === 'vspace' || evt.name === 'hspace' || evt.name === 'border' || evt.name === 'borderstyle') {
changeAStyle(helpers, info, api);
} else if (evt.name === 'fileinput') {
changeFileInput(helpers, info, state, api);
} else if (evt.name === 'isDecorative') {
if (api.getData().isDecorative) {
api.disable('alt');
} else {
api.enable('alt');
}
}
};
};
var closeHandler = function (state) {
return function () {
state.open = false;
};
};
var makeDialogBody = function (info) {
if (info.hasAdvTab || info.hasUploadUrl || info.hasUploadHandler) {
var tabPanel = {
type: 'tabpanel',
tabs: flatten([
[MainTab.makeTab(info)],
info.hasAdvTab ? [AdvTab.makeTab(info)] : [],
info.hasUploadTab && (info.hasUploadUrl || info.hasUploadHandler) ? [UploadTab.makeTab(info)] : []
])
};
return tabPanel;
} else {
var panel = {
type: 'panel',
items: MainTab.makeItems(info)
};
return panel;
}
};
var makeDialog = function (helpers) {
return function (info) {
var state = createState(info);
return {
title: 'Insert/Edit Image',
size: 'normal',
body: makeDialogBody(info),
buttons: [
{
type: 'cancel',
name: 'cancel',
text: 'Cancel'
},
{
type: 'submit',
name: 'save',
text: 'Save',
primary: true
}
],
initialData: fromImageData(info.image),
onSubmit: helpers.onSubmit(info),
onChange: changeHandler(helpers, info, state),
onClose: closeHandler(state)
};
};
};
var submitHandler = function (editor) {
return function (info) {
return function (api) {
var data = deepMerge(fromImageData(info.image), api.getData());
editor.execCommand('mceUpdateImage', false, toImageData(data, info.hasAccessibilityOptions));
editor.editorUpload.uploadImagesAuto();
api.close();
};
};
};
var imageSize = function (editor) {
return function (url) {
return getImageSize(editor.documentBaseURI.toAbsolute(url)).then(function (dimensions) {
return {
width: String(dimensions.width),
height: String(dimensions.height)
};
});
};
};
var createBlobCache = function (editor) {
return function (file, blobUri, dataUrl) {
return editor.editorUpload.blobCache.create({
blob: file,
blobUri: blobUri,
name: file.name ? file.name.replace(/\.[^\.]+$/, '') : null,
filename: file.name,
base64: dataUrl.split(',')[1]
});
};
};
var addToBlobCache = function (editor) {
return function (blobInfo) {
editor.editorUpload.blobCache.add(blobInfo);
};
};
var alertErr = function (editor) {
return function (message) {
editor.windowManager.alert(message);
};
};
var normalizeCss$1 = function (editor) {
return function (cssText) {
return normalizeCss(editor, cssText);
};
};
var parseStyle = function (editor) {
return function (cssText) {
return editor.dom.parseStyle(cssText);
};
};
var serializeStyle = function (editor) {
return function (stylesArg, name) {
return editor.dom.serializeStyle(stylesArg, name);
};
};
var uploadImage = function (editor) {
return function (blobInfo) {
return global$4(editor).upload([blobInfo], false).then(function (results) {
if (results.length === 0) {
return global$2.reject('Failed to upload image');
} else if (results[0].status === false) {
return global$2.reject(results[0].error.message);
} else {
return results[0];
}
});
};
};
var Dialog = function (editor) {
var helpers = {
onSubmit: submitHandler(editor),
imageSize: imageSize(editor),
addToBlobCache: addToBlobCache(editor),
createBlobCache: createBlobCache(editor),
alertErr: alertErr(editor),
normalizeCss: normalizeCss$1(editor),
parseStyle: parseStyle(editor),
serializeStyle: serializeStyle(editor),
uploadImage: uploadImage(editor)
};
var open = function () {
collect(editor).then(makeDialog(helpers)).then(editor.windowManager.open);
};
return { open: open };
};
var register = function (editor) {
editor.addCommand('mceImage', Dialog(editor).open);
editor.addCommand('mceUpdateImage', function (_ui, data) {
editor.undoManager.transact(function () {
return insertOrUpdateImage(editor, data);
});
});
};
var hasImageClass = function (node) {
var className = node.attr('class');
return className && /\bimage\b/.test(className);
};
var toggleContentEditableState = function (state) {
return function (nodes) {
var i = nodes.length;
var toggleContentEditable = function (node) {
node.attr('contenteditable', state ? 'true' : null);
};
while (i--) {
var node = nodes[i];
if (hasImageClass(node)) {
node.attr('contenteditable', state ? 'false' : null);
global$5.each(node.getAll('figcaption'), toggleContentEditable);
}
}
};
};
var setup = function (editor) {
editor.on('PreInit', function () {
editor.parser.addNodeFilter('figure', toggleContentEditableState(true));
editor.serializer.addNodeFilter('figure', toggleContentEditableState(false));
});
};
var register$1 = function (editor) {
editor.ui.registry.addToggleButton('image', {
icon: 'image',
tooltip: 'Insert/edit image',
onAction: Dialog(editor).open,
onSetup: function (buttonApi) {
return editor.selection.selectorChangedWithUnbind('img:not([data-mce-object],[data-mce-placeholder]),figure.image', buttonApi.setActive).unbind;
}
});
editor.ui.registry.addMenuItem('image', {
icon: 'image',
text: 'Image...',
onAction: Dialog(editor).open
});
editor.ui.registry.addContextMenu('image', {
update: function (element) {
return isFigure(element) || isImage(element) && !isPlaceholderImage(element) ? ['image'] : [];
}
});
};
function Plugin () {
global.add('image', function (editor) {
setup(editor);
register$1(editor);
register(editor);
});
}
Plugin();
}());
|
const registry = new Map();
function register(className, factory) {
registry.set(className, factory);
return className;
}
function resolve(rule, context) {
const factory = registry.get(rule.n);
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument
return factory ? factory(rule, context) : context.r(rule.n);
}
const escape = typeof CSS !== 'undefined' && CSS.escape || // Simplified: escaping only special characters
// Needed for NodeJS and Edge <79 (https://caniuse.com/mdn-api_css_escape)
((className)=>className// Simplifed escape testing only for chars that we know happen to be in tailwind directives
.replace(/[!"'`*+.,;:\\/<=>?@#$%&^|~()[\]{}]/g, '\\$&')// If the character is the first character and is in the range [0-9] (2xl, ...)
// https://drafts.csswg.org/cssom/#escape-a-character-as-code-point
.replace(/^\d/, '\\3$& ')
);
// Based on https://stackoverflow.com/a/52171480
function hash(value) {
// eslint-disable-next-line no-var
for(var h = 9, index = value.length; index--;){
h = Math.imul(h ^ value.charCodeAt(index), 1597334677);
}
return '#' + ((h ^ h >>> 9) >>> 0).toString(36);
}
function mql(screen1, prefix = '@media ') {
return prefix + asArray(screen1).map((screen)=>{
if (typeof screen == 'string') {
screen = {
min: screen
};
}
return screen.raw || Object.keys(screen).map((feature)=>`(${feature}-width:${screen[feature]})`
).join(' and ');
}).join(',');
}
function asArray(value = []) {
return Array.isArray(value) ? value : value == null ? [] : [
value
];
}
function identity(value) {
return value;
}
function noop() {
// no-op
}
function toClassName(rule) {
return [
...rule.v,
(rule.i ? '!' : '') + rule.n
].join(':');
}
// Based on https://github.com/kripod/otion
// License MIT
// export const enum Shifts {
// darkMode = 30,
// layer = 27,
// screens = 26,
// responsive = 22,
// atRules = 18,
// variants = 0,
// }
const Layer = {
/**
* 1. `default` (public)
*/ d: 0 << 27 /* Shifts.layer */ ,
/**
* 2. `base` (public) —for things like reset rules or default styles applied to plain HTML elements.
*/ b: 1 << 27 /* Shifts.layer */ ,
/**
* 3. `components` (public, used by `style()`) — is for class-based styles that you want to be able to override with utilities.
*/ c: 2 << 27 /* Shifts.layer */ ,
// reserved for style():
// - props: 0b011
// - when: 0b100
/**
* 6. `shortcuts` (public, used by `apply()`) — `~(...)`
*/ s: 5 << 27 /* Shifts.layer */ ,
/**
* 6. `utilities` (public) — for small, single-purpose classes
*/ u: 6 << 27 /* Shifts.layer */ ,
/**
* 7. `overrides` (public, used by `css()`)
*/ o: 7 << 27 /* Shifts.layer */
};
/*
To have a predictable styling the styles must be ordered.
This order is represented by a precedence number. The lower values
are inserted before higher values. Meaning higher precedence styles
overwrite lower precedence styles.
Each rule has some traits that are put into a bit set which form
the precedence:
| bits | trait |
| ---- | ---------------------------------------------------- |
| 1 | dark mode |
| 2 | layer: preflight, global, components, utilities, css |
| 1 | screens: is this a responsive variation of a rule |
| 5 | responsive based on min-width |
| 4 | at-rules |
| 18 | pseudo and group variants |
| 4 | number of declarations (descending) |
| 4 | greatest precedence of properties |
**Dark Mode: 1 bit**
Flag for dark mode rules.
**Layer: 3 bits**
- defaults = 0: The preflight styles and any base styles registered by plugins.
- vase = 1: The global styles registered by plugins.
- components = 2
- variants = 3
- compounds = 4
- shortcuts = 5
- utilities = 6: Utility classes and any utility classes registered by plugins.
- css = 7: Styles generated by css
**Screens: 1 bit**
Flag for screen variants. They may not always have a `min-width` to be detected by _Responsive_ below.
**Responsive: 4 bits**
Based on extracted `min-width` value:
- 576px -> 3
- 1536px -> 10
- 36rem -> 3
- 96rem -> 9
**At-Rules: 4 bits**
Based on the count of special chars (`-:,`) within the at-rule.
**Pseudo and group variants: 18 bits**
Ensures predictable order of pseudo classes.
- https://bitsofco.de/when-do-the-hover-focus-and-active-pseudo-classes-apply/#orderofstyleshoverthenfocusthenactive
- https://developer.mozilla.org/docs/Web/CSS/:active#Active_links
- https://github.com/tailwindlabs/tailwindcss/blob/master/stubs/defaultConfig.stub.js#L718
**Number of declarations (descending): 4 bits**
Allows single declaration styles to overwrite styles from multi declaration styles.
**Greatest precedence of properties: 4 bits**
Ensure shorthand properties are inserted before longhand properties; eg longhand override shorthand
*/ function moveToLayer(precedence, layer) {
// Set layer (first reset, than set)
return precedence & ~Layer.o | layer;
}
/*
To set a bit: n |= mask;
To clear a bit: n &= ~mask;
To test if a bit is set: (n & mask)
Bit shifts for the primary bits:
| bits | trait | shift |
| ---- | ------------------------------------------------------- | ----- |
| 1 | dark mode | 30 |
| 3 | layer: preflight, global, components, utilities, css | 27 |
| 1 | screens: is this a responsive variation of a rule | 26 |
| 4 | responsive based on min-width, max-width or width | 22 |
| 4 | at-rules | 18 |
| 18 | pseudo and group variants | 0 |
Layer: 0 - 7: 3 bits
- defaults: 0 << 27
- base: 1 << 27
- components: 2 << 27
- variants: 3 << 27
- joints: 4 << 27
- shortcuts: 5 << 27
- utilities: 6 << 27
- overrides: 7 << 27
These are calculated by serialize and added afterwards:
| bits | trait |
| ---- | ----------------------------------- |
| 4 | number of selectors (descending) |
| 4 | number of declarations (descending) |
| 4 | greatest precedence of properties |
These are added by shifting the primary bits using multiplication as js only
supports bit shift up to 32 bits.
*/ // Colon and dash count of string (ascending)
function seperatorPrecedence(string) {
return string.match(/[-=:;]/g)?.length || 0;
}
function atRulePrecedence(css) {
// 0=none, 1=sm, 2=md, 3=lg, 4=xl, 5=2xl, 6=??, 7=??
// 0 - 15: 4 bits (max 150rem or 2250px)
// 576px -> 3
// 1536px -> 10
// 36rem -> 3
// 96rem -> 9
return Math.min(/(?:^|width[^\d]+)(\d+(?:.\d+)?)(p)?/.test(css) ? +RegExp.$1 / (RegExp.$2 ? 15 : 1) / 10 : 0, 15) << 22 | Math.min(seperatorPrecedence(css), 15) << 18;
}
// Pesudo variant presedence
// Chars 3 - 8: Uniquely identifies a pseudo selector
// represented as a bit set for each relevant value
// 18 bits: one for each variant plus one for unknown variants
//
// ':group-*' variants are normalized to their native pseudo class (':group-hover' -> ':hover')
// as they already have a higher selector presedence due to the add '.group' ('.group:hover .group-hover:...')
// Sources:
// - https://bitsofco.de/when-do-the-hover-focus-and-active-pseudo-classes-apply/#orderofstyleshoverthenfocusthenactive
// - https://developer.mozilla.org/docs/Web/CSS/:active#Active_links
// - https://github.com/tailwindlabs/tailwindcss/blob/master/stubs/defaultConfig.stub.js#L931
const PRECEDENCES_BY_PSEUDO_CLASS = [
/* fi */ 'rst-c' /* hild: 0 */ ,
/* la */ 'st-ch' /* ild: 1 */ ,
// even and odd use: nth-child
/* nt */ 'h-chi' /* ld: 2 */ ,
/* an */ 'y-lin' /* k: 3 */ ,
/* li */ 'nk' /* : 4 */ ,
/* vi */ 'sited' /* : 5 */ ,
/* ch */ 'ecked' /* : 6 */ ,
/* em */ 'pty' /* : 7 */ ,
/* re */ 'ad-on' /* ly: 8 */ ,
/* fo */ 'cus-w' /* ithin : 9 */ ,
/* ho */ 'ver' /* : 10 */ ,
/* fo */ 'cus' /* : 11 */ ,
/* fo */ 'cus-v' /* isible : 12 */ ,
/* ac */ 'tive' /* : 13 */ ,
/* di */ 'sable' /* d : 14 */ ,
/* op */ 'tiona' /* l: 15 */ ,
/* re */ 'quire' /* d: 16 */ ,
];
function pseudoPrecedence(selector) {
// use first found pseudo-class
return 1 << ~(/:([a-z-]+)/.test(selector) && ~PRECEDENCES_BY_PSEUDO_CLASS.indexOf(RegExp.$1.slice(2, 7)) || ~17);
}
// https://github.com/kripod/otion/blob/main/packages/otion/src/propertyMatchers.ts
// "+1": [
// /* ^border-.*(w|c|sty) */
// "border-.*(width,color,style)",
// /* ^[tlbr].{2,4}m?$ */
// "top",
// "left",
// "bottom",
// "right",
// /* ^c.{7}$ */
// "continue",
// ],
// "-1": [
// /* ^[fl].{5}l */
// "flex-flow",
// "line-clamp",
// /* ^g.{8}$ */
// "grid-area",
// /* ^pl */
// "place-content",
// "place-items",
// "place-self",
// ],
// group: 1 => +1
// group: 2 => -1
// 0 - 15 => 4 bits
// Ignore vendor prefixed and custom properties
function declarationPropertyPrecedence(property) {
return property[0] == '-' ? 0 : seperatorPrecedence(property) + (/^(?:(border-(?!w|c|sty)|[tlbr].{2,4}m?$|c.{7}$)|([fl].{5}l|g.{8}$|pl))/.test(property) ? +!!RegExp.$1 /* +1 */ || -!!RegExp.$2 /* -1 */ : 0) + 1;
}
function convert({ n: name , i: important , v: variants = [] }, context, precedence, conditions) {
if (name) {
name = toClassName({
n: name,
i: important,
v: variants
});
}
conditions = [
...asArray(conditions)
];
for (const variant of variants){
const screen = context.theme('screens', variant);
const condition = screen && mql(screen) || context.v(variant);
conditions.push(condition);
precedence |= screen ? 1 << 26 | atRulePrecedence(condition) : variant == 'dark' ? 1 << 30 /* Shifts.darkMode */ : condition[0] == '@' ? atRulePrecedence(condition) : pseudoPrecedence(condition);
}
return {
n: name,
p: precedence,
r: conditions,
i: important
};
}
function stringify$1(rule) {
if (rule.d) {
const groups = [];
const selector1 = replaceEach(// merge all conditions into a selector string
rule.r.reduce((selector, condition)=>{
if (condition[0] == '@') {
groups.push(condition);
return selector;
}
// Go over the selector and replace the matching multiple selectors if any
return condition ? merge$1(selector, condition) : selector;
}, '&'), // replace '&' with rule name or an empty string
(selectorPart)=>replaceReference(selectorPart, rule.n ? '.' + escape(rule.n) : '')
);
if (selector1) {
groups.push(selector1.replace(/:merge\((.+?)\)/g, '$1'));
}
return groups.reduceRight((body, grouping)=>grouping + '{' + body + '}'
, rule.d);
}
}
function replaceEach(selector, iteratee) {
return selector.replace(/ *((?:\(.+?\)|\[.+?\]|[^,])+) *(,|$)/g, (_, selectorPart, comma)=>iteratee(selectorPart) + comma
);
}
function replaceReference(selector, reference) {
return selector.replace(/&/g, reference);
}
function merge$1(selector, condition) {
return replaceEach(selector, (selectorPart)=>replaceEach(condition, // If the current condition has a nested selector replace it
(conditionPart)=>{
const mergeMatch = /(:merge\(.+?\))(:[a-z-]+|\\[.+])/.exec(conditionPart);
if (mergeMatch) {
const selectorIndex = selectorPart.indexOf(mergeMatch[1]);
if (~selectorIndex) {
// [':merge(.group):hover .rule', ':merge(.group):focus &'] -> ':merge(.group):focus:hover .rule'
// ':merge(.group)' + ':focus' + ':hover .rule'
return selectorPart.slice(0, selectorIndex) + mergeMatch[0] + selectorPart.slice(selectorIndex + mergeMatch[1].length);
}
// [':merge(.peer):focus~&', ':merge(.group):hover &'] -> ':merge(.peer):focus~:merge(.group):hover &'
return replaceReference(selectorPart, conditionPart);
}
// Return the current selector with the key matching multiple selectors if any
return replaceReference(conditionPart, selectorPart);
})
);
}
function define(className, layer, rules, useOrderOfRules) {
return register(className, (rule, context)=>{
const { n: name , p: precedence , r: conditions , i: important } = convert(rule, context, layer);
return rules && translateWith(name, layer, rules, context, precedence, conditions, important, useOrderOfRules);
});
}
function format(rules, seperator = ',') {
return rules.map(toClassName).join(seperator);
}
function createRule(active, current) {
if (active[active.length - 1] != '(') {
const variants = [];
let important = false;
let negated = false;
let name = '';
for (let value of active){
if (value == '(' || /[~@]$/.test(value)) continue;
if (value[0] == '!') {
value = value.slice(1);
important = !important;
}
if (value.endsWith(':')) {
variants[value == 'dark:' ? 'unshift' : 'push'](value.slice(0, -1));
continue;
}
if (value[0] == '-') {
value = value.slice(1);
negated = !negated;
}
if (value.endsWith('-')) {
value = value.slice(0, -1);
}
if (value && value != '&') {
name += (name && '-') + value;
}
}
if (name) {
if (negated) name = '-' + name;
current[0].push({
n: name,
v: variants.filter(uniq),
i: important
});
}
}
}
function uniq(value, index, values) {
return values.indexOf(value) == index;
}
// Remove comments (multiline and single line)
function removeComments(tokens) {
return tokens.replace(/\/\*[^]*?\*\/|\s\s+|\n/gm, ' ');
}
const cache = new Map();
function parse(token) {
let parsed = cache.get(token);
if (!parsed) {
token = removeComments(token);
// Stack of active groupings (`(`), variants, or nested (`~` or `@`)
const active = [];
// Stack of current rule list to put new rules in
// the first `0` element is the current list
const current = [
[]
];
let startIndex = 0;
let skip = 0;
let position = 0;
// eslint-disable-next-line no-inner-declarations
const commit = (isRule, endOffset = 0)=>{
if (startIndex != position) {
active.push(token.slice(startIndex, position + endOffset));
if (isRule) {
createRule(active, current);
}
}
startIndex = position + 1;
};
for(; position < token.length; position++){
const char = token[position];
if (skip) {
// within [...]
// skip over until not skipping
// ignore escaped chars
if (token[position - 1] != '\\') {
skip += +(char == '[') || -(char == ']');
}
} else if (char == '[') {
// start to skip
skip += 1;
} else if (char == '(') {
// hover:(...) or utilitity-(...)
commit();
active.push(char);
} else if (char == ':') {
// hover: or after::
if (token[position + 1] != ':') {
commit(false, 1);
}
} else if (/[\s,)]/.test(char)) {
// whitespace, comma or closing brace
commit(true);
let lastGroup = active.lastIndexOf('(');
if (char == ')') {
// Close nested block
const nested = active[lastGroup - 1];
if (/[~@]$/.test(nested)) {
const rules = current.shift();
active.length = lastGroup;
// remove variants that are already applied through active
createRule([
...active,
'#'
], current);
const { v } = current[0].pop();
for (const rule of rules){
// if a rule has dark we need to splice after the first entry eg dark
rule.v.splice(+(rule.v[0] == 'dark') - +(v[0] == 'dark'), v.length);
}
createRule([
...active,
define(// named nested
nested.length > 1 ? nested.slice(0, -1) + hash(JSON.stringify([
nested,
rules
])) : nested + '(' + format(rules) + ')', Layer.s, rules, /@$/.test(nested)),
], current);
}
lastGroup = active.lastIndexOf('(', lastGroup - 1);
}
active.length = lastGroup + 1;
} else if (/[~@]/.test(char) && token[position + 1] == '(') {
// start nested block
// ~(...) or button~(...)
// @(...) or button@(...)
current.unshift([]);
}
}
// Consume remaining stack
commit(true);
cache.set(token, parsed = current[0]);
}
return parsed;
}
const collator = new Intl.Collator('en', {
numeric: true
});
/**
* Find the array index of where to add an element to keep it sorted.
*
* @returns The insertion index
*/ function sortedInsertionIndex(array, element) {
// Find position using binary search
// eslint-disable-next-line no-var
for(var low = 0, high = array.length; low < high;){
const pivot = high + low >> 1;
// Less-Then-Equal to add new equal element after all existing equal elements (stable sort)
if (compareTwindRules(array[pivot], element) <= 0) {
low = pivot + 1;
} else {
high = pivot;
}
}
return high;
}
function compareTwindRules(a, b) {
// base and overrides (css) layers are kept in order they are declared
const layer = a.p & Layer.o;
if (layer == (b.p & Layer.o) && (layer == Layer.b || layer == Layer.o)) {
return 0;
}
return a.p - b.p || a.o - b.o || collator.compare(a.n, b.n);
}
function merge(rules, name) {
// merge:
// - same conditions
// - replace name with hash of name + condititions + declarations
// - precedence:
// - combine bits or use max precendence
// - set layer bit to merged
const result = [];
let current;
for (const rule of rules){
// only merge rules with declarations and names (eg no global rules)
if (!(rule.d && rule.n)) {
result.push({
...rule,
n: rule.n && name
});
} else if (current?.p == rule.p && '' + current.r == '' + rule.r) {
current.c = [
current.c,
rule.c
].filter(Boolean).join(' ');
current.d = current.d + ';' + rule.d;
} else {
// only set name for named rules eg not for global or className propagation rules
result.push(current = {
...rule,
n: rule.n && name
});
}
}
return result;
}
function translate(rules, context, precedence = Layer.u, conditions, important) {
// Sorted by precedence
const result = [];
for (const rule of rules){
for (const cssRule of translate$(rule, context, precedence, conditions, important)){
result.splice(sortedInsertionIndex(result, cssRule), 0, cssRule);
}
}
return result;
}
function translate$(rule1, context, precedence, conditions, important) {
rule1 = {
...rule1,
i: rule1.i || important
};
const resolved = resolve(rule1, context);
if (!resolved) {
// propagate className as is
return [
{
c: toClassName(rule1),
p: 0,
o: 0,
r: []
}
];
}
// a list of class names
if (typeof resolved == 'string') {
({ r: conditions , p: precedence } = convert(rule1, context, precedence, conditions));
return merge(translate(parse(resolved), context, precedence, conditions, rule1.i), rule1.n);
}
if (Array.isArray(resolved)) {
return resolved.map((rule)=>({
o: 0,
...rule,
r: [
...asArray(conditions),
...asArray(rule.r)
],
p: moveToLayer(precedence, rule.p ?? precedence)
})
);
}
return serialize(resolved, rule1, context, precedence, conditions);
}
function translateWith(name, layer, rules, context, precedence, conditions, important, useOrderOfRules) {
return merge((useOrderOfRules ? rules.flatMap((rule)=>translate([
rule
], context, precedence, conditions, important)
) : translate(rules, context, precedence, conditions, important)).map((rule)=>// do not move defaults
// move only rules with a name unless they are in the base layer
rule.p & Layer.o && (rule.n || layer == Layer.b) ? {
...rule,
p: moveToLayer(rule.p, layer),
o: 0
} : rule
), name);
}
function serialize(style, rule, context, precedence, conditions = []) {
return serialize$(style, convert(rule, context, precedence, conditions), context);
}
function serialize$(style, { n: name , p: precedence , r: conditions = [] , i: important }, context) {
const rules = [];
// The generated declaration block eg body of the css rule
let declarations = '';
// This ensures that 'border-top-width' has a higher precedence than 'border-top'
let maxPropertyPrecedence = 0;
// More specific utilities have less declarations and a higher precedence
let numberOfDeclarations = 0;
for(let key in style || {}){
const value1 = style[key];
if (key[0] == '@') {
// at rules: https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule
if (!value1) continue;
// @apply ...;
if (key[1] == 'a') {
rules.push(...translateWith(name, precedence, // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
parse('' + value1), context, precedence, conditions, important, true));
continue;
}
// @layer <layer>
if (key[1] == 'l') {
for (const css of asArray(value1)){
rules.push(...serialize$(css, {
n: name,
p: moveToLayer(precedence, Layer[key[7]]),
r: conditions,
i: important
}, context));
}
continue;
}
// @import
if (key[1] == 'i') {
rules.push(...asArray(value1).map((value)=>({
// before all layers
p: -1,
o: 0,
r: [],
d: key + ' ' + value
})
));
continue;
}
// @keyframes
if (key[1] == 'k') {
// Use defaults layer
rules.push({
p: Layer.d,
o: 0,
r: [
key
],
d: serialize$(value1, {
p: Layer.d
}, context).map(stringify$1).join('')
});
continue;
}
// @font-face
// TODO @font-feature-values
if (key[1] == 'f') {
// Use defaults layer
rules.push(...asArray(value1).map((value)=>({
p: Layer.d,
o: 0,
r: [
key
],
d: serialize$(value, {
p: Layer.d
}, context).map(stringify$1).join('')
})
));
continue;
}
// -> All other are handled below; same as selector
}
// @media
// @supports
// selector
if (typeof value1 == 'object' && !Array.isArray(value1)) {
// at-rule or non-global selector
if (key[0] == '@' || key.includes('&')) {
let rulePrecedence = precedence;
if (key[0] == '@') {
// Handle `@media screen(sm)` and `@media (screen(sm) or ...)`
key = key.replace(/\bscreen\(([^)]+)\)/g, (_, screenKey)=>{
const screen = context.theme('screens', screenKey);
if (screen) {
rulePrecedence |= 1 << 26 /* Shifts.screens */ ;
return mql(screen, '');
}
return _;
});
rulePrecedence |= atRulePrecedence(key);
}
rules.push(...serialize$(value1, {
n: name,
p: rulePrecedence,
r: [
...conditions,
key
],
i: important
}, context));
} else {
// global selector
rules.push(...serialize$(value1, {
p: precedence,
r: [
key
]
}, context));
}
} else if (key == 'label' && value1) {
name = value1 + hash(JSON.stringify([
precedence,
important,
style
]));
} else if (value1 || value1 === 0) {
// property -> hyphenate
key = key.replace(/[A-Z]/g, (_)=>'-' + _.toLowerCase()
);
// Update precedence
numberOfDeclarations += 1;
maxPropertyPrecedence = Math.max(maxPropertyPrecedence, declarationPropertyPrecedence(key));
declarations += (declarations ? ';' : '') + asArray(value1).map((value)=>context.s(key, // support theme(...) function in values
// calc(100vh - theme('spacing.12'))
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
resolveThemeFunction('' + value, context) + (important ? ' !important' : ''))
).join(';');
}
}
// PERF: prevent unshift using `rules = [{}]` above and then `rules[0] = {...}`
rules.unshift({
n: name && context.h(name),
p: precedence,
o: // number of declarations (descending)
Math.max(0, 15 - numberOfDeclarations) + // greatest precedence of properties
// if there is no property precedence this is most likely a custom property only declaration
// these have the highest precedence
Math.min(maxPropertyPrecedence || 15, 15) * 1.5,
r: conditions,
// stringified declarations
d: declarations
});
return rules.sort(compareTwindRules);
}
function resolveThemeFunction(value3, context) {
// support theme(...) function in values
// calc(100vh - theme('spacing.12'))
// theme('borderColor.DEFAULT', 'currentColor')
// PERF: check for theme before running the regexp
// if (value.includes('theme')) {
return value3.replace(/theme\((["'`])?(.+?)\1(?:\s*,\s*(["'`])?(.+?)\3)?\)/g, (_, __, key, ___, value)=>context.theme(key, value)
);
// }
// return value
}
function interleave(strings, interpolations, handle) {
return interpolations.reduce((result, interpolation, index)=>result + handle(interpolation) + strings[index + 1]
, strings[0]);
}
function astish(strings, interpolations) {
return Array.isArray(strings) ? astish$(interleave(strings, interpolations, (interpolation)=>interpolation != null && typeof interpolation != 'boolean' ? interpolation : ''
)) : typeof strings == 'string' ? astish$(strings) : [
strings
];
}
// Based on https://github.com/cristianbote/goober/blob/master/src/core/astish.js
const newRule = / *(?:(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}))/g;
/**
* Convert a css style string into a object
*/ function astish$(css) {
css = removeComments(css);
const tree = [
{}
];
const rules = [
tree[0]
];
const conditions = [];
let block;
while(block = newRule.exec(css)){
// Remove the current entry
if (block[4]) {
tree.shift();
conditions.shift();
}
if (block[3]) {
// new nested
conditions.unshift(block[3]);
tree.unshift({});
rules.push(conditions.reduce((body, condition)=>({
[condition]: body
})
, tree[0]));
} else if (!block[4]) {
// if we already have that property — start a new CSSObject
if (tree[0][block[1]]) {
tree.unshift({});
rules.push(conditions.reduce((body, condition)=>({
[condition]: body
})
, tree[0]));
}
tree[0][block[1]] = block[2];
}
}
// console.log(rules)
return rules;
}
function css(strings, ...interpolations) {
const ast = astish(strings, interpolations);
const className = (ast.find((o)=>o.label
)?.label || 'css') + hash(JSON.stringify(ast));
return register(className, (rule, context)=>merge(ast.flatMap((css1)=>serialize(css1, rule, context, Layer.o)
), className)
);
}
const animation = /* @__PURE__ */ new Proxy(function animation1(animation1, waypoints) {
return animation$('animation', animation1, waypoints);
}, {
get (target, name) {
if (name in target) return target[name];
return function namedAnimation(animation2, waypoints) {
return animation$(name, animation2, waypoints);
};
}
});
function animation$(label, animation3, waypoints) {
return {
toString () {
return css({
label,
...typeof animation3 == 'object' ? animation3 : {
animation: animation3
},
animationName: '' + waypoints
});
}
};
}
function parseColorComponent(chars, factor) {
return Math.round(parseInt(chars, 16) * factor);
}
function toColorValue(color, options = {}) {
if (typeof color == 'function') {
return color(options);
}
const { opacityValue ='1' , opacityVariable } = options;
const opacity = opacityVariable ? `var(${opacityVariable})` : opacityValue;
if (opacity == '1') return color;
if (opacity == '0') return '#0000';
// rgb hex: #0123 and #001122
if (color[0] == '#' && (color.length == 4 || color.length == 7)) {
const size = (color.length - 1) / 3;
const factor = [
17,
1,
0.062272
][size - 1];
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
return `rgba(${[
parseColorComponent(color.substr(1, size), factor),
parseColorComponent(color.substr(1 + size, size), factor),
parseColorComponent(color.substr(1 + 2 * size, size), factor),
opacity,
]})`;
}
return color;
}
/**
* Determines if two class name strings contain the same classes.
*
* @param a first class names
* @param b second class names
* @returns are they different
*/ function changed(a, b) {
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
return a != b && '' + a.split(' ').sort() != '' + b.split(' ').sort();
}
function makeThemeFunction({ extend ={} , ...base }) {
const resolved = {};
const resolveContext = {
colors: theme('colors'),
theme,
// Stub implementation as negated values are automatically infered and do _not_ need to be in the theme
negative () {
return {};
},
breakpoints (screens) {
const breakpoints = {};
for(const key in screens){
if (typeof screens[key] == 'string') {
breakpoints['screen-' + key] = screens[key];
}
}
return breakpoints;
}
};
return theme;
function theme(sectionKey, key, defaultValue) {
if (sectionKey) {
if (/[.[]/.test(sectionKey)) {
const path = [];
// dotted deep access: colors.gray.500 or or spacing[2.5]
sectionKey.replace(/\[([^\]]+)\]|([^.[]+)/g, (_, $1, $2 = $1)=>path.push($2)
);
sectionKey = path.shift();
defaultValue = key;
key = path.join('-');
}
const section = resolved[sectionKey] || // two-step deref to allow extend section to reference base section
Object.assign(Object.assign(// Make sure to not get into recursive calls
(resolved[sectionKey] = {}), deref(base, sectionKey)), deref(extend, sectionKey));
if (key == null) return section;
return section[key || 'DEFAULT'] ?? defaultValue;
}
// Collect the whole theme
const result = {};
for(const section in base){
result[section] = theme(section);
}
return result;
}
function deref(source, section) {
let value = source[section];
if (typeof value == 'function') {
value = value(resolveContext);
}
if (value && /color/i.test(section)) {
return flattenColorPalette(value);
}
return value;
}
}
function flattenColorPalette(colors, path = []) {
const flattend = {};
for(const key in colors){
const value = colors[key];
const keyPath = key == 'DEFAULT' ? path : [
...path,
key
];
if (typeof value == 'object') {
Object.assign(flattend, flattenColorPalette(value, keyPath));
}
flattend[keyPath.join('-')] = value;
if (key == 'DEFAULT') {
flattend[[
...path,
key
].join('-')] = value;
}
}
return flattend;
}
function createContext({ theme , darkMode , variants , rules , hash: hash$1 , stringify , ignorelist }) {
// Used to cache resolved rule values
const variantCache = new Map();
// lazy created resolve functions
const variantResolvers = new Map();
// Used to cache resolved rule values
const ruleCache = new Map();
// lazy created resolve functions
const ruleResolvers = new Map();
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const ignored = createRegExpExecutor(ignorelist, (value, condition)=>condition.test(value)
);
// add dark as last variant to allow user to override it
// we can modify variants as it has been passed through defineConfig which already made a copy
variants.push([
'dark',
darkMode == 'class' ? '.dark &' : typeof darkMode === 'string' && darkMode != 'media' ? darkMode // a custom selector
: '@media (prefers-color-scheme:dark)',
]);
return {
theme: makeThemeFunction(theme),
e: escape,
h: typeof hash$1 == 'function' ? (value)=>hash$1(value, hash)
: hash$1 ? hash : identity,
s (property, value) {
return stringify(property, value, this);
},
v (value) {
if (!variantCache.has(value)) {
variantCache.set(value, find(value, variants, variantResolvers, getVariantResolver, this) || '&:' + value);
}
return variantCache.get(value);
},
r (value) {
if (!ruleCache.has(value)) {
ruleCache.set(value, // TODO console.warn(`[twind] unknown rule "${value}"`),
!ignored(value, this) && find(value, rules, ruleResolvers, getRuleResolver, this));
}
return ruleCache.get(value);
}
};
}
function find(value, list, cache, getResolver, context) {
for (const item of list){
let resolver = cache.get(item);
if (!resolver) {
cache.set(item, resolver = getResolver(item));
}
const resolved = resolver(value, context);
if (resolved) return resolved;
}
}
function getVariantResolver(variant) {
return createVariantFunction(variant[0], variant[1]);
}
function getRuleResolver(rule) {
if (Array.isArray(rule)) {
return createResolveFunction(rule[0], rule[1], rule[2]);
}
return createResolveFunction(rule);
}
function createVariantFunction(patterns, resolve) {
return createResolve(patterns, typeof resolve == 'function' ? resolve : ()=>resolve
);
}
function createResolveFunction(patterns, resolve, convert) {
return createResolve(patterns, !resolve ? (match)=>({
[match[1]]: maybeNegate(match.input, match.slice(2).find(Boolean) || match.$$ || match.input)
})
: typeof resolve == 'function' ? resolve : typeof resolve == 'string' && /^[\w-]+$/.test(resolve) // a CSS property alias
? (match, context)=>({
[resolve]: convert ? convert(match, context) : maybeNegate(match.input, match.slice(1).find(Boolean) || match.$$ || match.input)
})
: ()=>resolve
);
}
function maybeNegate($_, value) {
return $_[0] == '-' ? `calc(${value} * -1)` : value;
}
function createResolve(patterns, resolve) {
return createRegExpExecutor(patterns, (value, condition, context)=>{
const match = condition.exec(value);
if (match) {
// MATCH.$_ = value
match.$$ = value.slice(match[0].length);
return resolve(match, context);
}
});
}
function createRegExpExecutor(patterns, run) {
const conditions = asArray(patterns).map(toCondition);
return (value, context)=>{
for (const condition of conditions){
const result = run(value, condition, context);
if (result) return result;
}
};
}
/**
* Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search.
* @param string The String object or string literal on which to perform the search.
*/ // type Condition = (string: string) => RegExpExecArray | Falsey
function toCondition(value) {
// "visible" -> /^visible$/
// "(float)-(left|right|none)" -> /^(float)-(left|right|none)$/
// "auto-rows-" -> /^auto-rows-/
// "gap(-|$)" -> /^gap(-|$)/
// PERF: try to detect if we can skip the regex execution
// if (typeof value == 'string') {
// const prefix = /^[\w-#~@]+(?!\?)/.exec(value)?.[0]
// value = new RegExp('^' + value + (value.includes('$') || value.slice(-1) == '-' ? '' : '$'))
// if (prefix) {
// return (string) => string.startsWith(prefix) && (value as RegExp).exec(string)
// }
// }
// return (string) => (value as RegExp).exec(string)
return typeof value == 'string' ? new RegExp('^' + value + (value.includes('$') || value.slice(-1) == '-' ? '' : '$')) : value;
}
function defineConfig({ presets =[] , ...userConfig }) {
// most user config values go first to have precendence over preset config
// only `preflight` and `theme` are applied as last preset to override all presets
let config = {
preflight: userConfig.preflight !== false && [],
darkMode: undefined,
theme: {},
variants: asArray(userConfig.variants),
rules: asArray(userConfig.rules),
ignorelist: asArray(userConfig.ignorelist),
hash: userConfig.hash,
stringify: userConfig.stringify || noprefix
};
for (const preset of asArray([
...presets,
{
darkMode: userConfig.darkMode,
preflight: userConfig.preflight !== false && asArray(userConfig.preflight),
theme: userConfig.theme
},
])){
const { preflight , darkMode =config.darkMode , theme , variants , rules , hash =config.hash , ignorelist , stringify =config.stringify , } = typeof preset == 'function' ? preset(config) : preset;
config = {
// values defined by user or previous presets take precedence
preflight: config.preflight !== false && preflight !== false && [
...config.preflight,
...asArray(preflight)
],
darkMode,
theme: {
...config.theme,
...theme,
extend: {
...config.theme.extend,
...theme?.extend
}
},
variants: [
...config.variants,
...asArray(variants)
],
rules: [
...config.rules,
...asArray(rules)
],
ignorelist: [
...config.ignorelist,
...asArray(ignorelist)
],
hash,
stringify
};
}
return config;
}
function noprefix(property, value) {
return property + ':' + value;
}
function twind(userConfig, sheet) {
const config = defineConfig(userConfig);
const context = createContext(config);
// Map of tokens to generated className
const cache = new Map();
// An array of precedence by index within the sheet
// always sorted
const sortedPrecedences = [];
// Cache for already inserted css rules
// to prevent double insertions
const insertedRules = new Set();
sheet.resume((className)=>cache.set(className, className)
, (rule, cssText)=>{
sheet.insert(cssText, sortedPrecedences.length, rule);
sortedPrecedences.push(rule);
insertedRules.add(cssText);
});
function insert(rule) {
rule = {
...rule,
n: rule.n && context.h(rule.n)
};
const cssText = stringify$1(rule);
// If not already inserted
if (cssText && !insertedRules.has(cssText)) {
// Mark rule as inserted
insertedRules.add(cssText);
// Find the correct position
const index = sortedInsertionIndex(sortedPrecedences, rule);
// Insert
sheet.insert(cssText, index, rule);
// Update sorted index
sortedPrecedences.splice(index, 0, rule);
}
return rule.n;
}
return Object.defineProperties(function tw(tokens) {
if (!cache.size) {
for (let preflight of asArray(config.preflight)){
if (typeof preflight == 'function') {
preflight = preflight(context);
}
if (preflight) {
(typeof preflight == 'string' ? translateWith('', Layer.b, parse(preflight), context, Layer.b, [], false, true) : serialize(preflight, {}, context, Layer.b)).forEach(insert);
}
}
}
tokens = '' + tokens;
let className = cache.get(tokens);
if (!className) {
const classNames = new Set();
for (const rule of translate(parse(tokens), context)){
classNames.add(rule.c).add(insert(rule));
}
className = [
...classNames
].filter(Boolean).join(' ');
// Remember the generated class name
cache.set(tokens, className).set(className, className);
}
return className;
}, Object.getOwnPropertyDescriptors({
get target () {
return sheet.target;
},
theme: context.theme,
config,
clear () {
sheet.clear();
insertedRules.clear();
cache.clear();
sortedPrecedences.length = 0;
},
destroy () {
this.clear();
sheet.destroy();
}
}));
}
function observe(tw$1 = tw, target1 = typeof document != 'undefined' && document.documentElement) {
if (!target1) return tw$1;
const observer = new MutationObserver(handleMutationRecords);
observer.observe(target1, {
attributeFilter: [
'class'
],
subtree: true,
childList: true
});
// handle class attribute on target
handleClassAttributeChange(target1);
// handle children of target
handleMutationRecords([
{
target: target1,
type: ''
}
]);
// monkey patch tw.destroy to disconnect this observer
// eslint-disable-next-line @typescript-eslint/unbound-method
const { destroy } = tw$1;
tw$1.destroy = ()=>{
observer.disconnect();
destroy.call(tw$1);
};
return tw$1;
function handleMutationRecords(records) {
for (const { type , target } of records){
if (type[0] == 'a' /* attribute */ ) {
// class attribute has been changed
handleClassAttributeChange(target);
} else {
target.querySelectorAll('[class]').forEach(handleClassAttributeChange);
}
}
// remove pending mutations — these are triggered by updating the class attributes
observer.takeRecords();
// XXX maybe we need to handle all pending mutations
// observer.takeRecords().forEach(handleMutation)
}
function handleClassAttributeChange(target) {
// Not using target.classList.value (not supported in all browsers) or target.class (this is an SVGAnimatedString for svg)
const tokens = target.getAttribute('class');
let className;
// try do keep classNames unmodified
if (tokens && changed(tokens, className = tw$1(tokens))) {
// Not using `target.className = ...` as that is read-only for SVGElements
target.setAttribute('class', className);
}
}
}
function getStyleElement(element) {
let style = element || document.querySelector('style[data-twind]');
if (!style || style.tagName != 'STYLE') {
style = document.createElement('style');
style.dataset.twind = '';
document.head.prepend(style);
}
return style;
}
function cssom(element) {
const target = element?.cssRules ? element : getStyleElement(element).sheet;
return {
target,
clear () {
// remove all added rules
for(let index = target.cssRules.length; index--;){
target.deleteRule(index);
}
},
destroy () {
target.ownerNode?.remove();
},
insert (css, index) {
try {
// Insert
target.insertRule(css, index);
} catch (error) {
// Empty rule to keep index valid — not using `*{}` as that would show up in all rules (DX)
target.insertRule(':root{}', index);
// Some thrown errors are because of specific pseudo classes
// lets filter them to prevent unnecessary warnings
// ::-moz-focus-inner
// :-moz-focusring
if (!/:-[mwo]/.test(css)) {
console.warn(error, css);
}
}
},
resume: noop
};
}
function dom(element) {
const target = getStyleElement(element);
return {
target,
clear () {
target.innerHTML = '';
},
destroy () {
target.remove();
},
insert (css, index) {
target.insertBefore(document.createTextNode(css), target.childNodes[index] || null);
},
resume: noop
};
}
function virtual(includeResumeData) {
const target = [];
const rules = [];
return {
get target () {
return includeResumeData ? target.map((css, index)=>{
const rule = rules[index];
const p = rule.p - (rules[index - 1]?.p || 0);
return `/*!${p.toString(36)},${(rule.o * 2).toString(36)}${rule.n ? ',' + rule.n : ''}*/${css}`;
}) : target;
},
clear () {
target.length = 0;
},
destroy () {
this.clear();
},
insert (css, index, rule) {
target.splice(index, 0, css);
rules.splice(index, 0, rule);
},
resume: noop
};
}
/**
* Returns a sheet useable in the current environment.
*
* @param useDOMSheet usually something like `process.env.NODE_ENV != 'production'` (default: browser={@link cssom}, server={@link virtual})
* @param disableResume to not include or use resume data
* @returns a sheet to use
*/ function getSheet(useDOMSheet, disableResume) {
const sheet = typeof document == 'undefined' ? virtual(!disableResume) : useDOMSheet ? dom() : cssom();
if (!disableResume) sheet.resume = resume;
return sheet;
}
function stringify(target) {
// string[] | CSSStyleSheet | HTMLStyleElement
return(// prefer the raw test content of a CSSStyleSheet as it may include the resume data
(target.ownerNode || target)?.textContent || (target.cssRules ? Array.from(target.cssRules, (rule)=>rule.cssText
) : asArray(target)).join(''));
}
function resume(addClassName, insert) {
// hydration from SSR sheet
const textContent = stringify(this.target);
const RE = /\/\*!([\da-z]+),([\da-z]+)(?:,(.+?))?\*\//g;
// only if this is a hydratable sheet
if (RE.test(textContent)) {
// RE has global flag — reset index to get the first match as well
RE.lastIndex = 0;
// 1. start with a fresh sheet
this.clear();
// 2. add all existing class attributes to the token/className cache
if (typeof document != 'undefined') {
for (const el of document.querySelectorAll('[class]')){
addClassName(el.getAttribute('class'));
}
}
// 3. parse SSR styles
let lastMatch;
let lastPrecedence = 0;
while((function commit(match) {
if (lastMatch) {
insert({
p: lastPrecedence += parseInt(lastMatch[1], 36),
o: parseInt(lastMatch[2], 36) / 2,
n: lastMatch[3] ?? undefined
}, // grep the cssText from the previous match end up to this match start
textContent.slice(lastMatch.index + lastMatch[0].length, match?.index));
}
return lastMatch = match;
})(RE.exec(textContent))){
/* no-op */ }
}
}
function auto(setup1) {
// If we run in the browser we call setup at latest when the body is inserted
// This algorith works well for _normal_ scripts (`<script src="..."></script>`)
// but not for modules because those are executed __after__ the DOM is ready
// and we would have FOUC
if (typeof document != 'undefined' && document.currentScript) {
const cancelAutoSetup = ()=>observer.disconnect()
;
const observer = new MutationObserver((mutationsList)=>{
for (const { target } of mutationsList){
// If we reach the body we immediately run the setup to prevent FOUC
if (target === document.body) {
setup1();
return cancelAutoSetup();
}
}
});
observer.observe(document.documentElement, {
childList: true,
subtree: true
});
return cancelAutoSetup;
}
return noop;
}
/**
* A proxy to the currently active Twind instance.
*/ const tw = /* @__PURE__ */ Object.defineProperties(// just exposing the active as tw should work with most bundlers
// as ES module export can be re-assigned BUT some bundlers to not honor this
// -> using a delegation proxy here
function tw(...args) {
return active(...args);
}, Object.getOwnPropertyDescriptors({
get target () {
return active.target;
},
theme (...args) {
return active.theme(...args);
},
get config () {
return active.config;
},
clear () {
return active.clear();
},
destroy () {
return active.destroy();
}
}));
let active;
function setup(config = {}, sheet = getSheet(), target) {
const firstRun = !active;
if (!firstRun) {
active.destroy();
}
active = observe(twind(config, sheet), target);
if (firstRun && typeof document != 'undefined') {
// first run in browser
// If they body was hidden autofocus the first element
if (!document.activeElement) {
document.querySelector('[autofocus]')?.focus();
}
}
return active;
}
/**
* Used for static HTML processing (usually to provide SSR support for your javascript-powered web apps)
*
* **Note**: Consider using {@link inject} or {@link extract} instead.
*
* 1. parse the markup and process element classes with the provided Twind instance
* 2. update the class attributes _if_ necessary
* 3. return the HTML string with the final element classes
*
* ```js
* import { consume, stringify, tw } from 'twind'
*
* function render() {
* const html = renderApp()
*
* // clear all styles — optional
* tw.clear()
*
* // generated markup
* const markup = consume(html)
*
* // create CSS
* const css = stringify(tw.target)
*
* // inject as last element into the head
* return markup.replace('</head>', `<style data-twind>${css}</style></head>`)
* }
* ```
*
* You can provide your own Twind instance:
*
* ```js
* import { consume, stringify } from 'twind'
* import { tw } from './custom/twind/instance'
*
* function render() {
* const html = renderApp()
*
* // clear all styles — optional
* tw.clear()
*
* // generated markup
* const markup = consume(html)
*
* // create CSS
* const css = stringify(tw.target)
*
* // inject as last element into the head
* return markup.replace('</head>', `<style data-twind>${css}</style></head>`)
* }
* ```
*
* @param markup HTML to process
* @param tw a {@link Twind} instance
* @returns possibly modified HTML
*/ function consume(markup, tw$1 = tw) {
let result = '';
let lastChunkStart = 0;
extract$1(markup, (startIndex, endIndex, quote)=>{
const value = markup.slice(startIndex, endIndex);
const className = tw$1(value);
// We only need to shift things around if we need to actually change the markup
if (changed(value, className)) {
// We've hit another mutation boundary
// Add quote if necessary
quote = quote ? '' : '"';
result += markup.slice(lastChunkStart, startIndex) + quote + className + quote;
lastChunkStart = endIndex;
}
});
// Combine the current result with the tail-end of the input
return result + markup.slice(lastChunkStart, markup.length);
}
// For now we are using a simple parser adapted from htm (https://github.com/developit/htm/blob/master/src/build.mjs)
// If we find any issues we can switch to something more sophisticated like
// - https://github.com/acrazing/html5parser
// - https://github.com/fb55/htmlparser2
const MODE_SLASH = 0;
const MODE_TEXT = 1;
const MODE_WHITESPACE = 2;
const MODE_TAGNAME = 3;
const MODE_COMMENT = 4;
const MODE_ATTRIBUTE = 5;
function extract$1(markup, onClass) {
let mode = MODE_TEXT;
let startIndex = 0;
let quote = '';
let attributeName = '';
const commit = (currentIndex)=>{
if (mode == MODE_ATTRIBUTE && attributeName == 'class') {
onClass(startIndex, currentIndex, quote);
}
};
for(let position = 0; position < markup.length; position++){
const char = markup[position];
if (mode == MODE_TEXT) {
if (char == '<') {
mode = markup.substr(position + 1, 3) == '!--' ? MODE_COMMENT : MODE_TAGNAME;
}
} else if (mode == MODE_COMMENT) {
// Ignore everything until the last three characters are '-', '-' and '>'
if (char == '>' && markup.slice(position - 2, position) == '--') {
mode = MODE_TEXT;
}
} else if (quote) {
if (char == quote && markup[position - 1] != '\\') {
commit(position);
mode = MODE_WHITESPACE;
quote = '';
}
} else if (char == '"' || char == "'") {
quote = char;
startIndex += 1;
} else if (char == '>') {
commit(position);
mode = MODE_TEXT;
} else if (!mode) ; else if (char == '=') {
attributeName = markup.slice(startIndex, position);
mode = MODE_ATTRIBUTE;
startIndex = position + 1;
} else if (char == '/' && (mode < MODE_ATTRIBUTE || markup[position + 1] == '>')) {
commit(position);
mode = MODE_SLASH;
} else if (/\s/.test(char)) {
// <a class=font-bold>
commit(position);
mode = MODE_WHITESPACE;
startIndex = position + 1;
}
}
}
// based on https://github.com/lukeed/clsx and https://github.com/jorgebucaran/classcat
function interpolate(strings, interpolations) {
return Array.isArray(strings) && Array.isArray(strings.raw) ? interleave(strings, interpolations, (value)=>toString(value).trim()
) : interpolations.filter(Boolean).reduce((result, value)=>result + toString(value)
, strings ? toString(strings) : '');
}
function toString(value) {
let result = '';
let tmp;
if (value && typeof value == 'object') {
if (Array.isArray(value)) {
if (tmp = interpolate(value[0], value.slice(1))) {
result += ' ' + tmp;
}
} else {
for(const key in value){
if (value[key]) result += ' ' + key;
}
}
} else if (value != null && typeof value != 'boolean') {
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
result += ' ' + value;
}
return result;
}
function cx(strings, ...interpolations) {
return format(parse(interpolate(strings, interpolations)), ' ');
}
/**
* Used for static HTML processing (usually to provide SSR support for your javascript-powered web apps)
*
* **Note**: Consider using {@link inject} instead.
*
* **Note**: This {@link Twind.clear clears} the Twind instance before processing the HTML.
*
* 1. parse the markup and process element classes with the provided Twind instance
* 2. update the class attributes _if_ necessary
* 3. return the HTML string with the final element classes
*
* ```js
* import { extract } from 'twind'
*
* function render() {
* const { html, css } = extract(renderApp())
*
* // inject as last element into the head
* return html.replace('</head>', `<style data-twind>${css}</style></head>`)
* }
* ```
*
* You can provide your own Twind instance:
*
* ```js
* import { extract } from 'twind'
* import { tw } from './custom/twind/instance'
*
* function render() {
* const { html, css } = extract(renderApp(), tw)
*
* // inject as last element into the head
* return html.replace('</head>', `<style data-twind>${css}</style></head>`)
* }
* ```
*
* @param markup HTML to process
* @param tw a {@link Twind} instance (default: twind managed tw)
* @returns the possibly modified html and css
*/ function extract(html, tw$1 = tw) {
tw$1.clear();
return {
html: consume(html, tw$1),
css: stringify(tw$1.target)
};
}
/**
* Injects styles into the global scope and is useful for applications such as gloabl styles, CSS resets or font faces.
*
* It **does not** return a class name, but adds the styles within the base layer to the stylesheet directly.
*/ const injectGlobal = function injectGlobal(strings, ...interpolations) {
const tw$1 = typeof this == 'function' ? this : tw;
tw$1(css({
'@layer base': astish(strings, interpolations)
}));
};
/**
* Used for static HTML processing (usually to provide SSR support for your javascript-powered web apps)
*
* **Note**: This {@link Twind.clear clears} the Twind instance before processing the HTML.
*
* 1. parse the markup and process element classes with the provided Twind instance
* 2. update the class attributes _if_ necessary
* 3. inject a style element with the CSS as last element into the head
* 4. return the HTML string with the final element classes
*
* ```js
* import { inline } from 'twind'
*
* function render() {
* return inline(renderApp())
* }
* ```
*
* Minify CSS with [@parcel/css](https://www.npmjs.com/package/@parcel/css):
*
* ```js
* import { inline } from 'twind'
* import { transform } from '@parcel/css'
*
* function render() {
* return inline(renderApp(), { minify: (css) => transform({ filename: 'twind.css', code: Buffer.from(css), minify: true }) })
* }
* ```
*
* You can provide your own Twind instance:
*
* ```js
* import { inline } from 'twind'
* import { tw } from './custom/twind/instance'
*
* function render() {
* return inline(renderApp(), { tw })
* }
* ```
*
* @param markup HTML to process
* @param tw a {@link Twind} instance
* @returns the resulting HTML
*/ function inline(markup, options = {}) {
const { tw: tw$1 =tw , minify =identity } = typeof options == 'function' ? {
tw: options
} : options;
const { html , css } = extract(markup, tw$1);
// inject as last element into the head
return html.replace('</head>', `<style data-twind>${minify(css, html)}</style></head>`);
}
const keyframes = /* @__PURE__ */ bind();
function bind(thisArg) {
return new Proxy(function keyframes(strings, ...interpolations) {
return keyframes$(thisArg, '', strings, interpolations);
}, {
get (target, name) {
if (name === 'bind') {
return bind;
}
if (name in target) return target[name];
return function namedKeyframes(strings, ...interpolations) {
return keyframes$(thisArg, name, strings, interpolations);
};
}
});
}
function keyframes$(thisArg, name, strings, interpolations) {
// lazy inject keyframes
return {
toString () {
// lazy access tw
const tw$1 = typeof thisArg == 'function' ? thisArg : tw;
const ast = astish(strings, interpolations);
const keyframeName = escape(name + hash(JSON.stringify([
name,
ast
])));
tw$1(css({
[`@keyframes ${keyframeName}`]: astish(strings, interpolations)
}));
return keyframeName;
}
};
}
const apply = /* @__PURE__ */ nested('@');
const shortcut = /* @__PURE__ */ nested('~');
function nested(marker) {
return new Proxy(function nested(strings, ...interpolations) {
return nested$('', strings, interpolations);
}, {
get (target, name) {
if (name in target) return target[name];
return function namedNested(strings, ...interpolations) {
return nested$(name, strings, interpolations);
};
}
});
function nested$(name, strings, interpolations) {
return format(parse(name + marker + '(' + interpolate(strings, interpolations) + ')'));
}
}
function fromTheme(/** Theme section to use (default: `$1` — The first matched group) */ section1, /** The css property (default: value of {@link section}) */ resolve, convert) {
const factory = !resolve ? ({ 1: $1 , _ }, context, section)=>({
[$1 || section]: _
})
: typeof resolve == 'string' ? (match, context)=>({
[resolve]: convert ? convert(match, context) : match._
})
: resolve;
return (match, context)=>{
const themeSection = camelize(section1 || match[1]);
const value = context.theme(themeSection, match.$$) ?? /** Arbitrary lookup type */ // https://github.com/tailwindlabs/tailwindcss/blob/875c850b37a57bc651e1fed91e3d89af11bdc79f/src/util/pluginUtils.js#L163
// type?: 'lookup' | 'color' | 'line-width' | 'length' | 'any' | 'shadow'
arbitrary(match.$$, themeSection, context);
if (value != null) {
match._ = match.input[0] == '-' ? `calc(${value} * -1)` : value;
return factory(match, context, themeSection);
}
};
}
function colorFromTheme(options1 = {}, resolve) {
return (match, context)=>{
// text- -> textColor
// ring-offset(?:-|$) -> ringOffsetColor
const { section =camelize(match[0]).replace('-', '') + 'Color' } = options1;
// extract color and opacity
// rose-500 -> ['rose-500']
// [hsl(0_100%_/_50%)] -> ['[hsl(0_100%_/_50%)]']
// indigo-500/100 -> ['indigo-500', '100']
// [hsl(0_100%_/_50%)]/[.25] -> ['[hsl(0_100%_/_50%)]', '[.25]']
// eslint-disable-next-line no-sparse-arrays
if (!/^(\[[^\]]+]|[^/]+?)(?:\/(.+))?$/.test(match.$$)) return;
const { $1: colorMatch , $2: opacityMatch } = RegExp;
const colorValue = context.theme(section, colorMatch) || arbitrary(colorMatch, section, context);
if (!colorValue) return;
const { // text- -> --tw-text-opacity
// ring-offset(?:-|$) -> --tw-ring-offset-opacity
// TODO move this default into preset-tailwind?
opacityVariable =`--tw-${match[0].replace(/-$/, '')}-opacity` , opacitySection =section.replace('Color', 'Opacity') , property =section , selector , } = options1;
const opacityValue = context.theme(opacitySection, opacityMatch || 'DEFAULT') || opacityMatch && arbitrary(opacityMatch, opacitySection, context);
const color = toColorValue(colorValue, {
opacityVariable: opacityVariable || undefined,
opacityValue: opacityValue || undefined
});
// if (typeof color != 'string') {
// console.warn(`Invalid color ${colorMatch} (from ${match.input}):`, color)
// return
// }
if (resolve) {
match._ = {
value: color,
color: (options)=>toColorValue(colorValue, options)
};
return resolve(match, context);
}
const properties = {};
if (opacityVariable && color.includes(opacityVariable)) {
properties[opacityVariable] = opacityValue || '1';
}
properties[property] = color;
return selector ? {
[selector]: properties
} : properties;
};
}
function arbitrary(value, section, context) {
if (value[0] == '[' && value.slice(-1) == ']') {
value = resolveThemeFunction(value.slice(1, -1), context);
// TODO remove arbitrary type prefix — we do not need it but user may use it
// https://github.com/tailwindlabs/tailwindcss/blob/master/src/util/dataTypes.js
// url, number, percentage, length, line-width, shadow, color, image, gradient, position, family-name, lookup, any, generic-name, absolute-size, relative-size
// If this is a color section and the value is a hex color, color function or color name
if (/color|fill|stroke/i.test(section)) {
if (/^(#|((hsl|rgb)a?|hwb|lab|lch|color)\(|[a-z]+$)/.test(value)) {
return value;
}
} else if (/image/i.test(section)) {
// url(, [a-z]-gradient(, image(, cross-fade(, image-set(
if (/^[a-z-]+\(/.test(value)) {
return value;
}
} else {
// TODO how to differentiate arbitary values for
// - backgroundSize vs backgroundPosition
// - fontWeight vs fontFamily
if (value.includes('calc(')) {
value = value.replace(/(-?\d*\.?\d(?!\b-.+[,)](?![^+\-/*])\D)(?:%|[a-z]+)?|\))([+\-/*])/g, '$1 $2 ');
}
// Convert `_` to ` `, except for escaped underscores `\_` but not between brackets
return value.replace(/(^|[^\\])_+(?![^(]*\))/g, (fullMatch, characterBefore)=>characterBefore + ' '.repeat(fullMatch.length - 1)
).replace(/\\_(?![^(]*\))/g, '_');
}
}
}
function camelize(value) {
return value.replace(/-./g, (x)=>x[1].toUpperCase()
);
}
const style = (base, config)=>typeof base == 'function' ? createStyle(config, base) : createStyle(base)
;
function createStyle(config = {}, parent) {
const { label ='style' , base , props: variants = {} , defaults: localDefaults , when =[] } = config;
const defaults = {
...parent?.defaults,
...localDefaults
};
const id = hash(JSON.stringify([
label,
parent?.className,
base,
variants,
defaults,
when
]));
// Layers:
// component: 0b010
// props: 0b011
// when: 0b100
const className = register('', base || '', Layer.c);
function register(mq, token, layer) {
return define(// `<name>#<id>` or `<parent>~<name>#<id>`
((parent ? parent.className.replace(/#.+$/, '~') : '') + label + mq + id).replace(/[: ,()[\]]/, ''), layer, token && parse(token));
}
return Object.defineProperties(function style(allProps) {
let isWithinRuleDeclaration;
if (Array.isArray(allProps)) {
isWithinRuleDeclaration = true;
allProps = Object.fromEntries(new URLSearchParams(allProps[1]).entries());
}
const props = {
...defaults,
...allProps
};
// If this style is used within config.rules we do NOT include the marker classes
let classNames = isWithinRuleDeclaration ? '' : (parent ? parent(props) + ' ' : '') + className;
let token;
for(const variantKey1 in variants){
const variant = variants[variantKey1];
const propsValue = props[variantKey1];
if (propsValue === Object(propsValue)) {
// inline responsive breakpoints
let mq = '';
token = '';
for(const breakpoint in propsValue){
const breakpointToken = variant[propsValue[breakpoint]];
if (breakpointToken) {
mq += '@' + breakpoint + '-' + propsValue[breakpoint];
token += (token && ' ') + (breakpoint == '_' ? breakpointToken : breakpoint + ':(' + breakpointToken + ')');
}
}
if (token) {
classNames += ' ' + register('--' + variantKey1 + '-' + mq, token, 3 << 27 /* Shifts.layer */ );
}
} else if (token = variant[propsValue]) {
classNames += ' ' + register('--' + variantKey1 + '-' + propsValue, token, 3 << 27 /* Shifts.layer */ );
}
}
when.forEach((match, index)=>{
let mq = '';
for(const variantKey in match[0]){
const propsValue = props[variantKey];
// TODO we ignore inline responsive breakpoints for now — what be the result??
if (propsValue !== Object(propsValue) && '' + propsValue == '' + match[0][variantKey]) {
mq += (mq && '_') + variantKey + '-' + propsValue;
} else {
mq = '';
break;
}
}
if (mq && (token = match[1])) {
classNames += ' ' + register('-' + index + '--' + mq, token, 4 << 27 /* Shifts.layer */ );
}
});
return classNames;
}, Object.getOwnPropertyDescriptors({
className,
defaults,
selector: '.' + escape(className)
}));
}
/**
* Combines {@link tw} and {@link cx}.
*
* Using the default `tw` instance:
*
* ```js
* import { tw } from 'twind'
* tx`underline ${falsy && 'italic'}`
* tx('underline', falsy && 'italic')
* tx({'underline': true, 'italic': false})
*
* // using a custom twind instance
* import { tw } from './custom/twind'
* import { tw } from './custom/twind'
* tx.bind(tw)
* ```
*
* Using a custom `tw` instance:
*
* ```js
* import { tx as tx$ } from 'twind'
* import { tw } from './custom/twind'
*
* export const tx = tx$.bind(tw)
*
* tx`underline ${falsy && 'italic'}`
* tx('underline', falsy && 'italic')
* tx({'underline': true, 'italic': false})
* ```
*
* @param this {@link Twind} instance to use (default: {@link tw})
* @param strings
* @param interpolations
* @returns the class name
*/ const tx = function tx(strings, ...interpolations) {
const tw$1 = typeof this == 'function' ? this : tw;
return tw$1(interpolate(strings, interpolations));
};
export { animation, apply, arbitrary, asArray, auto, colorFromTheme, consume, css, cssom, cx, defineConfig, dom, escape, extract, fromTheme, getSheet, hash, identity, injectGlobal, inline, keyframes, mql, noop, observe, setup, shortcut, stringify, style, toColorValue, tw, twind, tx, virtual };
//# sourceMappingURL=twind.js.map
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.