code
stringlengths 2
1.05M
|
---|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M15 6H4v12.01h16V11h-5z",
opacity: ".3"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M4 4c-1.1 0-2 .9-2 2v12.01c0 1.1.9 1.99 2 1.99h16c1.1 0 2-.9 2-2v-8l-6-6H4zm16 14.01H4V6h11v5h5v7.01z"
}, "1")], 'NoteTwoTone');
exports.default = _default; |
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const _ = require("underscore")
const path = require("path")
const jade = require("jade")
const fs = require("fs")
const moment = require("moment")
const Curation = require("../../../../../models/curation.coffee")
const Article = require("../../../../../models/article.coffee")
const render = function (templateName) {
const filename = path.resolve(
__dirname,
`../../../components/venice_2017/templates/${templateName}.jade`
)
return jade.compile(fs.readFileSync(filename), { filename })
}
describe("Venice index", () =>
it("uses social metadata", function () {
const curation = new Curation({
sections: [
{
social_description: "Social Description",
social_title: "Social Title",
social_image: "files.artsy.net/img/social_image.jpg",
seo_description: "Seo Description",
},
],
sub_articles: [],
})
const html = render("index")({
videoIndex: 0,
curation,
isSubscribed: false,
sub_articles: [],
videoGuide: new Article(),
crop(url) {
return url
},
resize(url) {
return url
},
moment,
sd: {},
markdown() {},
asset() {},
})
html.should.containEql(
'<meta property="og:image" content="files.artsy.net/img/social_image.jpg">'
)
html.should.containEql('<meta property="og:title" content="Social Title">')
html.should.containEql(
'<meta property="og:description" content="Social Description">'
)
return html.should.containEql(
'<meta name="description" content="Seo Description">'
)
}))
describe("Venice video_completed", () =>
it("passes section url to social mixin", function () {
const html = render("video_completed")({
section: {
social_title: "Social Title",
slug: "ep-1",
},
sd: { APP_URL: "http://localhost:5000" },
})
html.should.containEql(
"https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Flocalhost%3A5000%2Fvenice-biennale%2Fep-1"
)
return html.should.containEql("Social Title")
}))
describe("Venice video_description", () =>
it("passes section url to social mixin", function () {
const html = render("video_description")({
section: {
social_title: "Social Title",
slug: "ep-1",
published: true,
},
sd: { APP_URL: "http://localhost:5000" },
markdown() {},
})
html.should.containEql(
"https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Flocalhost%3A5000%2Fvenice-biennale%2Fep-1"
)
return html.should.containEql("Social Title")
}))
|
module.exports = require('../lib/')
.extend('faker', function() {
try {
return require('faker/locale/zh_CN');
} catch (e) {
return null;
}
});
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 2);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* jQuery JavaScript Library v3.2.1
* https://jquery.com/
*
* Includes Sizzle.js
* https://sizzlejs.com/
*
* Copyright JS Foundation and other contributors
* Released under the MIT license
* https://jquery.org/license
*
* Date: 2017-03-20T18:59Z
*/
( function( global, factory ) {
"use strict";
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get jQuery.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real `window`.
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info.
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1
// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode
// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common
// enough that all such attempts are guarded in a try block.
"use strict";
var arr = [];
var document = window.document;
var getProto = Object.getPrototypeOf;
var slice = arr.slice;
var concat = arr.concat;
var push = arr.push;
var indexOf = arr.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var fnToString = hasOwn.toString;
var ObjectFunctionString = fnToString.call( Object );
var support = {};
function DOMEval( code, doc ) {
doc = doc || document;
var script = doc.createElement( "script" );
script.text = code;
doc.head.appendChild( script ).parentNode.removeChild( script );
}
/* global Symbol */
// Defining this global in .eslintrc.json would create a danger of using the global
// unguarded in another place, it seems safer to define global only for this module
var
version = "3.2.1",
// 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.0 only
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([a-z])/g,
// 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,
// 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 all the elements in a clean array
if ( num == null ) {
return slice.call( this );
}
// Return just the one element from the set
return num < 0 ? this[ num + this.length ] : this[ num ];
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
each: function( callback ) {
return jQuery.each( this, callback );
},
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();
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: arr.sort,
splice: arr.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[ 0 ] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// Skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
target = {};
}
// Extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( ( options = arguments[ i ] ) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
( copyIsArray = Array.isArray( copy ) ) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && Array.isArray( src ) ? src : [];
} else {
clone = src && jQuery.isPlainObject( src ) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend( {
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
isFunction: function( obj ) {
return jQuery.type( obj ) === "function";
},
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
// As of jQuery 3.0, isNumeric is limited to
// strings and numbers (primitives or objects)
// that can be coerced to finite numbers (gh-2662)
var type = jQuery.type( obj );
return ( type === "number" || type === "string" ) &&
// parseFloat NaNs numeric-cast false positives ("")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
!isNaN( obj - parseFloat( obj ) );
},
isPlainObject: function( obj ) {
var proto, Ctor;
// Detect obvious negatives
// Use toString instead of jQuery.type to catch host objects
if ( !obj || toString.call( obj ) !== "[object Object]" ) {
return false;
}
proto = getProto( obj );
// Objects with no prototype (e.g., `Object.create( null )`) are plain
if ( !proto ) {
return true;
}
// Objects with prototype are plain iff they were constructed by a global Object function
Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor;
return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString;
},
isEmptyObject: function( obj ) {
/* eslint-disable no-unused-vars */
// See https://github.com/eslint/eslint/issues/6125
var name;
for ( name in obj ) {
return false;
}
return true;
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
// Support: Android <=2.3 only (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call( obj ) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
globalEval: function( code ) {
DOMEval( code );
},
// Convert dashed to camelCase; used by the css and data modules
// Support: IE <=9 - 11, Edge 12 - 13
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
each: function( obj, callback ) {
var length, i = 0;
if ( isArrayLike( obj ) ) {
length = obj.length;
for ( ; i < length; i++ ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
} else {
for ( i in obj ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
}
return obj;
},
// Support: Android <=4.0 only
trim: function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArrayLike( Object( arr ) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : indexOf.call( arr, elem, i );
},
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
for ( ; j < len; j++ ) {
first[ i++ ] = second[ j ];
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var length, value,
i = 0,
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArrayLike( elems ) ) {
length = elems.length;
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: Date.now,
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
} );
if ( typeof Symbol === "function" ) {
jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
}
// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
function( i, name ) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
} );
function isArrayLike( obj ) {
// Support: real iOS 8.2 only (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 = !!obj && "length" in obj && obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v2.3.3
* https://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-08-08
*/
(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;
},
// 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
// https://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
// http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+",
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + identifier + ")(?:\\((" +
// 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( "^#(" + identifier + ")" ),
"CLASS": new RegExp( "^\\.(" + identifier + ")" ),
"TAG": new RegExp( "^(" + identifier + "|[*])" ),
"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 = /[+~]/,
// 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 );
},
// CSS string/identifier serialization
// https://drafts.csswg.org/cssom/#common-serializing-idioms
rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,
fcssescape = function( ch, asCodePoint ) {
if ( asCodePoint ) {
// U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
if ( ch === "\0" ) {
return "\uFFFD";
}
// Control characters and (dependent upon position) numbers get escaped as code points
return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
}
// Other potentially-special ASCII characters get backslash-escaped
return "\\" + ch;
},
// Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function() {
setDocument();
},
disabledAncestor = addCombinator(
function( elem ) {
return elem.disabled === true && ("form" in elem || "label" in elem);
},
{ dir: "parentNode", next: "legend" }
);
// 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 m, i, elem, nid, match, groups, newSelector,
newContext = context && context.ownerDocument,
// nodeType defaults to 9, since context defaults to document
nodeType = context ? context.nodeType : 9;
results = results || [];
// Return early from calls with invalid selector or context
if ( typeof selector !== "string" || !selector ||
nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
return results;
}
// Try to shortcut find operations (as opposed to filters) in HTML documents
if ( !seed ) {
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
if ( documentIsHTML ) {
// If the selector is sufficiently simple, try using a "get*By*" DOM method
// (excepting DocumentFragment context, where the methods don't exist)
if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
// ID selector
if ( (m = match[1]) ) {
// Document context
if ( nodeType === 9 ) {
if ( (elem = context.getElementById( m )) ) {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
// Element context
} else {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( newContext && (elem = newContext.getElementById( m )) &&
contains( context, elem ) &&
elem.id === m ) {
results.push( elem );
return results;
}
}
// Type selector
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Class selector
} else if ( (m = match[3]) && support.getElementsByClassName &&
context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// Take advantage of querySelectorAll
if ( support.qsa &&
!compilerCache[ selector + " " ] &&
(!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
if ( nodeType !== 1 ) {
newContext = context;
newSelector = selector;
// qSA looks outside Element context, which is not what we want
// Thanks to Andrew Dupont for this workaround technique
// Support: IE <=8
// Exclude object elements
} else if ( context.nodeName.toLowerCase() !== "object" ) {
// Capture the context ID, setting it first if necessary
if ( (nid = context.getAttribute( "id" )) ) {
nid = nid.replace( rcssescape, fcssescape );
} else {
context.setAttribute( "id", (nid = expando) );
}
// Prefix every selector in the list
groups = tokenize( selector );
i = groups.length;
while ( i-- ) {
groups[i] = "#" + nid + " " + toSelector( groups[i] );
}
newSelector = groups.join( "," );
// Expand context for sibling selectors
newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
context;
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch ( qsaError ) {
} finally {
if ( nid === expando ) {
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 element and returns a boolean result
*/
function assert( fn ) {
var el = document.createElement("fieldset");
try {
return !!fn( el );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( el.parentNode ) {
el.parentNode.removeChild( el );
}
// release memory in IE
el = 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 = arr.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 &&
a.sourceIndex - b.sourceIndex;
// 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 :enabled/:disabled
* @param {Boolean} disabled true for :disabled; false for :enabled
*/
function createDisabledPseudo( disabled ) {
// Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
return function( elem ) {
// Only certain elements can match :enabled or :disabled
// https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
// https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
if ( "form" in elem ) {
// Check for inherited disabledness on relevant non-disabled elements:
// * listed form-associated elements in a disabled fieldset
// https://html.spec.whatwg.org/multipage/forms.html#category-listed
// https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
// * option elements in a disabled optgroup
// https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
// All such elements have a "form" property.
if ( elem.parentNode && elem.disabled === false ) {
// Option elements defer to a parent optgroup if present
if ( "label" in elem ) {
if ( "label" in elem.parentNode ) {
return elem.parentNode.disabled === disabled;
} else {
return elem.disabled === disabled;
}
}
// Support: IE 6 - 11
// Use the isDisabled shortcut property to check for disabled fieldset ancestors
return elem.isDisabled === disabled ||
// Where there is no isDisabled, check manually
/* jshint -W018 */
elem.isDisabled !== !disabled &&
disabledAncestor( elem ) === disabled;
}
return elem.disabled === disabled;
// Try to winnow out elements that can't be disabled before trusting the disabled property.
// Some victims get caught in our net (label, legend, menu, track), but it shouldn't
// even exist on them, let alone have a boolean value.
} else if ( "label" in elem ) {
return elem.disabled === disabled;
}
// Remaining elements are neither :enabled nor :disabled
return false;
};
}
/**
* 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, subWindow,
doc = node ? node.ownerDocument || node : preferredDoc;
// Return early if doc is invalid or already selected
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Update global variables
document = doc;
docElem = document.documentElement;
documentIsHTML = !isXML( document );
// Support: IE 9-11, Edge
// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
if ( preferredDoc !== document &&
(subWindow = document.defaultView) && subWindow.top !== subWindow ) {
// Support: IE 11, Edge
if ( subWindow.addEventListener ) {
subWindow.addEventListener( "unload", unloadHandler, false );
// Support: IE 9 - 10 only
} else if ( subWindow.attachEvent ) {
subWindow.attachEvent( "onunload", unloadHandler );
}
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties
// (excepting IE8 booleans)
support.attributes = assert(function( el ) {
el.className = "i";
return !el.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( el ) {
el.appendChild( document.createComment("") );
return !el.getElementsByTagName("*").length;
});
// Support: IE<9
support.getElementsByClassName = rnative.test( document.getElementsByClassName );
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programmatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( el ) {
docElem.appendChild( el ).id = expando;
return !document.getElementsByName || !document.getElementsByName( expando ).length;
});
// ID filter and find
if ( support.getById ) {
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var elem = context.getElementById( id );
return elem ? [ elem ] : [];
}
};
} else {
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;
};
};
// Support: IE 6 - 7 only
// getElementById is not reliable as a find shortcut
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var node, i, elems,
elem = context.getElementById( id );
if ( elem ) {
// Verify the id attribute
node = elem.getAttributeNode("id");
if ( node && node.value === id ) {
return [ elem ];
}
// Fall back on getElementsByName
elems = context.getElementsByName( id );
i = 0;
while ( (elem = elems[i++]) ) {
node = elem.getAttributeNode("id");
if ( node && node.value === id ) {
return [ elem ];
}
}
}
return [];
}
};
}
// 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 ( typeof context.getElementsByClassName !== "undefined" && 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 https://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( el ) {
// 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
// https://bugs.jquery.com/ticket/12359
docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" +
"<select id='" + expando + "-\r\\' 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
// https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( el.querySelectorAll("[msallowcapture^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !el.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
if ( !el.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 ( !el.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
// Support: Safari 8+, iOS 8+
// https://bugs.webkit.org/show_bug.cgi?id=136851
// In-page `selector#id sibling-combinator selector` fails
if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) {
rbuggyQSA.push(".#.+[+~]");
}
});
assert(function( el ) {
el.innerHTML = "<a href='' disabled='disabled'></a>" +
"<select disabled='disabled'><option/></select>";
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = document.createElement("input");
input.setAttribute( "type", "hidden" );
el.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( el.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 ( el.querySelectorAll(":enabled").length !== 2 ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Support: IE9-11+
// IE's :disabled selector does not pick up the children of disabled fieldsets
docElem.appendChild( el ).disabled = true;
if ( el.querySelectorAll(":disabled").length !== 2 ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
el.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( el ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( el, "*" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( el, "[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 self-exclusive
// 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 === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === document || 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 === document ? -1 :
b === document ? 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 document;
};
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 &&
!compilerCache[ expr + " " ] &&
( !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.escape = function( sel ) {
return (sel + "").replace( rcssescape, fcssescape );
};
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, uniqueCache, outerCache, node, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType,
diff = false;
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
// ...in a gzip-friendly way
node = parent;
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex && 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 ) {
uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
} else {
// Use previously-cached element index if available
if ( useCache ) {
// ...in a gzip-friendly way
node = elem;
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex;
}
// xml :nth-child(...)
// or :nth-last-child(...) or :nth(-last)?-of-type(...)
if ( diff === false ) {
// 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 ) {
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
uniqueCache[ 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": createDisabledPseudo( false ),
"disabled": createDisabledPseudo( 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,
skip = combinator.next,
key = skip || dir,
checkNonElements = base && key === "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 );
}
}
return false;
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, uniqueCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from combinator 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 ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});
if ( skip && skip === elem.nodeName.toLowerCase() ) {
elem = elem[ dir ] || elem;
} else if ( (oldCache = uniqueCache[ key ]) &&
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
uniqueCache[ key ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
return false;
};
}
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 || outermost;
}
// Add elements passing elementMatchers directly to results
// 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;
if ( !context && elem.ownerDocument !== document ) {
setDocument( elem );
xml = !documentIsHTML;
}
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context || document, 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 );
}
}
}
// `i` is now the count of elements visited above, and adding it to `matchedCount`
// makes the latter nonnegative.
matchedCount += i;
// Apply set filters to unmatched elements
// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
// no element matchers and no seed.
// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
// case, which will result in a "00" `matchedCount` that differs from `i` but is also
// numerically zero.
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 only one selector in the list and no seed
// (the latter of which guarantees us context)
if ( match.length === 1 ) {
// Reduce context if the leading compound selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
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,
!context || 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( el ) {
// Should return 1, but returns 4 (following)
return el.compareDocumentPosition( document.createElement("fieldset") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( el ) {
el.innerHTML = "<a href='#'></a>";
return el.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( el ) {
el.innerHTML = "<input/>";
el.firstChild.setAttribute( "value", "" );
return el.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( el ) {
return el.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;
// Deprecated
jQuery.expr[ ":" ] = jQuery.expr.pseudos;
jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
jQuery.escapeSelector = Sizzle.escape;
var dir = function( elem, dir, until ) {
var matched = [],
truncate = until !== undefined;
while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
};
var siblings = function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
};
var rneedsContext = jQuery.expr.match.needsContext;
function nodeName( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
};
var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i );
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 ) {
return !!qualifier.call( elem, i, elem ) !== not;
} );
}
// Single element
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
} );
}
// Arraylike of elements (jQuery, arguments, Array)
if ( typeof qualifier !== "string" ) {
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) > -1 ) !== not;
} );
}
// Simple selector that can be filtered directly, removing non-Elements
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
// Complex selector, compare the two sets, removing non-Elements
qualifier = jQuery.filter( qualifier, elements );
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1;
} );
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
if ( elems.length === 1 && elem.nodeType === 1 ) {
return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [];
}
return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
} ) );
};
jQuery.fn.extend( {
find: function( selector ) {
var i, ret,
len = this.length,
self = this;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter( function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
} ) );
}
ret = this.pushStack( [] );
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
return len > 1 ? jQuery.uniqueSort( ret ) : ret;
},
filter: function( selector ) {
return this.pushStack( winnow( this, selector || [], false ) );
},
not: function( selector ) {
return this.pushStack( winnow( this, selector || [], true ) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
}
} );
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
// Shortcut simple #id case for speed
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,
init = jQuery.fn.init = function( selector, context, root ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Method init() accepts an alternate rootjQuery
// so migrate can support jQuery.sub (gh-2101)
root = root || rootjQuery;
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector[ 0 ] === "<" &&
selector[ selector.length - 1 ] === ">" &&
selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && ( match[ 1 ] || !context ) ) {
// HANDLE: $(html) -> $(array)
if ( match[ 1 ] ) {
context = context instanceof jQuery ? context[ 0 ] : context;
// Option to run scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[ 1 ],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[ 2 ] );
if ( elem ) {
// Inject the element directly into the jQuery object
this[ 0 ] = elem;
this.length = 1;
}
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || root ).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[ 0 ] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return root.ready !== undefined ?
root.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
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.fn.extend( {
has: function( target ) {
var targets = jQuery( target, this ),
l = targets.length;
return this.filter( function() {
var i = 0;
for ( ; i < l; i++ ) {
if ( jQuery.contains( this, targets[ i ] ) ) {
return true;
}
}
} );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
targets = typeof selectors !== "string" && jQuery( selectors );
// Positional selectors never match, since there's no _selection_ context
if ( !rneedsContext.test( selectors ) ) {
for ( ; i < l; i++ ) {
for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && ( targets ?
targets.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.uniqueSort( matched ) : matched );
},
// Determine the position of an element within the set
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
}
// Index in selector
if ( typeof elem === "string" ) {
return indexOf.call( jQuery( elem ), this[ 0 ] );
}
// Locate the position of the desired element
return indexOf.call( this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem
);
},
add: function( selector, context ) {
return this.pushStack(
jQuery.uniqueSort(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
}
} );
function sibling( cur, dir ) {
while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {}
return cur;
}
jQuery.each( {
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return siblings( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return siblings( elem.firstChild );
},
contents: function( elem ) {
if ( nodeName( elem, "iframe" ) ) {
return elem.contentDocument;
}
// Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only
// Treat the template element as a regular one in browsers that
// don't support it.
if ( nodeName( elem, "template" ) ) {
elem = elem.content || elem;
}
return jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var matched = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
matched = jQuery.filter( selector, matched );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
jQuery.uniqueSort( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
} );
var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g );
// Convert String-formatted options into Object-formatted ones
function createOptions( options ) {
var object = {};
jQuery.each( options.match( rnothtmlwhite ) || [], 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" ?
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,
// Flag to prevent firing
locked,
// Actual callback list
list = [],
// Queue of execution data for repeatable lists
queue = [],
// Index of currently firing callback (modified by add/remove as needed)
firingIndex = -1,
// Fire callbacks
fire = function() {
// Enforce single-firing
locked = locked || options.once;
// Execute callbacks for all pending executions,
// respecting firingIndex overrides and runtime changes
fired = firing = true;
for ( ; queue.length; firingIndex = -1 ) {
memory = queue.shift();
while ( ++firingIndex < list.length ) {
// Run callback and check for early termination
if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
options.stopOnFalse ) {
// Jump to end and forget the data so .add doesn't re-fire
firingIndex = list.length;
memory = false;
}
}
}
// Forget the data if we're done with it
if ( !options.memory ) {
memory = false;
}
firing = false;
// Clean up if we're done firing for good
if ( locked ) {
// Keep an empty list if we have data for future add calls
if ( memory ) {
list = [];
// Otherwise, this object is spent
} else {
list = "";
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// If we have memory from a past run, we should fire after adding
if ( memory && !firing ) {
firingIndex = list.length - 1;
queue.push( memory );
}
( function add( args ) {
jQuery.each( args, function( _, arg ) {
if ( jQuery.isFunction( arg ) ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) {
// Inspect recursively
add( arg );
}
} );
} )( arguments );
if ( memory && !firing ) {
fire();
}
}
return this;
},
// Remove a callback from the list
remove: function() {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
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.length > 0;
},
// Remove all callbacks from the list
empty: function() {
if ( list ) {
list = [];
}
return this;
},
// Disable .fire and .add
// Abort any current/pending executions
// Clear all callbacks and values
disable: function() {
locked = queue = [];
list = memory = "";
return this;
},
disabled: function() {
return !list;
},
// Disable .fire
// Also disable .add unless we have memory (since it would have no effect)
// Abort any pending executions
lock: function() {
locked = queue = [];
if ( !memory && !firing ) {
list = memory = "";
}
return this;
},
locked: function() {
return !!locked;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( !locked ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
queue.push( args );
if ( !firing ) {
fire();
}
}
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;
};
function Identity( v ) {
return v;
}
function Thrower( ex ) {
throw ex;
}
function adoptValue( value, resolve, reject, noValue ) {
var method;
try {
// Check for promise aspect first to privilege synchronous behavior
if ( value && jQuery.isFunction( ( method = value.promise ) ) ) {
method.call( value ).done( resolve ).fail( reject );
// Other thenables
} else if ( value && jQuery.isFunction( ( method = value.then ) ) ) {
method.call( value, resolve, reject );
// Other non-thenables
} else {
// Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer:
// * false: [ value ].slice( 0 ) => resolve( value )
// * true: [ value ].slice( 1 ) => resolve()
resolve.apply( undefined, [ value ].slice( noValue ) );
}
// For Promises/A+, convert exceptions into rejections
// Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in
// Deferred#then to conditionally suppress rejection.
} catch ( value ) {
// Support: Android 4.0 only
// Strict mode functions invoked without .call/.apply get global-object context
reject.apply( undefined, [ value ] );
}
}
jQuery.extend( {
Deferred: function( func ) {
var tuples = [
// action, add listener, callbacks,
// ... .then handlers, argument index, [final state]
[ "notify", "progress", jQuery.Callbacks( "memory" ),
jQuery.Callbacks( "memory" ), 2 ],
[ "resolve", "done", jQuery.Callbacks( "once memory" ),
jQuery.Callbacks( "once memory" ), 0, "resolved" ],
[ "reject", "fail", jQuery.Callbacks( "once memory" ),
jQuery.Callbacks( "once memory" ), 1, "rejected" ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
"catch": function( fn ) {
return promise.then( null, fn );
},
// Keep pipe for back-compat
pipe: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred( function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
// Map tuples (progress, done, fail) to arguments (done, fail, progress)
var fn = jQuery.isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ];
// deferred.progress(function() { bind to newDefer or newDefer.notify })
// deferred.done(function() { bind to newDefer or newDefer.resolve })
// deferred.fail(function() { bind to newDefer or newDefer.reject })
deferred[ tuple[ 1 ] ]( function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.progress( newDefer.notify )
.done( newDefer.resolve )
.fail( newDefer.reject );
} else {
newDefer[ tuple[ 0 ] + "With" ](
this,
fn ? [ returned ] : arguments
);
}
} );
} );
fns = null;
} ).promise();
},
then: function( onFulfilled, onRejected, onProgress ) {
var maxDepth = 0;
function resolve( depth, deferred, handler, special ) {
return function() {
var that = this,
args = arguments,
mightThrow = function() {
var returned, then;
// Support: Promises/A+ section 2.3.3.3.3
// https://promisesaplus.com/#point-59
// Ignore double-resolution attempts
if ( depth < maxDepth ) {
return;
}
returned = handler.apply( that, args );
// Support: Promises/A+ section 2.3.1
// https://promisesaplus.com/#point-48
if ( returned === deferred.promise() ) {
throw new TypeError( "Thenable self-resolution" );
}
// Support: Promises/A+ sections 2.3.3.1, 3.5
// https://promisesaplus.com/#point-54
// https://promisesaplus.com/#point-75
// Retrieve `then` only once
then = returned &&
// Support: Promises/A+ section 2.3.4
// https://promisesaplus.com/#point-64
// Only check objects and functions for thenability
( typeof returned === "object" ||
typeof returned === "function" ) &&
returned.then;
// Handle a returned thenable
if ( jQuery.isFunction( then ) ) {
// Special processors (notify) just wait for resolution
if ( special ) {
then.call(
returned,
resolve( maxDepth, deferred, Identity, special ),
resolve( maxDepth, deferred, Thrower, special )
);
// Normal processors (resolve) also hook into progress
} else {
// ...and disregard older resolution values
maxDepth++;
then.call(
returned,
resolve( maxDepth, deferred, Identity, special ),
resolve( maxDepth, deferred, Thrower, special ),
resolve( maxDepth, deferred, Identity,
deferred.notifyWith )
);
}
// Handle all other returned values
} else {
// Only substitute handlers pass on context
// and multiple values (non-spec behavior)
if ( handler !== Identity ) {
that = undefined;
args = [ returned ];
}
// Process the value(s)
// Default process is resolve
( special || deferred.resolveWith )( that, args );
}
},
// Only normal processors (resolve) catch and reject exceptions
process = special ?
mightThrow :
function() {
try {
mightThrow();
} catch ( e ) {
if ( jQuery.Deferred.exceptionHook ) {
jQuery.Deferred.exceptionHook( e,
process.stackTrace );
}
// Support: Promises/A+ section 2.3.3.3.4.1
// https://promisesaplus.com/#point-61
// Ignore post-resolution exceptions
if ( depth + 1 >= maxDepth ) {
// Only substitute handlers pass on context
// and multiple values (non-spec behavior)
if ( handler !== Thrower ) {
that = undefined;
args = [ e ];
}
deferred.rejectWith( that, args );
}
}
};
// Support: Promises/A+ section 2.3.3.3.1
// https://promisesaplus.com/#point-57
// Re-resolve promises immediately to dodge false rejection from
// subsequent errors
if ( depth ) {
process();
} else {
// Call an optional hook to record the stack, in case of exception
// since it's otherwise lost when execution goes async
if ( jQuery.Deferred.getStackHook ) {
process.stackTrace = jQuery.Deferred.getStackHook();
}
window.setTimeout( process );
}
};
}
return jQuery.Deferred( function( newDefer ) {
// progress_handlers.add( ... )
tuples[ 0 ][ 3 ].add(
resolve(
0,
newDefer,
jQuery.isFunction( onProgress ) ?
onProgress :
Identity,
newDefer.notifyWith
)
);
// fulfilled_handlers.add( ... )
tuples[ 1 ][ 3 ].add(
resolve(
0,
newDefer,
jQuery.isFunction( onFulfilled ) ?
onFulfilled :
Identity
)
);
// rejected_handlers.add( ... )
tuples[ 2 ][ 3 ].add(
resolve(
0,
newDefer,
jQuery.isFunction( onRejected ) ?
onRejected :
Thrower
)
);
} ).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 = {};
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 5 ];
// promise.progress = list.add
// promise.done = list.add
// promise.fail = list.add
promise[ tuple[ 1 ] ] = list.add;
// Handle state
if ( stateString ) {
list.add(
function() {
// state = "resolved" (i.e., fulfilled)
// state = "rejected"
state = stateString;
},
// rejected_callbacks.disable
// fulfilled_callbacks.disable
tuples[ 3 - i ][ 2 ].disable,
// progress_callbacks.lock
tuples[ 0 ][ 2 ].lock
);
}
// progress_handlers.fire
// fulfilled_handlers.fire
// rejected_handlers.fire
list.add( tuple[ 3 ].fire );
// deferred.notify = function() { deferred.notifyWith(...) }
// deferred.resolve = function() { deferred.resolveWith(...) }
// deferred.reject = function() { deferred.rejectWith(...) }
deferred[ tuple[ 0 ] ] = function() {
deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments );
return this;
};
// deferred.notifyWith = list.fireWith
// deferred.resolveWith = list.fireWith
// deferred.rejectWith = list.fireWith
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( singleValue ) {
var
// count of uncompleted subordinates
remaining = arguments.length,
// count of unprocessed arguments
i = remaining,
// subordinate fulfillment data
resolveContexts = Array( i ),
resolveValues = slice.call( arguments ),
// the master Deferred
master = jQuery.Deferred(),
// subordinate callback factory
updateFunc = function( i ) {
return function( value ) {
resolveContexts[ i ] = this;
resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( !( --remaining ) ) {
master.resolveWith( resolveContexts, resolveValues );
}
};
};
// Single- and empty arguments are adopted like Promise.resolve
if ( remaining <= 1 ) {
adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject,
!remaining );
// Use .then() to unwrap secondary thenables (cf. gh-3000)
if ( master.state() === "pending" ||
jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) {
return master.then();
}
}
// Multiple arguments are aggregated like Promise.all array elements
while ( i-- ) {
adoptValue( resolveValues[ i ], updateFunc( i ), master.reject );
}
return master.promise();
}
} );
// These usually indicate a programmer mistake during development,
// warn about them ASAP rather than swallowing them by default.
var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;
jQuery.Deferred.exceptionHook = function( error, stack ) {
// Support: IE 8 - 9 only
// Console exists when dev tools are open, which can happen at any time
if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) {
window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack );
}
};
jQuery.readyException = function( error ) {
window.setTimeout( function() {
throw error;
} );
};
// The deferred used on DOM ready
var readyList = jQuery.Deferred();
jQuery.fn.ready = function( fn ) {
readyList
.then( fn )
// Wrap jQuery.readyException in a function so that the lookup
// happens at the time of error handling instead of callback
// registration.
.catch( function( error ) {
jQuery.readyException( error );
} );
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,
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
}
} );
jQuery.ready.then = readyList.then;
// The ready event handler and self cleanup method
function completed() {
document.removeEventListener( "DOMContentLoaded", completed );
window.removeEventListener( "load", completed );
jQuery.ready();
}
// Catch cases where $(document).ready() is called
// after the browser event has already occurred.
// Support: IE <=9 - 10 only
// Older IE sometimes signals "interactive" too soon
if ( document.readyState === "complete" ||
( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
window.setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed );
}
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
len = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
access( elems, fn, i, key[ i ], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < len; i++ ) {
fn(
elems[ i ], key, raw ?
value :
value.call( elems[ i ], i, fn( elems[ i ], key ) )
);
}
}
}
if ( chainable ) {
return elems;
}
// Gets
if ( bulk ) {
return fn.call( elems );
}
return len ? fn( elems[ 0 ], key ) : emptyGet;
};
var acceptData = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};
function Data() {
this.expando = jQuery.expando + Data.uid++;
}
Data.uid = 1;
Data.prototype = {
cache: function( owner ) {
// Check if the owner object already has a cache
var value = owner[ this.expando ];
// If not, create one
if ( !value ) {
value = {};
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return an empty object.
if ( acceptData( owner ) ) {
// If it is a node unlikely to be stringify-ed or looped over
// use plain assignment
if ( owner.nodeType ) {
owner[ this.expando ] = value;
// Otherwise secure it in a non-enumerable property
// configurable must be true to allow the property to be
// deleted when data is removed
} else {
Object.defineProperty( owner, this.expando, {
value: value,
configurable: true
} );
}
}
}
return value;
},
set: function( owner, data, value ) {
var prop,
cache = this.cache( owner );
// Handle: [ owner, key, value ] args
// Always use camelCase key (gh-2257)
if ( typeof data === "string" ) {
cache[ jQuery.camelCase( data ) ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Copy the properties one-by-one to the cache object
for ( prop in data ) {
cache[ jQuery.camelCase( prop ) ] = data[ prop ];
}
}
return cache;
},
get: function( owner, key ) {
return key === undefined ?
this.cache( owner ) :
// Always use camelCase key (gh-2257)
owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ];
},
access: function( owner, key, value ) {
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if ( key === undefined ||
( ( key && typeof key === "string" ) && value === undefined ) ) {
return this.get( owner, key );
}
// When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set( owner, key, value );
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function( owner, key ) {
var i,
cache = owner[ this.expando ];
if ( cache === undefined ) {
return;
}
if ( key !== undefined ) {
// Support array or space separated string of keys
if ( Array.isArray( key ) ) {
// If key is an array of keys...
// We always set camelCase keys, so remove that.
key = key.map( jQuery.camelCase );
} else {
key = jQuery.camelCase( key );
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
key = key in cache ?
[ key ] :
( key.match( rnothtmlwhite ) || [] );
}
i = key.length;
while ( i-- ) {
delete cache[ key[ i ] ];
}
}
// Remove the expando if there's no more data
if ( key === undefined || jQuery.isEmptyObject( cache ) ) {
// Support: Chrome <=35 - 45
// Webkit & Blink performance suffers when deleting properties
// from DOM nodes, so set to undefined instead
// https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
if ( owner.nodeType ) {
owner[ this.expando ] = undefined;
} else {
delete owner[ this.expando ];
}
}
},
hasData: function( owner ) {
var cache = owner[ this.expando ];
return cache !== undefined && !jQuery.isEmptyObject( cache );
}
};
var dataPriv = new Data();
var dataUser = new Data();
// Implementation Summary
//
// 1. Enforce API surface and semantic compatibility with 1.9.x branch
// 2. Improve the module's maintainability by reducing the storage
// paths to a single mechanism.
// 3. Use the same single mechanism to support "private" and "user" data.
// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
// 5. Avoid exposing implementation details on user objects (eg. expando properties)
// 6. Provide a clear path for implementation upgrade to WeakMap in 2014
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /[A-Z]/g;
function getData( data ) {
if ( data === "true" ) {
return true;
}
if ( data === "false" ) {
return false;
}
if ( data === "null" ) {
return null;
}
// Only convert to a number if it doesn't change the string
if ( data === +data + "" ) {
return +data;
}
if ( rbrace.test( data ) ) {
return JSON.parse( data );
}
return data;
}
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = getData( data );
} catch ( e ) {}
// Make sure we set the data so it isn't changed later
dataUser.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend( {
hasData: function( elem ) {
return dataUser.hasData( elem ) || dataPriv.hasData( elem );
},
data: function( elem, name, data ) {
return dataUser.access( elem, name, data );
},
removeData: function( elem, name ) {
dataUser.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to dataPriv methods, these can be deprecated.
_data: function( elem, name, data ) {
return dataPriv.access( elem, name, data );
},
_removeData: function( elem, name ) {
dataPriv.remove( elem, name );
}
} );
jQuery.fn.extend( {
data: function( key, value ) {
var i, name, data,
elem = this[ 0 ],
attrs = elem && elem.attributes;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = dataUser.get( elem );
if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE 11 only
// 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 ] );
}
}
}
dataPriv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each( function() {
dataUser.set( this, key );
} );
}
return access( this, function( value ) {
var data;
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if ( elem && value === undefined ) {
// Attempt to get data from the cache
// The key will always be camelCased in Data
data = dataUser.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, key );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each( function() {
// We always store the camelCased key
dataUser.set( this, key, value );
} );
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each( function() {
dataUser.remove( this, key );
} );
}
} );
jQuery.extend( {
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = dataPriv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || Array.isArray( data ) ) {
queue = dataPriv.access( elem, type, jQuery.makeArray( data ) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// Clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// Not public - generate a queueHooks object, or return the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return dataPriv.get( elem, key ) || dataPriv.access( elem, key, {
empty: jQuery.Callbacks( "once memory" ).add( function() {
dataPriv.remove( elem, [ type + "queue", key ] );
} )
} );
}
} );
jQuery.fn.extend( {
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[ 0 ], type );
}
return data === undefined ?
this :
this.each( function() {
var queue = jQuery.queue( this, type, data );
// Ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
} );
},
dequeue: function( type ) {
return this.each( function() {
jQuery.dequeue( this, type );
} );
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = dataPriv.get( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
} );
var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;
var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHiddenWithinTree = function( elem, el ) {
// isHiddenWithinTree might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
// Inline style trumps all
return elem.style.display === "none" ||
elem.style.display === "" &&
// Otherwise, check computed style
// Support: Firefox <=43 - 45
// Disconnected elements can have computed display: none, so first confirm that elem is
// in the document.
jQuery.contains( elem.ownerDocument, elem ) &&
jQuery.css( elem, "display" ) === "none";
};
var 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;
};
function adjustCSS( elem, prop, valueParts, tween ) {
var adjusted,
scale = 1,
maxIterations = 20,
currentValue = tween ?
function() {
return tween.cur();
} :
function() {
return jQuery.css( elem, prop, "" );
},
initial = currentValue(),
unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&
rcssNum.exec( jQuery.css( elem, prop ) );
if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || initialInUnit[ 3 ];
// Make sure we update the tween properties later on
valueParts = valueParts || [];
// Iteratively approximate from a nonzero starting point
initialInUnit = +initial || 1;
do {
// If previous iteration zeroed out, double until we get *something*.
// Use string for doubling so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
initialInUnit = initialInUnit / scale;
jQuery.style( elem, prop, initialInUnit + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// Break the loop if scale is unchanged or perfect, or if we've just had enough.
} while (
scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations
);
}
if ( valueParts ) {
initialInUnit = +initialInUnit || +initial || 0;
// Apply relative offset (+=/-=) if specified
adjusted = valueParts[ 1 ] ?
initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
+valueParts[ 2 ];
if ( tween ) {
tween.unit = unit;
tween.start = initialInUnit;
tween.end = adjusted;
}
}
return adjusted;
}
var defaultDisplayMap = {};
function getDefaultDisplay( elem ) {
var temp,
doc = elem.ownerDocument,
nodeName = elem.nodeName,
display = defaultDisplayMap[ nodeName ];
if ( display ) {
return display;
}
temp = doc.body.appendChild( doc.createElement( nodeName ) );
display = jQuery.css( temp, "display" );
temp.parentNode.removeChild( temp );
if ( display === "none" ) {
display = "block";
}
defaultDisplayMap[ nodeName ] = display;
return display;
}
function showHide( elements, show ) {
var display, elem,
values = [],
index = 0,
length = elements.length;
// Determine new display value for elements that need to change
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
display = elem.style.display;
if ( show ) {
// Since we force visibility upon cascade-hidden elements, an immediate (and slow)
// check is required in this first loop unless we have a nonempty display value (either
// inline or about-to-be-restored)
if ( display === "none" ) {
values[ index ] = dataPriv.get( elem, "display" ) || null;
if ( !values[ index ] ) {
elem.style.display = "";
}
}
if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) {
values[ index ] = getDefaultDisplay( elem );
}
} else {
if ( display !== "none" ) {
values[ index ] = "none";
// Remember what we're overwriting
dataPriv.set( elem, "display", display );
}
}
}
// Set the display of the elements in a second loop to avoid constant reflow
for ( index = 0; index < length; index++ ) {
if ( values[ index ] != null ) {
elements[ index ].style.display = values[ index ];
}
}
return elements;
}
jQuery.fn.extend( {
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 ( isHiddenWithinTree( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
} );
}
} );
var rcheckableType = ( /^(?:checkbox|radio)$/i );
var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i );
var rscriptType = ( /^$|\/(?:java|ecma)script/i );
// We have to close these tags to support XHTML (#13200)
var wrapMap = {
// Support: IE <=9 only
option: [ 1, "<select multiple='multiple'>", "</select>" ],
// XHTML parsers do not magically insert elements in the
// same way that tag soup parsers do. So we cannot shorten
// this by omitting <tbody> or other required elements.
thead: [ 1, "<table>", "</table>" ],
col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
_default: [ 0, "", "" ]
};
// Support: IE <=9 only
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function getAll( context, tag ) {
// Support: IE <=9 - 11 only
// Use typeof to avoid zero-argument method invocation on host objects (#15151)
var ret;
if ( typeof context.getElementsByTagName !== "undefined" ) {
ret = context.getElementsByTagName( tag || "*" );
} else if ( typeof context.querySelectorAll !== "undefined" ) {
ret = context.querySelectorAll( tag || "*" );
} else {
ret = [];
}
if ( tag === undefined || tag && nodeName( context, tag ) ) {
return jQuery.merge( [ context ], ret );
}
return ret;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
dataPriv.set(
elems[ i ],
"globalEval",
!refElements || dataPriv.get( refElements[ i ], "globalEval" )
);
}
}
var rhtml = /<|&#?\w+;/;
function buildFragment( elems, context, scripts, selection, ignored ) {
var elem, tmp, tag, wrap, contains, j,
fragment = context.createDocumentFragment(),
nodes = [],
i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || fragment.appendChild( context.createElement( "div" ) );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ];
// Descend through wrappers to the right content
j = wrap[ 0 ];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Ensure the created nodes are orphaned (#12392)
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while ( ( elem = nodes[ i++ ] ) ) {
// Skip elements already in the context collection (trac-4087)
if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
if ( ignored ) {
ignored.push( elem );
}
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( fragment.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( ( elem = tmp[ j++ ] ) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
return fragment;
}
( function() {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild( document.createElement( "div" ) ),
input = document.createElement( "input" );
// Support: Android 4.0 - 4.3 only
// Check state lost if the name is set (#11217)
// Support: Windows Web Apps (WWA)
// `name` and `type` must use .setAttribute for WWA (#14901)
input.setAttribute( "type", "radio" );
input.setAttribute( "checked", "checked" );
input.setAttribute( "name", "t" );
div.appendChild( input );
// Support: Android <=4.1 only
// Older WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE <=11 only
// Make sure textarea (and checkbox) defaultValue is properly cloned
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
} )();
var documentElement = document.documentElement;
var
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
// Support: IE <=9 only
// See #13393 for more info
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
function on( elem, types, selector, data, fn, one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
on( elem, type, selector, data, types[ type ], one );
}
return elem;
}
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 elem;
}
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 elem.each( function() {
jQuery.event.add( this, types, fn, data, selector );
} );
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = dataPriv.get( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Ensure that invalid selectors throw exceptions at attach time
// Evaluate against documentElement in case elem is a non-element node (e.g., document)
if ( selector ) {
jQuery.find.matchesSelector( documentElement, 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 !== "undefined" && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[ t ] ) || [];
type = origType = tmp[ 1 ];
namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend( {
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join( "." )
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !( handlers = events[ type ] ) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if ( !special.setup ||
special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = dataPriv.hasData( elem ) && dataPriv.get( elem );
if ( !elemData || !( events = elemData.events ) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
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 data and the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
dataPriv.remove( elem, "handle events" );
}
},
dispatch: function( nativeEvent ) {
// Make a writable jQuery.Event from the native event object
var event = jQuery.event.fix( nativeEvent );
var i, j, ret, matched, handleObj, handlerQueue,
args = new Array( arguments.length ),
handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[ 0 ] = event;
for ( i = 1; i < arguments.length; i++ ) {
args[ i ] = arguments[ i ];
}
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.rnamespace || event.rnamespace.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
handleObj.handler ).apply( matched.elem, args );
if ( ret !== undefined ) {
if ( ( event.result = ret ) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, handleObj, sel, matchedHandlers, matchedSelectors,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
if ( delegateCount &&
// Support: IE <=9
// Black-hole SVG <use> instance trees (trac-13180)
cur.nodeType &&
// Support: Firefox <=42
// Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861)
// https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click
// Support: IE 11 only
// ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343)
!( event.type === "click" && event.button >= 1 ) ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) {
matchedHandlers = [];
matchedSelectors = {};
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matchedSelectors[ sel ] === undefined ) {
matchedSelectors[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) > -1 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matchedSelectors[ sel ] ) {
matchedHandlers.push( handleObj );
}
}
if ( matchedHandlers.length ) {
handlerQueue.push( { elem: cur, handlers: matchedHandlers } );
}
}
}
}
// Add the remaining (directly-bound) handlers
cur = this;
if ( delegateCount < handlers.length ) {
handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } );
}
return handlerQueue;
},
addProp: function( name, hook ) {
Object.defineProperty( jQuery.Event.prototype, name, {
enumerable: true,
configurable: true,
get: jQuery.isFunction( hook ) ?
function() {
if ( this.originalEvent ) {
return hook( this.originalEvent );
}
} :
function() {
if ( this.originalEvent ) {
return this.originalEvent[ name ];
}
},
set: function( value ) {
Object.defineProperty( this, name, {
enumerable: true,
configurable: true,
writable: true,
value: value
} );
}
} );
},
fix: function( originalEvent ) {
return originalEvent[ jQuery.expando ] ?
originalEvent :
new jQuery.Event( originalEvent );
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( this.type === "checkbox" && this.click && nodeName( this, "input" ) ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return 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;
}
}
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
// This "if" is needed for plain objects
if ( elem.removeEventListener ) {
elem.removeEventListener( type, 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: Android <=2.3 only
src.returnValue === false ?
returnTrue :
returnFalse;
// Create target properties
// Support: Safari <=6 - 7 only
// Target should not be a text node (#504, #13143)
this.target = ( src.target && src.target.nodeType === 3 ) ?
src.target.parentNode :
src.target;
this.currentTarget = src.currentTarget;
this.relatedTarget = src.relatedTarget;
// 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
// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
constructor: jQuery.Event,
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
isSimulated: false,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && !this.isSimulated ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && !this.isSimulated ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && !this.isSimulated ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Includes all common event props including KeyEvent and MouseEvent specific props
jQuery.each( {
altKey: true,
bubbles: true,
cancelable: true,
changedTouches: true,
ctrlKey: true,
detail: true,
eventPhase: true,
metaKey: true,
pageX: true,
pageY: true,
shiftKey: true,
view: true,
"char": true,
charCode: true,
key: true,
keyCode: true,
button: true,
buttons: true,
clientX: true,
clientY: true,
offsetX: true,
offsetY: true,
pointerId: true,
pointerType: true,
screenX: true,
screenY: true,
targetTouches: true,
toElement: true,
touches: true,
which: function( event ) {
var button = event.button;
// Add which for key events
if ( event.which == null && rkeyEvent.test( event.type ) ) {
return event.charCode != null ? event.charCode : event.keyCode;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) {
if ( button & 1 ) {
return 1;
}
if ( button & 2 ) {
return 3;
}
if ( button & 4 ) {
return 2;
}
return 0;
}
return event.which;
}
}, jQuery.event.addProp );
// Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
// https://bugs.chromium.org/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
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 mouseenter/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;
}
};
} );
jQuery.fn.extend( {
on: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn );
},
one: function( types, selector, data, fn ) {
return on( this, 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 );
} );
}
} );
var
/* eslint-disable max-len */
// See https://github.com/eslint/eslint/issues/3229
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,
/* eslint-enable */
// Support: IE <=10 - 11, Edge 12 - 13
// In IE/Edge using regex groups here causes severe slowdowns.
// See https://connect.microsoft.com/IE/feedback/details/1736512/
rnoInnerhtml = /<script|<style|<link/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;
// Prefer a tbody over its parent table for containing new rows
function manipulationTarget( elem, content ) {
if ( nodeName( elem, "table" ) &&
nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {
return jQuery( ">tbody", elem )[ 0 ] || elem;
}
return elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[ 1 ];
} else {
elem.removeAttribute( "type" );
}
return elem;
}
function cloneCopyEvent( src, dest ) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if ( dest.nodeType !== 1 ) {
return;
}
// 1. Copy private data: events, handlers, etc.
if ( dataPriv.hasData( src ) ) {
pdataOld = dataPriv.access( src );
pdataCur = dataPriv.set( dest, pdataOld );
events = pdataOld.events;
if ( events ) {
delete pdataCur.handle;
pdataCur.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
}
// 2. Copy user data
if ( dataUser.hasData( src ) ) {
udataOld = dataUser.access( src );
udataCur = jQuery.extend( {}, udataOld );
dataUser.set( dest, udataCur );
}
}
// Fix IE bugs, see support tests
function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
function domManip( collection, args, callback, ignored ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = collection.length,
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 collection.each( function( index ) {
var self = collection.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
domManip( self, args, callback, ignored );
} );
}
if ( l ) {
fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
// Require either new content or an interest in ignored elements to invoke the callback
if ( first || ignored ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item
// instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( collection[ 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 || "" ) &&
!dataPriv.access( node, "globalEval" ) &&
jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
DOMEval( node.textContent.replace( rcleanScript, "" ), doc );
}
}
}
}
}
}
return collection;
}
function remove( elem, selector, keepData ) {
var node,
nodes = selector ? jQuery.filter( selector, elem ) : elem,
i = 0;
for ( ; ( node = nodes[ i ] ) != null; i++ ) {
if ( !keepData && node.nodeType === 1 ) {
jQuery.cleanData( getAll( node ) );
}
if ( node.parentNode ) {
if ( keepData && jQuery.contains( node.ownerDocument, node ) ) {
setGlobalEval( getAll( node, "script" ) );
}
node.parentNode.removeChild( node );
}
}
return elem;
}
jQuery.extend( {
htmlPrefilter: function( html ) {
return html.replace( rxhtmlTag, "<$1></$2>" );
},
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Fix IE cloning issues
if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
!jQuery.isXMLDoc( elem ) ) {
// We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
fixInput( srcElements[ i ], destElements[ i ] );
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
cloneCopyEvent( srcElements[ i ], destElements[ i ] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
// Return the cloned set
return clone;
},
cleanData: function( elems ) {
var data, elem, type,
special = jQuery.event.special,
i = 0;
for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) {
if ( acceptData( elem ) ) {
if ( ( data = elem[ dataPriv.expando ] ) ) {
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 );
}
}
}
// Support: Chrome <=35 - 45+
// Assign undefined instead of using delete, see Data#remove
elem[ dataPriv.expando ] = undefined;
}
if ( elem[ dataUser.expando ] ) {
// Support: Chrome <=35 - 45+
// Assign undefined instead of using delete, see Data#remove
elem[ dataUser.expando ] = undefined;
}
}
}
}
} );
jQuery.fn.extend( {
detach: function( selector ) {
return remove( this, selector, true );
},
remove: function( selector ) {
return remove( this, selector );
},
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().each( function() {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.textContent = value;
}
} );
}, null, value, arguments.length );
},
append: function() {
return domManip( this, arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
} );
},
prepend: function() {
return domManip( this, 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 domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
} );
},
after: function() {
return domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
} );
},
empty: function() {
var elem,
i = 0;
for ( ; ( elem = this[ i ] ) != null; i++ ) {
if ( elem.nodeType === 1 ) {
// Prevent memory leaks
jQuery.cleanData( getAll( elem, false ) );
// Remove any remaining nodes
elem.textContent = "";
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
} );
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = jQuery.htmlPrefilter( value );
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch ( e ) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var ignored = [];
// Make the changes, replacing each non-ignored context element with the new content
return domManip( this, arguments, function( elem ) {
var parent = this.parentNode;
if ( jQuery.inArray( this, ignored ) < 0 ) {
jQuery.cleanData( getAll( this ) );
if ( parent ) {
parent.replaceChild( elem, this );
}
}
// Force callback invocation
}, ignored );
}
} );
jQuery.each( {
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: Android <=4.0 only, PhantomJS 1 only
// .get() because push.apply(_, arraylike) throws on ancient WebKit
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
} );
var rmargin = ( /^margin/ );
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles = function( elem ) {
// Support: IE <=11 only, Firefox <=30 (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
var view = elem.ownerDocument.defaultView;
if ( !view || !view.opener ) {
view = window;
}
return view.getComputedStyle( elem );
};
( function() {
// Executing both pixelPosition & boxSizingReliable tests require only one layout
// so they're executed at the same time to save the second computation.
function computeStyleTests() {
// This is a singleton, we need to execute it only once
if ( !div ) {
return;
}
div.style.cssText =
"box-sizing:border-box;" +
"position:relative;display:block;" +
"margin:auto;border:1px;padding:1px;" +
"top:1%;width:50%";
div.innerHTML = "";
documentElement.appendChild( container );
var divStyle = window.getComputedStyle( div );
pixelPositionVal = divStyle.top !== "1%";
// Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
reliableMarginLeftVal = divStyle.marginLeft === "2px";
boxSizingReliableVal = divStyle.width === "4px";
// Support: Android 4.0 - 4.3 only
// Some styles come back with percentage values, even though they shouldn't
div.style.marginRight = "50%";
pixelMarginRightVal = divStyle.marginRight === "4px";
documentElement.removeChild( container );
// Nullify the div so it wouldn't be stored in the memory and
// it will also be a sign that checks already performed
div = null;
}
var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal,
container = document.createElement( "div" ),
div = document.createElement( "div" );
// Finish early in limited (non-browser) environments
if ( !div.style ) {
return;
}
// Support: IE <=9 - 11 only
// Style of cloned element affects source element cloned (#8908)
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" +
"padding:0;margin-top:1px;position:absolute";
container.appendChild( div );
jQuery.extend( support, {
pixelPosition: function() {
computeStyleTests();
return pixelPositionVal;
},
boxSizingReliable: function() {
computeStyleTests();
return boxSizingReliableVal;
},
pixelMarginRight: function() {
computeStyleTests();
return pixelMarginRightVal;
},
reliableMarginLeft: function() {
computeStyleTests();
return reliableMarginLeftVal;
}
} );
} )();
function curCSS( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
// Support: Firefox 51+
// Retrieving style before computed somehow
// fixes an issue with getting wrong values
// on detached elements
style = elem.style;
computed = computed || getStyles( elem );
// getPropertyValue is needed for:
// .css('filter') (IE 9 only, #12537)
// .css('--customProperty) (#3144)
if ( computed ) {
ret = computed.getPropertyValue( name ) || computed[ name ];
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Android Browser returns percentage for some values,
// but width seems to be reliably pixels.
// This is against the CSSOM draft spec:
// https://drafts.csswg.org/cssom/#resolved-values
if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret !== undefined ?
// Support: IE <=9 - 11 only
// IE returns zIndex value as an integer.
ret + "" :
ret;
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
if ( conditionFn() ) {
// Hook not needed (or it's not possible to use it due
// to missing dependency), remove it.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return ( this.get = hookFn ).apply( this, arguments );
}
};
}
var
// Swappable if display is none or starts with table
// except "table", "table-cell", or "table-caption"
// See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rcustomProp = /^--/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "Moz", "ms" ],
emptyStyle = document.createElement( "div" ).style;
// Return a css property mapped to a potentially vendor prefixed property
function vendorPropName( name ) {
// Shortcut for names that are not vendor prefixed
if ( name in emptyStyle ) {
return name;
}
// Check for vendor prefixed names
var capName = name[ 0 ].toUpperCase() + name.slice( 1 ),
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in emptyStyle ) {
return name;
}
}
}
// Return a property mapped along what jQuery.cssProps suggests or to
// a vendor prefixed property.
function finalPropName( name ) {
var ret = jQuery.cssProps[ name ];
if ( !ret ) {
ret = jQuery.cssProps[ name ] = vendorPropName( name ) || name;
}
return ret;
}
function setPositiveNumber( elem, value, subtract ) {
// Any relative (+/-) values have already been
// normalized at this point
var matches = rcssNum.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i,
val = 0;
// If we already have the right measurement, avoid augmentation
if ( extra === ( isBorderBox ? "border" : "content" ) ) {
i = 4;
// Otherwise initialize for horizontal or vertical properties
} else {
i = name === "width" ? 1 : 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 computed style
var valueIsBorderBox,
styles = getStyles( elem ),
val = curCSS( elem, name, styles ),
isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test( val ) ) {
return val;
}
// Check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox &&
( support.boxSizingReliable() || val === elem.style[ name ] );
// Fall back to offsetWidth/Height when value is "auto"
// This happens for inline elements with no explicit setting (gh-3571)
if ( val === "auto" ) {
val = elem[ "offset" + name[ 0 ].toUpperCase() + name.slice( 1 ) ];
}
// 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: {
"animationIterationCount": true,
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
"float": "cssFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
isCustomProp = rcustomProp.test( name ),
style = elem.style;
// Make sure that we're working with the right name. We don't
// want to query the value if it is a CSS custom property
// since they are user-defined.
if ( !isCustomProp ) {
name = finalPropName( origName );
}
// Gets hook for the prefixed version, then unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// Convert "+=" or "-=" to relative numbers (#7345)
if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
value = adjustCSS( elem, name, ret );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set (#7116)
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add the unit (except for certain CSS properties)
if ( type === "number" ) {
value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
}
// background-* props affect original clone's values
if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !( "set" in hooks ) ||
( value = hooks.set( elem, value, extra ) ) !== undefined ) {
if ( isCustomProp ) {
style.setProperty( name, value );
} else {
style[ name ] = value;
}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks &&
( ret = hooks.get( elem, false, extra ) ) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var val, num, hooks,
origName = jQuery.camelCase( name ),
isCustomProp = rcustomProp.test( name );
// Make sure that we're working with the right name. We don't
// want to modify the value if it is a CSS custom property
// since they are user-defined.
if ( !isCustomProp ) {
name = finalPropName( origName );
}
// Try prefixed name followed by the unprefixed name
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
// Convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Make numeric if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || isFinite( num ) ? num || 0 : val;
}
return val;
}
} );
jQuery.each( [ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// Certain elements can have dimension info if we invisibly show them
// but it must have a current display style that would benefit
return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&
// Support: Safari 8+
// Table columns in Safari have non-zero offsetWidth & zero
// getBoundingClientRect().width unless display is changed.
// Support: IE <=11 only
// Running getBoundingClientRect on a disconnected node
// in IE throws an error.
( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ?
swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
} ) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var matches,
styles = extra && getStyles( elem ),
subtract = extra && augmentWidthOrHeight(
elem,
name,
extra,
jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
);
// Convert to pixels if value adjustment is needed
if ( subtract && ( matches = rcssNum.exec( value ) ) &&
( matches[ 3 ] || "px" ) !== "px" ) {
elem.style[ name ] = value;
value = jQuery.css( elem, name );
}
return setPositiveNumber( elem, value, subtract );
}
};
} );
jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
function( elem, computed ) {
if ( computed ) {
return ( parseFloat( curCSS( elem, "marginLeft" ) ) ||
elem.getBoundingClientRect().left -
swap( elem, { marginLeft: 0 }, function() {
return elem.getBoundingClientRect().left;
} )
) + "px";
}
}
);
// 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 ( Array.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 );
}
} );
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 || jQuery.easing._default;
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;
// Use a property on the element directly when it is not a DOM element,
// or when there is no matching style property that exists.
if ( tween.elem.nodeType !== 1 ||
tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) {
return tween.elem[ tween.prop ];
}
// Passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails.
// Simple values such as "10px" are parsed to Float;
// complex values such as "rotate(1rad)" are returned as-is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// Use step hook for back compat.
// Use cssHook if its there.
// Use .style if available and use plain properties where available.
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.nodeType === 1 &&
( 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 only
// 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;
},
_default: "swing"
};
jQuery.fx = Tween.prototype.init;
// Back compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, inProgress,
rfxtypes = /^(?:toggle|show|hide)$/,
rrun = /queueHooks$/;
function schedule() {
if ( inProgress ) {
if ( document.hidden === false && window.requestAnimationFrame ) {
window.requestAnimationFrame( schedule );
} else {
window.setTimeout( schedule, jQuery.fx.interval );
}
jQuery.fx.tick();
}
}
// Animations created synchronously will run synchronously
function createFxNow() {
window.setTimeout( function() {
fxNow = undefined;
} );
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
i = 0,
attrs = { height: type };
// If we include width, step value is 1 to do all cssExpand values,
// otherwise step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween( value, prop, animation ) {
var tween,
collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.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 ) {
var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display,
isBox = "width" in props || "height" in props,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHiddenWithinTree( elem ),
dataShow = dataPriv.get( elem, "fxshow" );
// Queue-skipping animations hijack the fx hooks
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always( function() {
// Ensure the complete handler is called before this completes
anim.always( function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
} );
} );
}
// Detect show/hide animations
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.test( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// Pretend to be hidden if this is a "show" and
// there is still data from a stopped show/hide
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
// Ignore all other no-op show/hide data
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
}
}
// Bail out if this is a no-op like .hide().hide()
propTween = !jQuery.isEmptyObject( props );
if ( !propTween && jQuery.isEmptyObject( orig ) ) {
return;
}
// Restrict "overflow" and "display" styles during box animations
if ( isBox && elem.nodeType === 1 ) {
// Support: IE <=9 - 11, Edge 12 - 13
// Record all 3 overflow attributes because IE does not infer the shorthand
// from identically-valued overflowX and overflowY
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Identify a display type, preferring old show/hide data over the CSS cascade
restoreDisplay = dataShow && dataShow.display;
if ( restoreDisplay == null ) {
restoreDisplay = dataPriv.get( elem, "display" );
}
display = jQuery.css( elem, "display" );
if ( display === "none" ) {
if ( restoreDisplay ) {
display = restoreDisplay;
} else {
// Get nonempty value(s) by temporarily forcing visibility
showHide( [ elem ], true );
restoreDisplay = elem.style.display || restoreDisplay;
display = jQuery.css( elem, "display" );
showHide( [ elem ] );
}
}
// Animate inline elements as inline-block
if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) {
if ( jQuery.css( elem, "float" ) === "none" ) {
// Restore the original display value at the end of pure show/hide animations
if ( !propTween ) {
anim.done( function() {
style.display = restoreDisplay;
} );
if ( restoreDisplay == null ) {
display = style.display;
restoreDisplay = display === "none" ? "" : display;
}
}
style.display = "inline-block";
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
anim.always( function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
} );
}
// Implement show/hide animations
propTween = false;
for ( prop in orig ) {
// General show/hide setup for this element animation
if ( !propTween ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } );
}
// Store hidden/visible for toggle so `.stop().toggle()` "reverses"
if ( toggle ) {
dataShow.hidden = !hidden;
}
// Show elements before animating them
if ( hidden ) {
showHide( [ elem ], true );
}
/* eslint-disable no-loop-func */
anim.done( function() {
/* eslint-enable no-loop-func */
// The final step of a "hide" animation is actually hiding the element
if ( !hidden ) {
showHide( [ elem ] );
}
dataPriv.remove( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
} );
}
// Per-property setup
propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = propTween.start;
if ( hidden ) {
propTween.end = propTween.start;
propTween.start = 0;
}
}
}
}
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 ( Array.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// Not quite $.extend, this won't overwrite existing keys.
// Reusing 'index' because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = Animation.prefilters.length,
deferred = jQuery.Deferred().always( function() {
// Don't match elem in the :animated selector
delete tick.elem;
} ),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// Support: Android 2.3 only
// 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 there's more to do, yield
if ( percent < 1 && length ) {
return remaining;
}
// If this was an empty animation, synthesize a final progress notification
if ( !length ) {
deferred.notifyWith( elem, [ animation, 1, 0 ] );
}
// Resolve the animation and report its conclusion
deferred.resolveWith( elem, [ animation ] );
return false;
},
animation = deferred.promise( {
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, {
specialEasing: {},
easing: jQuery.easing._default
}, 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.notifyWith( elem, [ animation, 1, 0 ] );
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 = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
if ( jQuery.isFunction( result.stop ) ) {
jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
jQuery.proxy( result.stop, result );
}
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
// Attach callbacks from options
animation
.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
} )
);
return animation;
}
jQuery.Animation = jQuery.extend( Animation, {
tweeners: {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value );
adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
return tween;
} ]
},
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.match( rnothtmlwhite );
}
var prop,
index = 0,
length = props.length;
for ( ; index < length; index++ ) {
prop = props[ index ];
Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
Animation.tweeners[ prop ].unshift( callback );
}
},
prefilters: [ defaultPrefilter ],
prefilter: function( callback, prepend ) {
if ( prepend ) {
Animation.prefilters.unshift( callback );
} else {
Animation.prefilters.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
};
// Go to the end state if fx are off
if ( jQuery.fx.off ) {
opt.duration = 0;
} else {
if ( typeof opt.duration !== "number" ) {
if ( opt.duration in jQuery.fx.speeds ) {
opt.duration = jQuery.fx.speeds[ opt.duration ];
} else {
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( isHiddenWithinTree ).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 || dataPriv.get( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each( function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = dataPriv.get( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this &&
( type == null || timers[ index ].queue === type ) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// Start the next in the queue if the last step wasn't forced.
// Timers currently will call their complete callbacks, which
// will dequeue but only if they were gotoEnd.
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
} );
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each( function() {
var index,
data = dataPriv.get( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// Enable finishing flag on private data
data.finish = true;
// Empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// Look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// Look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// Turn off finishing flag
delete data.finish;
} );
}
} );
jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
} );
// Generate shortcuts for custom animations
jQuery.each( {
slideDown: genFx( "show" ),
slideUp: genFx( "hide" ),
slideToggle: genFx( "toggle" ),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
} );
jQuery.timers = [];
jQuery.fx.tick = function() {
var timer,
i = 0,
timers = jQuery.timers;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Run the timer and safely remove it when done (allowing for external removal)
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 );
jQuery.fx.start();
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( inProgress ) {
return;
}
inProgress = true;
schedule();
};
jQuery.fx.stop = function() {
inProgress = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// https://web.archive.org/web/20100324014747/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 = window.setTimeout( next, time );
hooks.stop = function() {
window.clearTimeout( timeout );
};
} );
};
( function() {
var input = document.createElement( "input" ),
select = document.createElement( "select" ),
opt = select.appendChild( document.createElement( "option" ) );
input.type = "checkbox";
// Support: Android <=4.3 only
// Default value for a checkbox should be "on"
support.checkOn = input.value !== "";
// Support: IE <=11 only
// Must access selectedIndex to make default options select
support.optSelected = opt.selected;
// Support: IE <=11 only
// An input loses its value after becoming a radio
input = document.createElement( "input" );
input.value = "t";
input.type = "radio";
support.radioValue = input.value === "t";
} )();
var boolHook,
attrHandle = jQuery.expr.attrHandle;
jQuery.fn.extend( {
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each( function() {
jQuery.removeAttr( this, name );
} );
}
} );
jQuery.extend( {
attr: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set attributes on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
// Attribute hooks are determined by the lowercase version
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
hooks = jQuery.attrHooks[ name.toLowerCase() ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : undefined );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
}
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
elem.setAttribute( name, value + "" );
return value;
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ? undefined : ret;
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" &&
nodeName( elem, "input" ) ) {
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
removeAttr: function( elem, value ) {
var name,
i = 0,
// Attribute names can contain non-HTML whitespace characters
// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
attrNames = value && value.match( rnothtmlwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( ( name = attrNames[ i++ ] ) ) {
elem.removeAttribute( name );
}
}
}
} );
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
elem.setAttribute( name, name );
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = function( elem, name, isXML ) {
var ret, handle,
lowercaseName = name.toLowerCase();
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ lowercaseName ];
attrHandle[ lowercaseName ] = ret;
ret = getter( elem, name, isXML ) != null ?
lowercaseName :
null;
attrHandle[ lowercaseName ] = handle;
}
return ret;
};
} );
var rfocusable = /^(?:input|select|textarea|button)$/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 ) {
return this.each( function() {
delete this[ jQuery.propFix[ name ] || name ];
} );
}
} );
jQuery.extend( {
prop: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set properties on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
return ( elem[ name ] = value );
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
return elem[ name ];
},
propHooks: {
tabIndex: {
get: function( elem ) {
// Support: IE <=9 - 11 only
// elem.tabIndex doesn't always return the
// correct value when it hasn't been explicitly set
// https://web.archive.org/web/20141116233347/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" );
if ( tabindex ) {
return parseInt( tabindex, 10 );
}
if (
rfocusable.test( elem.nodeName ) ||
rclickable.test( elem.nodeName ) &&
elem.href
) {
return 0;
}
return -1;
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
}
} );
// Support: IE <=11 only
// Accessing the selectedIndex property
// forces the browser to respect setting selected
// on the option
// The getter ensures a default option is selected
// when in an optgroup
// eslint rule "no-unused-expressions" is disabled for this code
// since it considers such accessions noop
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
/* eslint no-unused-expressions: "off" */
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
},
set: function( elem ) {
/* eslint no-unused-expressions: "off" */
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
}
};
}
jQuery.each( [
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
} );
// Strip and collapse whitespace according to HTML spec
// https://html.spec.whatwg.org/multipage/infrastructure.html#strip-and-collapse-whitespace
function stripAndCollapse( value ) {
var tokens = value.match( rnothtmlwhite ) || [];
return tokens.join( " " );
}
function getClass( elem ) {
return elem.getAttribute && elem.getAttribute( "class" ) || "";
}
jQuery.fn.extend( {
addClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( jQuery.isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
} );
}
if ( typeof value === "string" && value ) {
classes = value.match( rnothtmlwhite ) || [];
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = stripAndCollapse( cur );
if ( curValue !== finalValue ) {
elem.setAttribute( "class", finalValue );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( jQuery.isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
} );
}
if ( !arguments.length ) {
return this.attr( "class", "" );
}
if ( typeof value === "string" && value ) {
classes = value.match( rnothtmlwhite ) || [];
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = stripAndCollapse( cur );
if ( curValue !== finalValue ) {
elem.setAttribute( "class", 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, getClass( this ), stateVal ),
stateVal
);
} );
}
return this.each( function() {
var className, i, self, classNames;
if ( type === "string" ) {
// Toggle individual class names
i = 0;
self = jQuery( this );
classNames = value.match( rnothtmlwhite ) || [];
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 ( value === undefined || type === "boolean" ) {
className = getClass( this );
if ( className ) {
// Store className if set
dataPriv.set( this, "__className__", 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.
if ( this.setAttribute ) {
this.setAttribute( "class",
className || value === false ?
"" :
dataPriv.get( this, "__className__" ) || ""
);
}
}
} );
},
hasClass: function( selector ) {
var className, elem,
i = 0;
className = " " + selector + " ";
while ( ( elem = this[ i++ ] ) ) {
if ( elem.nodeType === 1 &&
( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) {
return true;
}
}
return false;
}
} );
var rreturn = /\r/g;
jQuery.fn.extend( {
val: function( value ) {
var hooks, ret, isFunction,
elem = this[ 0 ];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] ||
jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks &&
"get" in hooks &&
( ret = hooks.get( elem, "value" ) ) !== undefined
) {
return ret;
}
ret = elem.value;
// Handle most common string cases
if ( typeof ret === "string" ) {
return ret.replace( rreturn, "" );
}
// Handle cases where value is null/undef or number
return 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 ( Array.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: IE <=10 - 11 only
// option.text throws exceptions (#14686, #14858)
// Strip and collapse whitespace
// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
stripAndCollapse( jQuery.text( elem ) );
}
},
select: {
get: function( elem ) {
var value, option, i,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one",
values = one ? null : [],
max = one ? index + 1 : options.length;
if ( index < 0 ) {
i = max;
} else {
i = one ? index : 0;
}
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// Support: IE <=9 only
// IE8-9 doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
!option.disabled &&
( !option.parentNode.disabled ||
!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 ];
/* eslint-disable no-cond-assign */
if ( option.selected =
jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1
) {
optionSet = true;
}
/* eslint-enable no-cond-assign */
}
// Force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
}
} );
// Radios and checkboxes getter/setter
jQuery.each( [ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( Array.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
return elem.getAttribute( "value" ) === null ? "on" : elem.value;
};
}
} );
// Return jQuery for attributes-only inclusion
var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/;
jQuery.extend( jQuery.event, {
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "." ) > -1 ) {
// 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.rnamespace = 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 = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] &&
dataPriv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && 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 ) &&
acceptData( elem ) ) {
// Call a native DOM method on the target with the same name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
// Piggyback on a donor event to simulate a different one
// Used only for `focus(in | out)` events
simulate: function( type, elem, event ) {
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true
}
);
jQuery.event.trigger( e, null, elem );
}
} );
jQuery.fn.extend( {
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 );
}
}
} );
jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup 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 );
}
} );
support.focusin = "onfocusin" in window;
// Support: Firefox <=44
// Firefox doesn't have focus(in | out) events
// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
//
// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1
// focus(in | out) events fire after focus & blur events,
// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857
if ( !support.focusin ) {
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 ) );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = dataPriv.access( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
dataPriv.access( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = dataPriv.access( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
dataPriv.remove( doc, fix );
} else {
dataPriv.access( doc, fix, attaches );
}
}
};
} );
}
var location = window.location;
var nonce = jQuery.now();
var rquery = ( /\?/ );
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE 9 - 11 only
// IE throws on parseFromString with invalid input.
try {
xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
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 ( Array.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" && v != null ? 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, valueOrFunction ) {
// If value is a function, invoke it and use its return value
var value = jQuery.isFunction( valueOrFunction ) ?
valueOrFunction() :
valueOrFunction;
s[ s.length ] = encodeURIComponent( key ) + "=" +
encodeURIComponent( value == null ? "" : value );
};
// If an array was passed in, assume that it is an array of form elements.
if ( Array.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( "&" );
};
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();
if ( val == null ) {
return null;
}
if ( Array.isArray( val ) ) {
return jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
} );
}
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
} ).get();
}
} );
var
r20 = /%20/g,
rhash = /#.*$/,
rantiCache = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
/* 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( "*" ),
// Anchor tag for parsing the document origin
originAnchor = document.createElement( "a" );
originAnchor.href = location.href;
// 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( rnothtmlwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( ( dataType = dataTypes[ i++ ] ) ) {
// Prepend if requested
if ( dataType[ 0 ] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );
// Otherwise append
} else {
( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if ( typeof dataTypeOrTransport === "string" &&
!seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
} );
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while ( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s.throws ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return {
state: "parsererror",
error: conv ? e : "No conversion from " + prev + " to " + current
};
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.extend( {
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: location.href,
type: "GET",
isLocal: rlocalProtocol.test( location.protocol ),
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: /\bxml\b/,
html: /\bhtml/,
json: /\bjson\b/
},
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": JSON.parse,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var transport,
// URL without anti-cache param
cacheURL,
// Response headers
responseHeadersString,
responseHeaders,
// timeout handle
timeoutTimer,
// Url cleanup var
urlAnchor,
// Request state (becomes false upon send and true upon completion)
completed,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// uncached part of the url
uncached,
// 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 = {},
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( completed ) {
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 completed ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
if ( completed == null ) {
name = requestHeadersNames[ name.toLowerCase() ] =
requestHeadersNames[ name.toLowerCase() ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( completed == null ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( completed ) {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
} else {
// Lazy-add the new callbacks in a way that preserves old ones
for ( code in map ) {
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
}
}
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 );
// Add protocol if not provided (prefilters might expect it)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || location.href ) + "" )
.replace( rprotocol, location.protocol + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ];
// A cross-domain request is in order when the origin doesn't match the current origin.
if ( s.crossDomain == null ) {
urlAnchor = document.createElement( "a" );
// Support: IE <=8 - 11, Edge 12 - 13
// IE throws exception on accessing the href property if url is malformed,
// e.g. http://example.com:80x/
try {
urlAnchor.href = s.url;
// Support: IE <=8 - 11 only
// Anchor's host property isn't correctly set when s.url is relative
urlAnchor.href = urlAnchor.href;
s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !==
urlAnchor.protocol + "//" + urlAnchor.host;
} catch ( e ) {
// If there is an error parsing the URL, assume it is crossDomain,
// it can be rejected by the transport if it is invalid
s.crossDomain = true;
}
}
// 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 ( completed ) {
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
// Remove hash to simplify url manipulation
cacheURL = s.url.replace( rhash, "" );
// More options handling for requests with no content
if ( !s.hasContent ) {
// Remember the hash so we can put it back
uncached = s.url.slice( cacheURL.length );
// If data is available, append data to url
if ( s.data ) {
cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add or update anti-cache param if needed
if ( s.cache === false ) {
cacheURL = cacheURL.replace( rantiCache, "$1" );
uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached;
}
// Put hash and anti-cache on the URL that will be requested (gh-1732)
s.url = cacheURL + uncached;
// Change '%20' to '+' if this is encoded form body content (gh-2658)
} else if ( s.data && s.processData &&
( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) {
s.data = s.data.replace( r20, "+" );
}
// 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 || completed ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// Aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
completeDeferred.add( s.complete );
jqXHR.done( s.success );
jqXHR.fail( s.error );
// 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 ] );
}
// If request was aborted inside ajaxSend, stop there
if ( completed ) {
return jqXHR;
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = window.setTimeout( function() {
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
completed = false;
transport.send( requestHeaders, done );
} catch ( e ) {
// Rethrow post-completion exceptions
if ( completed ) {
throw e;
}
// Propagate others as results
done( -1, e );
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Ignore repeat invocations
if ( completed ) {
return;
}
completed = true;
// Clear timeout if it exists
if ( timeoutTimer ) {
window.clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader( "Last-Modified" );
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader( "etag" );
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// Extract error from statusText and normalize for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
} );
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// Shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
// The url can be an options object (which then must have .url)
return jQuery.ajax( jQuery.extend( {
url: url,
type: method,
dataType: type,
data: data,
success: callback
}, jQuery.isPlainObject( url ) && url ) );
};
} );
jQuery._evalUrl = function( url ) {
return jQuery.ajax( {
url: url,
// Make this explicit, since user can override this through ajaxSetup (#11264)
type: "GET",
dataType: "script",
cache: true,
async: false,
global: false,
"throws": true
} );
};
jQuery.fn.extend( {
wrapAll: function( html ) {
var wrap;
if ( this[ 0 ] ) {
if ( jQuery.isFunction( html ) ) {
html = html.call( this[ 0 ] );
}
// The elements to wrap the target around
wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
if ( this[ 0 ].parentNode ) {
wrap.insertBefore( this[ 0 ] );
}
wrap.map( function() {
var elem = this;
while ( elem.firstElementChild ) {
elem = elem.firstElementChild;
}
return elem;
} ).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each( function( i ) {
jQuery( this ).wrapInner( html.call( this, i ) );
} );
}
return this.each( function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
} );
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each( function( i ) {
jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html );
} );
},
unwrap: function( selector ) {
this.parent( selector ).not( "body" ).each( function() {
jQuery( this ).replaceWith( this.childNodes );
} );
return this;
}
} );
jQuery.expr.pseudos.hidden = function( elem ) {
return !jQuery.expr.pseudos.visible( elem );
};
jQuery.expr.pseudos.visible = function( elem ) {
return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};
jQuery.ajaxSettings.xhr = function() {
try {
return new window.XMLHttpRequest();
} catch ( e ) {}
};
var xhrSuccessStatus = {
// File protocol always yields status code 0, assume 200
0: 200,
// Support: IE <=9 only
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
xhrSupported = jQuery.ajaxSettings.xhr();
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport( function( options ) {
var callback, errorCallback;
// Cross domain only allowed if supported through XMLHttpRequest
if ( support.cors || xhrSupported && !options.crossDomain ) {
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr();
xhr.open(
options.type,
options.url,
options.async,
options.username,
options.password
);
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
// Callback
callback = function( type ) {
return function() {
if ( callback ) {
callback = errorCallback = xhr.onload =
xhr.onerror = xhr.onabort = xhr.onreadystatechange = null;
if ( type === "abort" ) {
xhr.abort();
} else if ( type === "error" ) {
// Support: IE <=9 only
// On a manual native abort, IE9 throws
// errors on any property access that is not readyState
if ( typeof xhr.status !== "number" ) {
complete( 0, "error" );
} else {
complete(
// File: protocol always yields status 0; see #8605, #14207
xhr.status,
xhr.statusText
);
}
} else {
complete(
xhrSuccessStatus[ xhr.status ] || xhr.status,
xhr.statusText,
// Support: IE <=9 only
// IE9 has no XHR2 but throws on binary (trac-11426)
// For XHR2 non-text, let the caller handle it (gh-2498)
( xhr.responseType || "text" ) !== "text" ||
typeof xhr.responseText !== "string" ?
{ binary: xhr.response } :
{ text: xhr.responseText },
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
errorCallback = xhr.onerror = callback( "error" );
// Support: IE 9 only
// Use onreadystatechange to replace onabort
// to handle uncaught aborts
if ( xhr.onabort !== undefined ) {
xhr.onabort = errorCallback;
} else {
xhr.onreadystatechange = function() {
// Check readyState before timeout as it changes
if ( xhr.readyState === 4 ) {
// Allow onerror to be called first,
// but that will not handle a native abort
// Also, save errorCallback to a variable
// as xhr.onerror cannot be accessed
window.setTimeout( function() {
if ( callback ) {
errorCallback();
}
} );
}
};
}
// Create the abort callback
callback = callback( "abort" );
try {
// Do send the request (this may raise an exception)
xhr.send( options.hasContent && options.data || null );
} catch ( e ) {
// #14683: Only rethrow if this hasn't been notified as an error yet
if ( callback ) {
throw e;
}
}
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
} );
// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432)
jQuery.ajaxPrefilter( function( s ) {
if ( s.crossDomain ) {
s.contents.script = false;
}
} );
// Install script dataType
jQuery.ajaxSetup( {
accepts: {
script: "text/javascript, application/javascript, " +
"application/ecmascript, application/x-ecmascript"
},
contents: {
script: /\b(?:java|ecma)script\b/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
} );
// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
}
} );
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script, callback;
return {
send: function( _, complete ) {
script = jQuery( "<script>" ).prop( {
charset: s.scriptCharset,
src: s.url
} ).on(
"load error",
callback = function( evt ) {
script.remove();
callback = null;
if ( evt ) {
complete( evt.type === "error" ? 404 : 200, evt.type );
}
}
);
// Use native DOM manipulation to avoid our domManip AJAX trickery
document.head.appendChild( script[ 0 ] );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
} );
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup( {
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
} );
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" &&
( s.contentType || "" )
.indexOf( "application/x-www-form-urlencoded" ) === 0 &&
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() {
// If previous value didn't exist - remove it
if ( overwritten === undefined ) {
jQuery( window ).removeProp( callbackName );
// Otherwise restore preexisting value
} else {
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";
}
} );
// Support: Safari 8 only
// In Safari 8 documents created via document.implementation.createHTMLDocument
// collapse sibling forms: the second one becomes a child of the first one.
// Because of that, this security measure has to be disabled in Safari 8.
// https://bugs.webkit.org/show_bug.cgi?id=137337
support.createHTMLDocument = ( function() {
var body = document.implementation.createHTMLDocument( "" ).body;
body.innerHTML = "<form></form><form></form>";
return body.childNodes.length === 2;
} )();
// Argument "data" should be 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 ( typeof data !== "string" ) {
return [];
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
var base, parsed, scripts;
if ( !context ) {
// Stop scripts or inline event handlers from being executed immediately
// by using document.implementation
if ( support.createHTMLDocument ) {
context = document.implementation.createHTMLDocument( "" );
// Set the base href for the created document
// so any parsed elements with URLs
// are based on the document's URL (gh-2965)
base = context.createElement( "base" );
base.href = document.location.href;
context.head.appendChild( base );
} else {
context = document;
}
}
parsed = rsingleTag.exec( data );
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[ 1 ] ) ];
}
parsed = buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
var selector, type, response,
self = this,
off = url.indexOf( " " );
if ( off > -1 ) {
selector = stripAndCollapse( url.slice( off ) );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax( {
url: url,
// If "type" variable is undefined, then "GET" method will be used.
// Make value of this field explicit since
// user can override it through ajaxSetup method
type: type || "GET",
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 );
// If the request succeeds, this function gets "data", "status", "jqXHR"
// but they are ignored because response was set above.
// If it fails, this function gets "jqXHR", "status", "error"
} ).always( callback && function( jqXHR, status ) {
self.each( function() {
callback.apply( this, 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.pseudos.animated = function( elem ) {
return jQuery.grep( jQuery.timers, function( fn ) {
return elem === fn.elem;
} ).length;
};
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1;
// Need to be able to calculate position if either
// top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
options = options.call( elem, i, jQuery.extend( {}, 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 ) {
// Preserve chaining for setter
if ( arguments.length ) {
return options === undefined ?
this :
this.each( function( i ) {
jQuery.offset.setOffset( this, options, i );
} );
}
var doc, docElem, rect, win,
elem = this[ 0 ];
if ( !elem ) {
return;
}
// Return zeros for disconnected and hidden (display: none) elements (gh-2310)
// Support: IE <=11 only
// Running getBoundingClientRect on a
// disconnected node in IE throws an error
if ( !elem.getClientRects().length ) {
return { top: 0, left: 0 };
}
rect = elem.getBoundingClientRect();
doc = elem.ownerDocument;
docElem = doc.documentElement;
win = doc.defaultView;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0},
// because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// Assume getBoundingClientRect is there when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset = {
top: parentOffset.top + jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ),
left: parentOffset.left + jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true )
};
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
},
// This method will return documentElement in the following cases:
// 1) For the element inside the iframe without offsetParent, this method will return
// documentElement of the parent window
// 2) For the hidden or detached element
// 3) For body or html element, i.e. in case of the html node - it will return itself
//
// but those exceptions were never presented as a real life use-cases
// and might be considered as more preferable results.
//
// This logic, however, is not guaranteed and can change at any point in the future
offsetParent: function() {
return this.map( function() {
var offsetParent = this.offsetParent;
while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || documentElement;
} );
}
} );
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
// Coalesce documents and windows
var win;
if ( jQuery.isWindow( elem ) ) {
win = elem;
} else if ( elem.nodeType === 9 ) {
win = elem.defaultView;
}
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : win.pageXOffset,
top ? val : win.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length );
};
} );
// Support: Safari <=7 - 9.1, Chrome <=37 - 49
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// If curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
} );
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name },
function( defaultExtra, funcName ) {
// Margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// $( window ).outerWidth/Height return w/h including scrollbars (gh-1729)
return funcName.indexOf( "outer" ) === 0 ?
elem[ "inner" + name ] :
elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
// whichever is greatest
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable );
};
} );
} );
jQuery.fn.extend( {
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 );
}
} );
jQuery.holdReady = function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
};
jQuery.isArray = Array.isArray;
jQuery.parseJSON = JSON.parse;
jQuery.nodeName = nodeName;
// 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 ( true ) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() {
return jQuery;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
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 ( !noGlobal ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
} );
/***/ }),
/* 1 */
/***/ (function(module, exports) {
var cats = ['dave', 'henry', 'martha'];
module.exports = cats;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
var cats = __webpack_require__(1);
var $ = __webpack_require__(0);
console.log('$(cats).length', $(cats).length);
$('#app').text("cats");
console.log(cats);
/***/ })
/******/ ]); |
var webpack = require("webpack"),
HtmlWebpackPlugin = require("html-webpack-plugin"),
ExtractTextPlugin = require("extract-text-webpack-plugin"),
CopyWebpackPlugin = require("copy-webpack-plugin"),
helpers = require("./helpers");
const exercisePath = process.env.exercise;
var plugins = [
new webpack.optimize.CommonsChunkPlugin({
name: ["app", "vendor", "polyfills"]
}),
new ExtractTextPlugin("[name].css"),
new HtmlWebpackPlugin({
template: "index.html"
})
];
if (exercisePath === 'localization') {
plugins.push(
new CopyWebpackPlugin([{
from: "i18n", to: "i18n"
}])
)
}
module.exports = {
context: helpers.root() + '/' + exercisePath + "/src",
entry: {
app: "./main.ts",
vendor: helpers.root() + "/common/vendor.ts",
polyfills: helpers.root() + "/common/polyfills.ts"
},
resolve: {
extensions: [".webpack.js", ".web.js", ".ts", ".js"]
},
module: {
exprContextCritical: false,
loaders: [
{
test: /\.ts$/,
loaders: ["ts-loader", "angular2-router-loader?debug=true"]
},
{
test: /\.html$/,
loader: "html-loader"
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: "file?name=assets/[name].[hash].[ext]"
},
{
test: /\.css$/,
exclude: helpers.root("src", "app"),
loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: 'css-loader' })
},
{
test: /\.css$/,
include: helpers.root("src", "app"),
loader: "raw-loader"
},
{
test: /\.s(a|c)ss$/,
loaders: ["raw-loader", "sass-loader"]
}
]
},
plugins: plugins,
devtool: "source-map",
output: {
path: helpers.root("dist"),
publicPath: "http://localhost:8080/",
filename: "[name].js",
chunkFilename: "[id].chunk.js"
},
devServer: {
historyApiFallback: {
index: "http://localhost:8080/index.html"
}
}
}
|
import React, { Component, PropTypes } from 'react';
import DatePicker from 'material-ui/lib/date-picker/date-picker';
import * as layouts from '../../store/db_layouts.js';
function fmtDate( dt ) {
return dt.toLocaleDateString();
}
const CompFormDate = (props) => {
const f = props.field;
const curr_date = new Date( props.value );
// Drop the first argument, and send date in a god format for us
let handleChange = ( this_is_null, new_date ) => {
props.onChange( f, layouts.asYYYYMMDD( new_date ));
};
return (
<DatePicker
hintText={f.field}
className="form_input"
floatingLabelText={f.field}
autoOk
textFieldStyle={f.textstyle}
style={f.style}
formatDate={fmtDate}
value={curr_date}
mode="landscape"
onChange={handleChange}
/>);
};
CompFormDate.propTypes = {
field: PropTypes.object.isRequired,
value: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired
};
export default CompFormDate; |
/*
RequireJS 2.2.0 Copyright jQuery Foundation and other contributors.
Released under MIT license, http://github.com/requirejs/requirejs/LICENSE
*/
var requirejs, require, define;
(function(ga) {
function ka(b, c, d, g) {
return g || ""
}
function K(b) {
return "[object Function]" === Q.call(b)
}
function L(b) {
return "[object Array]" === Q.call(b)
}
function y(b, c) {
if (b) {
var d;
for (d = 0; d < b.length && (!b[d] || !c(b[d], d, b)); d += 1)
;
}
}
function X(b, c) {
if (b) {
var d;
for (d = b.length - 1; -1 < d && (!b[d] || !c(b[d], d, b)); --d)
;
}
}
function x(b, c) {
return la.call(b, c)
}
function e(b, c) {
return x(b, c) && b[c]
}
function D(b, c) {
for (var d in b)
if (x(b, d) && c(b[d], d))
break
}
function Y(b, c, d, g) {
c && D(c, function(c, e) {
if (d || !x(b, e))
!g || "object" !== typeof c || !c || L(c) || K(c) || c instanceof RegExp ? b[e] = c : (b[e] || (b[e] = {}),
Y(b[e], c, d, g))
});
return b
}
function z(b, c) {
return function() {
return c.apply(b, arguments)
}
}
function ha(b) {
throw b;
}
function ia(b) {
if (!b)
return b;
var c = ga;
y(b.split("."), function(b) {
c = c[b]
});
return c
}
function F(b, c, d, g) {
c = Error(c + "\nhttp://requirejs.org/docs/errors.html#" + b);
c.requireType = b;
c.requireModules = g;
d && (c.originalError = d);
return c
}
function ma(b) {
function c(a, n, b) {
var h, k, f, c, d, l, g, r;
n = n && n.split("/");
var q = p.map
, m = q && q["*"];
if (a) {
a = a.split("/");
k = a.length - 1;
p.nodeIdCompat && U.test(a[k]) && (a[k] = a[k].replace(U, ""));
"." === a[0].charAt(0) && n && (k = n.slice(0, n.length - 1),
a = k.concat(a));
k = a;
for (f = 0; f < k.length; f++)
c = k[f],
"." === c ? (k.splice(f, 1),
--f) : ".." === c && 0 !== f && (1 !== f || ".." !== k[2]) && ".." !== k[f - 1] && 0 < f && (k.splice(f - 1, 2),
f -= 2);
a = a.join("/")
}
if (b && q && (n || m)) {
k = a.split("/");
f = k.length;
a: for (; 0 < f; --f) {
d = k.slice(0, f).join("/");
if (n)
for (c = n.length; 0 < c; --c)
if (b = e(q, n.slice(0, c).join("/")))
if (b = e(b, d)) {
h = b;
l = f;
break a
}
!g && m && e(m, d) && (g = e(m, d),
r = f)
}
!h && g && (h = g,
l = r);
h && (k.splice(0, l, h),
a = k.join("/"))
}
return (h = e(p.pkgs, a)) ? h : a
}
function d(a) {
E && y(document.getElementsByTagName("script"), function(n) {
if (n.getAttribute("data-requiremodule") === a && n.getAttribute("data-requirecontext") === l.contextName)
return n.parentNode.removeChild(n),
!0
})
}
function m(a) {
var n = e(p.paths, a);
if (n && L(n) && 1 < n.length)
return n.shift(),
l.require.undef(a),
l.makeRequire(null, {
skipMap: !0
})([a]),
!0
}
function r(a) {
var n, b = a ? a.indexOf("!") : -1;
-1 < b && (n = a.substring(0, b),
a = a.substring(b + 1, a.length));
return [n, a]
}
function q(a, n, b, h) {
var k, f, d = null, g = n ? n.name : null, p = a, q = !0, m = "";
a || (q = !1,
a = "_@r" + (Q += 1));
a = r(a);
d = a[0];
a = a[1];
d && (d = c(d, g, h),
f = e(v, d));
a && (d ? m = f && f.normalize ? f.normalize(a, function(a) {
return c(a, g, h)
}) : -1 === a.indexOf("!") ? c(a, g, h) : a : (m = c(a, g, h),
a = r(m),
d = a[0],
m = a[1],
b = !0,
k = l.nameToUrl(m)));
b = !d || f || b ? "" : "_unnormalized" + (T += 1);
return {
prefix: d,
name: m,
parentMap: n,
unnormalized: !!b,
url: k,
originalName: p,
isDefine: q,
id: (d ? d + "!" + m : m) + b
}
}
function u(a) {
var b = a.id
, c = e(t, b);
c || (c = t[b] = new l.Module(a));
return c
}
function w(a, b, c) {
var h = a.id
, k = e(t, h);
if (!x(v, h) || k && !k.defineEmitComplete)
if (k = u(a),
k.error && "error" === b)
c(k.error);
else
k.on(b, c);
else
"defined" === b && c(v[h])
}
function A(a, b) {
var c = a.requireModules
, h = !1;
if (b)
b(a);
else if (y(c, function(b) {
if (b = e(t, b))
b.error = a,
b.events.error && (h = !0,
b.emit("error", a))
}),
!h)
g.onError(a)
}
function B() {
V.length && (y(V, function(a) {
var b = a[0];
"string" === typeof b && (l.defQueueMap[b] = !0);
G.push(a)
}),
V = [])
}
function C(a) {
delete t[a];
delete Z[a]
}
function J(a, b, c) {
var h = a.map.id;
a.error ? a.emit("error", a.error) : (b[h] = !0,
y(a.depMaps, function(h, f) {
var d = h.id
, g = e(t, d);
!g || a.depMatched[f] || c[d] || (e(b, d) ? (a.defineDep(f, v[d]),
a.check()) : J(g, b, c))
}),
c[h] = !0)
}
function H() {
var a, b, c = (a = 1E3 * p.waitSeconds) && l.startTime + a < (new Date).getTime(), h = [], k = [], f = !1, g = !0;
if (!aa) {
aa = !0;
D(Z, function(a) {
var l = a.map
, e = l.id;
if (a.enabled && (l.isDefine || k.push(a),
!a.error))
if (!a.inited && c)
m(e) ? f = b = !0 : (h.push(e),
d(e));
else if (!a.inited && a.fetched && l.isDefine && (f = !0,
!l.prefix))
return g = !1
});
if (c && h.length)
return a = F("timeout", "Load timeout for modules: " + h, null, h),
a.contextName = l.contextName,
A(a);
g && y(k, function(a) {
J(a, {}, {})
});
c && !b || !f || !E && !ja || ba || (ba = setTimeout(function() {
ba = 0;
H()
}, 50));
aa = !1
}
}
function I(a) {
x(v, a[0]) || u(q(a[0], null, !0)).init(a[1], a[2])
}
function O(a) {
a = a.currentTarget || a.srcElement;
var b = l.onScriptLoad;
a.detachEvent && !ca ? a.detachEvent("onreadystatechange", b) : a.removeEventListener("load", b, !1);
b = l.onScriptError;
a.detachEvent && !ca || a.removeEventListener("error", b, !1);
return {
node: a,
id: a && a.getAttribute("data-requiremodule")
}
}
function P() {
var a;
for (B(); G.length; ) {
a = G.shift();
if (null === a[0])
return A(F("mismatch", "Mismatched anonymous define() module: " + a[a.length - 1]));
I(a)
}
l.defQueueMap = {}
}
var aa, da, l, R, ba, p = {
waitSeconds: 7,
baseUrl: "./",
paths: {},
bundles: {},
pkgs: {},
shim: {},
config: {}
}, t = {}, Z = {}, ea = {}, G = [], v = {}, W = {}, fa = {}, Q = 1, T = 1;
R = {
require: function(a) {
return a.require ? a.require : a.require = l.makeRequire(a.map)
},
exports: function(a) {
a.usingExports = !0;
if (a.map.isDefine)
return a.exports ? v[a.map.id] = a.exports : a.exports = v[a.map.id] = {}
},
module: function(a) {
return a.module ? a.module : a.module = {
id: a.map.id,
uri: a.map.url,
config: function() {
return e(p.config, a.map.id) || {}
},
exports: a.exports || (a.exports = {})
}
}
};
da = function(a) {
this.events = e(ea, a.id) || {};
this.map = a;
this.shim = e(p.shim, a.id);
this.depExports = [];
this.depMaps = [];
this.depMatched = [];
this.pluginMaps = {};
this.depCount = 0
}
;
da.prototype = {
init: function(a, b, c, h) {
h = h || {};
if (!this.inited) {
this.factory = b;
if (c)
this.on("error", c);
else
this.events.error && (c = z(this, function(a) {
this.emit("error", a)
}));
this.depMaps = a && a.slice(0);
this.errback = c;
this.inited = !0;
this.ignore = h.ignore;
h.enabled || this.enabled ? this.enable() : this.check()
}
},
defineDep: function(a, b) {
this.depMatched[a] || (this.depMatched[a] = !0,
--this.depCount,
this.depExports[a] = b)
},
fetch: function() {
if (!this.fetched) {
this.fetched = !0;
l.startTime = (new Date).getTime();
var a = this.map;
if (this.shim)
l.makeRequire(this.map, {
enableBuildCallback: !0
})(this.shim.deps || [], z(this, function() {
return a.prefix ? this.callPlugin() : this.load()
}));
else
return a.prefix ? this.callPlugin() : this.load()
}
},
load: function() {
var a = this.map.url;
W[a] || (W[a] = !0,
l.load(this.map.id, a))
},
check: function() {
if (this.enabled && !this.enabling) {
var a, b, c = this.map.id;
b = this.depExports;
var h = this.exports
, k = this.factory;
if (!this.inited)
x(l.defQueueMap, c) || this.fetch();
else if (this.error)
this.emit("error", this.error);
else if (!this.defining) {
this.defining = !0;
if (1 > this.depCount && !this.defined) {
if (K(k)) {
if (this.events.error && this.map.isDefine || g.onError !== ha)
try {
h = l.execCb(c, k, b, h)
} catch (d) {
a = d
}
else
h = l.execCb(c, k, b, h);
this.map.isDefine && void 0 === h && ((b = this.module) ? h = b.exports : this.usingExports && (h = this.exports));
if (a)
return a.requireMap = this.map,
a.requireModules = this.map.isDefine ? [this.map.id] : null,
a.requireType = this.map.isDefine ? "define" : "require",
A(this.error = a)
} else
h = k;
this.exports = h;
if (this.map.isDefine && !this.ignore && (v[c] = h,
g.onResourceLoad)) {
var f = [];
y(this.depMaps, function(a) {
f.push(a.normalizedMap || a)
});
g.onResourceLoad(l, this.map, f)
}
C(c);
this.defined = !0
}
this.defining = !1;
this.defined && !this.defineEmitted && (this.defineEmitted = !0,
this.emit("defined", this.exports),
this.defineEmitComplete = !0)
}
}
},
callPlugin: function() {
var a = this.map
, b = a.id
, d = q(a.prefix);
this.depMaps.push(d);
w(d, "defined", z(this, function(h) {
var k, f, d = e(fa, this.map.id), M = this.map.name, r = this.map.parentMap ? this.map.parentMap.name : null, m = l.makeRequire(a.parentMap, {
enableBuildCallback: !0
});
if (this.map.unnormalized) {
if (h.normalize && (M = h.normalize(M, function(a) {
return c(a, r, !0)
}) || ""),
f = q(a.prefix + "!" + M, this.map.parentMap),
w(f, "defined", z(this, function(a) {
this.map.normalizedMap = f;
this.init([], function() {
return a
}, null, {
enabled: !0,
ignore: !0
})
})),
h = e(t, f.id)) {
this.depMaps.push(f);
if (this.events.error)
h.on("error", z(this, function(a) {
this.emit("error", a)
}));
h.enable()
}
} else
d ? (this.map.url = l.nameToUrl(d),
this.load()) : (k = z(this, function(a) {
this.init([], function() {
return a
}, null, {
enabled: !0
})
}),
k.error = z(this, function(a) {
this.inited = !0;
this.error = a;
a.requireModules = [b];
D(t, function(a) {
0 === a.map.id.indexOf(b + "_unnormalized") && C(a.map.id)
});
A(a)
}),
k.fromText = z(this, function(h, c) {
var d = a.name
, f = q(d)
, M = S;
c && (h = c);
M && (S = !1);
u(f);
x(p.config, b) && (p.config[d] = p.config[b]);
try {
g.exec(h)
} catch (e) {
return A(F("fromtexteval", "fromText eval for " + b + " failed: " + e, e, [b]))
}
M && (S = !0);
this.depMaps.push(f);
l.completeLoad(d);
m([d], k)
}),
h.load(a.name, m, k, p))
}));
l.enable(d, this);
this.pluginMaps[d.id] = d
},
enable: function() {
Z[this.map.id] = this;
this.enabling = this.enabled = !0;
y(this.depMaps, z(this, function(a, b) {
var c, h;
if ("string" === typeof a) {
a = q(a, this.map.isDefine ? this.map : this.map.parentMap, !1, !this.skipMap);
this.depMaps[b] = a;
if (c = e(R, a.id)) {
this.depExports[b] = c(this);
return
}
this.depCount += 1;
w(a, "defined", z(this, function(a) {
this.undefed || (this.defineDep(b, a),
this.check())
}));
this.errback ? w(a, "error", z(this, this.errback)) : this.events.error && w(a, "error", z(this, function(a) {
this.emit("error", a)
}))
}
c = a.id;
h = t[c];
x(R, c) || !h || h.enabled || l.enable(a, this)
}));
D(this.pluginMaps, z(this, function(a) {
var b = e(t, a.id);
b && !b.enabled && l.enable(a, this)
}));
this.enabling = !1;
this.check()
},
on: function(a, b) {
var c = this.events[a];
c || (c = this.events[a] = []);
c.push(b)
},
emit: function(a, b) {
y(this.events[a], function(a) {
a(b)
});
"error" === a && delete this.events[a]
}
};
l = {
config: p,
contextName: b,
registry: t,
defined: v,
urlFetched: W,
defQueue: G,
defQueueMap: {},
Module: da,
makeModuleMap: q,
nextTick: g.nextTick,
onError: A,
configure: function(a) {
a.baseUrl && "/" !== a.baseUrl.charAt(a.baseUrl.length - 1) && (a.baseUrl += "/");
if ("string" === typeof a.urlArgs) {
var b = a.urlArgs;
a.urlArgs = function(a, c) {
return (-1 === c.indexOf("?") ? "?" : "&") + b
}
}
var c = p.shim
, h = {
paths: !0,
bundles: !0,
config: !0,
map: !0
};
D(a, function(a, b) {
h[b] ? (p[b] || (p[b] = {}),
Y(p[b], a, !0, !0)) : p[b] = a
});
a.bundles && D(a.bundles, function(a, b) {
y(a, function(a) {
a !== b && (fa[a] = b)
})
});
a.shim && (D(a.shim, function(a, b) {
L(a) && (a = {
deps: a
});
!a.exports && !a.init || a.exportsFn || (a.exportsFn = l.makeShimExports(a));
c[b] = a
}),
p.shim = c);
a.packages && y(a.packages, function(a) {
var b;
a = "string" === typeof a ? {
name: a
} : a;
b = a.name;
a.location && (p.paths[b] = a.location);
p.pkgs[b] = a.name + "/" + (a.main || "main").replace(na, "").replace(U, "")
});
D(t, function(a, b) {
a.inited || a.map.unnormalized || (a.map = q(b, null, !0))
});
(a.deps || a.callback) && l.require(a.deps || [], a.callback)
},
makeShimExports: function(a) {
return function() {
var b;
a.init && (b = a.init.apply(ga, arguments));
return b || a.exports && ia(a.exports)
}
},
makeRequire: function(a, n) {
function m(c, d, f) {
var e, r;
n.enableBuildCallback && d && K(d) && (d.__requireJsBuild = !0);
if ("string" === typeof c) {
if (K(d))
return A(F("requireargs", "Invalid require call"), f);
if (a && x(R, c))
return R[c](t[a.id]);
if (g.get)
return g.get(l, c, a, m);
e = q(c, a, !1, !0);
e = e.id;
return x(v, e) ? v[e] : A(F("notloaded", 'Module name "' + e + '" has not been loaded yet for context: ' + b + (a ? "" : ". Use require([])")))
}
P();
l.nextTick(function() {
P();
r = u(q(null, a));
r.skipMap = n.skipMap;
r.init(c, d, f, {
enabled: !0
});
H()
});
return m
}
n = n || {};
Y(m, {
isBrowser: E,
toUrl: function(b) {
var d, f = b.lastIndexOf("."), g = b.split("/")[0];
-1 !== f && ("." !== g && ".." !== g || 1 < f) && (d = b.substring(f, b.length),
b = b.substring(0, f));
return l.nameToUrl(c(b, a && a.id, !0), d, !0)
},
defined: function(b) {
return x(v, q(b, a, !1, !0).id)
},
specified: function(b) {
b = q(b, a, !1, !0).id;
return x(v, b) || x(t, b)
}
});
a || (m.undef = function(b) {
B();
var c = q(b, a, !0)
, f = e(t, b);
f.undefed = !0;
d(b);
delete v[b];
delete W[c.url];
delete ea[b];
X(G, function(a, c) {
a[0] === b && G.splice(c, 1)
});
delete l.defQueueMap[b];
f && (f.events.defined && (ea[b] = f.events),
C(b))
}
);
return m
},
enable: function(a) {
e(t, a.id) && u(a).enable()
},
completeLoad: function(a) {
var b, c, d = e(p.shim, a) || {}, g = d.exports;
for (B(); G.length; ) {
c = G.shift();
if (null === c[0]) {
c[0] = a;
if (b)
break;
b = !0
} else
c[0] === a && (b = !0);
I(c)
}
l.defQueueMap = {};
c = e(t, a);
if (!b && !x(v, a) && c && !c.inited)
if (!p.enforceDefine || g && ia(g))
I([a, d.deps || [], d.exportsFn]);
else
return m(a) ? void 0 : A(F("nodefine", "No define call for " + a, null, [a]));
H()
},
nameToUrl: function(a, b, c) {
var d, k, f, m;
(d = e(p.pkgs, a)) && (a = d);
if (d = e(fa, a))
return l.nameToUrl(d, b, c);
if (g.jsExtRegExp.test(a))
d = a + (b || "");
else {
d = p.paths;
k = a.split("/");
for (f = k.length; 0 < f; --f)
if (m = k.slice(0, f).join("/"),
m = e(d, m)) {
L(m) && (m = m[0]);
k.splice(0, f, m);
break
}
d = k.join("/");
d += b || (/^data\:|^blob\:|\?/.test(d) || c ? "" : ".js");
d = ("/" === d.charAt(0) || d.match(/^[\w\+\.\-]+:/) ? "" : p.baseUrl) + d
}
return p.urlArgs && !/^blob\:/.test(d) ? d + p.urlArgs(a, d) : d
},
load: function(a, b) {
g.load(l, a, b)
},
execCb: function(a, b, c, d) {
return b.apply(d, c)
},
onScriptLoad: function(a) {
if ("load" === a.type || oa.test((a.currentTarget || a.srcElement).readyState))
N = null,
a = O(a),
l.completeLoad(a.id)
},
onScriptError: function(a) {
var b = O(a);
if (!m(b.id)) {
var c = [];
D(t, function(a, d) {
0 !== d.indexOf("_@r") && y(a.depMaps, function(a) {
if (a.id === b.id)
return c.push(d),
!0
})
});
return A(F("scripterror", 'Script error for "' + b.id + (c.length ? '", needed by: ' + c.join(", ") : '"'), a, [b.id]))
}
}
};
l.require = l.makeRequire();
return l
}
function pa() {
if (N && "interactive" === N.readyState)
return N;
X(document.getElementsByTagName("script"), function(b) {
if ("interactive" === b.readyState)
return N = b
});
return N
}
var g, B, C, H, O, I, N, P, u, T, qa = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, ra = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, U = /\.js$/, na = /^\.\//;
B = Object.prototype;
var Q = B.toString
, la = B.hasOwnProperty
, E = !("undefined" === typeof window || "undefined" === typeof navigator || !window.document)
, ja = !E && "undefined" !== typeof importScripts
, oa = E && "PLAYSTATION 3" === navigator.platform ? /^complete$/ : /^(complete|loaded)$/
, ca = "undefined" !== typeof opera && "[object Opera]" === opera.toString()
, J = {}
, w = {}
, V = []
, S = !1;
if ("undefined" === typeof define) {
if ("undefined" !== typeof requirejs) {
if (K(requirejs))
return;
w = requirejs;
requirejs = void 0
}
"undefined" === typeof require || K(require) || (w = require,
require = void 0);
g = requirejs = function(b, c, d, m) {
var r, q = "_";
L(b) || "string" === typeof b || (r = b,
L(c) ? (b = c,
c = d,
d = m) : b = []);
r && r.context && (q = r.context);
(m = e(J, q)) || (m = J[q] = g.s.newContext(q));
r && m.configure(r);
return m.require(b, c, d)
}
;
g.config = function(b) {
return g(b)
}
;
g.nextTick = "undefined" !== typeof setTimeout ? function(b) {
setTimeout(b, 4)
}
: function(b) {
b()
}
;
require || (require = g);
g.version = "2.2.0";
g.jsExtRegExp = /^\/|:|\?|\.js$/;
g.isBrowser = E;
B = g.s = {
contexts: J,
newContext: ma
};
g({});
y(["toUrl", "undef", "defined", "specified"], function(b) {
g[b] = function() {
var c = J._;
return c.require[b].apply(c, arguments)
}
});
E && (C = B.head = document.getElementsByTagName("head")[0],
H = document.getElementsByTagName("base")[0]) && (C = B.head = H.parentNode);
g.onError = ha;
g.createNode = function(b, c, d) {
c = b.xhtml ? document.createElementNS("http://www.w3.org/1999/xhtml", "html:script") : document.createElement("script");
c.type = b.scriptType || "text/javascript";
c.charset = "utf-8";
c.async = !0;
return c
}
;
g.load = function(b, c, d) {
var m = b && b.config || {}, e;
if (E) {
e = g.createNode(m, c, d);
e.setAttribute("data-requirecontext", b.contextName);
e.setAttribute("data-requiremodule", c);
!e.attachEvent || e.attachEvent.toString && 0 > e.attachEvent.toString().indexOf("[native code") || ca ? (e.addEventListener("load", b.onScriptLoad, !1),
e.addEventListener("error", b.onScriptError, !1)) : (S = !0,
e.attachEvent("onreadystatechange", b.onScriptLoad));
e.src = d;
if (m.onNodeCreated)
m.onNodeCreated(e, m, c, d);
P = e;
H ? C.insertBefore(e, H) : C.appendChild(e);
P = null;
return e
}
if (ja)
try {
setTimeout(function() {}, 0),
importScripts(d),
b.completeLoad(c)
} catch (q) {
b.onError(F("importscripts", "importScripts failed for " + c + " at " + d, q, [c]))
}
}
;
E && !w.skipDataMain && X(document.getElementsByTagName("script"), function(b) {
C || (C = b.parentNode);
if (O = b.getAttribute("data-main"))
return u = O,
w.baseUrl || -1 !== u.indexOf("!") || (I = u.split("/"),
u = I.pop(),
T = I.length ? I.join("/") + "/" : "./",
w.baseUrl = T),
u = u.replace(U, ""),
g.jsExtRegExp.test(u) && (u = O),
w.deps = w.deps ? w.deps.concat(u) : [u],
!0
});
define = function(b, c, d) {
var e, g;
"string" !== typeof b && (d = c,
c = b,
b = null);
L(c) || (d = c,
c = null);
!c && K(d) && (c = [],
d.length && (d.toString().replace(qa, ka).replace(ra, function(b, d) {
c.push(d)
}),
c = (1 === d.length ? ["require"] : ["require", "exports", "module"]).concat(c)));
S && (e = P || pa()) && (b || (b = e.getAttribute("data-requiremodule")),
g = J[e.getAttribute("data-requirecontext")]);
g ? (g.defQueue.push([b, c, d]),
g.defQueueMap[b] = !0) : V.push([b, c, d])
}
;
define.amd = {
jQuery: !0
};
g.exec = function(b) {
return eval(b)
}
;
g(w)
}
}
)(this);
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M12 3.7c-.66 0-1.2.54-1.2 1.2v1.51l2.39 2.39.01-3.9c0-.66-.54-1.2-1.2-1.2z" opacity=".3" /><path d="M19 11h-1.7c0 .58-.1 1.13-.27 1.64l1.27 1.27c.44-.88.7-1.87.7-2.91zM4.41 2.86L3 4.27l6 6V11c0 1.66 1.34 3 3 3 .23 0 .44-.03.65-.08l1.66 1.66c-.71.33-1.5.52-2.31.52-2.76 0-5.3-2.1-5.3-5.1H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c.91-.13 1.77-.45 2.55-.9l4.2 4.2 1.41-1.41L4.41 2.86zM10.8 4.9c0-.66.54-1.2 1.2-1.2s1.2.54 1.2 1.2l-.01 3.91L15 10.6V5c0-1.66-1.34-3-3-3-1.54 0-2.79 1.16-2.96 2.65l1.76 1.76V4.9z" /></React.Fragment>
, 'MicOffTwoTone');
|
/*global console: false, creatis_carpenterStorage_replaceContentFromStorage: false */
$(function () {
function initDesktop() {
$("#accordion").accordion({
collapsible: true,
active: localStorage.selectedCarpenter ? false : true,
});
// Kontaktseite Suche
$("#search-site-submit").click(function () {
var searchQuery = $("#search-query-site").val();
if (isValidPostal(searchQuery)) {
document.location = "/tischler?query=" + searchQuery;
}
return false;
});
$("#search-query-site").on('input', function () {
var isValid = isValidPostal($("#search-query-site").val());
$("#search-query-site").css('border-color', !isValid ? 'red' : '#d5d5d5');
});
$("#search-query").on('input', function () {
var isValid = isValidPostal($("#search-query").val());
$("#search-query").css('border-color', !isValid ? 'red' : '#d5d5d5');
});
//Prevent default on enter
$('#search-query').keypress(function (event) {
if (event.keyCode == 10 || event.keyCode == 13)
event.preventDefault();
});
$("#accordion").removeClass('c-hidden');
$("#search-flyout-submit").click(function () {
var searchQuery = $("#search-query").val();
if (searchQuery !== null && searchQuery !== "" && isValidPostal(searchQuery)) {
document.location = "/tischler?query=" + searchQuery;
}
return false;
});
if (typeof (creatis_carpenterStorage_replaceContentFromStorage) !== "undefined") {
creatis_carpenterStorage_replaceContentFromStorage();
}
}
function initMobile() {
//code taken from https://github.com/codrops/ButtonComponentMorph/blob/master/index.html
var docElem = window.document.documentElement, didScroll, scrollPosition;
// trick to prevent scrolling when opening/closing button
function noScrollFn() {
window.scrollTo(scrollPosition ? scrollPosition.x : 0, scrollPosition ? scrollPosition.y : 0);
}
function noScroll() {
window.removeEventListener('scroll', scrollHandler);
window.addEventListener('scroll', noScrollFn);
}
function scrollFn() {
window.addEventListener('scroll', scrollHandler);
}
function canScroll() {
window.removeEventListener('scroll', noScrollFn);
scrollFn();
}
function scrollHandler() {
if (!didScroll) {
didScroll = true;
setTimeout(function () { scrollPage(); }, 60);
}
};
function scrollPage() {
scrollPosition = { x: window.pageXOffset || docElem.scrollLeft, y: window.pageYOffset || docElem.scrollTop };
didScroll = false;
};
scrollFn();
// Mobile carpenter search button
var mobileSearchButton = document.querySelector('#search-mobile .morph-button');
$('#search-mobile .morph-button').click(function (ev) {
if (ev.originalEvent) {
ev.originalEvent.preventDefault();
}
});
var mobileSearchMorphingButton = new UIMorphingButton(mobileSearchButton, {
closeEl: '.icon-close',
onBeforeOpen: function () {
// don't allow to scroll
noScroll();
},
onAfterOpen: function () {
// can scroll again
canScroll();
$('.dialog-page').hide();
$('.mobile-search-page-overview').show();
},
onBeforeClose: function () {
// don't allow to scroll
noScroll();
},
onAfterClose: function () {
// can scroll again
if (window.buyWithoutCarpenter && localStorage.selectedCarpenter !== null) {
$('#purchase-request-starter')[0].click();
}
else
{
window.buyWithoutCarpenter = false;
}
canScroll();
}
});
}
(function startup() {
if (isMobile()) {
initMobile();
} else {
if ($("#accordion").length > 0) {
initDesktop();
}
}
//initDesktop();
//initMobile();
displaySelectedCarpenter();
})();
});
function isMobile() {
return $("#search-mobile").css("visibility") === "visible";
}
function displaySelectedCarpenter() {
if (localStorage.selectedCarpenter) {
$('#div_text').css('display', 'none');
var data = JSON.parse(localStorage.getItem('selectedCarpenter'));
var cId = data.id;
setTimeout(function () {
$('#' + cId + ' .btn-select').first().trigger('click');
}, 50);
}
} |
import { create, visitable } from 'ember-cli-page-object';
import accountSetup from 'code-corps-ember/tests/pages/components/payments/account-setup';
export default create({
visit: visitable(':organization/:project/settings/donations/payments'),
accountSetup
});
|
'use strict';
/* main App */
var app = angular.module('submitConformationcontroller', []);
app.controller('confirmationCtrl', ['$scope', function($scope){
$scope.volunteerList = ["Joop Bakker", "Dirk Dijkstra", "Sterre Hendriks",
"Hendrik Jacobs", "Hans Heuvel", "Jaap Beek", "Jan-Jaap Dijk",
"Marleen Jansen", "Geert Hoek", "Beer Heuvel"];
$scope.jobTitle = '';
$scope.jobType = '';
$scope.describeWork = '';
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$scope.jobTitle = getParameterByName('jobTitle');
$scope.jobType = getParameterByName('jobType');
$scope.describeWork = getParameterByName('describeWork');
}]); |
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
"use strict";
// these $ globals are defined by external environment
// they are redefined here to make R# like tools understand them
var _log = $log;
var _load_module = $load_module;
function log(message) {
_log("PROJECTIONS (JS): " + message);
}
function initializeModules() {
// load module load new instance of the given module every time
// this is a responsibility of prelude to manage instances of modules
var modules = _load_module('Modules');
// TODO: replace with createRequire($load_module)
modules.$load_module = _load_module;
return modules;
}
function initializeProjections() {
var projections = _load_module('Projections');
return projections;
}
var modules = initializeModules();
var projections = initializeProjections();
var eventProcessor;
function scope($on, $notify) {
eventProcessor = projections.createEventProcessor(log, $notify);
eventProcessor.register_command_handlers($on);
function queryLog(message) {
if (typeof message === "string")
_log(message);
else
_log(JSON.stringify(message));
}
function translateOn(handlers) {
for (var name in handlers) {
if (name == 0 || name === "$init") {
eventProcessor.on_init_state(handlers[name]);
} else if (name === "$initShared") {
eventProcessor.on_init_shared_state(handlers[name]);
} else if (name === "$any") {
eventProcessor.on_any(handlers[name]);
} else if (name === "$deleted") {
eventProcessor.on_deleted_notification(handlers[name]);
} else if (name === "$created") {
eventProcessor.on_created_notification(handlers[name]);
} else {
eventProcessor.on_event(name, handlers[name]);
}
}
}
function $defines_state_transform() {
eventProcessor.$defines_state_transform();
}
function transformBy(by) {
eventProcessor.chainTransformBy(by);
return {
transformBy: transformBy,
filterBy: filterBy,
outputState: outputState,
outputTo: outputTo,
};
}
function filterBy(by) {
eventProcessor.chainTransformBy(function (s) {
var result = by(s);
return result ? s : null;
});
return {
transformBy: transformBy,
filterBy: filterBy,
outputState: outputState,
outputTo: outputTo,
};
}
function outputTo(resultStream, partitionResultStreamPattern) {
eventProcessor.$defines_state_transform();
eventProcessor.options({
resultStreamName: resultStream,
partitionResultStreamNamePattern: partitionResultStreamPattern,
});
}
function outputState() {
eventProcessor.$outputState();
return {
transformBy: transformBy,
filterBy: filterBy,
outputTo: outputTo,
};
}
function when(handlers) {
translateOn(handlers);
return {
$defines_state_transform: $defines_state_transform,
transformBy: transformBy,
filterBy: filterBy,
outputTo: outputTo,
outputState: outputState,
};
}
function foreachStream() {
eventProcessor.byStream();
return {
when: when,
};
}
function partitionBy(byHandler) {
eventProcessor.partitionBy(byHandler);
return {
when: when,
};
}
function fromCategory(category) {
eventProcessor.fromCategory(category);
return {
partitionBy: partitionBy,
foreachStream: foreachStream,
when: when,
outputState: outputState,
};
}
function fromAll() {
eventProcessor.fromAll();
return {
partitionBy: partitionBy,
when: when,
foreachStream: foreachStream,
outputState: outputState,
};
}
function fromStream(stream) {
eventProcessor.fromStream(stream);
return {
partitionBy: partitionBy,
when: when,
outputState: outputState,
};
}
function fromStreamCatalog(streamCatalog, transformer) {
eventProcessor.fromStreamCatalog(streamCatalog, transformer ? transformer : null);
return {
foreachStream: foreachStream,
};
}
function fromStreamsMatching(filter) {
eventProcessor.fromStreamsMatching(filter);
return {
when: when,
};
}
function fromStreams(streams) {
var arr = Array.isArray(streams) ? streams : arguments;
for (var i = 0; i < arr.length; i++)
eventProcessor.fromStream(arr[i]);
return {
partitionBy: partitionBy,
when: when,
outputState: outputState,
};
}
function emit(streamId, eventName, eventBody, metadata) {
var message = { streamId: streamId, eventName: eventName , body: JSON.stringify(eventBody), metadata: metadata, isJson: true };
eventProcessor.emit(message);
}
function linkTo(streamId, event, metadata) {
var message = { streamId: streamId, eventName: "$>", body: event.sequenceNumber + "@" + event.streamId, metadata: metadata, isJson: false };
eventProcessor.emit(message);
}
function copyTo(streamId, event, metadata) {
var m = {};
var em = event.metadata;
if (em)
for (var p1 in em)
if (p1.indexOf("$") !== 0 || p1 === "$correlationId")
m[p1] = em[p1];
if (metadata)
for (var p2 in metadata)
if (p2.indexOf("$") !== 0)
m[p2] = metadata[p2];
var message = { streamId: streamId, eventName: event.eventType, body: event.bodyRaw, metadata: m };
eventProcessor.emit(message);
}
function linkStreamTo(streamId, linkedStreamId, metadata) {
var message = { streamId: streamId, eventName: "$@", body: linkedStreamId, metadata: metadata, isJson: false };
eventProcessor.emit(message);
}
function options(options_object) {
eventProcessor.options(options_object);
}
return {
log: queryLog,
on_any: eventProcessor.on_any,
on_raw: eventProcessor.on_raw,
fromAll: fromAll,
fromCategory: fromCategory,
fromStream: fromStream,
fromStreams: fromStreams,
fromStreamCatalog: fromStreamCatalog,
fromStreamsMatching: fromStreamsMatching,
options: options,
emit: emit,
linkTo: linkTo,
copyTo: copyTo,
linkStreamTo: linkStreamTo,
require: modules.require,
};
};
scope; |
'use strict';
var R6MStatsOpData = (function(R6MLangTerms, undefined) {
var WARNING_THRESHOLD = 20,
opStats = {
attackers: [],
defenders: [],
sortInfo: {
field: null,
rank: null,
isDescending: null
}
};
var getAveragesTotals = function getAveragesTotals(opRoleStats) {
var count = 0,
averagesTotals = {};
for (var opKey in opRoleStats) {
for (var sarKey in opRoleStats[opKey].statsAllRanks) {
averagesTotals[sarKey] = averagesTotals[sarKey] || {};
averagesTotals[sarKey].all = averagesTotals[sarKey].all || { total: 0, avg: 0 };
averagesTotals[sarKey].all.total += opRoleStats[opKey].statsAllRanks[sarKey];
}
for (var sbrKey in opRoleStats[opKey].statsByRank) {
for (var key in opRoleStats[opKey].statsByRank[sbrKey]) {
averagesTotals[key] = averagesTotals[key] || {};
averagesTotals[key][sbrKey] = averagesTotals[key][sbrKey] || { total: 0, avg: 0 };
averagesTotals[key][sbrKey].total += opRoleStats[opKey].statsByRank[sbrKey][key];
}
}
count++;
}
for (var statKey in averagesTotals) {
for (var operator in averagesTotals[statKey]) {
averagesTotals[statKey][operator].avg = averagesTotals[statKey][operator].total / count;
}
}
return averagesTotals;
};
var getEmptyStatsObject = function getEmptyStatsObject() {
return {
totalKills: 0,
totalDeaths: 0,
totalPlays: 0,
totalWins: 0,
killsPerRound: 0,
killsPerDeath: 0,
pickRate: 0,
winRate: 0,
survivalRate: 0,
warning: false
};
};
var getCurrentStats = function getCurrentStats() {
return opStats;
};
var getOpRoleStats = function getOpRoleStats(apiOpData, totalRounds, opMetaData) {
var opRoleStats = [],
totalPlaysByRank = {},
totalPlaysAllRanks = 0;
for (var opKey in apiOpData) {
var newOpStats = {
key: opKey,
name: opMetaData[opKey].name,
cssClass: opMetaData[opKey].cssClass,
statsByRank: {},
statsAllRanks: getEmptyStatsObject()
};
for (var rankKey in apiOpData[opKey]) {
var opRankStats = getEmptyStatsObject(),
apiOpRankData = apiOpData[opKey][rankKey];
['totalWins', 'totalKills', 'totalDeaths', 'totalPlays'].forEach(function(statKey) {
opRankStats[statKey] = +apiOpRankData[statKey];
newOpStats.statsAllRanks[statKey] += opRankStats[statKey];
});
totalPlaysByRank[rankKey] = totalPlaysByRank[rankKey] ?
totalPlaysByRank[rankKey] + opRankStats.totalPlays : opRankStats.totalPlays;
totalPlaysAllRanks += opRankStats.totalPlays;
newOpStats.statsByRank[rankKey] = opRankStats;
}
opRoleStats.push(newOpStats);
}
setTallies(opRoleStats, totalRounds, totalPlaysByRank, totalPlaysAllRanks);
setWarnings(opRoleStats);
return {
operators: opRoleStats,
averagesTotals: getAveragesTotals(opRoleStats)
};
};
var set = function set(apiData, totalRounds, opMetaData) {
opStats.attackers = getOpRoleStats(apiData.role.Attacker, totalRounds, opMetaData);
opStats.defenders = getOpRoleStats(apiData.role.Defender, totalRounds, opMetaData);
};
var setTallies = function setTallies(opRoleStats, totalRounds, totalPlaysByRank, totalPlaysAllRanks) {
opRoleStats.forEach(function(operator) {
setTalliesForRank(operator.statsAllRanks);
operator.statsAllRanks.pickRate = (!totalRounds) ? 0 : operator.statsAllRanks.totalPlays / totalRounds;
for (var rankKey in operator.statsByRank) {
var stats = operator.statsByRank[rankKey];
setTalliesForRank(stats);
stats.pickRate = (!totalPlaysByRank[rankKey] || !operator.statsAllRanks.totalPlays || !totalPlaysAllRanks) ? 0 :
(stats.totalPlays / totalPlaysByRank[rankKey]) / (operator.statsAllRanks.totalPlays / totalPlaysAllRanks) * operator.statsAllRanks.pickRate;
stats.pickRate = Math.min(0.99, Math.max(0.001, stats.pickRate));
}
});
};
var setTalliesForRank = function setTalliesForRank(stats) {
stats.killsPerDeath = (!stats.totalDeaths) ? 0 : stats.totalKills / stats.totalDeaths;
stats.killsPerRound = (!stats.totalPlays) ? 0 : stats.totalKills / stats.totalPlays;
stats.survivalRate = (!stats.totalPlays) ? 0 : (stats.totalPlays - stats.totalDeaths) / stats.totalPlays;
stats.winRate = (!stats.totalPlays) ? 0 : stats.totalWins / stats.totalPlays;
};
var setWarnings = function setWarnings(opRoleStats) {
for (var opKey in opRoleStats) {
if (opRoleStats[opKey].statsAllRanks.totalPlays < WARNING_THRESHOLD) {
opRoleStats[opKey].statsAllRanks.warning = true;
}
for (var rankKey in opRoleStats[opKey].statsByRank) {
if (opRoleStats[opKey].statsByRank[rankKey].totalPlays < WARNING_THRESHOLD) {
opRoleStats[opKey].statsByRank[rankKey].warning = true;
}
}
}
};
var trySort = function trySort(sortField, isDescending, optionalRank) {
opStats.sortInfo.field = sortField || 'name';
opStats.sortInfo.rank = optionalRank;
opStats.sortInfo.isDescending = isDescending;
trySortRole(opStats.attackers.operators, sortField, isDescending, optionalRank);
trySortRole(opStats.defenders.operators, sortField, isDescending, optionalRank);
};
var trySortRole = function trySortRole(newOpStats, sortField, isDescending, optionalRank) {
newOpStats.sort(function(a, b) {
var aValue = a.name,
bValue = b.name,
nameCompare = true;
if (sortField != 'name') {
nameCompare = false;
if (!optionalRank) {
aValue = a.statsAllRanks[sortField];
bValue = b.statsAllRanks[sortField];
} else {
aValue = (a.statsByRank[optionalRank]) ? a.statsByRank[optionalRank][sortField] : -1;
bValue = (b.statsByRank[optionalRank]) ? b.statsByRank[optionalRank][sortField] : -1;
}
if (aValue == bValue) {
aValue = a.name;
bValue = b.name;
nameCompare = true;
}
}
if (nameCompare) {
if (aValue > bValue) {
return 1;
}
if (aValue < bValue) {
return -1;
}
} else {
if (aValue < bValue) {
return 1;
}
if (aValue > bValue) {
return -1;
}
}
return 0;
});
if (isDescending) {
newOpStats.reverse();
}
};
return {
get: getCurrentStats,
set: set,
trySort: trySort
};
})(R6MLangTerms);
|
var React = require('react');
var Router = require('react-router');
var whenKeys = require('when/keys');
var EventEmitter = require('events').EventEmitter;
var { Route, DefaultRoute, RouteHandler, Link } = Router;
var API = 'http://addressbook-api.herokuapp.com';
var loadingEvents = new EventEmitter();
function getJSON(url) {
if (getJSON._cache[url])
return Promise.resolve(getJSON._cache[url]);
return new Promise((resolve, reject) => {
var req = new XMLHttpRequest();
req.onload = function () {
if (req.status === 404) {
reject(new Error('not found'));
} else {
// fake a slow response every now and then
setTimeout(function () {
var data = JSON.parse(req.response);
resolve(data);
getJSON._cache[url] = data;
}, Math.random() > 0.5 ? 0 : 1000);
}
};
req.open('GET', url);
req.send();
});
}
getJSON._cache = {};
var App = React.createClass({
statics: {
fetchData (params) {
return getJSON(`${API}/contacts`).then((res) => res.contacts);
}
},
getInitialState () {
return { loading: false };
},
componentDidMount () {
var timer;
loadingEvents.on('loadStart', () => {
clearTimeout(timer);
// for slow responses, indicate the app is thinking
// otherwise its fast enough to just wait for the
// data to load
timer = setTimeout(() => {
this.setState({ loading: true });
}, 300);
});
loadingEvents.on('loadEnd', () => {
clearTimeout(timer);
this.setState({ loading: false });
});
},
renderContacts () {
return this.props.data.contacts.map((contact) => {
return (
<li>
<Link to="contact" params={contact}>{contact.first} {contact.last}</Link>
</li>
);
});
},
render () {
return (
<div className={this.state.loading ? 'loading' : ''}>
<ul>
{this.renderContacts()}
</ul>
<RouteHandler {...this.props}/>
</div>
);
}
});
var Contact = React.createClass({
statics: {
fetchData (params) {
return getJSON(`${API}/contacts/${params.id}`).then((res) => res.contact);
}
},
render () {
var { contact } = this.props.data;
return (
<div>
<p><Link to="contacts">Back</Link></p>
<h1>{contact.first} {contact.last}</h1>
<img key={contact.avatar} src={contact.avatar}/>
</div>
);
}
});
var Index = React.createClass({
render () {
return (
<div>
<h1>Welcome!</h1>
</div>
);
}
});
var routes = (
<Route name="contacts" path="/" handler={App}>
<DefaultRoute name="index" handler={Index}/>
<Route name="contact" path="contact/:id" handler={Contact}/>
</Route>
);
function fetchData(routes, params) {
return whenKeys.all(routes.filter((route) => {
return route.handler.fetchData;
}).reduce((data, route) => {
data[route.name] = route.handler.fetchData(params);
return data;
}, {}));
}
Router.run(routes, function (Handler, state) {
loadingEvents.emit('loadStart');
fetchData(state.routes, state.params).then((data) => {
loadingEvents.emit('loadEnd');
React.render(<Handler data={data}/>, document.getElementById('example'));
});
});
|
//= require ./core/monocle
//= require ./compat/env
//= require ./compat/css
//= require ./compat/stubs
//= require ./compat/browser
//= require ./compat/gala
//= require ./core/bookdata
//= require ./core/factory
//= require ./core/events
//= require ./core/styles
//= require ./core/formatting
//= require ./core/reader
//= require ./core/book
//= require ./core/place
//= require ./core/component
//= require ./core/selection
//= require ./core/billboard
//= require ./controls/panel
//= require ./panels/twopane
//= require ./panels/imode
//= require ./panels/eink
//= require ./panels/marginal
//= require ./panels/magic
//= require ./dimensions/columns
//= require ./flippers/slider
//= require ./flippers/scroller
//= require ./flippers/instant
|
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
const fs = jest.genMockFromModule('fs');
const mockFiles = new Map();
function __setMockFiles(newMockFiles) {
mockFiles.clear();
Object.keys(newMockFiles).forEach(fileName => {
mockFiles.set(fileName, newMockFiles[fileName]);
});
}
fs.__setMockFiles = __setMockFiles;
fs.readFileSync = jest.fn(file => mockFiles.get(file));
module.exports = fs;
|
'use strict';
module.exports = {
up: function(queryInterface, Sequelize) {
return queryInterface.createTable('Profiles', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
first_name: {
type: Sequelize.STRING
},
last_name: {
type: Sequelize.STRING
},
gender: {
type: Sequelize.STRING
},
age: {
type: Sequelize.INTEGER
},
country_origin: {
type: Sequelize.STRING
},
catch_phrase: {
type: Sequelize.STRING
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});
},
down: function(queryInterface, Sequelize) {
return queryInterface.dropTable('Profiles');
}
}; |
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactMixin = require('react-mixin');
var _reactMixin2 = _interopRequireDefault(_reactMixin);
var _mixins = require('./mixins');
var _utilsHexToRgb = require('../../utils/hexToRgb');
var _utilsHexToRgb2 = _interopRequireDefault(_utilsHexToRgb);
var styles = {
base: {
paddingTop: 3,
paddingBottom: 3,
paddingRight: 0,
marginLeft: 14
},
label: {
display: 'inline-block',
marginRight: 5
}
};
var JSONStringNode = (function (_React$Component) {
_inherits(JSONStringNode, _React$Component);
function JSONStringNode() {
_classCallCheck(this, _JSONStringNode);
_React$Component.apply(this, arguments);
}
JSONStringNode.prototype.render = function render() {
var backgroundColor = 'transparent';
if (this.props.previousValue !== this.props.value) {
var bgColor = _utilsHexToRgb2['default'](this.props.theme.base06);
backgroundColor = 'rgba(' + bgColor.r + ', ' + bgColor.g + ', ' + bgColor.b + ', 0.1)';
}
return _react2['default'].createElement(
'li',
{ style: _extends({}, styles.base, { backgroundColor: backgroundColor }), onClick: this.handleClick.bind(this) },
_react2['default'].createElement(
'label',
{ style: _extends({}, styles.label, {
color: this.props.theme.base0D
}) },
this.props.keyName,
':'
),
_react2['default'].createElement(
'span',
{ style: { color: this.props.theme.base0B } },
'"',
this.props.value,
'"'
)
);
};
var _JSONStringNode = JSONStringNode;
JSONStringNode = _reactMixin2['default'].decorate(_mixins.SquashClickEventMixin)(JSONStringNode) || JSONStringNode;
return JSONStringNode;
})(_react2['default'].Component);
exports['default'] = JSONStringNode;
module.exports = exports['default']; |
import falcor from 'falcor';
import _ from 'lodash';
import * as db from 'lib/db';
import { has } from 'lib/utilities';
const $ref = falcor.Model.ref;
export default [
{
// get featured article
route: "issues['byNumber'][{integers:issueNumbers}]['featured']",
get: pathSet =>
new Promise(resolve => {
db.featuredArticleQuery(pathSet.issueNumbers).then(data => {
const results = [];
data.forEach(row => {
results.push({
path: ['issues', 'byNumber', row.issue_number, 'featured'],
value: $ref(['articles', 'bySlug', row.slug]),
});
});
resolve(results);
});
}),
},
{
// get editor's picks
route:
"issues['byNumber'][{integers:issueNumbers}]['picks'][{integers:indices}]",
get: pathSet =>
new Promise(resolve => {
db.editorPickQuery(pathSet.issueNumbers).then(data => {
const results = [];
_.forEach(data, (postSlugArray, issueNumber) => {
pathSet.indices.forEach(index => {
if (index < postSlugArray.length) {
results.push({
path: ['issues', 'byNumber', issueNumber, 'picks', index],
value: $ref(['articles', 'bySlug', postSlugArray[index]]),
});
}
});
});
resolve(results);
});
}),
},
{
// Get articles category information from articles.
/* This is a special case as it actually makes us store a bit of information twice
But we can't just give a ref here since because the articles of a category is different
depending on whether it is fetched directly from categories which is ordered chronologically
and all articles from that category are fetched or from an issue where it is ordered by
editor tools */
route:
"issues['byNumber'][{integers:issueNumbers}]['categories'][{integers:indices}]['id', 'name', 'slug']", // eslint-disable-line max-len
get: pathSet =>
new Promise(resolve => {
const requestedFields = pathSet[5];
db.issueCategoryQuery(pathSet.issueNumbers, requestedFields).then(
data => {
// data is an object with keys of issue numbers and values
// arrays of category objects in correct order as given in editor tools
const results = [];
_.forEach(data, (categorySlugArray, issueNumber) => {
pathSet.indices.forEach(index => {
if (index < categorySlugArray.length) {
requestedFields.forEach(field => {
results.push({
path: [
'issues',
'byNumber',
issueNumber,
'categories',
index,
field,
],
value: categorySlugArray[index][field],
});
});
}
});
});
resolve(results);
},
);
}),
},
{
// Get articles within issue categories
route:
"issues['byNumber'][{integers:issueNumbers}]['categories'][{integers:categoryIndices}]['articles'][{integers:articleIndices}]", // eslint-disable-line max-len
get: pathSet =>
// This will currently fetch every single article from the issue
// every time, and then just only return the ones asked for
// which shouldn't at all be a problem at current capacity of
// 10-20 articles an issue.
new Promise(resolve => {
db.issueCategoryArticleQuery(pathSet.issueNumbers).then(data => {
// data is an object with keys equal to issueNumbers and values
// being an array of arrays, the upper array being the categories
// in their given order, and the lower level array within each category
// is article slugs also in their given order.
const results = [];
_.forEach(data, (categoryArray, issueNumber) => {
pathSet.categoryIndices.forEach(categoryIndex => {
if (categoryIndex < categoryArray.length) {
pathSet.articleIndices.forEach(articleIndex => {
if (articleIndex < categoryArray[categoryIndex].length) {
results.push({
path: [
'issues',
'byNumber',
issueNumber,
'categories',
categoryIndex,
'articles',
articleIndex,
],
value: $ref([
'articles',
'bySlug',
categoryArray[categoryIndex][articleIndex],
]),
});
}
});
}
});
});
resolve(results);
});
}),
},
{
// Get issue data
// eslint-disable-next-line max-len
route:
"issues['byNumber'][{integers:issueNumbers}]['id', 'published_at', 'name', 'issueNumber']",
get: pathSet => {
const mapFields = field => {
switch (field) {
case 'issueNumber':
return 'issue_number';
default:
return field;
}
};
return new Promise(resolve => {
const requestedFields = pathSet[3];
const dbColumns = requestedFields.map(mapFields);
db.issueQuery(pathSet.issueNumbers, dbColumns).then(data => {
const results = [];
data.forEach(issue => {
// Convert Date object to time integer
const processedIssue = { ...issue };
if (
has.call(processedIssue, 'published_at') &&
processedIssue.published_at instanceof Date
) {
processedIssue.published_at = processedIssue.published_at.getTime();
}
requestedFields.forEach(field => {
results.push({
path: [
'issues',
'byNumber',
processedIssue.issue_number,
field,
],
value: processedIssue[mapFields(field)],
});
});
});
resolve(results);
});
});
},
set: jsonGraphArg =>
new Promise(resolve => {
const issueNumber = Object.keys(jsonGraphArg.issues.byNumber)[0];
const issueObject = jsonGraphArg.issues.byNumber[issueNumber];
const results = [];
db.updateIssueData(jsonGraphArg).then(flag => {
if (flag !== true) {
throw new Error('Error while updating issue data');
}
_.forEach(issueObject, (value, field) => {
results.push({
path: ['issues', 'byNumber', parseInt(issueNumber, 10), field],
value,
});
});
results.push({
path: ['issues', 'latest'],
invalidated: true,
});
resolve(results);
});
}),
},
{
route: "issues['byNumber']['updateIssueArticles']",
call: (callPath, args) =>
new Promise(resolve => {
const issueNumber = args[0];
const featuredArticles = args[1];
const picks = args[2];
const mainArticles = args[3];
db.updateIssueArticles(
issueNumber,
featuredArticles,
picks,
mainArticles,
).then(data => {
let results = [];
const toAdd = data.data;
const toInvalidate = data.invalidated;
// Build the return array from the structure we know it returns
// from db.js
if (toInvalidate) {
results = results.concat(toInvalidate);
}
if (has.call(toAdd, 'featured')) {
results.push(toAdd.featured);
}
if (has.call(toAdd, 'picks')) {
results = results.concat(toAdd.picks);
}
if (has.call(toAdd, 'categories')) {
_.forEach(toAdd.categories, (category, key) => {
results.push({
path: [
'issues',
'byNumber',
issueNumber,
'categories',
key,
'name',
],
value: category.name,
});
results.push({
path: [
'issues',
'byNumber',
issueNumber,
'categories',
key,
'slug',
],
value: category.slug,
});
results = results.concat(category.articles);
});
}
if (has.call(toAdd, 'published')) {
results = results.concat(toAdd.published);
}
resolve(results);
});
}),
},
{
route:
"issues['byNumber'][{integers:issueNumbers}]['updateIssueCategories']",
call: (callPath, args) =>
new Promise(resolve => {
const issueNumber = callPath.issueNumbers[0];
const idArray = args[0];
db.updateIssueCategories(issueNumber, idArray).then(flag => {
if (flag !== true) {
throw new Error('updateIssueCategories returned non-true flag');
}
const results = [
{
path: ['placeholder'],
value: 'placeholder',
},
{
path: ['issues', 'byNumber', issueNumber, 'categories'],
invalidated: true,
},
];
resolve(results);
});
}),
},
{
route: "issues['byNumber'][{integers:issueNumbers}]['publishIssue']",
call: (callPath, args) =>
new Promise(resolve => {
const issueId = args[0];
const issueNumber = callPath.issueNumbers[0];
db.publishIssue(issueId).then(data => {
const results = [];
const publishTime = data.date.getTime();
results.push({
path: ['issues', 'byNumber', issueNumber, 'published_at'],
value: publishTime,
});
data.publishedArticles.forEach(slug => {
results.push({
path: ['articles', 'bySlug', slug, 'published_at'],
value: publishTime,
});
});
resolve(results);
});
}),
},
{
route: "issues['byNumber']['addIssue']",
call: (callPath, args) =>
new Promise((resolve, reject) => {
const issue = args[0];
verifyIssue(issue);
const fields = Object.keys(issue);
db.addIssue(issue)
.then(flag => {
if (flag !== true) {
throw new Error(
'For some reason addIssue db function returned a non-true flag',
);
}
const results = [];
fields.forEach(field => {
results.push({
path: ['issues', 'byNumber', issue.issue_number, field],
value: issue[field],
});
});
results.push({
path: ['issues', 'latest'],
invalidated: true,
});
resolve(results);
})
.catch(reject);
}),
},
];
function verifyIssue(issue) {
const requiredFields = ['name', 'issue_number'];
const optionalFields = ['published_at'];
requiredFields.every(field => {
if (!has.call(issue, field)) {
throw new Error(`Required field ${field} was not present`);
}
return true;
});
const allFields = requiredFields.concat(optionalFields);
Object.keys(issue).every(issueField => {
if (!allFields.includes(issueField)) {
throw new Error(`Unknown field ${issueField} was found on issue`);
}
return true;
});
}
|
import React, {PropTypes} from 'react'
import styles from './Form.css'
export default React.createClass({
propTypes: {
username: PropTypes.string.isRequired,
onLogout: PropTypes.func
},
render() {
return (
<div className={styles.forms}>
<section>
<label>当前用户:</label>
<input type="text" value={this.props.username} readOnly />
</section>
<section>
<button
onClick={this.props.onLogout}
className={`${styles.btn} ${styles.btnBorderOpen} ${styles.btnPurple}`}
>
注销
</button>
</section>
</div>
)
}
})
|
(function() {
'use strict';
angular
.module('echarliApp')
.factory('Activate', Activate);
Activate.$inject = ['$resource'];
function Activate ($resource) {
var service = $resource('api/activate', {}, {
'get': { method: 'GET', params: {}, isArray: false}
});
return service;
}
})();
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M22 11h-5V6h-3v5h-4V3H7v8H1.84v2H7v8h3v-8h4v5h3v-5h5z"
}), 'AlignVerticalCenterOutlined');
exports.default = _default; |
// conf.js
exports.config = {
seleniumServerJar: "./node_modules/protractor/selenium/selenium-server-standalone-2.45.0.jar",
specs: ["test/e2e/*.scenarios.coffee"],
baseUrl: "http://localhost:3000",
capabilities: {
"browserName": "chrome"
},
framework: "mocha"
}
|
/* Magic Mirror
* Log
*
* This logger is very simple, but needs to be extended.
* This system can eventually be used to push the log messages to an external target.
*
* By Michael Teeuw https://michaelteeuw.nl
* MIT Licensed.
*/
(function (root, factory) {
if (typeof exports === "object") {
if (process.env.JEST_WORKER_ID === undefined) {
// add timestamps in front of log messages
require("console-stamp")(console, {
pattern: "yyyy-mm-dd HH:MM:ss.l",
include: ["debug", "log", "info", "warn", "error"]
});
}
// Node, CommonJS-like
module.exports = factory(root.config);
} else {
// Browser globals (root is window)
root.Log = factory(root.config);
}
})(this, function (config) {
let logLevel;
let enableLog;
if (typeof exports === "object") {
// in nodejs and not running with jest
enableLog = process.env.JEST_WORKER_ID === undefined;
} else {
// in browser and not running with jsdom
enableLog = typeof window === "object" && window.name !== "jsdom";
}
if (enableLog) {
logLevel = {
debug: Function.prototype.bind.call(console.debug, console),
log: Function.prototype.bind.call(console.log, console),
info: Function.prototype.bind.call(console.info, console),
warn: Function.prototype.bind.call(console.warn, console),
error: Function.prototype.bind.call(console.error, console),
group: Function.prototype.bind.call(console.group, console),
groupCollapsed: Function.prototype.bind.call(console.groupCollapsed, console),
groupEnd: Function.prototype.bind.call(console.groupEnd, console),
time: Function.prototype.bind.call(console.time, console),
timeEnd: Function.prototype.bind.call(console.timeEnd, console),
timeStamp: Function.prototype.bind.call(console.timeStamp, console)
};
logLevel.setLogLevel = function (newLevel) {
if (newLevel) {
Object.keys(logLevel).forEach(function (key, index) {
if (!newLevel.includes(key.toLocaleUpperCase())) {
logLevel[key] = function () {};
}
});
}
};
} else {
logLevel = {
debug: function () {},
log: function () {},
info: function () {},
warn: function () {},
error: function () {},
group: function () {},
groupCollapsed: function () {},
groupEnd: function () {},
time: function () {},
timeEnd: function () {},
timeStamp: function () {}
};
logLevel.setLogLevel = function () {};
}
return logLevel;
});
|
/**
* Dummy file for grunt-nodemon to run node-inspector task
*/
|
'use strict';
var a = 0;
var b = 1;
var x = a;
var y = b;
console.log( x + y ); |
module.exports={A:{A:{"2":"H D G E A B EB"},B:{"2":"C p x J L N I"},C:{"2":"0 1 2 3 4 5 6 8 9 YB BB F K H D G E A B C p x J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y WB QB"},D:{"1":"0 1 2 3 4 5 6 8 9 J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w y KB aB FB a GB HB IB","16":"F K H D G E A B C p x"},E:{"1":"H D G E A B C LB MB NB OB PB z RB","16":"F K JB CB"},F:{"1":"0 J L N I O P Q R S T U V W X Y Z b c d e f g h i j k l m n o M q r s t u v w","2":"7 E B C SB TB UB VB z AB XB"},G:{"1":"G bB cB dB eB fB gB hB iB jB kB","16":"CB ZB DB"},H:{"2":"lB"},I:{"1":"BB F a oB pB DB qB rB","16":"mB nB"},J:{"1":"D A"},K:{"1":"M","2":"7 A B C z AB"},L:{"1":"a"},M:{"2":"y"},N:{"2":"A B"},O:{"1":"sB"},P:{"1":"F K tB"},Q:{"1":"uB"},R:{"1":"vB"}},B:7,C:"Element.scrollIntoViewIfNeeded()"};
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S12.10_A1.4_T4;
* @section: 12.10;
* @assertion: The with statement adds a computed object to the front of the
* scope chain of the current execution context;
* @description: Using "with" statement within iteration statement, leading to completion by break;
* @strict_mode_negative
*/
this.p1 = 1;
this.p2 = 2;
this.p3 = 3;
var result = "result";
var myObj = {p1: 'a',
p2: 'b',
p3: 'c',
value: 'myObj_value',
valueOf : function(){return 'obj_valueOf';},
parseInt : function(){return 'obj_parseInt';},
NaN : 'obj_NaN',
Infinity : 'obj_Infinity',
eval : function(){return 'obj_eval';},
parseFloat : function(){return 'obj_parseFloat';},
isNaN : function(){return 'obj_isNaN';},
isFinite : function(){return 'obj_isFinite';}
}
var del;
var st_p1 = "p1";
var st_p2 = "p2";
var st_p3 = "p3";
var st_parseInt = "parseInt";
var st_NaN = "NaN";
var st_Infinity = "Infinity";
var st_eval = "eval";
var st_parseFloat = "parseFloat";
var st_isNaN = "isNaN";
var st_isFinite = "isFinite";
do{
with(myObj){
st_p1 = p1;
st_p2 = p2;
st_p3 = p3;
st_parseInt = parseInt;
st_NaN = NaN;
st_Infinity = Infinity;
st_eval = eval;
st_parseFloat = parseFloat;
st_isNaN = isNaN;
st_isFinite = isFinite;
p1 = 'x1';
this.p2 = 'x2';
del = delete p3;
var p4 = 'x4';
p5 = 'x5';
var value = 'value';
break;
}
}
while(false);
if(!(p1 === 1)){
$ERROR('#1: p1 === 1. Actual: p1 ==='+ p1 );
}
if(!(p2 === "x2")){
$ERROR('#2: p2 === "x2". Actual: p2 ==='+ p2 );
}
if(!(p3 === 3)){
$ERROR('#3: p3 === 3. Actual: p3 ==='+ p3 );
}
if(!(p4 === "x4")){
$ERROR('#4: p4 === "x4". Actual: p4 ==='+ p4 );
}
if(!(p5 === "x5")){
$ERROR('#5: p5 === "x5". Actual: p5 ==='+ p5 );
}
if(!(myObj.p1 === "x1")){
$ERROR('#6: myObj.p1 === "x1". Actual: myObj.p1 ==='+ myObj.p1 );
}
if(!(myObj.p2 === "b")){
$ERROR('#7: myObj.p2 === "b". Actual: myObj.p2 ==='+ myObj.p2 );
}
if(!(myObj.p3 === undefined)){
$ERROR('#8: myObj.p3 === undefined. Actual: myObj.p3 ==='+ myObj.p3 );
}
if(!(myObj.p4 === undefined)){
$ERROR('#9: myObj.p4 === undefined. Actual: myObj.p4 ==='+ myObj.p4 );
}
if(!(myObj.p5 === undefined)){
$ERROR('#10: myObj.p5 === undefined. Actual: myObj.p5 ==='+ myObj.p5 );
}
if(!(st_parseInt !== parseInt)){
$ERROR('#11: myObj.parseInt !== parseInt');
}
if(!(st_NaN === "obj_NaN")){
$ERROR('#12: myObj.NaN !== NaN');
}
if(!(st_Infinity !== Infinity)){
$ERROR('#13: myObj.Infinity !== Infinity');
}
if(!(st_eval !== eval)){
$ERROR('#14: myObj.eval !== eval');
}
if(!(st_parseFloat !== parseFloat)){
$ERROR('#15: myObj.parseFloat !== parseFloat');
}
if(!(st_isNaN !== isNaN)){
$ERROR('#16: myObj.isNaN !== isNaN');
}
if(!(st_isFinite !== isFinite)){
$ERROR('#17: myObj.isFinite !== isFinite');
}
if(!(value === undefined)){
$ERROR('#18: value === undefined. Actual: value ==='+ value );
}
if(!(myObj.value === "value")){
$ERROR('#19: myObj.value === "value". Actual: myObj.value ==='+ myObj.value );
}
|
frappe.ui.form.ControlCurrency = frappe.ui.form.ControlFloat.extend({
format_for_input: function(value) {
var formatted_value = format_number(value, this.get_number_format(), this.get_precision());
return isNaN(parseFloat(value)) ? "" : formatted_value;
},
get_precision: function() {
// always round based on field precision or currency's precision
// this method is also called in this.parse()
if (!this.df.precision) {
if(frappe.boot.sysdefaults.currency_precision) {
this.df.precision = frappe.boot.sysdefaults.currency_precision;
} else {
this.df.precision = get_number_format_info(this.get_number_format()).precision;
}
}
return this.df.precision;
}
});
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M19 5c0-1.1-.9-2-2-2h-6.17c-.53 0-1.04.21-1.42.59L7.95 5.06 19 16.11V5zM3.09 4.44c-.39.39-.39 1.02 0 1.41L5 7.78V19c0 1.11.9 2 2 2h11.23l.91.91c.39.39 1.02.39 1.41 0 .39-.39.39-1.02 0-1.41L4.5 4.44a.9959.9959 0 0 0-1.41 0z"
}), 'SignalCellularNoSimRounded');
exports.default = _default; |
describe('ngThrottleSpec', function() {
var $animate, body, $rootElement, $throttle, $timeout;
beforeEach(module('material.services.throttle', 'material.animations'));
beforeEach(inject(function(_$throttle_, _$timeout_, _$animate_, _$rootElement_, $document ){
$throttle = _$throttle_;
$timeout = _$timeout_;
$animate = _$animate_;
$rootElement = _$rootElement_;
body = angular.element($document[0].body);
body.append($rootElement);
}));
describe('use $throttle with no configurations', function() {
var finished, started, ended;
var done = function() { finished = true; };
beforeEach( function() { finished = started = ended = false; });
it("should start and end without configuration",function() {
var process = $throttle()( done );
$timeout.flush();
expect(finished).toBe(true);
});
it("should run process function without throttle configuration",function() {
var process = $throttle()( done );
process("a");
$timeout.flush();
expect(finished).toBe(true);
});
it("should start and end with `done` callbacks",function() {
var startFn = function(done){ started = true; done(); };
var process = $throttle({start:startFn})( done );
expect(process).toBeDefined();
expect(started).toBe(false);
$timeout.flush(); // flush start()
expect(started).toBe(true);
expect(finished).toBe(true);
});
it("should start and end withOUT `done` callbacks",function() {
var startFn = function(){ started = true; };
var endFn = function(){ ended = true; };
var process = $throttle({start:startFn, end:endFn})( done );
$timeout.flush(); // throttle()
expect(started).toBe(true);
expect(ended).toBe(true);
expect(finished).toBe(true);
});
it("should start without throttle or end calls specified",function() {
var startFn = function(){ started = true; };
var throttledFn = $throttle({start:startFn})();
$timeout.flush();
expect(started).toBe(true);
});
it("should start but NOT end if throttle does not complete",function() {
var startFn = function(){ started = true;},
endFn = function(){ ended = true;};
lockFn = function(done){ ; }, // do not callback for completion
$throttle({start:startFn, throttle:lockFn, end:endFn})();
$timeout.flush();
expect(started).toBe(true);
expect(ended).toBe(false);
});
});
describe('use $throttle with synchronous processing', function() {
it("should process n-times correctly",function() {
var wanted="The Hulk";
var sCount=0, title="",
startFn = function(){
sCount++;
},
processFn = function(text, done){
title += text;
if ( title == wanted ) {
// Conditional termination of throttle phase
done();
}
};
concat = $throttle({start:startFn, throttle:processFn})( );
concat("The ");
concat("Hulk");
$timeout.flush();
expect(title).toBe(wanted);
});
it("should properly process with report callbacks",function() {
var pCount= 10, total, callCount= 0,
processFn = function(count, done){
pCount -= count;
if ( pCount == 5 ) {
// Conditional termination of throttle phase
// report total value in callback
done(pCount);
}
},
/**
* only called when ALL processing is done
*/
reportFn = function(count){ total = count; callCount +=1;},
subtract = $throttle({throttle:processFn})( );
subtract(2, reportFn );
subtract(3, reportFn );
$timeout.flush();
expect(total).toBe(5);
expect(callCount).toBe(1);
});
it("should restart if already finished",function() {
var total= 0, started = 0,
startFn = function(){
started += 1;
},
processFn = function(count, done){
total += count;
done(); // !!finish throttling
},
add = $throttle({start:startFn, throttle:processFn})();
add(1); $timeout.flush(); // proceed to end()
add(1); $timeout.flush(); // proceed to end()
add(1); $timeout.flush(); // proceed to end()
expect(total).toBe(3);
expect(started).toBe(3); // restarted 1x
});
});
describe('use $throttle with exceptions', function() {
it("should report error within start()", function() {
var started = false;
var error = "";
var fn = $throttle({start:function(done){
started = true;
throw new Error("fault_with_start");
}})(null, function(fault){
error = fault;
});
$timeout.flush();
expect(started).toBe(true);
expect(error).toNotBe("");
});
it("should report error within end()", function() {
var ended = false, error = "";
var config = { end : function(done){
ended = true;
throw new Error("fault_with_end");
}};
var captureError = function(fault) { error = fault; };
$throttle(config)(null, captureError );
$timeout.flush();
expect(ended).toBe(true);
expect(error).toNotBe("");
});
it("should report error within throttle()", function() {
var count = 0, error = "";
var config = { throttle : function(done){
count += 1;
switch(count)
{
case 1 : break;
case 2 : throw new Error("fault_with_throttle"); break;
case 3 : done(); break;
}
}};
var captureError = function(fault) { error = fault; };
var fn = $throttle(config)(null, captureError );
$timeout.flush();
fn( 1 );
fn( 2 );
fn( 3 );
expect(count).toBe(2);
expect(error).toNotBe("");
});
});
describe('use $throttle with async processing', function() {
var finished = false;
var done = function() { finished = true; };
beforeEach( function() { finished = false; });
it("should pass with async start()",function() {
var sCount=0,
startFn = function(){
return $timeout(function(){
sCount++;
},100)
},
concat = $throttle({start:startFn})( done );
concat("The ");
concat("Hulk");
$timeout.flush();
expect(sCount).toBe(1);
});
it("should pass with async start(done)",function() {
var sCount=0,
startFn = function(done){
return $timeout(function(){
sCount++;
done();
},100)
},
concat = $throttle({start:startFn})( done );
concat("The ");
concat("Hulk");
$timeout.flush(); // flush to begin 1st deferred start()
expect(sCount).toBe(1);
});
it("should pass with async start(done) and end(done)",function() {
var sCount=3, eCount= 0,
startFn = function(done){
return $timeout(function(){
sCount--;
done();
},100)
},
endFn = function(done){
return $timeout(function(){
eCount++;
done();
},100)
};
$throttle({start:startFn, end:endFn})( done );
$timeout.flush(); // flush to begin 1st deferred start()
$timeout.flush(); // start()
$timeout.flush(); // end()
expect(sCount).toBe(2);
expect(eCount).toBe(1);
expect(finished).toBe(true);
});
it("should pass with async start(done) and process(done)",function() {
var title="",
startFn = function(){
return $timeout(function(){
done();
},200);
},
processFn = function(data, done){
$timeout(function(){
title += data;
},400);
},
concat = $throttle({start:startFn, throttle:processFn})( done );
$timeout.flush(); // start()
concat("The "); $timeout.flush(); // throttle(1)
concat("Hulk"); $timeout.flush(); // throttle(2)
expect(title).toBe("The Hulk");
});
it("should pass with async process(done) and restart with cancellable end",function() {
var content="", numStarts= 0, numEnds = 0,
startFn = function(done){
numStarts++;
done("start-done");
},
throttleFn = function(data, done){
$timeout(function(){
content += data;
if ( data == "e" ) {
done("throttle-done");
}
},400);
},
endFn = function(done){
numEnds++;
var procID = $timeout(function(){
done("end-done");
},500,false);
return function() {
$timeout.cancel( procID );
};
},
concat = $throttle({ start:startFn, throttle:throttleFn, end:endFn })( done );
$timeout.flush(); // flush to begin 1st start()
concat("a"); // Build string...
concat("b");
concat("c");
concat("d");
concat("e"); // forces end()
$timeout.flush(); // flush to throttle( 5x )
$timeout(function(){
concat("a"); // forces restart()
concat("e"); // forces end()
},400,false);
$timeout.flush(); // flush() 278
$timeout.flush(); // flush to throttle( 2x )
expect(content).toBe("abcdeae");
expect(numStarts).toBe(2);
expect(numEnds).toBe(2);
});
});
describe('use $throttle with inkRipple', function(){
var finished, started, ended;
var done = function() { finished = true; };
beforeEach( function() { finished = started = ended = false; });
function setup() {
var el;
var tmpl = '' +
'<div style="width:50px; height:50px;">'+
'<canvas class="material-ink-ripple" ></canvas>' +
'</div>';
inject(function($compile, $rootScope) {
el = $compile(tmpl)($rootScope);
$rootElement.append( el );
$rootScope.$apply();
});
return el;
}
it('should start, animate, and end.', inject(function($compile, $rootScope, $materialEffects) {
var cntr = setup(),
canvas = cntr.find('canvas'),
rippler, makeRipple, throttled = 0,
config = {
start : function() {
rippler = rippler || $materialEffects.inkRipple( canvas[0] );
cntr.on('mousedown', makeRipple);
started = true;
},
throttle : function(e, done) {
throttled += 1;
switch(e.type)
{
case 'mousedown' :
rippler.createAt( {x:25,y:25} );
rippler.draw( done );
break;
default:
break;
}
}
}
// prepare rippler wave function...
makeRipple = $throttle(config)(done);
$timeout.flush();
expect(started).toBe(true);
// trigger wave animation...
cntr.triggerHandler("mousedown");
// Allow animation to finish...
$timeout(function(){
expect(throttled).toBe(1);
expect(ended).toBe(true);
expect(finished).toBe(true);
},10);
// Remove from $rootElement
cntr.remove();
}));
});
});
|
//Libraries
const React = require("react");
const _ = require("lodash");
const DataActions = require("../actions/data_actions");
const DataStore = require("../stores/data_store");
const FilterStore = require("../stores/filter_store");
const ColumnsStore = require("../stores/columns_store");
//Mixins
const cssMixins = require("morse-react-mixins").css_mixins;
const textMixins = require("morse-react-mixins").text_mixins;
class SearchFilters extends React.Component{
constructor(props) {
super(props);
this.dropdown = ["input-group-btn", {"open":false}];
this.state = {
dropdown:this.getClasses(this.dropdown),
expanded:"false",
selectedkey:"all",
searchVal:""
};
}
componentDidMount() {
this.quickSearch = (_.isBoolean(this.props.quickSearch)) ? this.props.quickSearch : true;
if(FilterStore.isSelectedKey(this.props.item)){
this.active = [{active:true}];
this.setState({active:this.getClasses(this.active)});
}
this.setState({searchVal:DataStore.getSearchVal()});
// FilterStore.addChangeListener("change_key", this._openDropdown.bind(this));
ColumnsStore.addChangeListener("adding", this._onAdd.bind(this));
}
componentWillUnmount() {
// FilterStore.removeChangeListener("change_key", this._openDropdown);
ColumnsStore.removeChangeListener("adding", this._onAdd);
}
_onAdd(){
this.setState({
keys:ColumnsStore.getSearchable()
});
}
_onChange(e){
if(this.quickSearch){
if(this.loop){
window.clearTimeout(this.loop);
}
this.loop = window.setTimeout((val)=>{
if(val.length > 2 || val === ""){
DataActions.searching(val);
}
}, 200, e.target.value);
this.setState({searchVal:e.target.value});
}
// _.defer((val)=>{
// DataActions.searching(val);
// }, e.target.value);
}
// _openDropdown(){
// this.dropdown = this.toggleCss(this.dropdown);
// let expanded = (this.state.expended === "true") ? "false" : "true";
// this.setState({
// dropdown:this.getClasses(this.dropdown),
// expanded:expanded,
// selectedkey:FilterStore.getSelectedKey()
// });
// }
_preventSubmit(e){
// console.log("submiting", e);
e.preventDefault();
}
// renderKeys(){
// if(this.state.keys){
// let items = this.state.keys.map(function(k){
// return (<Keys item={k} key={_.uniqueId("key")} />);
// });
// return items;
// }
// }
render() {
return (
<form onSubmit={this._preventSubmit.bind(this)} className="search-filter">
<input alt="Search" type="image" src={this.props.icon} />
<div className="fields-container">
<input type="text" name="querystr" id="querystr" placeholder="Search" value={this.state.searchVal} onChange={this._onChange.bind(this)} />
</div>
</form>
);
}
}
Object.assign(SearchFilters.prototype, cssMixins);
Object.assign(SearchFilters.prototype, textMixins);
module.exports = SearchFilters;
|
/* State
* @class
* @classdesc This class reprensent an automata state, a sub-type of a generic Node */
k.data.State = (function(_super)
{
'use strict';
/* jshint latedef:false */
k.utils.obj.inherit(state, _super);
/*
* Constructor Automata State
*
* @constructor
* @param {[ItemRule]} options.items Array of item rules that initialy compone this state
* @param {[Object]} options.transitions Array of object that initialy compone this node
* @param {[Node]} options.nodes Array of State instances that are children of this State
*/
function state (options) {
_super.apply(this, arguments);
k.utils.obj.defineProperty(this, 'isAcceptanceState'); // This is set by the automata generator
k.utils.obj.defineProperty(this, '_items');
k.utils.obj.defineProperty(this, '_registerItems');
k.utils.obj.defineProperty(this, '_condencedView');
k.utils.obj.defineProperty(this, '_unprocessedItems');
this.isAcceptanceState = false;
this._items = options.items || [];
this._unprocessedItems = this._items.length ? k.utils.obj.shallowClone(this._items) : [];
options.items = null;
this._registerItems = {};
this._registerItemRules();
}
/* @method REgister the list of item rules of the current stateso they are assesible by its id
* @returns {Void} */
state.prototype._registerItemRules = function ()
{
k.utils.obj.each(this._items, function (itemRule)
{
this._registerItems[itemRule.getIdentity()] = itemRule;
}, this);
};
state.constants = {
AcceptanceStateName: 'AcceptanceState'
};
/* @method Get the next unprocessed item rule
* @returns {ItemRule} Next Item Rule */
state.prototype.getNextItem = function() {
return this._unprocessedItems.splice(0,1)[0];
};
/* @method Adds an array of item rule into the state. Only the rules that are not already present in the state will be added
* @param {[ItemRule]} itemRules Array of item rules to add into the state
* @param {Boolean} options.notMergeLookAhead If specified as true does not marge the lookAhead of the already existing items. Default: falsy
* @returns {void} Nothing */
state.prototype.addItems = function(itemRules, options) {
this._id = null;
k.utils.obj.each(itemRules, function (itemRule)
{
// The same item rule can be added more than once if the grammar has loops.
// For sample: (1)S -> A *EXPS B (2)EXPS -> *EXPS
if (!this._registerItems[itemRule.getIdentity()])
{
this._registerItems[itemRule.getIdentity()] = itemRule;
this._items.push(itemRule);
this._unprocessedItems.push(itemRule);
}
else if (!options || !options.notMergeLookAhead)
{
//As a way of generating a LALR(1) automata adds a item rule for each lookAhead we simply merge its lookAheads
var original_itemRule = this._registerItems[itemRule.getIdentity()];
if (itemRule.lookAhead && itemRule.lookAhead.length)
{
original_itemRule.lookAhead = original_itemRule.lookAhead || [];
itemRule.lookAhead = itemRule.lookAhead || [];
var mergedLookAheads = original_itemRule.lookAhead.concat(itemRule.lookAhead),
original_itemRule_lookAhead_length = this._registerItems[itemRule.getIdentity()].lookAhead.length;
this._registerItems[itemRule.getIdentity()].lookAhead = k.utils.obj.uniq(mergedLookAheads, function (item) { return item.name;});
var is_item_already_queued = k.utils.obj.filter(this._unprocessedItems, function (unprocessed_item)
{
return unprocessed_item.getIdentity() === itemRule.getIdentity();
}).length > 0;
//If there were changes in the lookAhead and the rule is not already queued.
if (original_itemRule_lookAhead_length !== this._registerItems[itemRule.getIdentity()].lookAhead.length && !is_item_already_queued)
{
this._unprocessedItems.push(itemRule);
}
}
}
}, this);
};
/* @method Convert the current state to its string representation
* @returns {String} formatted string */
state.prototype.toString = function() {
var strResult = 'ID: ' + this.getIdentity() + '\n' +
this._items.join('\n') +
'\nTRANSITIONS:\n';
k.utils.obj.each(this.transitions, function (transition)
{
strResult += '*--' + transition.symbol + '-->' + transition.state.getIdentity() + '\n';
});
return strResult;
};
/* @method Returns the condenced (one line) string that reprenset the current 'state' of the current state
* @returns {String} State Representation in one line */
state.prototype.getCondencedString = function() {
if(!this._condencedView)
{
this._condencedView = this._generateCondencedString();
}
return this._condencedView;
};
/* @method Internal method to generate a condenced (one line) string that reprenset the current 'state' of the current state
* @returns {String} State Representation in one line */
state.prototype._generateCondencedString = function() {
return k.utils.obj.map(
k.utils.obj.sortBy(this._items, function(item)
{
return item.rule.index;
}),
function (item) {
return item.rule.index;
}).join('-');
};
/* @method Generates an ID that identify this state from any other state
* @returns {String} Generated ID */
state.prototype._generateIdentity = function() {
if (this.isAcceptanceState)
{
return state.constants.AcceptanceStateName;
}
else if (!this._items.length)
{
return _super.prototype._generateIdentity.apply(this, arguments);
}
return k.utils.obj.reduce(
k.utils.obj.sortBy(this._items, function(item)
{
return item.rule.index;
}),
function (acc, item) {
return acc + item.getIdentity(); //.rule.index + '(' + item.dotLocation + ')';
}, '');
};
/* @method Returns a copy the items contained in the current state
* @returns {[ItemRule]} Array of cloned item rules */
state.prototype.getItems = function() {
return k.utils.obj.map(this._items, function(item) {
return item.clone();
});
};
/* @method Returns an orignal item rule based on its id.
This method is intended to be use as READ-ONLY, editing the returned items will affect the state and the rest of the automata at with this state belongs to.
* @returns {[ItemRule]} Array of current item rules */
state.prototype.getOriginalItems = function() {
return this._items;
};
/* @method Returns an orignal item rule based on its id.
This method is intended to be use as READ-ONLY, editing the returned items will affect the state and the rest of the automata at with this state belongs to.
* @returns {ItemRule} Item rule corresponding to the id passed in if present or null otherwise */
state.prototype.getOriginalItemById = function(id) {
return this._registerItems[id];
};
/** @method Get the list of all supported symbol which are valid to generata transition from the current state.
* @returns {[Object]} Array of object of the form: {symbol, items} where items have an array of item rules */
state.prototype.getSupportedTransitionSymbols = function() {
var itemsAux = {},
result = [],
symbol;
k.utils.obj.each(this._items, function (item)
{
symbol = item.getCurrentSymbol();
if (symbol)
{
if (itemsAux[symbol.name]) {
itemsAux[symbol.name].push(item);
}
else
{
itemsAux[symbol.name] = [item];
result.push({
symbol: symbol,
items: itemsAux[symbol.name]
});
}
}
});
return result;
};
/* @method Responsible of new transitions. We override this method to use the correct variable names and be more meanful
* @param {Symbol} symbol Symbol use to make the transition, like the name of the transition
* @param {State} state Destination state arrived when moving with the specified tranisiotn
* @returns {Object} Transition object */
state.prototype._generateNewTransition = function (symbol, state) {
return {
symbol: symbol,
state: state
};
};
/* @method Returns the list of item rules contained in the current state that are reduce item rules.
* @returns {[ItemRule]} Recude Item Rules */
state.prototype.getRecudeItems = function () {
return k.utils.obj.filter(this._items, function (item) {
return item.isReduce();
});
};
return state;
})(k.data.Node); |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function (mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function (CodeMirror) {
"use strict";
CodeMirror.defineMode("dylan", function (_config) {
// Words
var words = {
// Words that introduce unnamed definitions like "define interface"
unnamedDefinition: ["interface"],
// Words that introduce simple named definitions like "define library"
namedDefinition: ["module", "library", "macro",
"C-struct", "C-union",
"C-function", "C-callable-wrapper"
],
// Words that introduce type definitions like "define class".
// These are also parameterized like "define method" and are
// appended to otherParameterizedDefinitionWords
typeParameterizedDefinition: ["class", "C-subtype", "C-mapped-subtype"],
// Words that introduce trickier definitions like "define method".
// These require special definitions to be added to startExpressions
otherParameterizedDefinition: ["method", "function",
"C-variable", "C-address"
],
// Words that introduce module constant definitions.
// These must also be simple definitions and are
// appended to otherSimpleDefinitionWords
constantSimpleDefinition: ["constant"],
// Words that introduce module variable definitions.
// These must also be simple definitions and are
// appended to otherSimpleDefinitionWords
variableSimpleDefinition: ["variable"],
// Other words that introduce simple definitions
// (without implicit bodies).
otherSimpleDefinition: ["generic", "domain",
"C-pointer-type",
"table"
],
// Words that begin statements with implicit bodies.
statement: ["if", "block", "begin", "method", "case",
"for", "select", "when", "unless", "until",
"while", "iterate", "profiling", "dynamic-bind"
],
// Patterns that act as separators in compound statements.
// This may include any general pattern that must be indented
// specially.
separator: ["finally", "exception", "cleanup", "else",
"elseif", "afterwards"
],
// Keywords that do not require special indentation handling,
// but which should be highlighted
other: ["above", "below", "by", "from", "handler", "in",
"instance", "let", "local", "otherwise", "slot",
"subclass", "then", "to", "keyed-by", "virtual"
],
// Condition signaling function calls
signalingCalls: ["signal", "error", "cerror",
"break", "check-type", "abort"
]
};
words["otherDefinition"] =
words["unnamedDefinition"]
.concat(words["namedDefinition"])
.concat(words["otherParameterizedDefinition"]);
words["definition"] =
words["typeParameterizedDefinition"]
.concat(words["otherDefinition"]);
words["parameterizedDefinition"] =
words["typeParameterizedDefinition"]
.concat(words["otherParameterizedDefinition"]);
words["simpleDefinition"] =
words["constantSimpleDefinition"]
.concat(words["variableSimpleDefinition"])
.concat(words["otherSimpleDefinition"]);
words["keyword"] =
words["statement"]
.concat(words["separator"])
.concat(words["other"]);
// Patterns
var symbolPattern = "[-_a-zA-Z?!*@<>$%]+";
var symbol = new RegExp("^" + symbolPattern);
var patterns = {
// Symbols with special syntax
symbolKeyword: symbolPattern + ":",
symbolClass: "<" + symbolPattern + ">",
symbolGlobal: "\\*" + symbolPattern + "\\*",
symbolConstant: "\\$" + symbolPattern
};
var patternStyles = {
symbolKeyword: "atom",
symbolClass: "tag",
symbolGlobal: "variable-2",
symbolConstant: "variable-3"
};
// Compile all patterns to regular expressions
for (var patternName in patterns)
if (patterns.hasOwnProperty(patternName))
patterns[patternName] = new RegExp("^" + patterns[patternName]);
// Names beginning "with-" and "without-" are commonly
// used as statement macro
patterns["keyword"] = [/^with(?:out)?-[-_a-zA-Z?!*@<>$%]+/];
var styles = {};
styles["keyword"] = "keyword";
styles["definition"] = "def";
styles["simpleDefinition"] = "def";
styles["signalingCalls"] = "builtin";
// protected words lookup table
var wordLookup = {};
var styleLookup = {};
[
"keyword",
"definition",
"simpleDefinition",
"signalingCalls"
].forEach(function (type) {
words[type].forEach(function (word) {
wordLookup[word] = type;
styleLookup[word] = styles[type];
});
});
function chain(stream, state, f) {
state.tokenize = f;
return f(stream, state);
}
function tokenBase(stream, state) {
// String
var ch = stream.peek();
if (ch == "'" || ch == '"') {
stream.next();
return chain(stream, state, tokenString(ch, "string"));
}
// Comment
else if (ch == "/") {
stream.next();
if (stream.eat("*")) {
return chain(stream, state, tokenComment);
} else if (stream.eat("/")) {
stream.skipToEnd();
return "comment";
}
stream.backUp(1);
}
// Decimal
else if (/[+\-\d\.]/.test(ch)) {
if (stream.match(/^[+-]?[0-9]*\.[0-9]*([esdx][+-]?[0-9]+)?/i) ||
stream.match(/^[+-]?[0-9]+([esdx][+-]?[0-9]+)/i) ||
stream.match(/^[+-]?\d+/)) {
return "number";
}
}
// Hash
else if (ch == "#") {
stream.next();
// Symbol with string syntax
ch = stream.peek();
if (ch == '"') {
stream.next();
return chain(stream, state, tokenString('"', "string"));
}
// Binary number
else if (ch == "b") {
stream.next();
stream.eatWhile(/[01]/);
return "number";
}
// Hex number
else if (ch == "x") {
stream.next();
stream.eatWhile(/[\da-f]/i);
return "number";
}
// Octal number
else if (ch == "o") {
stream.next();
stream.eatWhile(/[0-7]/);
return "number";
}
// Token concatenation in macros
else if (ch == '#') {
stream.next();
return "punctuation";
}
// Sequence literals
else if ((ch == '[') || (ch == '(')) {
stream.next();
return "bracket";
// Hash symbol
} else if (stream.match(/f|t|all-keys|include|key|next|rest/i)) {
return "atom";
} else {
stream.eatWhile(/[-a-zA-Z]/);
return "error";
}
} else if (ch == "~") {
stream.next();
ch = stream.peek();
if (ch == "=") {
stream.next();
ch = stream.peek();
if (ch == "=") {
stream.next();
return "operator";
}
return "operator";
}
return "operator";
} else if (ch == ":") {
stream.next();
ch = stream.peek();
if (ch == "=") {
stream.next();
return "operator";
} else if (ch == ":") {
stream.next();
return "punctuation";
}
} else if ("[](){}".indexOf(ch) != -1) {
stream.next();
return "bracket";
} else if (".,".indexOf(ch) != -1) {
stream.next();
return "punctuation";
} else if (stream.match("end")) {
return "keyword";
}
for (var name in patterns) {
if (patterns.hasOwnProperty(name)) {
var pattern = patterns[name];
if ((pattern instanceof Array && pattern.some(function (p) {
return stream.match(p);
})) || stream.match(pattern))
return patternStyles[name];
}
}
if (/[+\-*\/^=<>&|]/.test(ch)) {
stream.next();
return "operator";
}
if (stream.match("define")) {
return "def";
} else {
stream.eatWhile(/[\w\-]/);
// Keyword
if (wordLookup[stream.current()]) {
return styleLookup[stream.current()];
} else if (stream.current().match(symbol)) {
return "variable";
} else {
stream.next();
return "variable-2";
}
}
}
function tokenComment(stream, state) {
var maybeEnd = false, maybeNested = false, nestedCount = 0, ch;
while ((ch = stream.next())) {
if (ch == "/" && maybeEnd) {
if (nestedCount > 0) {
nestedCount--;
} else {
state.tokenize = tokenBase;
break;
}
} else if (ch == "*" && maybeNested) {
nestedCount++;
}
maybeEnd = (ch == "*");
maybeNested = (ch == "/");
}
return "comment";
}
function tokenString(quote, style) {
return function (stream, state) {
var escaped = false, next, end = false;
while ((next = stream.next()) != null) {
if (next == quote && !escaped) {
end = true;
break;
}
escaped = !escaped && next == "\\";
}
if (end || !escaped) {
state.tokenize = tokenBase;
}
return style;
};
}
// Interface
return {
startState: function () {
return {
tokenize: tokenBase,
currentIndent: 0
};
},
token: function (stream, state) {
if (stream.eatSpace())
return null;
var style = state.tokenize(stream, state);
return style;
},
blockCommentStart: "/*",
blockCommentEnd: "*/"
};
});
CodeMirror.defineMIME("text/x-dylan", "dylan");
});
|
$(document).ready(function() {
$("#frmChangePass").submit(function() {
//get the url for the form
AJAX.post(
$("#frmChangePass").attr("action"),
{
_password_current : $("#currentPass").val(),
_password : $("#newPass").val(),
_password_confirm : $("#newPass2").val()
},
$("#msgbox_changepass"),
$("#btnChangepass"));
//we dont what the browser to submit the form
return false;
});
});
|
/**
* Created by joonkukang on 2014. 1. 16..
*/
var math = require('./utils').math;
let optimize = module.exports;
optimize.hillclimb = function(options){
var domain = options['domain'];
var costf = options['costf'];
var i;
var vec = [];
for(i=0 ; i<domain.length ; i++)
vec.push(math.randInt(domain[i][0],domain[i][1]));
var current, best;
while(true) {
var neighbors = [];
var i,j;
for(i=0 ; i<domain.length ; i++) {
if(vec[i] > domain[i][0]) {
var newVec = [];
for(j=0 ; j<domain.length ; j++)
newVec.push(vec[j]);
newVec[i]-=1;
neighbors.push(newVec);
} else if (vec[i] < domain[i][1]) {
var newVec = [];
for(j=0 ; j<domain.length ; j++)
newVec.push(vec[j]);
newVec[i]+=1;
neighbors.push(newVec);
}
}
current = costf(vec);
best = current;
for(i=0 ; i<neighbors.length ; i++) {
var cost = costf(neighbors[i]);
if(cost < best) {
best = cost;
vec = neighbors[i];
}
}
if(best === current)
break;
}
return vec;
}
optimize.anneal = function(options){
var domain = options['domain'];
var costf = options['costf'];
var temperature = options['temperature'];
var cool = options['cool'];
var step = options['step'];
var callback
var i;
var vec = [];
for(i=0 ; i<domain.length ; i++)
vec.push(math.randInt(domain[i][0],domain[i][1]));
while(temperature > 0.1) {
var idx = math.randInt(0,domain.length - 1);
var dir = math.randInt(-step,step);
var newVec = [];
for(i=0; i<vec.length ; i++)
newVec.push(vec[i]);
newVec[idx]+=dir;
if(newVec[idx] < domain[idx][0]) newVec[idx] = domain[idx][0];
if(newVec[idx] > domain[idx][1]) newVec[idx] = domain[idx][1];
var ea = costf(vec);
var eb = costf(newVec);
var p = Math.exp(-1.*(eb-ea)/temperature);
if(eb < ea || Math.random() < p)
vec = newVec;
temperature *= cool;
}
return vec;
}
optimize.genetic = function(options){
var domain = options['domain'];
var costf = options['costf'];
var population = options['population'];
var q = options['q'] || 0.3;
var elite = options['elite'] || population * 0.04;
var epochs = options['epochs'] || 100;
var i,j;
// Initialize population array
var pop =[];
for(i=0; i<population; i++) {
var vec = [];
for(j=0; j<domain.length; j++)
vec.push(math.randInt(domain[j][0],domain[j][1]));
pop.push(vec);
}
pop.sort(function(a,b){return costf(a) - costf(b);});
for(i=0 ; i<epochs ; i++) {
// elitism
var newPop = [];
for(j=0;j<elite;j++)
newPop.push(pop[j]);
// compute fitnesses
var fitnesses = [];
for(j=0; j<pop.length; j++)
fitnesses[j] = q * Math.pow(1-q,j);
fitnesses = math.normalizeVec(fitnesses);
// crossover, mutate
for(j=0; j<pop.length - elite;j++) {
var idx1 = rouletteWheel(fitnesses);
var idx2 = rouletteWheel(fitnesses);
var crossovered = crossover(pop[idx1],pop[idx2]);
var mutated = mutate(crossovered);
newPop.push(mutated);
}
// replacement
pop = newPop;
pop.sort(function(a,b){return costf(a) - costf(b);});
//console.log("Current Cost : ",costf(pop[0]));
}
return pop[0];
function mutate(vec) {
var idx = math.randInt(0,domain.length - 1);
var newVec = [];
var i;
for(i=0; i<domain.length ; i++)
newVec.push(vec[i]);
newVec[idx] += (Math.random() < 0.5) ? 1 : -1;
if(newVec[idx] < domain[idx][0]) newVec[idx] = domain[idx][0];
if(newVec[idx] > domain[idx][1]) newVec[idx] = domain[idx][1];
return newVec;
}
function crossover(vec1,vec2) {
var idx = math.randInt(0,domain.length - 2);
var newVec = [];
var i;
for(i=0; i<idx ; i++)
newVec.push(vec1[i]);
for(i=idx; i<domain.length; i++)
newVec.push(vec2[i]);
return newVec;
}
function rouletteWheel(vec) {
var a = [0.0];
var i;
for(i=0;i<vec.length;i++) {
a.push(a[i] + vec[i]);
}
var rand = Math.random();
for(i=0;i< a.length;i++) {
if(rand > a[i] && rand <= a[i+1])
return i;
}
return -1;
}
};
|
System.register(['@angular/core', '@angular/router', '../user/user.service', './login.service', '../shared/alert/dtalert.component', '../shared/spinner/dtspinner.component'], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1, router_1, user_service_1, login_service_1, dtalert_component_1, dtspinner_component_1;
var LoginComponent;
return {
setters:[
function (core_1_1) {
core_1 = core_1_1;
},
function (router_1_1) {
router_1 = router_1_1;
},
function (user_service_1_1) {
user_service_1 = user_service_1_1;
},
function (login_service_1_1) {
login_service_1 = login_service_1_1;
},
function (dtalert_component_1_1) {
dtalert_component_1 = dtalert_component_1_1;
},
function (dtspinner_component_1_1) {
dtspinner_component_1 = dtspinner_component_1_1;
}],
execute: function() {
LoginComponent = (function () {
function LoginComponent(_loginService, _router, _userService) {
this._loginService = _loginService;
this._router = _router;
this._userService = _userService;
this.pageTitle = "Login";
this.EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
this.dtAlert = new dtalert_component_1.DtAlertComponent();
}
LoginComponent.prototype.submit = function () {
var _this = this;
var isValid = this.validateEmailAndPassword();
if (!isValid) {
return;
}
var payload = { "email": this.email, "password": this.password };
this._loginService
.login(payload)
.subscribe(function (result) {
if (!result.success) {
_this.dtAlert.failure(result.message);
return;
}
_this._userService.add(result);
_this._router.navigate(['dashboard']);
}, function (error) { return _this.dtAlert.failure(error); });
};
LoginComponent.prototype.validateEmailAndPassword = function () {
if (this.email == null || this.email == "" || !this.EMAIL_REGEXP.test(this.email)) {
this.dtAlert.failure("Please enter a valid email");
return false;
}
if (this.password == null || this.password == "") {
this.dtAlert.failure("Please enter a password");
return false;
}
return true;
};
__decorate([
core_1.Input(),
__metadata('design:type', String)
], LoginComponent.prototype, "email", void 0);
__decorate([
core_1.Input(),
__metadata('design:type', String)
], LoginComponent.prototype, "password", void 0);
LoginComponent = __decorate([
core_1.Component({
templateUrl: 'app/login/login.component.html',
directives: [dtalert_component_1.DtAlertComponent, dtspinner_component_1.DtSpinButtonComponent]
}),
__metadata('design:paramtypes', [login_service_1.LoginService, router_1.Router, user_service_1.UserService])
], LoginComponent);
return LoginComponent;
}());
exports_1("LoginComponent", LoginComponent);
}
}
});
//# sourceMappingURL=login.component.js.map |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm2 16H5V5h11.17L19 7.83V19zm-7-7c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3zM6 6h9v4H6z"
}), 'SaveOutlined');
exports.default = _default; |
/*global module:false*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: '<json:jquery-disqus.jquery.json>',
meta: {
banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
},
concat: {
dist: {
src: ['<banner:meta.banner>', '<file_strip_banner:src/<%= pkg.name %>.js>'],
dest: 'dist/<%= pkg.name %>.js'
}
},
min: {
dist: {
src: ['<banner:meta.banner>', '<config:concat.dist.dest>'],
dest: 'dist/<%= pkg.name %>.min.js'
}
},
qunit: {
files: ['test/**/*.html']
},
lint: {
files: ['grunt.js', 'src/**/*.js', 'test/**/*.js']
},
watch: {
files: '<config:lint.files>',
tasks: 'lint qunit'
},
jshint: {
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
boss: true,
eqnull: true,
browser: true
},
globals: {
jQuery: true
}
},
uglify: {}
});
// Default task.
grunt.registerTask('default', 'lint qunit concat min');
};
|
define(['../lib/circle', '../lib/aura', './collision', '../lib/vector', '../lib/dictionary'],function(Circle, Aura, collision, Vector, Dictionary){
var Particle = function(world, options) {
var options = options || {}
Circle.call(this, options);
//TODO: implement singleton for the world
this.world = world;
this.mass = this.radius;
// this.energy = 100;
this.speed = options.speed || 3;
// todo: move this somewhere else
this.directions = new Dictionary({
n: new Vector(0, 1),
s: new Vector(0, -1),
e: new Vector(1, 0),
w: new Vector(-1, 0),
ne: new Vector(1, 1),
se: new Vector(1, -1),
nw: new Vector(-1, 1),
sw: new Vector(-1, -1)
});
this.setDirection(options.direction || this.directions.random());
this.aura = new Aura(this);
};
// inheritance
Particle.prototype = Object.create(Circle.prototype);
Particle.prototype.act = function() {
this.move();
};
/**
* Change position of object based on direction
* and speed
*/
Particle.prototype.move = function() {
var pos = this.position.add(new Vector(this.direction.normalize().x * this.speed, this.direction.normalize().y * this.speed));
this.setPosition(pos);
};
/**
* React to collision depending on the type of object
*/
Particle.prototype.reactToCollision = function(other) {
//TODO: fix this
//http://en.wikipedia.org/wiki/Elastic_collision
//http://www.gamasutra.com/view/feature/131424/pool_hall_lessons_fast_accurate_.php?page=3
var n = this.position.sub(other.prevPosition).normalize();
var a1 = this.direction.dot(n);
var a2 = other.prevDirection.dot(n);
var optimizedP = (2 * (a1 - a2)) / (this.mass + other.mass);
var newDir = this.direction.sub(n.mult(optimizedP * other.mass));
// this.setPosition(this.prevPosition);
this.setDirection(newDir);
// this.move();
};
/**
* Needed to keep track of the previous direction
*/
Particle.prototype.setDirection = function(vector){
this.prevDirection = this.direction || vector;
this.direction = vector;
};
/**
* Render
*/
Particle.prototype.render = function(){
this.aura.render();
this.constructor.prototype.render.call(this);
};
Particle.prototype.setPosition = function(pos){
this.prevPosition = this.position || pos;
this.constructor.prototype.setPosition.call(this, pos);
};
return Particle;
}); |
/*
Copyright 2013-2015 ASIAL CORPORATION
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import animit from '../../ons/animit';
import SplitterAnimator from './animator.js';
export default class PushSplitterAnimator extends SplitterAnimator {
_getSlidingElements() {
const slidingElements = [this._side, this._content];
if (this._oppositeSide && this._oppositeSide.mode === 'split') {
slidingElements.push(this._oppositeSide);
}
return slidingElements;
}
translate(distance) {
if (!this._slidingElements) {
this._slidingElements = this._getSlidingElements();
}
animit(this._slidingElements)
.queue({
transform: `translate3d(${this.minus + distance}px, 0px, 0px)`
})
.play();
}
/**
* @param {Function} done
*/
open(done) {console.log('opening');
const max = this._side.offsetWidth;
this._slidingElements = this._getSlidingElements();
animit.runAll(
animit(this._slidingElements)
.wait(this.delay)
.queue({
transform: `translate3d(${this.minus + max}px, 0px, 0px)`
}, {
duration: this.duration,
timing: this.timing
})
.queue(callback => {
this._slidingElements = null;
callback();
done && done();
}),
animit(this._mask)
.wait(this.delay)
.queue({
display: 'block'
})
);
}
/**
* @param {Function} done
*/
close(done) {
this._slidingElements = this._getSlidingElements();
animit.runAll(
animit(this._slidingElements)
.wait(this.delay)
.queue({
transform: 'translate3d(0px, 0px, 0px)'
}, {
duration: this.duration,
timing: this.timing
})
.queue(callback => {
this._slidingElements = null;
super.clearTransition();
done && done();
callback();
}),
animit(this._mask)
.wait(this.delay)
.queue({
display: 'none'
})
);
}
}
|
config.$inject = [ '$stateProvider' ];
function config ($stateProvider) {
$stateProvider
.state('main.admin-dashboard', {
url: '/inicio',
templateUrl: 'templates/components/main/dashboard/admin-dashboard.html',
controller: 'AdminDashboardController as vm',
onEnter: onStateEnter
})
.state('main.student-dashboard', {
url: '/inicio',
templateUrl: 'templates/components/main/dashboard/student-dashboard.html',
controller: 'StudentDashboardController as vm',
onEnter: onStateEnter
})
.state('main.professor-dashboard', {
url: '/inicio',
templateUrl: 'templates/components/main/dashboard/professor-dashboard.html',
controller: 'ProfessorDashboardController as vm',
onEnter: onStateEnter
});
}
const onStateEnter = [ '$rootScope',
rootScope => {
rootScope.viewTitle = "Vinculacion | Inicio";
rootScope.viewStyles = "main dashboard";
}
];
module.exports = config;
|
;modjewel.define("weinre/target/SqlStepper", function(require, exports, module) { // Generated by CoffeeScript 1.3.3
var Binding, SqlStepper, executeSql, ourErrorCallback, runStep;
Binding = require('../common/Binding');
module.exports = SqlStepper = (function() {
function SqlStepper(steps) {
var context;
if (!(this instanceof SqlStepper)) {
return new SqlStepper(steps);
}
this.__context = {};
context = this.__context;
context.steps = steps;
}
SqlStepper.prototype.run = function(db, errorCallback) {
var context;
context = this.__context;
if (context.hasBeenRun) {
throw new Ex(arguments, "stepper has already been run");
}
context.hasBeenRun = true;
context.db = db;
context.errorCallback = errorCallback;
context.nextStep = 0;
context.ourErrorCallback = new Binding(this, ourErrorCallback);
context.runStep = new Binding(this, runStep);
this.executeSql = new Binding(this, executeSql);
return db.transaction(context.runStep);
};
SqlStepper.example = function(db, id) {
var errorCb, step1, step2, stepper;
step1 = function() {
return this.executeSql("SELECT name FROM sqlite_master WHERE type='table'");
};
step2 = function(resultSet) {
var i, name, result, rows;
rows = resultSet.rows;
result = [];
i = 0;
while (i < rows.length) {
name = rows.item(i).name;
if (name === "__WebKitDatabaseInfoTable__") {
i++;
continue;
}
result.push(name);
i++;
}
return console.log(("[" + this.id + "] table names: ") + result.join(", "));
};
errorCb = function(sqlError) {
return console.log(("[" + this.id + "] sql error:" + sqlError.code + ": ") + sqlError.message);
};
stepper = new SqlStepper([step1, step2]);
stepper.id = id;
return stepper.run(db, errorCb);
};
return SqlStepper;
})();
executeSql = function(statement, data) {
var context;
context = this.__context;
return context.tx.executeSql(statement, data, context.runStep, context.ourErrorCallback);
};
ourErrorCallback = function(tx, sqlError) {
var context;
context = this.__context;
return context.errorCallback.call(this, sqlError);
};
runStep = function(tx, resultSet) {
var context, step;
context = this.__context;
if (context.nextStep >= context.steps.length) {
return;
}
context.tx = tx;
context.currentStep = context.nextStep;
context.nextStep++;
step = context.steps[context.currentStep];
return step.call(this, resultSet);
};
require("../common/MethodNamer").setNamesForClass(module.exports);
});
|
import {test} from '../qunit';
import {localeModule} from '../qunit-locale';
import moment from '../../moment';
localeModule('hu');
test('parse', function (assert) {
var tests = 'január jan_február feb_március márc_április ápr_május máj_június jún_július júl_augusztus aug_szeptember szept_október okt_november nov_december dec'.split('_'),
i;
function equalTest(input, mmm, i) {
assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1));
}
for (i = 0; i < 12; i++) {
tests[i] = tests[i].split(' ');
equalTest(tests[i][0], 'MMM', i);
equalTest(tests[i][1], 'MMM', i);
equalTest(tests[i][0], 'MMMM', i);
equalTest(tests[i][1], 'MMMM', i);
equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i);
equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i);
equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i);
equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i);
}
});
test('format', function (assert) {
var a = [
['dddd, MMMM Do YYYY, HH:mm:ss', 'vasárnap, február 14. 2010, 15:25:50'],
['ddd, HH', 'vas, 15'],
['M Mo MM MMMM MMM', '2 2. 02 február feb'],
['YYYY YY', '2010 10'],
['D Do DD', '14 14. 14'],
['d do dddd ddd dd', '0 0. vasárnap vas v'],
['DDD DDDo DDDD', '45 45. 045'],
['w wo ww', '6 6. 06'],
['H HH', '15 15'],
['m mm', '25 25'],
['s ss', '50 50'],
['[az év] DDDo [napja]', 'az év 45. napja'],
['LTS', '15:25:50'],
['L', '2010.02.14.'],
['LL', '2010. február 14.'],
['LLL', '2010. február 14. 15:25'],
['LLLL', '2010. február 14., vasárnap 15:25'],
['l', '2010.2.14.'],
['ll', '2010. feb 14.'],
['lll', '2010. feb 14. 15:25'],
['llll', '2010. feb 14., vas 15:25']
],
b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)),
i;
for (i = 0; i < a.length; i++) {
assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]);
}
});
test('meridiem', function (assert) {
assert.equal(moment([2011, 2, 23, 0, 0]).format('a'), 'de', 'am');
assert.equal(moment([2011, 2, 23, 11, 59]).format('a'), 'de', 'am');
assert.equal(moment([2011, 2, 23, 12, 0]).format('a'), 'du', 'pm');
assert.equal(moment([2011, 2, 23, 23, 59]).format('a'), 'du', 'pm');
assert.equal(moment([2011, 2, 23, 0, 0]).format('A'), 'DE', 'AM');
assert.equal(moment([2011, 2, 23, 11, 59]).format('A'), 'DE', 'AM');
assert.equal(moment([2011, 2, 23, 12, 0]).format('A'), 'DU', 'PM');
assert.equal(moment([2011, 2, 23, 23, 59]).format('A'), 'DU', 'PM');
});
test('format ordinal', function (assert) {
assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.');
assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.');
assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.');
assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.');
assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.');
assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.');
assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.');
assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.');
assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.');
assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.');
assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.');
assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.');
assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.');
assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.');
assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.');
assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.');
assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.');
assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.');
assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.');
assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.');
assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.');
assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.');
assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.');
assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.');
assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.');
assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.');
assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.');
assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.');
assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.');
assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.');
assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.');
});
test('format month', function (assert) {
var expected = 'január jan_február feb_március márc_április ápr_május máj_június jún_július júl_augusztus aug_szeptember szept_október okt_november nov_december dec'.split('_'),
i;
for (i = 0; i < expected.length; i++) {
assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]);
}
});
test('format week', function (assert) {
var expected = 'vasárnap vas_hétfő hét_kedd kedd_szerda sze_csütörtök csüt_péntek pén_szombat szo'.split('_'),
i;
for (i = 0; i < expected.length; i++) {
assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd'), expected[i], expected[i]);
}
});
test('from', function (assert) {
var start = moment([2007, 1, 28]);
assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'néhány másodperc', '44 másodperc = néhány másodperc');
assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'egy perc', '45 másodperc = egy perc');
assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'egy perc', '89 másodperc = egy perc');
assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 perc', '90 másodperc = 2 perc');
assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 perc', '44 perc = 44 perc');
assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'egy óra', '45 perc = egy óra');
assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'egy óra', '89 perc = egy óra');
assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 óra', '90 perc = 2 óra');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 óra', '5 óra = 5 óra');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 óra', '21 óra = 21 óra');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'egy nap', '22 óra = egy nap');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'egy nap', '35 óra = egy nap');
assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 nap', '36 óra = 2 nap');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'egy nap', '1 nap = egy nap');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 nap', '5 nap = 5 nap');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 nap', '25 nap = 25 nap');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'egy hónap', '26 nap = egy hónap');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'egy hónap', '30 nap = egy hónap');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'egy hónap', '45 nap = egy hónap');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 hónap', '46 nap = 2 hónap');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 hónap', '75 nap = 2 hónap');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 hónap', '76 nap = 3 hónap');
assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'egy hónap', '1 hónap = egy hónap');
assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 hónap', '5 hónap = 5 hónap');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'egy év', '345 nap = egy év');
assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 év', '548 nap = 2 év');
assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'egy év', '1 év = egy év');
assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 év', '5 év = 5 év');
});
test('suffix', function (assert) {
assert.equal(moment(30000).from(0), 'néhány másodperc múlva', 'prefix');
assert.equal(moment(0).from(30000), 'néhány másodperce', 'suffix');
});
test('now from now', function (assert) {
assert.equal(moment().fromNow(), 'néhány másodperce', 'now from now should display as in the past');
});
test('fromNow', function (assert) {
assert.equal(moment().add({s: 30}).fromNow(), 'néhány másodperc múlva', 'néhány másodperc múlva');
assert.equal(moment().add({d: 5}).fromNow(), '5 nap múlva', '5 nap múlva');
});
test('calendar day', function (assert) {
var a = moment().hours(12).minutes(0).seconds(0);
assert.equal(moment(a).calendar(), 'ma 12:00-kor', 'today at the same time');
assert.equal(moment(a).add({m: 25}).calendar(), 'ma 12:25-kor', 'Now plus 25 min');
assert.equal(moment(a).add({h: 1}).calendar(), 'ma 13:00-kor', 'Now plus 1 hour');
assert.equal(moment(a).add({d: 1}).calendar(), 'holnap 12:00-kor', 'tomorrow at the same time');
assert.equal(moment(a).subtract({h: 1}).calendar(), 'ma 11:00-kor', 'Now minus 1 hour');
assert.equal(moment(a).subtract({d: 1}).calendar(), 'tegnap 12:00-kor', 'yesterday at the same time');
});
test('calendar next week', function (assert) {
var i, m, days = 'vasárnap_hétfőn_kedden_szerdán_csütörtökön_pénteken_szombaton'.split('_');
for (i = 2; i < 7; i++) {
m = moment().add({d: i});
assert.equal(m.calendar(), m.format('[' + days[m.day()] + '] LT[-kor]'), 'today + ' + i + ' days current time');
m.hours(0).minutes(0).seconds(0).milliseconds(0);
assert.equal(m.calendar(), m.format('[' + days[m.day()] + '] LT[-kor]'), 'today + ' + i + ' days beginning of day');
m.hours(23).minutes(59).seconds(59).milliseconds(999);
assert.equal(m.calendar(), m.format('[' + days[m.day()] + '] LT[-kor]'), 'today + ' + i + ' days end of day');
}
});
test('calendar last week', function (assert) {
var i, m, days = 'vasárnap_hétfőn_kedden_szerdán_csütörtökön_pénteken_szombaton'.split('_');
for (i = 2; i < 7; i++) {
m = moment().subtract({d: i});
assert.equal(m.calendar(), m.format('[múlt ' + days[m.day()] + '] LT[-kor]'), 'today - ' + i + ' days current time');
m.hours(0).minutes(0).seconds(0).milliseconds(0);
assert.equal(m.calendar(), m.format('[múlt ' + days[m.day()] + '] LT[-kor]'), 'today - ' + i + ' days beginning of day');
m.hours(23).minutes(59).seconds(59).milliseconds(999);
assert.equal(m.calendar(), m.format('[múlt ' + days[m.day()] + '] LT[-kor]'), 'today - ' + i + ' days end of day');
}
});
test('calendar all else', function (assert) {
var weeksAgo = moment().subtract({w: 1}),
weeksFromNow = moment().add({w: 1});
assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), 'egy héte');
assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'egy hét múlva');
weeksAgo = moment().subtract({w: 2});
weeksFromNow = moment().add({w: 2});
assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 hete');
assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), '2 hét múlva');
});
test('weeks year starting sunday formatted', function (assert) {
assert.equal(moment([2011, 11, 26]).format('w ww wo'), '52 52 52.', 'Dec 26 2011 should be week 52');
assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52');
assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1');
assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1');
assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2');
});
|
// Break out the application running from the configuration definition to
// assist with testing.
require(['config'], function() {
// Kick off the application.
require(['app', 'router'], function(app, Router) {
// Define your master router on the application namespace and trigger all
// navigation from this instance.
app.router = new Router();
app.router.bind("all",function(route, router) {
$('#wrap').css('background-image', 'none');
$('.navbar').removeClass('bg').removeClass('bg-black');
$('.footer').removeClass('transparent');
$('.dropdown-menu').removeClass('bg-inverse');
});
// Trigger the initial route and enable HTML5 History API support, set the
// root folder to '/' by default. Change in app.js.
Backbone.history.start();
});
});
|
const dec = () => {};
class Foo {
@dec #x() {}
bar() {
([...this.#x] = this.baz);
}
}
|
(function () {
$(function () {
var _userService = abp.services.app.user;
var _$modal = $('#UserCreateModal');
var _$form = _$modal.find('form');
_$form.validate({
rules: {
Password: "required",
ConfirmPassword: {
equalTo: "#Password"
}
}
});
$('#RefreshButton').click(function () {
refreshUserList();
});
$('.delete-user').click(function () {
var userId = $(this).attr("data-user-id");
var userName = $(this).attr('data-user-name');
deleteUser(userId, userName);
});
$('.edit-user').click(function (e) {
var userId = $(this).attr("data-user-id");
e.preventDefault();
$.ajax({
url: abp.appPath + 'Users/EditUserModal?userId=' + userId,
type: 'POST',
contentType: 'application/html',
success: function (content) {
$('#UserEditModal div.modal-content').html(content);
},
error: function (e) { }
});
});
_$form.find('button[type="submit"]').click(function (e) {
e.preventDefault();
if (!_$form.valid()) {
return;
}
var user = _$form.serializeFormToObject(); //serializeFormToObject is defined in main.js
user.roleNames = [];
var _$roleCheckboxes = $("input[name='role']:checked");
if (_$roleCheckboxes) {
for (var roleIndex = 0; roleIndex < _$roleCheckboxes.length; roleIndex++) {
var _$roleCheckbox = $(_$roleCheckboxes[roleIndex]);
user.roleNames.push(_$roleCheckbox.attr('data-role-name'));
}
}
abp.ui.setBusy(_$modal);
_userService.create(user).done(function () {
_$modal.modal('hide');
location.reload(true); //reload page to see new user!
}).always(function () {
abp.ui.clearBusy(_$modal);
});
});
_$modal.on('shown.bs.modal', function () {
_$modal.find('input:not([type=hidden]):first').focus();
});
function refreshUserList() {
location.reload(true); //reload page to see new user!
}
function deleteUser(userId, userName) {
abp.message.confirm(
"Delete user '" + userName + "'?",
function (isConfirmed) {
if (isConfirmed) {
_userService.delete({
id: userId
}).done(function () {
refreshUserList();
});
}
}
);
}
});
})(); |
//>>built
define({nomatchMessage:"Die Kennw\u00f6rter stimmen nicht \u00fcberein.",badPasswordMessage:"Ung\u00fcltiges Kennwort."}); |
(function(){
if(!window.Prism) {
return;
}
function $$(expr, con) {
return Array.prototype.slice.call((con || document).querySelectorAll(expr));
}
var CRLF = crlf = /\r?\n|\r/g;
function highlightLines(pre, lines, classes) {
var ranges = lines.replace(/\s+/g, '').split(','),
offset = +pre.getAttribute('data-line-offset') || 0;
var lineHeight = parseFloat(getComputedStyle(pre).lineHeight);
for (var i=0, range; range = ranges[i++];) {
range = range.split('-');
var start = +range[0],
end = +range[1] || start;
var line = document.createElement('div');
line.textContent = Array(end - start + 2).join(' \r\n');
line.className = (classes || '') + ' line-highlight';
line.setAttribute('data-start', start);
if(end > start) {
line.setAttribute('data-end', end);
}
line.style.top = (start - offset - 1) * lineHeight + 'px';
(pre.querySelector('code') || pre).appendChild(line);
}
}
function applyHash() {
var hash = location.hash.slice(1);
// Remove pre-existing temporary lines
$$('.temporary.line-highlight').forEach(function (line) {
line.parentNode.removeChild(line);
});
var range = (hash.match(/\.([\d,-]+)$/) || [,''])[1];
if (!range || document.getElementById(hash)) {
return;
}
var id = hash.slice(0, hash.lastIndexOf('.')),
pre = document.getElementById(id);
if (!pre) {
return;
}
if (!pre.hasAttribute('data-line')) {
pre.setAttribute('data-line', '');
}
highlightLines(pre, range, 'temporary ');
document.querySelector('.temporary.line-highlight').scrollIntoView();
}
var fakeTimer = 0; // Hack to limit the number of times applyHash() runs
Prism.hooks.add('after-highlight', function(env) {
var pre = env.element.parentNode;
var lines = pre && pre.getAttribute('data-line');
if (!pre || !lines || !/pre/i.test(pre.nodeName)) {
return;
}
clearTimeout(fakeTimer);
$$('.line-highlight', pre).forEach(function (line) {
line.parentNode.removeChild(line);
});
highlightLines(pre, lines);
fakeTimer = setTimeout(applyHash, 1);
});
addEventListener('hashchange', applyHash);
})(); |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
var path = require("path");
var fs = require("fs");
var minify = require("jsonminify");
var js_beautify = require("js-beautify").js_beautify;
var css_beautify = require("js-beautify").css;
var html_beautify = require("js-beautify").html;
// Older versions of node have `existsSync` in the `path` module, not `fs`. Meh.
fs.existsSync = fs.existsSync || path.existsSync;
path.sep = path.sep || "/";
// The source file to be prettified, original source's path and some options.
var tempPath = process.argv[2] || "";
var filePath = process.argv[3] || "";
var pluginFolder = path.dirname(__dirname);
var sourceFolder = path.dirname(filePath);
var options = { html: {}, css: {}, js: {} };
var jsbeautifyrcPath;
// Try and get some persistent options from the plugin folder.
if (fs.existsSync(jsbeautifyrcPath = pluginFolder + path.sep + ".jsbeautifyrc")) {
setOptions(jsbeautifyrcPath, options);
}
// When a JSBeautify config file exists in the same directory as the source
// file, any directory above, or the user's home folder, then use that
// configuration to overwrite the default prefs.
var sourceFolderParts = path.resolve(sourceFolder).split(path.sep);
var pathsToLook = sourceFolderParts.map(function(value, key) {
return sourceFolderParts.slice(0, key + 1).join(path.sep);
});
// Start with the current directory first, end with the user's home folder.
pathsToLook.reverse();
pathsToLook.push(getUserHome());
pathsToLook.some(function(pathToLook) {
if (fs.existsSync(jsbeautifyrcPath = path.join(pathToLook, ".jsbeautifyrc"))) {
setOptions(jsbeautifyrcPath, options);
return true;
}
});
// Dump some diagnostics messages, parsed out by the plugin.
console.log("Using prettify options: " + JSON.stringify(options, null, 2));
// Read the source file and, when complete, beautify the code.
fs.readFile(tempPath, "utf8", function(err, data) {
if (err) {
return;
}
// Mark the output as being from this plugin.
console.log("*** HTMLPrettify output ***");
if (isCSS(filePath, data)) {
console.log(css_beautify(data, options["css"]));
}
else if (isHTML(filePath, data)) {
console.log(html_beautify(data, options["html"]));
}
else if (isJS(filePath, data)) {
console.log(js_beautify(data, options["js"]));
}
});
// Some handy utility functions.
function isTrue(value) {
return value == "true" || value == true;
}
function getUserHome() {
return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
}
function parseJSON(file) {
try {
return JSON.parse(minify(fs.readFileSync(file, "utf8")));
} catch (e) {
console.log("Could not parse JSON at: " + file);
return {};
}
}
function setOptions(file, optionsStore) {
var obj = parseJSON(file);
for (var key in obj) {
var value = obj[key];
// Options are defined as an object for each format, with keys as prefs.
if (key != "html" && key != "css" && key != "js") {
continue;
}
for (var pref in value) {
// Special case "true" and "false" pref values as actually booleans.
// This avoids common accidents in .jsbeautifyrc json files.
if (value == "true" || value == "false") {
optionsStore[key][pref] = isTrue(value[pref]);
} else {
optionsStore[key][pref] = value[pref];
}
}
}
}
// Checks if a file type is allowed by regexing the file name and expecting a
// certain extension loaded from the settings file.
function isTypeAllowed(type, path) {
var allowedFileExtensions = options[type]["allowed_file_extensions"] || {
"html": ["htm", "html", "xhtml", "shtml", "xml", "svg"],
"css": ["css", "scss", "sass", "less"],
"js": ["js", "json", "jshintrc", "jsbeautifyrc"]
}[type];
for (var i = 0, len = allowedFileExtensions.length; i < len; i++) {
if (path.match(new RegExp("\\." + allowedFileExtensions[i] + "$"))) {
return true;
}
}
return false;
}
function isCSS(path, data) {
// If file unsaved, there's no good way to determine whether or not it's
// CSS based on the file contents.
if (path == "?") {
return false;
}
return isTypeAllowed("css", path);
}
function isHTML(path, data) {
// If file unsaved, check if first non-whitespace character is <
if (path == "?") {
return data.match(/^\s*</);
}
return isTypeAllowed("html", path);
}
function isJS(path, data) {
// If file unsaved, check if first non-whitespace character is NOT <
if (path == "?") {
return !data.match(/^\s*</);
}
return isTypeAllowed("js", path);
}
|
module.exports = {
ignorePatterns: ['bin', 'commitlint.config.js'],
extends: [
'plugin:@typescript-eslint/recommended',
'prettier',
'prettier/@typescript-eslint',
'plugin:prettier/recommended',
],
parser: '@typescript-eslint/parser',
parserOptions: {
project: ['./tsconfig.json', './test/tsconfig.json'],
tsconfigRootDir: './',
},
plugins: ['@typescript-eslint', 'prettier'],
rules: {
'arrow-body-style': ['warn', 'as-needed'],
'react/jsx-one-expression-per-line': 'off',
'react/jsx-wrap-multilines': 'off',
'no-param-reassign': ['error', { props: false }],
'import/prefer-default-export': 'off',
curly: ['error', 'all'],
'eol-last': ['error', 'always'],
'no-debugger': 'error',
'import/no-unresolved': 'off',
'@typescript-eslint/unified-signatures': 'error',
'@typescript-eslint/member-delimiter-style': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-unused-vars': 'off',
},
}
|
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { deepmerge } from '@material-ui/utils';
import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled';
import Modal from '../Modal';
import Slide from '../Slide';
import Paper from '../Paper';
import capitalize from '../utils/capitalize';
import { duration } from '../styles/transitions';
import useTheme from '../styles/useTheme';
import useThemeProps from '../styles/useThemeProps';
import experimentalStyled from '../styles/experimentalStyled';
import drawerClasses, { getDrawerUtilityClass } from './drawerClasses';
const overridesResolver = (props, styles) => {
const {
styleProps
} = props;
return deepmerge(_extends({}, (styleProps.variant === 'permanent' || styleProps.variant === 'persistent') && styles.docked, styles.modal, {
[`& .${drawerClasses.paper}`]: _extends({}, styles.paper, styles[`paperAnchor${capitalize(styleProps.anchor)}`], styleProps.variant !== 'temporary' && styles[`paperAnchorDocked${capitalize(styleProps.anchor)}`])
}), styles.root || {});
};
const useUtilityClasses = styleProps => {
const {
classes,
anchor,
variant
} = styleProps;
const slots = {
root: ['root'],
docked: [(variant === 'permanent' || variant === 'persistent') && 'docked'],
modal: ['modal'],
paper: ['paper', `paperAnchor${capitalize(anchor)}`, variant !== 'temporary' && `paperAnchorDocked${capitalize(anchor)}`]
};
return composeClasses(slots, getDrawerUtilityClass, classes);
};
const DrawerRoot = experimentalStyled(Modal, {}, {
name: 'MuiDrawer',
slot: 'Root',
overridesResolver
})({});
const DrawerDockedRoot = experimentalStyled('div', {}, {
name: 'MuiDrawer',
slot: 'Docked',
overridesResolver
})({
/* Styles applied to the root element if `variant="permanent or persistent"`. */
flex: '0 0 auto'
});
const DrawerPaper = experimentalStyled(Paper, {}, {
name: 'MuiDrawer',
slot: 'Paper'
})(({
theme,
styleProps
}) => _extends({
/* Styles applied to the Paper component. */
overflowY: 'auto',
display: 'flex',
flexDirection: 'column',
height: '100%',
flex: '1 0 auto',
zIndex: theme.zIndex.drawer,
WebkitOverflowScrolling: 'touch',
// Add iOS momentum scrolling.
// temporary style
position: 'fixed',
top: 0,
// We disable the focus ring for mouse, touch and keyboard users.
// At some point, it would be better to keep it for keyboard users.
// :focus-ring CSS pseudo-class will help.
outline: 0
}, styleProps.anchor === 'left' && {
/* Styles applied to the Paper component if `anchor="left"`. */
left: 0,
right: 'auto'
}, styleProps.anchor === 'top' && {
/* Styles applied to the Paper component if `anchor="top"`. */
top: 0,
left: 0,
bottom: 'auto',
right: 0,
height: 'auto',
maxHeight: '100%'
}, styleProps.anchor === 'right' && {
/* Styles applied to the Paper component if `anchor="right"`. */
left: 'auto',
right: 0
}, styleProps.anchor === 'bottom' && {
/* Styles applied to the Paper component if `anchor="bottom"`. */
top: 'auto',
left: 0,
bottom: 0,
right: 0,
height: 'auto',
maxHeight: '100%'
}, styleProps.anchor === 'left' && styleProps.variant !== 'temporary' && {
/* Styles applied to the Paper component if `anchor="left"` and `variant` is not "temporary". */
borderRight: `1px solid ${theme.palette.divider}`
}, styleProps.anchor === 'top' && styleProps.variant !== 'temporary' && {
/* Styles applied to the Paper component if `anchor="top"` and `variant` is not "temporary". */
borderBottom: `1px solid ${theme.palette.divider}`
}, styleProps.anchor === 'right' && styleProps.variant !== 'temporary' && {
/* Styles applied to the Paper component if `anchor="right"` and `variant` is not "temporary". */
borderLeft: `1px solid ${theme.palette.divider}`
}, styleProps.anchor === 'bottom' && styleProps.variant !== 'temporary' && {
/* Styles applied to the Paper component if `anchor="bottom"` and `variant` is not "temporary". */
borderTop: `1px solid ${theme.palette.divider}`
}));
const oppositeDirection = {
left: 'right',
right: 'left',
top: 'down',
bottom: 'up'
};
export function isHorizontal(anchor) {
return ['left', 'right'].indexOf(anchor) !== -1;
}
export function getAnchor(theme, anchor) {
return theme.direction === 'rtl' && isHorizontal(anchor) ? oppositeDirection[anchor] : anchor;
}
const defaultTransitionDuration = {
enter: duration.enteringScreen,
exit: duration.leavingScreen
};
/**
* The props of the [Modal](/api/modal/) component are available
* when `variant="temporary"` is set.
*/
const Drawer = /*#__PURE__*/React.forwardRef(function Drawer(inProps, ref) {
const props = useThemeProps({
props: inProps,
name: 'MuiDrawer'
});
const {
anchor: anchorProp = 'left',
BackdropProps,
children,
className,
elevation = 16,
ModalProps: {
BackdropProps: BackdropPropsProp
} = {},
onClose,
open = false,
PaperProps = {},
SlideProps,
// eslint-disable-next-line react/prop-types
TransitionComponent = Slide,
transitionDuration = defaultTransitionDuration,
variant = 'temporary'
} = props,
ModalProps = _objectWithoutPropertiesLoose(props.ModalProps, ["BackdropProps"]),
other = _objectWithoutPropertiesLoose(props, ["anchor", "BackdropProps", "children", "className", "elevation", "ModalProps", "onClose", "open", "PaperProps", "SlideProps", "TransitionComponent", "transitionDuration", "variant"]);
const theme = useTheme(); // Let's assume that the Drawer will always be rendered on user space.
// We use this state is order to skip the appear transition during the
// initial mount of the component.
const mounted = React.useRef(false);
React.useEffect(() => {
mounted.current = true;
}, []);
const anchor = getAnchor(theme, anchorProp);
const styleProps = _extends({}, props, {
anchor,
elevation,
open,
variant
}, other);
const classes = useUtilityClasses(styleProps);
const drawer = /*#__PURE__*/React.createElement(DrawerPaper, _extends({
elevation: variant === 'temporary' ? elevation : 0,
square: true
}, PaperProps, {
className: clsx(classes.paper, PaperProps.className),
styleProps: styleProps
}), children);
if (variant === 'permanent') {
return /*#__PURE__*/React.createElement(DrawerDockedRoot, _extends({
className: clsx(classes.root, classes.docked, className),
styleProps: styleProps,
ref: ref
}, other), drawer);
}
const slidingDrawer = /*#__PURE__*/React.createElement(TransitionComponent, _extends({
in: open,
direction: oppositeDirection[anchor],
timeout: transitionDuration,
appear: mounted.current
}, SlideProps), drawer);
if (variant === 'persistent') {
return /*#__PURE__*/React.createElement(DrawerDockedRoot, _extends({
className: clsx(classes.root, classes.docked, className),
styleProps: styleProps,
ref: ref
}, other), slidingDrawer);
} // variant === temporary
return /*#__PURE__*/React.createElement(DrawerRoot, _extends({
BackdropProps: _extends({}, BackdropProps, BackdropPropsProp, {
transitionDuration
}),
className: clsx(classes.root, classes.modal, className),
open: open,
styleProps: styleProps,
onClose: onClose,
ref: ref
}, other, ModalProps), slidingDrawer);
});
process.env.NODE_ENV !== "production" ? Drawer.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* Side from which the drawer will appear.
* @default 'left'
*/
anchor: PropTypes.oneOf(['bottom', 'left', 'right', 'top']),
/**
* @ignore
*/
BackdropProps: PropTypes.object,
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The elevation of the drawer.
* @default 16
*/
elevation: PropTypes.number,
/**
* Props applied to the [`Modal`](/api/modal/) element.
* @default {}
*/
ModalProps: PropTypes.object,
/**
* Callback fired when the component requests to be closed.
*
* @param {object} event The event source of the callback.
*/
onClose: PropTypes.func,
/**
* If `true`, the component is shown.
* @default false
*/
open: PropTypes.bool,
/**
* Props applied to the [`Paper`](/api/paper/) element.
* @default {}
*/
PaperProps: PropTypes.object,
/**
* Props applied to the [`Slide`](/api/slide/) element.
*/
SlideProps: PropTypes.object,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.object,
/**
* The duration for the transition, in milliseconds.
* You may specify a single timeout for all transitions, or individually with an object.
* @default { enter: duration.enteringScreen, exit: duration.leavingScreen }
*/
transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({
appear: PropTypes.number,
enter: PropTypes.number,
exit: PropTypes.number
})]),
/**
* The variant to use.
* @default 'temporary'
*/
variant: PropTypes.oneOf(['permanent', 'persistent', 'temporary'])
} : void 0;
export default Drawer; |
/**
* simple
*/
var mysinleton = {
property1 : 'something',
property2 : 'something else',
method1 : function() {
console.log("hello world");
}
}
/***
* encapsulation like java get、set
*/
var mysinleton2 = function() {
var privateVariable = 'something private';
function showPrivate() {
console.log(privateVariable);
}
return {
publicMethod : function(){
showPrivate();
},
publicVar : "this is a public variable"
}
}
var mysinletonInstance = new mysinleton2();
mysinletonInstance.publicMethod();
console.log(mysinletonInstance.publicVar);
/***
*
* singleton realize
*/
var Mysingleton = (function(){
var _intstance ;
function getInstance() {
return _intstance;
};
function init() {
return {
publicMethod : function() {
console.log("this is public method");
},
publicProperty : 'test'
}
};
return {
getInstance : function() {
if(_intstance) {
return _intstance;
}else {
_intstance = init();
return _intstance;
}
}
}
})();
Mysingleton.getInstance().publicMethod();
var SingletonTester = (function () {
//参数:传递给单例的一个参数集合
function Singleton(args) {
//设置args变量为接收的参数或者为空(如果没有提供的话)
var args = args || {};
//设置name参数
this.name = 'SingletonTester';
//设置pointX的值
this.pointX = args.pointX || 6; //从接收的参数里获取,或者设置为默认值
//设置pointY的值
this.pointY = args.pointY || 10;
}
//实例容器
var instance;
var _static = {
name: 'SingletonTester',
//获取实例的方法
//返回Singleton的实例
getInstance: function (args) {
if (instance === undefined) {
instance = new Singleton(args);
}
return instance;
}
};
return _static;
})();
var singletonTest = SingletonTester.getInstance({ pointX: 5 });
console.log(singletonTest.pointX); // 输出 5 |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails oncall+relay
* @flow strict-local
* @format
*/
// flowlint ambiguous-object-type:error
'use strict';
const useRelayEnvironment = require('./useRelayEnvironment');
const warning = require('warning');
const {getFragmentResourceForEnvironment} = require('./FragmentResource');
const {useEffect, useRef, useState} = require('react');
const {getFragmentIdentifier} = require('relay-runtime');
import type {ReaderFragment} from 'relay-runtime';
type ReturnType<TFragmentData: mixed> = {|
data: TFragmentData,
disableStoreUpdates: () => void,
enableStoreUpdates: () => void,
shouldUpdateGeneration: number | null,
|};
function useFragmentNode<TFragmentData: mixed>(
fragmentNode: ReaderFragment,
fragmentRef: mixed,
componentDisplayName: string,
): ReturnType<TFragmentData> {
const environment = useRelayEnvironment();
const FragmentResource = getFragmentResourceForEnvironment(environment);
const isMountedRef = useRef(false);
const [, forceUpdate] = useState(0);
const fragmentIdentifier = getFragmentIdentifier(fragmentNode, fragmentRef);
// The values of these React refs are counters that should be incremented
// under their respective conditions. This allows us to use the counters as
// memoization values to indicate if computations for useMemo or useEffect
// should be re-executed.
const mustResubscribeGenerationRef = useRef(0);
const shouldUpdateGenerationRef = useRef(0);
const environmentChanged = useHasChanged(environment);
const fragmentIdentifierChanged = useHasChanged(fragmentIdentifier);
// If the fragment identifier changes, it means that the variables on the
// fragment owner changed, or the fragment ref points to different records.
// In this case, we need to resubscribe to the Relay store.
const mustResubscribe = environmentChanged || fragmentIdentifierChanged;
// We only want to update the component consuming this fragment under the
// following circumstances:
// - We receive an update from the Relay store, indicating that the data
// the component is directly subscribed to has changed.
// - We need to subscribe and render /different/ data (i.e. the fragment refs
// now point to different records, or the context changed).
// Note that even if identity of the fragment ref objects changes, we
// don't consider them as different unless they point to a different data ID.
//
// This prevents unnecessary updates when a parent re-renders this component
// with the same props, which is a common case when the parent updates due
// to change in the data /it/ is subscribed to, but which doesn't affect the
// child.
if (mustResubscribe) {
shouldUpdateGenerationRef.current++;
mustResubscribeGenerationRef.current++;
}
// Read fragment data; this might suspend.
const fragmentResult = FragmentResource.readWithIdentifier(
fragmentNode,
fragmentRef,
fragmentIdentifier,
componentDisplayName,
);
const isListeningForUpdatesRef = useRef(true);
function enableStoreUpdates() {
isListeningForUpdatesRef.current = true;
const didMissUpdates = FragmentResource.checkMissedUpdates(
fragmentResult,
)[0];
if (didMissUpdates) {
handleDataUpdate();
}
}
function disableStoreUpdates() {
isListeningForUpdatesRef.current = false;
}
function handleDataUpdate() {
if (
isMountedRef.current === false ||
isListeningForUpdatesRef.current === false
) {
return;
}
// If we receive an update from the Relay store, we need to make sure the
// consuming component updates.
shouldUpdateGenerationRef.current++;
// React bails out on noop state updates as an optimization.
// If we want to force an update via setState, we need to pass an value.
// The actual value can be arbitrary though, e.g. an incremented number.
forceUpdate(count => count + 1);
}
// Establish Relay store subscriptions in the commit phase, only if
// rendering for the first time, or if we need to subscribe to new data
useEffect(() => {
isMountedRef.current = true;
const disposable = FragmentResource.subscribe(
fragmentResult,
handleDataUpdate,
);
return () => {
// When unmounting or resubscribing to new data, clean up current
// subscription. This will also make sure fragment data is no longer
// cached for the so next time it its read, it will be read fresh from the
// Relay store
isMountedRef.current = false;
disposable.dispose();
};
// NOTE: We disable react-hooks-deps warning because mustResubscribeGenerationRef
// is capturing all information about whether the effect should be re-ran.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [mustResubscribeGenerationRef.current]);
if (__DEV__) {
if (fragmentRef != null && fragmentResult.data == null) {
warning(
false,
'Relay: Expected to have been able to read non-null data for ' +
'fragment `%s` declared in ' +
'`%s`, since fragment reference was non-null. ' +
"Make sure that that `%s`'s parent isn't " +
'holding on to and/or passing a fragment reference for data that ' +
'has been deleted.',
fragmentNode.name,
componentDisplayName,
componentDisplayName,
);
}
}
return {
// $FlowFixMe
data: fragmentResult.data,
disableStoreUpdates,
enableStoreUpdates,
shouldUpdateGeneration: shouldUpdateGenerationRef.current,
};
}
function useHasChanged(value: mixed): boolean {
const [mirroredValue, setMirroredValue] = useState(value);
const valueChanged = mirroredValue !== value;
if (valueChanged) {
setMirroredValue(value);
}
return valueChanged;
}
module.exports = useFragmentNode;
|
/**
* @providesModule Fabric
*/
'use strict';
module.exports.Crashlytics = require('./Crashlytics');
module.exports.Answers = require('./Answers');
|
'use strict';
describe('LoginController', function () {
// Load the parent app
beforeEach(module('demoSite'));
var $controller;
var $scope, controller, $window;
beforeEach(inject(function (_$controller_) {
$controller = _$controller_;
$scope = {};
$window = { location: {}, open: function () { } };
controller = $controller('LoginController', { $scope: $scope, $window: $window });
}));
describe('isTapIn variable', function () {
it('is true by default', function () {
expect($scope.isTapIn).toBe(true);
});
it('is true if that value is passed to initiateLogin', function () {
$scope.initiateLogin(true);
expect($scope.isTapIn).toBe(true);
});
it('is false if that value is passed to initiateLogin', function () {
$scope.initiateLogin(false);
expect($scope.isTapIn).toBe(false);
});
});
describe('popup creation', function () {
it('should pop up a new window when a new login is initiated', function () {
spyOn($window, 'open');
$scope.initiateLogin(true);
expect($window.open).toHaveBeenCalled();
})
})
describe('error message framework', function () {
it('should convert error codes to friendly messages', function () {
expect($scope.showError).toBe(false);
// Loop through each property in the errorMessages object and check that it is displayed properly.
for (var property in $scope.errorMessages) {
if ($scope.errorMessages.hasOwnProperty(property)) {
$scope.showErrorFromCode(property);
expect($scope.errorMessage).toBe($scope.errorMessages[property]);
expect($scope.showError).toBe(true);
}
}
});
it('should handle lack of connection to the server', function () {
expect($scope.showError).toBe(false);
$scope.handleGetURLError();
expect($scope.errorMessage).toBe($scope.errorMessages["no_connection"]);
expect($scope.showError).toBe(true);
});
it('should hide any errors when a new login is initiated', function () {
$scope.showError = true;
$scope.initiateLogin(true);
expect($scope.showError).toBe(false);
})
});
describe('polling framework', function () {
beforeEach(function () {
// Because the framework utilizes a popup, these variables are NOT inside the controller.
dataHasReturned = false;
returnedData = new Object();
});
it('should handle manually closing of the popup window', function () {
$scope.popupWindow = window.open();
$scope.popupWindow.close();
$scope.pollPopupForCompletedAuth();
expect(dataHasReturned).toBe(false);
});
it('should present an error if one comes back from the server', function () {
dataHasReturned = true;
returnedData.error = "access_denied";
expect($scope.showError).toBe(false);
$scope.pollPopupForCompletedAuth();
expect($scope.showError).toBe(true);
expect(dataHasReturned).toBe(false);
});
it('should redirect the user to the auth page when proper data has returned', function () {
dataHasReturned = true;
returnedData = {
subject: "1111-2222-3333-4444",
username: "Test User",
email: "[email protected]",
details: "Tech+Details"
};
$scope.pollPopupForCompletedAuth();
expect($window.location.href).toBe('/#/auth');
});
})
}); |
/* =========================================================
* bootstrap-datepicker.js
* http://www.eyecon.ro/bootstrap-datepicker
* =========================================================
* Copyright 2012 Stefan Petre
* Improvements by Andrew Rowls
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================= */
(function ($) {
var $window = $(window);
function UTCDate() {
return new Date(Date.UTC.apply(Date, arguments));
}
function UTCToday() {
var today = new Date();
return UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());
}
// Picker object
var Datepicker = function (element, options) {
var that = this;
this._process_options(options);
this.element = $(element);
this.isInline = false;
this.isInput = this.element.is('input');
this.component = this.element.is('.date') ? this.element.find('.add-on, .btn') : false;
this.hasInput = this.component && this.element.find('input').length;
if (this.component && this.component.length === 0)
this.component = false;
this.picker = $(DPGlobal.template);
this._buildEvents();
this._attachEvents();
if (this.isInline) {
this.picker.addClass('datepicker-inline').appendTo(this.element);
} else {
this.picker.addClass('datepicker-dropdown dropdown-menu');
}
if (this.o.rtl) {
this.picker.addClass('datepicker-rtl');
this.picker.find('.prev i, .next i')
.toggleClass('icon-arrow-left icon-arrow-right');
}
this.viewMode = this.o.startView;
if (this.o.calendarWeeks)
this.picker.find('tfoot th.today')
.attr('colspan', function (i, val) {
return parseInt(val) + 1;
});
this._allow_update = false;
this.setStartDate(this._o.startDate);
this.setEndDate(this._o.endDate);
this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled);
this.fillDow();
this.fillMonths();
this._allow_update = true;
this.update();
this.showMode();
if (this.isInline) {
this.show();
}
};
Datepicker.prototype = {
constructor: Datepicker,
_process_options: function (opts) {
// Store raw options for reference
this._o = $.extend({}, this._o, opts);
// Processed options
var o = this.o = $.extend({}, this._o);
// Check if "de-DE" style date is available, if not language should
// fallback to 2 letter code eg "de"
var lang = o.language;
if (!dates[lang]) {
lang = lang.split('-')[0];
if (!dates[lang])
lang = defaults.language;
}
o.language = lang;
switch (o.startView) {
case 2:
case 'decade':
o.startView = 2;
break;
case 1:
case 'year':
o.startView = 1;
break;
default:
o.startView = 0;
}
switch (o.minViewMode) {
case 1:
case 'months':
o.minViewMode = 1;
break;
case 2:
case 'years':
o.minViewMode = 2;
break;
default:
o.minViewMode = 0;
}
o.startView = Math.max(o.startView, o.minViewMode);
o.weekStart %= 7;
o.weekEnd = ((o.weekStart + 6) % 7);
var format = DPGlobal.parseFormat(o.format);
if (o.startDate !== -Infinity) {
if (!!o.startDate) {
if (o.startDate instanceof Date)
o.startDate = this._local_to_utc(this._zero_time(o.startDate));
else
o.startDate = DPGlobal.parseDate(o.startDate, format, o.language);
} else {
o.startDate = -Infinity;
}
}
if (o.endDate !== Infinity) {
if (!!o.endDate) {
if (o.endDate instanceof Date)
o.endDate = this._local_to_utc(this._zero_time(o.endDate));
else
o.endDate = DPGlobal.parseDate(o.endDate, format, o.language);
} else {
o.endDate = Infinity;
}
}
o.daysOfWeekDisabled = o.daysOfWeekDisabled || [];
if (!$.isArray(o.daysOfWeekDisabled))
o.daysOfWeekDisabled = o.daysOfWeekDisabled.split(/[,\s]*/);
o.daysOfWeekDisabled = $.map(o.daysOfWeekDisabled, function (d) {
return parseInt(d, 10);
});
var plc = String(o.orientation).toLowerCase().split(/\s+/g),
_plc = o.orientation.toLowerCase();
plc = $.grep(plc, function (word) {
return (/^auto|left|right|top|bottom$/).test(word);
});
o.orientation = { x: 'auto', y: 'auto' };
if (!_plc || _plc === 'auto')
; // no action
else if (plc.length === 1) {
switch (plc[0]) {
case 'top':
case 'bottom':
o.orientation.y = plc[0];
break;
case 'left':
case 'right':
o.orientation.x = plc[0];
break;
}
}
else {
_plc = $.grep(plc, function (word) {
return (/^left|right$/).test(word);
});
o.orientation.x = _plc[0] || 'auto';
_plc = $.grep(plc, function (word) {
return (/^top|bottom$/).test(word);
});
o.orientation.y = _plc[0] || 'auto';
}
},
_events: [],
_secondaryEvents: [],
_applyEvents: function (evs) {
for (var i = 0, el, ev; i < evs.length; i++) {
el = evs[i][0];
ev = evs[i][1];
el.on(ev);
}
},
_unapplyEvents: function (evs) {
for (var i = 0, el, ev; i < evs.length; i++) {
el = evs[i][0];
ev = evs[i][1];
el.off(ev);
}
},
_buildEvents: function () {
if (this.isInput) { // single input
this._events = [
[this.element, {
focus: $.proxy(this.show, this),
keyup: $.proxy(this.update, this),
keydown: $.proxy(this.keydown, this)
}]
];
}
else if (this.component && this.hasInput) { // component: input + button
this._events = [
// For components that are not readonly, allow keyboard nav
[this.element.find('input'), {
focus: $.proxy(this.show, this),
keyup: $.proxy(this.update, this),
keydown: $.proxy(this.keydown, this)
}],
[this.component, {
click: $.proxy(this.show, this)
}]
];
}
else if (this.element.is('div')) { // inline datepicker
this.isInline = true;
}
else {
this._events = [
[this.element, {
click: $.proxy(this.show, this)
}]
];
}
this._secondaryEvents = [
[this.picker, {
click: $.proxy(this.click, this)
}],
[$(window), {
resize: $.proxy(this.place, this)
}],
[$(document), {
mousedown: $.proxy(function (e) {
// Clicked outside the datepicker, hide it
if (!(
this.element.is(e.target) ||
this.element.find(e.target).length ||
this.picker.is(e.target) ||
this.picker.find(e.target).length
)) {
this.hide();
}
}, this)
}]
];
},
_attachEvents: function () {
this._detachEvents();
this._applyEvents(this._events);
},
_detachEvents: function () {
this._unapplyEvents(this._events);
},
_attachSecondaryEvents: function () {
this._detachSecondaryEvents();
this._applyEvents(this._secondaryEvents);
},
_detachSecondaryEvents: function () {
this._unapplyEvents(this._secondaryEvents);
},
_trigger: function (event, altdate) {
var date = altdate || this.date,
local_date = this._utc_to_local(date);
this.element.trigger({
type: event,
date: local_date,
format: $.proxy(function (altformat) {
var format = altformat || this.o.format;
return DPGlobal.formatDate(date, format, this.o.language);
}, this)
});
},
show: function (e) {
if (!this.isInline)
this.picker.appendTo('body');
this.picker.show();
this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
this.place();
this._attachSecondaryEvents();
if (e) {
e.preventDefault();
}
this._trigger('show');
},
hide: function (e) {
if (this.isInline) return;
if (!this.picker.is(':visible')) return;
this.picker.hide().detach();
this._detachSecondaryEvents();
this.viewMode = this.o.startView;
this.showMode();
if (
this.o.forceParse &&
(
this.isInput && this.element.val() ||
this.hasInput && this.element.find('input').val()
)
)
this.setValue();
this._trigger('hide');
},
remove: function () {
this.hide();
this._detachEvents();
this._detachSecondaryEvents();
this.picker.remove();
delete this.element.data().datepicker;
if (!this.isInput) {
delete this.element.data().date;
}
},
_utc_to_local: function (utc) {
return new Date(utc.getTime() + (utc.getTimezoneOffset() * 60000));
},
_local_to_utc: function (local) {
return new Date(local.getTime() - (local.getTimezoneOffset() * 60000));
},
_zero_time: function (local) {
return new Date(local.getFullYear(), local.getMonth(), local.getDate());
},
_zero_utc_time: function (utc) {
return new Date(Date.UTC(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate()));
},
getDate: function () {
return this._utc_to_local(this.getUTCDate());
},
getUTCDate: function () {
return this.date;
},
setDate: function (d) {
this.setUTCDate(this._local_to_utc(d));
},
setUTCDate: function (d) {
this.date = d;
this.setValue();
},
setValue: function () {
var formatted = this.getFormattedDate();
if (!this.isInput) {
if (this.component) {
this.element.find('input').val(formatted).change();
}
} else {
this.element.val(formatted).change();
}
},
getFormattedDate: function (format) {
if (format === undefined)
format = this.o.format;
return DPGlobal.formatDate(this.date, format, this.o.language);
},
setStartDate: function (startDate) {
this._process_options({ startDate: startDate });
this.update();
this.updateNavArrows();
},
setEndDate: function (endDate) {
this._process_options({ endDate: endDate });
this.update();
this.updateNavArrows();
},
setDaysOfWeekDisabled: function (daysOfWeekDisabled) {
this._process_options({ daysOfWeekDisabled: daysOfWeekDisabled });
this.update();
this.updateNavArrows();
},
place: function () {
if (this.isInline) return;
var calendarWidth = this.picker.outerWidth(),
calendarHeight = this.picker.outerHeight(),
visualPadding = 10,
windowWidth = $window.width(),
windowHeight = $window.height(),
scrollTop = $window.scrollTop();
var zIndex = parseInt(this.element.parents().filter(function () {
return $(this).css('z-index') != 'auto';
}).first().css('z-index')) + 10;
var offset = this.component ? this.component.parent().offset() : this.element.offset();
var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(false);
var width = this.component ? this.component.outerWidth(true) : this.element.outerWidth(false);
var left = offset.left,
top = offset.top;
this.picker.removeClass(
'datepicker-orient-top datepicker-orient-bottom ' +
'datepicker-orient-right datepicker-orient-left'
);
if (this.o.orientation.x !== 'auto') {
this.picker.addClass('datepicker-orient-' + this.o.orientation.x);
if (this.o.orientation.x === 'right')
left -= calendarWidth - width;
}
// auto x orientation is best-placement: if it crosses a window
// edge, fudge it sideways
else {
// Default to left
this.picker.addClass('datepicker-orient-left');
if (offset.left < 0)
left -= offset.left - visualPadding;
else if (offset.left + calendarWidth > windowWidth)
left = windowWidth - calendarWidth - visualPadding;
}
// auto y orientation is best-situation: top or bottom, no fudging,
// decision based on which shows more of the calendar
var yorient = this.o.orientation.y,
top_overflow, bottom_overflow;
if (yorient === 'auto') {
top_overflow = -scrollTop + offset.top - calendarHeight;
bottom_overflow = scrollTop + windowHeight - (offset.top + height + calendarHeight);
if (Math.max(top_overflow, bottom_overflow) === bottom_overflow)
yorient = 'top';
else
yorient = 'bottom';
}
this.picker.addClass('datepicker-orient-' + yorient);
if (yorient === 'top')
top += height;
else
top -= calendarHeight + parseInt(this.picker.css('padding-top'));
this.picker.css({
top: top,
left: left,
zIndex: zIndex
});
},
_allow_update: true,
update: function () {
if (!this._allow_update) return;
var oldDate = new Date(this.date),
date, fromArgs = false;
if (arguments && arguments.length && (typeof arguments[0] === 'string' || arguments[0] instanceof Date)) {
date = arguments[0];
if (date instanceof Date)
date = this._local_to_utc(date);
fromArgs = true;
} else {
date = this.isInput ? this.element.val() : this.element.data('date') || this.element.find('input').val();
delete this.element.data().date;
}
this.date = DPGlobal.parseDate(date, this.o.format, this.o.language);
if (fromArgs) {
// setting date by clicking
this.setValue();
} else if (date) {
// setting date by typing
if (oldDate.getTime() !== this.date.getTime())
this._trigger('changeDate');
} else {
// clearing date
this._trigger('clearDate');
}
if (this.date < this.o.startDate) {
this.viewDate = new Date(this.o.startDate);
this.date = new Date(this.o.startDate);
} else if (this.date > this.o.endDate) {
this.viewDate = new Date(this.o.endDate);
this.date = new Date(this.o.endDate);
} else {
this.viewDate = new Date(this.date);
this.date = new Date(this.date);
}
this.fill();
},
fillDow: function () {
var dowCnt = this.o.weekStart,
html = '<tr>';
if (this.o.calendarWeeks) {
var cell = '<th class="cw"> </th>';
html += cell;
this.picker.find('.datepicker-days thead tr:first-child').prepend(cell);
}
while (dowCnt < this.o.weekStart + 7) {
html += '<th class="dow">' + dates[this.o.language].daysMin[(dowCnt++) % 7] + '</th>';
}
html += '</tr>';
this.picker.find('.datepicker-days thead').append(html);
},
fillMonths: function () {
var html = '',
i = 0;
while (i < 12) {
html += '<span class="month">' + dates[this.o.language].monthsShort[i++] + '</span>';
}
this.picker.find('.datepicker-months td').html(html);
},
setRange: function (range) {
if (!range || !range.length)
delete this.range;
else
this.range = $.map(range, function (d) { return d.valueOf(); });
this.fill();
},
getClassNames: function (date) {
var cls = [],
year = this.viewDate.getUTCFullYear(),
month = this.viewDate.getUTCMonth(),
currentDate = this.date.valueOf(),
today = new Date();
if (date.getUTCFullYear() < year || (date.getUTCFullYear() == year && date.getUTCMonth() < month)) {
cls.push('old');
} else if (date.getUTCFullYear() > year || (date.getUTCFullYear() == year && date.getUTCMonth() > month)) {
cls.push('new');
}
// Compare internal UTC date with local today, not UTC today
if (this.o.todayHighlight &&
date.getUTCFullYear() == today.getFullYear() &&
date.getUTCMonth() == today.getMonth() &&
date.getUTCDate() == today.getDate()) {
cls.push('today');
}
if (currentDate && date.valueOf() == currentDate) {
cls.push('active');
}
if (date.valueOf() < this.o.startDate || date.valueOf() > this.o.endDate ||
$.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1) {
cls.push('disabled');
}
if (this.range) {
if (date > this.range[0] && date < this.range[this.range.length - 1]) {
cls.push('range');
}
if ($.inArray(date.valueOf(), this.range) != -1) {
cls.push('selected');
}
}
return cls;
},
fill: function () {
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth(),
startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity,
startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity,
endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity,
endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity,
currentDate = this.date && this.date.valueOf(),
tooltip;
this.picker.find('.datepicker-days thead th.datepicker-switch')
.text(dates[this.o.language].months[month] + ' ' + year);
this.picker.find('tfoot th.today')
.text(dates[this.o.language].today)
.toggle(this.o.todayBtn !== false);
this.picker.find('tfoot th.clear')
.text(dates[this.o.language].clear)
.toggle(this.o.clearBtn !== false);
this.updateNavArrows();
this.fillMonths();
var prevMonth = UTCDate(year, month - 1, 28, 0, 0, 0, 0),
day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
prevMonth.setUTCDate(day);
prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7) % 7);
var nextMonth = new Date(prevMonth);
nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
nextMonth = nextMonth.valueOf();
var html = [];
var clsName;
while (prevMonth.valueOf() < nextMonth) {
if (prevMonth.getUTCDay() == this.o.weekStart) {
html.push('<tr>');
if (this.o.calendarWeeks) {
// ISO 8601: First week contains first thursday.
// ISO also states week starts on Monday, but we can be more abstract here.
var
// Start of current week: based on weekstart/current date
ws = new Date(+prevMonth + (this.o.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5),
// Thursday of this week
th = new Date(+ws + (7 + 4 - ws.getUTCDay()) % 7 * 864e5),
// First Thursday of year, year from thursday
yth = new Date(+(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay()) % 7 * 864e5),
// Calendar week: ms between thursdays, div ms per day, div 7 days
calWeek = (th - yth) / 864e5 / 7 + 1;
html.push('<td class="cw">' + calWeek + '</td>');
}
}
clsName = this.getClassNames(prevMonth);
clsName.push('day');
if (this.o.beforeShowDay !== $.noop) {
var before = this.o.beforeShowDay(this._utc_to_local(prevMonth));
if (before === undefined)
before = {};
else if (typeof (before) === 'boolean')
before = { enabled: before };
else if (typeof (before) === 'string')
before = { classes: before };
if (before.enabled === false)
clsName.push('disabled');
if (before.classes)
clsName = clsName.concat(before.classes.split(/\s+/));
if (before.tooltip)
tooltip = before.tooltip;
}
clsName = $.unique(clsName);
html.push('<td class="' + clsName.join(' ') + '"' + (tooltip ? ' title="' + tooltip + '"' : '') + '>' + prevMonth.getUTCDate() + '</td>');
if (prevMonth.getUTCDay() == this.o.weekEnd) {
html.push('</tr>');
}
prevMonth.setUTCDate(prevMonth.getUTCDate() + 1);
}
this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
var currentYear = this.date && this.date.getUTCFullYear();
var months = this.picker.find('.datepicker-months')
.find('th:eq(1)')
.text(year)
.end()
.find('span').removeClass('active');
if (currentYear && currentYear == year) {
months.eq(this.date.getUTCMonth()).addClass('active');
}
if (year < startYear || year > endYear) {
months.addClass('disabled');
}
if (year == startYear) {
months.slice(0, startMonth).addClass('disabled');
}
if (year == endYear) {
months.slice(endMonth + 1).addClass('disabled');
}
html = '';
year = parseInt(year / 10, 10) * 10;
var yearCont = this.picker.find('.datepicker-years')
.find('th:eq(1)')
.text(year + '-' + (year + 9))
.end()
.find('td');
year -= 1;
for (var i = -1; i < 11; i++) {
html += '<span class="year' + (i == -1 ? ' old' : i == 10 ? ' new' : '') + (currentYear == year ? ' active' : '') + (year < startYear || year > endYear ? ' disabled' : '') + '">' + year + '</span>';
year += 1;
}
yearCont.html(html);
},
updateNavArrows: function () {
if (!this._allow_update) return;
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth();
switch (this.viewMode) {
case 0:
if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear() && month <= this.o.startDate.getUTCMonth()) {
this.picker.find('.prev').css({ visibility: 'hidden' });
} else {
this.picker.find('.prev').css({ visibility: 'visible' });
}
if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear() && month >= this.o.endDate.getUTCMonth()) {
this.picker.find('.next').css({ visibility: 'hidden' });
} else {
this.picker.find('.next').css({ visibility: 'visible' });
}
break;
case 1:
case 2:
if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear()) {
this.picker.find('.prev').css({ visibility: 'hidden' });
} else {
this.picker.find('.prev').css({ visibility: 'visible' });
}
if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear()) {
this.picker.find('.next').css({ visibility: 'hidden' });
} else {
this.picker.find('.next').css({ visibility: 'visible' });
}
break;
}
},
click: function (e) {
e.preventDefault();
var target = $(e.target).closest('span, td, th');
if (target.length == 1) {
switch (target[0].nodeName.toLowerCase()) {
case 'th':
switch (target[0].className) {
case 'datepicker-switch':
this.showMode(1);
break;
case 'prev':
case 'next':
var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className == 'prev' ? -1 : 1);
switch (this.viewMode) {
case 0:
this.viewDate = this.moveMonth(this.viewDate, dir);
this._trigger('changeMonth', this.viewDate);
break;
case 1:
case 2:
this.viewDate = this.moveYear(this.viewDate, dir);
if (this.viewMode === 1)
this._trigger('changeYear', this.viewDate);
break;
}
this.fill();
break;
case 'today':
var date = new Date();
date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
this.showMode(-2);
var which = this.o.todayBtn == 'linked' ? null : 'view';
this._setDate(date, which);
break;
case 'clear':
var element;
if (this.isInput)
element = this.element;
else if (this.component)
element = this.element.find('input');
if (element)
element.val("").change();
this._trigger('changeDate');
this.update();
if (this.o.autoclose)
this.hide();
break;
}
break;
case 'span':
if (!target.is('.disabled')) {
this.viewDate.setUTCDate(1);
if (target.is('.month')) {
var day = 1;
var month = target.parent().find('span').index(target);
var year = this.viewDate.getUTCFullYear();
this.viewDate.setUTCMonth(month);
this._trigger('changeMonth', this.viewDate);
if (this.o.minViewMode === 1) {
this._setDate(UTCDate(year, month, day, 0, 0, 0, 0));
}
} else {
var year = parseInt(target.text(), 10) || 0;
var day = 1;
var month = 0;
this.viewDate.setUTCFullYear(year);
this._trigger('changeYear', this.viewDate);
if (this.o.minViewMode === 2) {
this._setDate(UTCDate(year, month, day, 0, 0, 0, 0));
}
}
this.showMode(-1);
this.fill();
}
break;
case 'td':
if (target.is('.day') && !target.is('.disabled')) {
var day = parseInt(target.text(), 10) || 1;
var year = this.viewDate.getUTCFullYear(),
month = this.viewDate.getUTCMonth();
if (target.is('.old')) {
if (month === 0) {
month = 11;
year -= 1;
} else {
month -= 1;
}
} else if (target.is('.new')) {
if (month == 11) {
month = 0;
year += 1;
} else {
month += 1;
}
}
this._setDate(UTCDate(year, month, day, 0, 0, 0, 0));
}
break;
}
}
},
_setDate: function (date, which) {
if (!which || which == 'date')
this.date = new Date(date);
if (!which || which == 'view')
this.viewDate = new Date(date);
this.fill();
this.setValue();
this._trigger('changeDate');
var element;
if (this.isInput) {
element = this.element;
} else if (this.component) {
element = this.element.find('input');
}
if (element) {
element.change();
}
if (this.o.autoclose && (!which || which == 'date')) {
this.hide();
}
},
moveMonth: function (date, dir) {
if (!dir) return date;
var new_date = new Date(date.valueOf()),
day = new_date.getUTCDate(),
month = new_date.getUTCMonth(),
mag = Math.abs(dir),
new_month, test;
dir = dir > 0 ? 1 : -1;
if (mag == 1) {
test = dir == -1
// If going back one month, make sure month is not current month
// (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
? function () { return new_date.getUTCMonth() == month; }
// If going forward one month, make sure month is as expected
// (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
: function () { return new_date.getUTCMonth() != new_month; };
new_month = month + dir;
new_date.setUTCMonth(new_month);
// Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
if (new_month < 0 || new_month > 11)
new_month = (new_month + 12) % 12;
} else {
// For magnitudes >1, move one month at a time...
for (var i = 0; i < mag; i++)
// ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
new_date = this.moveMonth(new_date, dir);
// ...then reset the day, keeping it in the new month
new_month = new_date.getUTCMonth();
new_date.setUTCDate(day);
test = function () { return new_month != new_date.getUTCMonth(); };
}
// Common date-resetting loop -- if date is beyond end of month, make it
// end of month
while (test()) {
new_date.setUTCDate(--day);
new_date.setUTCMonth(new_month);
}
return new_date;
},
moveYear: function (date, dir) {
return this.moveMonth(date, dir * 12);
},
dateWithinRange: function (date) {
return date >= this.o.startDate && date <= this.o.endDate;
},
keydown: function (e) {
if (this.picker.is(':not(:visible)')) {
if (e.keyCode == 27) // allow escape to hide and re-show picker
this.show();
return;
}
var dateChanged = false,
dir, day, month,
newDate, newViewDate;
switch (e.keyCode) {
case 27: // escape
this.hide();
e.preventDefault();
break;
case 37: // left
case 39: // right
if (!this.o.keyboardNavigation) break;
dir = e.keyCode == 37 ? -1 : 1;
if (e.ctrlKey) {
newDate = this.moveYear(this.date, dir);
newViewDate = this.moveYear(this.viewDate, dir);
this._trigger('changeYear', this.viewDate);
} else if (e.shiftKey) {
newDate = this.moveMonth(this.date, dir);
newViewDate = this.moveMonth(this.viewDate, dir);
this._trigger('changeMonth', this.viewDate);
} else {
newDate = new Date(this.date);
newDate.setUTCDate(this.date.getUTCDate() + dir);
newViewDate = new Date(this.viewDate);
newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir);
}
if (this.dateWithinRange(newDate)) {
this.date = newDate;
this.viewDate = newViewDate;
this.setValue();
this.update();
e.preventDefault();
dateChanged = true;
}
break;
case 38: // up
case 40: // down
if (!this.o.keyboardNavigation) break;
dir = e.keyCode == 38 ? -1 : 1;
if (e.ctrlKey) {
newDate = this.moveYear(this.date, dir);
newViewDate = this.moveYear(this.viewDate, dir);
this._trigger('changeYear', this.viewDate);
} else if (e.shiftKey) {
newDate = this.moveMonth(this.date, dir);
newViewDate = this.moveMonth(this.viewDate, dir);
this._trigger('changeMonth', this.viewDate);
} else {
newDate = new Date(this.date);
newDate.setUTCDate(this.date.getUTCDate() + dir * 7);
newViewDate = new Date(this.viewDate);
newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7);
}
if (this.dateWithinRange(newDate)) {
this.date = newDate;
this.viewDate = newViewDate;
this.setValue();
this.update();
e.preventDefault();
dateChanged = true;
}
break;
case 13: // enter
this.hide();
e.preventDefault();
break;
case 9: // tab
this.hide();
break;
}
if (dateChanged) {
this._trigger('changeDate');
var element;
if (this.isInput) {
element = this.element;
} else if (this.component) {
element = this.element.find('input');
}
if (element) {
element.change();
}
}
},
showMode: function (dir) {
if (dir) {
this.viewMode = Math.max(this.o.minViewMode, Math.min(2, this.viewMode + dir));
}
/*
vitalets: fixing bug of very special conditions:
jquery 1.7.1 + webkit + show inline datepicker in bootstrap popover.
Method show() does not set display css correctly and datepicker is not shown.
Changed to .css('display', 'block') solve the problem.
See https://github.com/vitalets/x-editable/issues/37
In jquery 1.7.2+ everything works fine.
*/
//this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
this.picker.find('>div').hide().filter('.datepicker-' + DPGlobal.modes[this.viewMode].clsName).css('display', 'block');
this.updateNavArrows();
}
};
var DateRangePicker = function (element, options) {
this.element = $(element);
this.inputs = $.map(options.inputs, function (i) { return i.jquery ? i[0] : i; });
delete options.inputs;
$(this.inputs)
.datepicker(options)
.bind('changeDate', $.proxy(this.dateUpdated, this));
this.pickers = $.map(this.inputs, function (i) { return $(i).data('datepicker'); });
this.updateDates();
};
DateRangePicker.prototype = {
updateDates: function () {
this.dates = $.map(this.pickers, function (i) { return i.date; });
this.updateRanges();
},
updateRanges: function () {
var range = $.map(this.dates, function (d) { return d.valueOf(); });
$.each(this.pickers, function (i, p) {
p.setRange(range);
});
},
dateUpdated: function (e) {
var dp = $(e.target).data('datepicker'),
new_date = dp.getUTCDate(),
i = $.inArray(e.target, this.inputs),
l = this.inputs.length;
if (i == -1) return;
if (new_date < this.dates[i]) {
// Date being moved earlier/left
while (i >= 0 && new_date < this.dates[i]) {
this.pickers[i--].setUTCDate(new_date);
}
}
else if (new_date > this.dates[i]) {
// Date being moved later/right
while (i < l && new_date > this.dates[i]) {
this.pickers[i++].setUTCDate(new_date);
}
}
this.updateDates();
},
remove: function () {
$.map(this.pickers, function (p) { p.remove(); });
delete this.element.data().datepicker;
}
};
function opts_from_el(el, prefix) {
// Derive options from element data-attrs
var data = $(el).data(),
out = {}, inkey,
replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])'),
prefix = new RegExp('^' + prefix.toLowerCase());
for (var key in data)
if (prefix.test(key)) {
inkey = key.replace(replace, function (_, a) { return a.toLowerCase(); });
out[inkey] = data[key];
}
return out;
}
function opts_from_locale(lang) {
// Derive options from locale plugins
var out = {};
// Check if "de-DE" style date is available, if not language should
// fallback to 2 letter code eg "de"
if (!dates[lang]) {
lang = lang.split('-')[0]
if (!dates[lang])
return;
}
var d = dates[lang];
$.each(locale_opts, function (i, k) {
if (k in d)
out[k] = d[k];
});
return out;
}
var old = $.fn.datepicker;
$.fn.datepicker = function (option) {
var args = Array.apply(null, arguments);
args.shift();
var internal_return,
this_return;
this.each(function () {
var $this = $(this),
data = $this.data('datepicker'),
options = typeof option == 'object' && option;
if (!data) {
var elopts = opts_from_el(this, 'date'),
// Preliminary otions
xopts = $.extend({}, defaults, elopts, options),
locopts = opts_from_locale(xopts.language),
// Options priority: js args, data-attrs, locales, defaults
opts = $.extend({}, defaults, locopts, elopts, options);
if ($this.is('.input-daterange') || opts.inputs) {
var ropts = {
inputs: opts.inputs || $this.find('input').toArray()
};
$this.data('datepicker', (data = new DateRangePicker(this, $.extend(opts, ropts))));
}
else {
$this.data('datepicker', (data = new Datepicker(this, opts)));
}
}
if (typeof option == 'string' && typeof data[option] == 'function') {
internal_return = data[option].apply(data, args);
if (internal_return !== undefined)
return false;
}
});
if (internal_return !== undefined)
return internal_return;
else
return this;
};
var defaults = $.fn.datepicker.defaults = {
autoclose: false,
beforeShowDay: $.noop,
calendarWeeks: false,
clearBtn: false,
daysOfWeekDisabled: [],
endDate: Infinity,
forceParse: true,
format: 'mm/dd/yyyy',
keyboardNavigation: true,
language: 'en',
minViewMode: 0,
orientation: "auto",
rtl: false,
startDate: -Infinity,
startView: 0,
todayBtn: false,
todayHighlight: false,
weekStart: 0
};
var locale_opts = $.fn.datepicker.locale_opts = [
'format',
'rtl',
'weekStart'
];
$.fn.datepicker.Constructor = Datepicker;
var dates = $.fn.datepicker.dates = {
en: {
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Today",
clear: "Clear"
}
};
var DPGlobal = {
modes: [
{
clsName: 'days',
navFnc: 'Month',
navStep: 1
},
{
clsName: 'months',
navFnc: 'FullYear',
navStep: 1
},
{
clsName: 'years',
navFnc: 'FullYear',
navStep: 10
}],
isLeapYear: function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
},
getDaysInMonth: function (year, month) {
return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
},
validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,
parseFormat: function (format) {
// IE treats \0 as a string end in inputs (truncating the value),
// so it's a bad format delimiter, anyway
var separators = format.replace(this.validParts, '\0').split('\0'),
parts = format.match(this.validParts);
if (!separators || !separators.length || !parts || parts.length === 0) {
throw new Error("Invalid date format.");
}
return { separators: separators, parts: parts };
},
parseDate: function (date, format, language) {
if (date instanceof Date) return date;
if (typeof format === 'string')
format = DPGlobal.parseFormat(format);
if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)) {
var part_re = /([\-+]\d+)([dmwy])/,
parts = date.match(/([\-+]\d+)([dmwy])/g),
part, dir;
date = new Date();
for (var i = 0; i < parts.length; i++) {
part = part_re.exec(parts[i]);
dir = parseInt(part[1]);
switch (part[2]) {
case 'd':
date.setUTCDate(date.getUTCDate() + dir);
break;
case 'm':
date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir);
break;
case 'w':
date.setUTCDate(date.getUTCDate() + dir * 7);
break;
case 'y':
date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir);
break;
}
}
return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0);
}
var parts = date && date.match(this.nonpunctuation) || [],
date = new Date(),
parsed = {},
setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'],
setters_map = {
yyyy: function (d, v) { return d.setUTCFullYear(v); },
yy: function (d, v) { return d.setUTCFullYear(2000 + v); },
m: function (d, v) {
if (isNaN(d))
return d;
v -= 1;
while (v < 0) v += 12;
v %= 12;
d.setUTCMonth(v);
while (d.getUTCMonth() != v)
d.setUTCDate(d.getUTCDate() - 1);
return d;
},
d: function (d, v) { return d.setUTCDate(v); }
},
val, filtered, part;
setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
setters_map['dd'] = setters_map['d'];
date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
var fparts = format.parts.slice();
// Remove noop parts
if (parts.length != fparts.length) {
fparts = $(fparts).filter(function (i, p) {
return $.inArray(p, setters_order) !== -1;
}).toArray();
}
// Process remainder
if (parts.length == fparts.length) {
for (var i = 0, cnt = fparts.length; i < cnt; i++) {
val = parseInt(parts[i], 10);
part = fparts[i];
if (isNaN(val)) {
switch (part) {
case 'MM':
filtered = $(dates[language].months).filter(function () {
var m = this.slice(0, parts[i].length),
p = parts[i].slice(0, m.length);
return m == p;
});
val = $.inArray(filtered[0], dates[language].months) + 1;
break;
case 'M':
filtered = $(dates[language].monthsShort).filter(function () {
var m = this.slice(0, parts[i].length),
p = parts[i].slice(0, m.length);
return m == p;
});
val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
break;
}
}
parsed[part] = val;
}
for (var i = 0, _date, s; i < setters_order.length; i++) {
s = setters_order[i];
if (s in parsed && !isNaN(parsed[s])) {
_date = new Date(date);
setters_map[s](_date, parsed[s]);
if (!isNaN(_date))
date = _date;
}
}
}
return date;
},
formatDate: function (date, format, language) {
if (typeof format === 'string')
format = DPGlobal.parseFormat(format);
var val = {
d: date.getUTCDate(),
D: dates[language].daysShort[date.getUTCDay()],
DD: dates[language].days[date.getUTCDay()],
m: date.getUTCMonth() + 1,
M: dates[language].monthsShort[date.getUTCMonth()],
MM: dates[language].months[date.getUTCMonth()],
yy: date.getUTCFullYear().toString().substring(2),
yyyy: date.getUTCFullYear()
};
val.dd = (val.d < 10 ? '0' : '') + val.d;
val.mm = (val.m < 10 ? '0' : '') + val.m;
var date = [],
seps = $.extend([], format.separators);
for (var i = 0, cnt = format.parts.length; i <= cnt; i++) {
if (seps.length)
date.push(seps.shift());
date.push(val[format.parts[i]]);
}
return date.join('');
},
headTemplate: '<thead>' +
'<tr>' +
'<th class="prev">«</th>' +
'<th colspan="5" class="datepicker-switch"></th>' +
'<th class="next">»</th>' +
'</tr>' +
'</thead>',
contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr><tr><th colspan="7" class="clear"></th></tr></tfoot>'
};
DPGlobal.template = '<div class="datepicker">' +
'<div class="datepicker-days">' +
'<table class=" table-condensed">' +
DPGlobal.headTemplate +
'<tbody></tbody>' +
DPGlobal.footTemplate +
'</table>' +
'</div>' +
'<div class="datepicker-months">' +
'<table class="table-condensed">' +
DPGlobal.headTemplate +
DPGlobal.contTemplate +
DPGlobal.footTemplate +
'</table>' +
'</div>' +
'<div class="datepicker-years">' +
'<table class="table-condensed">' +
DPGlobal.headTemplate +
DPGlobal.contTemplate +
DPGlobal.footTemplate +
'</table>' +
'</div>' +
'</div>';
$.fn.datepicker.DPGlobal = DPGlobal;
/* DATEPICKER NO CONFLICT
* =================== */
$.fn.datepicker.noConflict = function () {
$.fn.datepicker = old;
return this;
};
/* DATEPICKER DATA-API
* ================== */
$(document).on(
'focus.datepicker.data-api click.datepicker.data-api',
'[data-provide="datepicker"]',
function (e) {
var $this = $(this);
if ($this.data('datepicker')) return;
e.preventDefault();
// component click requires us to explicitly show it
$this.datepicker('show');
}
);
$(function () {
$('[data-provide="datepicker-inline"]').datepicker();
});
}(window.jQuery));
/**
* Arabic translation for bootstrap-datepicker
* Mohammed Alshehri <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['ar'] = {
days: ["الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت", "الأحد"],
daysShort: ["أحد", "اثنين", "ثلاثاء", "أربعاء", "خميس", "جمعة", "سبت", "أحد"],
daysMin: ["ح", "ن", "ث", "ع", "خ", "ج", "س", "ح"],
months: ["يناير", "فبراير", "مارس", "أبريل", "مايو", "يونيو", "يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر"],
monthsShort: ["يناير", "فبراير", "مارس", "أبريل", "مايو", "يونيو", "يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر"],
today: "هذا اليوم",
rtl: true
};
}(jQuery));
/**
* Bulgarian translation for bootstrap-datepicker
* Apostol Apostolov <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['bg'] = {
days: ["Неделя", "Понеделник", "Вторник", "Сряда", "Четвъртък", "Петък", "Събота", "Неделя"],
daysShort: ["Нед", "Пон", "Вто", "Сря", "Чет", "Пет", "Съб", "Нед"],
daysMin: ["Н", "П", "В", "С", "Ч", "П", "С", "Н"],
months: ["Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"],
monthsShort: ["Ян", "Фев", "Мар", "Апр", "Май", "Юни", "Юли", "Авг", "Сеп", "Окт", "Ное", "Дек"],
today: "днес"
};
}(jQuery));
/**
* Catalan translation for bootstrap-datepicker
* J. Garcia <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['ca'] = {
days: ["Diumenge", "Dilluns", "Dimarts", "Dimecres", "Dijous", "Divendres", "Dissabte", "Diumenge"],
daysShort: ["Diu", "Dil", "Dmt", "Dmc", "Dij", "Div", "Dis", "Diu"],
daysMin: ["dg", "dl", "dt", "dc", "dj", "dv", "ds", "dg"],
months: ["Gener", "Febrer", "Març", "Abril", "Maig", "Juny", "Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre"],
monthsShort: ["Gen", "Feb", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Oct", "Nov", "Des"],
today: "Avui"
};
}(jQuery));
/**
* Czech translation for bootstrap-datepicker
* Matěj Koubík <[email protected]>
* Fixes by Michal Remiš <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['cs'] = {
days: ["Neděle", "Pondělí", "Úterý", "Středa", "Čtvrtek", "Pátek", "Sobota", "Neděle"],
daysShort: ["Ned", "Pon", "Úte", "Stř", "Čtv", "Pát", "Sob", "Ned"],
daysMin: ["Ne", "Po", "Út", "St", "Čt", "Pá", "So", "Ne"],
months: ["Leden", "Únor", "Březen", "Duben", "Květen", "Červen", "Červenec", "Srpen", "Září", "Říjen", "Listopad", "Prosinec"],
monthsShort: ["Led", "Úno", "Bře", "Dub", "Kvě", "Čer", "Čnc", "Srp", "Zář", "Říj", "Lis", "Pro"],
today: "Dnes"
};
}(jQuery));
/**
* Danish translation for bootstrap-datepicker
* Christian Pedersen <http://github.com/chripede>
*/
; (function ($) {
$.fn.datepicker.dates['da'] = {
days: ["Søndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag", "Søndag"],
daysShort: ["Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør", "Søn"],
daysMin: ["Sø", "Ma", "Ti", "On", "To", "Fr", "Lø", "Sø"],
months: ["Januar", "Februar", "Marts", "April", "Maj", "Juni", "Juli", "August", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
today: "I Dag"
};
}(jQuery));
/**
* German translation for bootstrap-datepicker
* Sam Zurcher <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['de'] = {
days: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"],
daysShort: ["Son", "Mon", "Die", "Mit", "Don", "Fre", "Sam", "Son"],
daysMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"],
months: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
monthsShort: ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
today: "Heute",
weekStart: 1,
format: "dd.mm.yyyy"
};
}(jQuery));
/**
* Greek translation for bootstrap-datepicker
*/
; (function ($) {
$.fn.datepicker.dates['el'] = {
days: ["Κυριακή", "Δευτέρα", "Τρίτη", "Τετάρτη", "Πέμπτη", "Παρασκευή", "Σάββατο", "Κυριακή"],
daysShort: ["Κυρ", "Δευ", "Τρι", "Τετ", "Πεμ", "Παρ", "Σαβ", "Κυρ"],
daysMin: ["Κυ", "Δε", "Τρ", "Τε", "Πε", "Πα", "Σα", "Κυ"],
months: ["Ιανουάριος", "Φεβρουάριος", "Μάρτιος", "Απρίλιος", "Μάιος", "Ιούνιος", "Ιούλιος", "Αύγουστος", "Σεπτέμβριος", "Οκτώβριος", "Νοέμβριος", "Δεκέμβριος"],
monthsShort: ["Ιαν", "Φεβ", "Μαρ", "Απρ", "Μάι", "Ιουν", "Ιουλ", "Αυγ", "Σεπ", "Οκτ", "Νοε", "Δεκ"],
today: "Σήμερα"
};
}(jQuery));
/**
* Spanish translation for bootstrap-datepicker
* Bruno Bonamin <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['es'] = {
days: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"],
daysShort: ["Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb", "Dom"],
daysMin: ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa", "Do"],
months: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"],
monthsShort: ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"],
today: "Hoy"
};
}(jQuery));
/**
* Estonian translation for bootstrap-datepicker
* Ando Roots <https://github.com/anroots>
*/
; (function ($) {
$.fn.datepicker.dates['et'] = {
days: ["Pühapäev", "Esmaspäev", "Teisipäev", "Kolmapäev", "Neljapäev", "Reede", "Laupäev", "Pühapäev"],
daysShort: ["Püh", "Esm", "Tei", "Kol", "Nel", "Ree", "Lau", "Sun"],
daysMin: ["P", "E", "T", "K", "N", "R", "L", "P"],
months: ["Jaanuar", "Veebruar", "Märts", "Aprill", "Mai", "Juuni", "Juuli", "August", "September", "Oktoober", "November", "Detsember"],
monthsShort: ["Jaan", "Veeb", "Märts", "Apr", "Mai", "Juuni", "Juuli", "Aug", "Sept", "Okt", "Nov", "Dets"],
today: "Täna"
};
}(jQuery));
/**
* Finnish translation for bootstrap-datepicker
* Jaakko Salonen <https://github.com/jsalonen>
*/
; (function ($) {
$.fn.datepicker.dates['fi'] = {
days: ["sunnuntai", "maanantai", "tiistai", "keskiviikko", "torstai", "perjantai", "lauantai", "sunnuntai"],
daysShort: ["sun", "maa", "tii", "kes", "tor", "per", "lau", "sun"],
daysMin: ["su", "ma", "ti", "ke", "to", "pe", "la", "su"],
months: ["tammikuu", "helmikuu", "maaliskuu", "huhtikuu", "toukokuu", "kesäkuu", "heinäkuu", "elokuu", "syyskuu", "lokakuu", "marraskuu", "joulukuu"],
monthsShort: ["tam", "hel", "maa", "huh", "tou", "kes", "hei", "elo", "syy", "lok", "mar", "jou"],
today: "tänään",
weekStart: 1,
format: "d.m.yyyy"
};
}(jQuery));
/**
* French translation for bootstrap-datepicker
* Nico Mollet <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['fr'] = {
days: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"],
daysShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"],
daysMin: ["D", "L", "Ma", "Me", "J", "V", "S", "D"],
months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
monthsShort: ["Jan", "Fev", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Dec"],
today: "Aujourd'hui",
clear: "Effacer",
weekStart: 1,
format: "dd/mm/yyyy"
};
}(jQuery));
/**
* Hebrew translation for bootstrap-datepicker
* Sagie Maoz <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['he'] = {
days: ["ראשון", "שני", "שלישי", "רביעי", "חמישי", "שישי", "שבת", "ראשון"],
daysShort: ["א", "ב", "ג", "ד", "ה", "ו", "ש", "א"],
daysMin: ["א", "ב", "ג", "ד", "ה", "ו", "ש", "א"],
months: ["ינואר", "פברואר", "מרץ", "אפריל", "מאי", "יוני", "יולי", "אוגוסט", "ספטמבר", "אוקטובר", "נובמבר", "דצמבר"],
monthsShort: ["ינו", "פבר", "מרץ", "אפר", "מאי", "יונ", "יול", "אוג", "ספט", "אוק", "נוב", "דצמ"],
today: "היום",
rtl: true
};
}(jQuery));
/**
* Croatian localisation
*/
; (function ($) {
$.fn.datepicker.dates['hr'] = {
days: ["Nedjelja", "Ponedjelja", "Utorak", "Srijeda", "Četrtak", "Petak", "Subota", "Nedjelja"],
daysShort: ["Ned", "Pon", "Uto", "Srr", "Čet", "Pet", "Sub", "Ned"],
daysMin: ["Ne", "Po", "Ut", "Sr", "Če", "Pe", "Su", "Ne"],
months: ["Siječanj", "Veljača", "Ožujak", "Travanj", "Svibanj", "Lipanj", "Srpanj", "Kolovoz", "Rujan", "Listopad", "Studeni", "Prosinac"],
monthsShort: ["Sije", "Velj", "Ožu", "Tra", "Svi", "Lip", "Jul", "Kol", "Ruj", "Lis", "Stu", "Pro"],
today: "Danas"
};
}(jQuery));
/**
* Hungarian translation for bootstrap-datepicker
* Sotus László <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['hu'] = {
days: ["Vasárnap", "Hétfő", "Kedd", "Szerda", "Csütörtök", "Péntek", "Szombat", "Vasárnap"],
daysShort: ["Vas", "Hét", "Ked", "Sze", "Csü", "Pén", "Szo", "Vas"],
daysMin: ["Va", "Hé", "Ke", "Sz", "Cs", "Pé", "Sz", "Va"],
months: ["Január", "Február", "Március", "Április", "Május", "Június", "Július", "Augusztus", "Szeptember", "Október", "November", "December"],
monthsShort: ["Jan", "Feb", "Már", "Ápr", "Máj", "Jún", "Júl", "Aug", "Sze", "Okt", "Nov", "Dec"],
today: "Ma",
weekStart: 1,
format: "yyyy.mm.dd"
};
}(jQuery));
/**
* Bahasa translation for bootstrap-datepicker
* Azwar Akbar <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['id'] = {
days: ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu", "Minggu"],
daysShort: ["Mgu", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab", "Mgu"],
daysMin: ["Mg", "Sn", "Sl", "Ra", "Ka", "Ju", "Sa", "Mg"],
months: ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Ags", "Sep", "Okt", "Nov", "Des"],
today: "Hari Ini",
clear: "Kosongkan"
};
}(jQuery));
/**
* Icelandic translation for bootstrap-datepicker
* Hinrik Örn Sigurðsson <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['is'] = {
days: ["Sunnudagur", "Mánudagur", "Þriðjudagur", "Miðvikudagur", "Fimmtudagur", "Föstudagur", "Laugardagur", "Sunnudagur"],
daysShort: ["Sun", "Mán", "Þri", "Mið", "Fim", "Fös", "Lau", "Sun"],
daysMin: ["Su", "Má", "Þr", "Mi", "Fi", "Fö", "La", "Su"],
months: ["Janúar", "Febrúar", "Mars", "Apríl", "Maí", "Júní", "Júlí", "Ágúst", "September", "Október", "Nóvember", "Desember"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maí", "Jún", "Júl", "Ágú", "Sep", "Okt", "Nóv", "Des"],
today: "Í Dag"
};
}(jQuery));
/**
* Italian translation for bootstrap-datepicker
* Enrico Rubboli <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['it'] = {
days: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato", "Domenica"],
daysShort: ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab", "Dom"],
daysMin: ["Do", "Lu", "Ma", "Me", "Gi", "Ve", "Sa", "Do"],
months: ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"],
monthsShort: ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"],
today: "Oggi",
weekStart: 1,
format: "dd/mm/yyyy"
};
}(jQuery));
/**
* Japanese translation for bootstrap-datepicker
* Norio Suzuki <https://github.com/suzuki/>
*/
; (function ($) {
$.fn.datepicker.dates['ja'] = {
days: ["日曜", "月曜", "火曜", "水曜", "木曜", "金曜", "土曜", "日曜"],
daysShort: ["日", "月", "火", "水", "木", "金", "土", "日"],
daysMin: ["日", "月", "火", "水", "木", "金", "土", "日"],
months: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
monthsShort: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
today: "今日",
format: "yyyy/mm/dd"
};
}(jQuery));
/**
* Georgian translation for bootstrap-datepicker
* Levan Melikishvili <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['ka'] = {
days: ["კვირა", "ორშაბათი", "სამშაბათი", "ოთხშაბათი", "ხუთშაბათი", "პარასკევი", "შაბათი", "კვირა"],
daysShort: ["კვი", "ორშ", "სამ", "ოთხ", "ხუთ", "პარ", "შაბ", "კვი"],
daysMin: ["კვ", "ორ", "სა", "ოთ", "ხუ", "პა", "შა", "კვ"],
months: ["იანვარი", "თებერვალი", "მარტი", "აპრილი", "მაისი", "ივნისი", "ივლისი", "აგვისტო", "სექტემბერი", "ოქტომები", "ნოემბერი", "დეკემბერი"],
monthsShort: ["იან", "თებ", "მარ", "აპრ", "მაი", "ივნ", "ივლ", "აგვ", "სექ", "ოქტ", "ნოე", "დეკ"],
today: "დღეს",
clear: "გასუფთავება"
};
}(jQuery));
/**
* Korean translation for bootstrap-datepicker
* Gu Youn <http://github.com/guyoun>
*/
; (function ($) {
$.fn.datepicker.dates['kr'] = {
days: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일", "일요일"],
daysShort: ["일", "월", "화", "수", "목", "금", "토", "일"],
daysMin: ["일", "월", "화", "수", "목", "금", "토", "일"],
months: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"],
monthsShort: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"]
};
}(jQuery));
/**
* Lithuanian translation for bootstrap-datepicker
* Šarūnas Gliebus <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['lt'] = {
days: ["Sekmadienis", "Pirmadienis", "Antradienis", "Trečiadienis", "Ketvirtadienis", "Penktadienis", "Šeštadienis", "Sekmadienis"],
daysShort: ["S", "Pr", "A", "T", "K", "Pn", "Š", "S"],
daysMin: ["Sk", "Pr", "An", "Tr", "Ke", "Pn", "Št", "Sk"],
months: ["Sausis", "Vasaris", "Kovas", "Balandis", "Gegužė", "Birželis", "Liepa", "Rugpjūtis", "Rugsėjis", "Spalis", "Lapkritis", "Gruodis"],
monthsShort: ["Sau", "Vas", "Kov", "Bal", "Geg", "Bir", "Lie", "Rugp", "Rugs", "Spa", "Lap", "Gru"],
today: "Šiandien",
weekStart: 1
};
}(jQuery));
/**
* Latvian translation for bootstrap-datepicker
* Artis Avotins <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['lv'] = {
days: ["Svētdiena", "Pirmdiena", "Otrdiena", "Trešdiena", "Ceturtdiena", "Piektdiena", "Sestdiena", "Svētdiena"],
daysShort: ["Sv", "P", "O", "T", "C", "Pk", "S", "Sv"],
daysMin: ["Sv", "Pr", "Ot", "Tr", "Ce", "Pk", "St", "Sv"],
months: ["Janvāris", "Februāris", "Marts", "Aprīlis", "Maijs", "Jūnijs", "Jūlijs", "Augusts", "Septembris", "Oktobris", "Novembris", "Decembris"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mai", "Jūn", "Jūl", "Aug", "Sep", "Okt", "Nov", "Dec."],
today: "Šodien",
weekStart: 1
};
}(jQuery));
/**
* Macedonian translation for bootstrap-datepicker
* Marko Aleksic <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['mk'] = {
days: ["Недела", "Понеделник", "Вторник", "Среда", "Четврток", "Петок", "Сабота", "Недела"],
daysShort: ["Нед", "Пон", "Вто", "Сре", "Чет", "Пет", "Саб", "Нед"],
daysMin: ["Не", "По", "Вт", "Ср", "Че", "Пе", "Са", "Не"],
months: ["Јануари", "Февруари", "Март", "Април", "Мај", "Јуни", "Јули", "Август", "Септември", "Октомври", "Ноември", "Декември"],
monthsShort: ["Јан", "Фев", "Мар", "Апр", "Мај", "Јун", "Јул", "Авг", "Сеп", "Окт", "Ное", "Дек"],
today: "Денес"
};
}(jQuery));
/**
* Malay translation for bootstrap-datepicker
* Ateman Faiz <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['ms'] = {
days: ["Ahad", "Isnin", "Selasa", "Rabu", "Khamis", "Jumaat", "Sabtu", "Ahad"],
daysShort: ["Aha", "Isn", "Sel", "Rab", "Kha", "Jum", "Sab", "Aha"],
daysMin: ["Ah", "Is", "Se", "Ra", "Kh", "Ju", "Sa", "Ah"],
months: ["Januari", "Februari", "Mac", "April", "Mei", "Jun", "Julai", "Ogos", "September", "Oktober", "November", "Disember"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Ogo", "Sep", "Okt", "Nov", "Dis"],
today: "Hari Ini"
};
}(jQuery));
/**
* Norwegian (bokmål) translation for bootstrap-datepicker
* Fredrik Sundmyhr <http://github.com/fsundmyhr>
*/
; (function ($) {
$.fn.datepicker.dates['nb'] = {
days: ["Søndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag", "Søndag"],
daysShort: ["Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør", "Søn"],
daysMin: ["Sø", "Ma", "Ti", "On", "To", "Fr", "Lø", "Sø"],
months: ["Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Des"],
today: "I Dag"
};
}(jQuery));
/**
* Dutch translation for bootstrap-datepicker
* Reinier Goltstein <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['nl'] = {
days: ["Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag", "Zondag"],
daysShort: ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za", "Zo"],
daysMin: ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za", "Zo"],
months: ["Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mrt", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
today: "Vandaag"
};
}(jQuery));
/**
* Norwegian translation for bootstrap-datepicker
**/
; (function ($) {
$.fn.datepicker.dates['no'] = {
days: ['Søndag', 'Mandag', 'Tirsdag', 'Onsdag', 'Torsdag', 'Fredag', 'Lørdag'],
daysShort: ['Søn', 'Man', 'Tir', 'Ons', 'Tor', 'Fre', 'Lør'],
daysMin: ['Sø', 'Ma', 'Ti', 'On', 'To', 'Fr', 'Lø'],
months: ['Januar', 'Februar', 'Mars', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Desember'],
monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Des'],
today: 'I dag',
clear: 'Nullstill',
weekStart: 0
};
}(jQuery));
/**
* Polish translation for bootstrap-datepicker
* Robert <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['pl'] = {
days: ["Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota", "Niedziela"],
daysShort: ["Nie", "Pn", "Wt", "Śr", "Czw", "Pt", "So", "Nie"],
daysMin: ["N", "Pn", "Wt", "Śr", "Cz", "Pt", "So", "N"],
months: ["Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień"],
monthsShort: ["Sty", "Lu", "Mar", "Kw", "Maj", "Cze", "Lip", "Sie", "Wrz", "Pa", "Lis", "Gru"],
today: "Dzisiaj",
weekStart: 1
};
}(jQuery));
/**
* Brazilian translation for bootstrap-datepicker
* Cauan Cabral <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['pt-BR'] = {
days: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo"],
daysShort: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb", "Dom"],
daysMin: ["Do", "Se", "Te", "Qu", "Qu", "Se", "Sa", "Do"],
months: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],
monthsShort: ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"],
today: "Hoje",
clear: "Limpar"
};
}(jQuery));
/**
* Portuguese translation for bootstrap-datepicker
* Original code: Cauan Cabral <[email protected]>
* Tiago Melo <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['pt'] = {
days: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo"],
daysShort: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb", "Dom"],
daysMin: ["Do", "Se", "Te", "Qu", "Qu", "Se", "Sa", "Do"],
months: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],
monthsShort: ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"],
today: "Hoje",
clear: "Limpar"
};
}(jQuery));
/**
* Romanian translation for bootstrap-datepicker
* Cristian Vasile <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['ro'] = {
days: ["Duminică", "Luni", "Marţi", "Miercuri", "Joi", "Vineri", "Sâmbătă", "Duminică"],
daysShort: ["Dum", "Lun", "Mar", "Mie", "Joi", "Vin", "Sâm", "Dum"],
daysMin: ["Du", "Lu", "Ma", "Mi", "Jo", "Vi", "Sâ", "Du"],
months: ["Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"],
monthsShort: ["Ian", "Feb", "Mar", "Apr", "Mai", "Iun", "Iul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Astăzi",
weekStart: 1
};
}(jQuery));
/**
* Serbian latin translation for bootstrap-datepicker
* Bojan Milosavlević <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['rs-latin'] = {
days: ["Nedelja", "Ponedeljak", "Utorak", "Sreda", "Četvrtak", "Petak", "Subota", "Nedelja"],
daysShort: ["Ned", "Pon", "Uto", "Sre", "Čet", "Pet", "Sub", "Ned"],
daysMin: ["N", "Po", "U", "Sr", "Č", "Pe", "Su", "N"],
months: ["Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Avg", "Sep", "Okt", "Nov", "Dec"],
today: "Danas"
};
}(jQuery));
/**
* Serbian cyrillic translation for bootstrap-datepicker
* Bojan Milosavlević <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['rs'] = {
days: ["Недеља", "Понедељак", "Уторак", "Среда", "Четвртак", "Петак", "Субота", "Недеља"],
daysShort: ["Нед", "Пон", "Уто", "Сре", "Чет", "Пет", "Суб", "Нед"],
daysMin: ["Н", "По", "У", "Ср", "Ч", "Пе", "Су", "Н"],
months: ["Јануар", "Фебруар", "Март", "Април", "Мај", "Јун", "Јул", "Август", "Септембар", "Октобар", "Новембар", "Децембар"],
monthsShort: ["Јан", "Феб", "Мар", "Апр", "Мај", "Јун", "Јул", "Авг", "Сеп", "Окт", "Нов", "Дец"],
today: "Данас"
};
}(jQuery));
/**
* Russian translation for bootstrap-datepicker
* Victor Taranenko <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['ru'] = {
days: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота", "Воскресенье"],
daysShort: ["Вск", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Суб", "Вск"],
daysMin: ["Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Вс"],
months: ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"],
monthsShort: ["Янв", "Фев", "Мар", "Апр", "Май", "Июн", "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек"],
today: "Сегодня",
weekStart: 1
};
}(jQuery));
/**
* Slovak translation for bootstrap-datepicker
* Marek Lichtner <[email protected]>
* Fixes by Michal Remiš <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates["sk"] = {
days: ["Nedeľa", "Pondelok", "Utorok", "Streda", "Štvrtok", "Piatok", "Sobota", "Nedeľa"],
daysShort: ["Ned", "Pon", "Uto", "Str", "Štv", "Pia", "Sob", "Ned"],
daysMin: ["Ne", "Po", "Ut", "St", "Št", "Pia", "So", "Ne"],
months: ["Január", "Február", "Marec", "Apríl", "Máj", "Jún", "Júl", "August", "September", "Október", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Máj", "Jún", "Júl", "Aug", "Sep", "Okt", "Nov", "Dec"],
today: "Dnes"
};
}(jQuery));
/**
* Slovene translation for bootstrap-datepicker
* Gregor Rudolf <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['sl'] = {
days: ["Nedelja", "Ponedeljek", "Torek", "Sreda", "Četrtek", "Petek", "Sobota", "Nedelja"],
daysShort: ["Ned", "Pon", "Tor", "Sre", "Čet", "Pet", "Sob", "Ned"],
daysMin: ["Ne", "Po", "To", "Sr", "Če", "Pe", "So", "Ne"],
months: ["Januar", "Februar", "Marec", "April", "Maj", "Junij", "Julij", "Avgust", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Avg", "Sep", "Okt", "Nov", "Dec"],
today: "Danes"
};
}(jQuery));
/**
* Albanian translation for bootstrap-datepicker
* Tomor Pupovci <http://www.github.com/ttomor>
*/
; (function ($) {
$.fn.datepicker.dates['sq'] = {
days: ["E Diel", "E Hënë", "E martē", "E mërkurë", "E Enjte", "E Premte", "E Shtunë", "E Diel"],
daysShort: ["Die", "Hën", "Mar", "Mër", "Enj", "Pre", "Shtu", "Die"],
daysMin: ["Di", "Hë", "Ma", "Më", "En", "Pr", "Sht", "Di"],
months: ["Janar", "Shkurt", "Mars", "Prill", "Maj", "Qershor", "Korrik", "Gusht", "Shtator", "Tetor", "Nëntor", "Dhjetor"],
monthsShort: ["Jan", "Shk", "Mar", "Pri", "Maj", "Qer", "Korr", "Gu", "Sht", "Tet", "Nën", "Dhjet"],
today: "Sot"
};
}(jQuery));
/**
* Swedish translation for bootstrap-datepicker
* Patrik Ragnarsson <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['sv'] = {
days: ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag"],
daysShort: ["Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör", "Sön"],
daysMin: ["Sö", "Må", "Ti", "On", "To", "Fr", "Lö", "Sö"],
months: ["Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
today: "I Dag",
format: "yyyy-mm-dd",
weekStart: 1
};
}(jQuery));
/**
* Swahili translation for bootstrap-datepicker
* Edwin Mugendi <https://github.com/edwinmugendi>
* Source: http://scriptsource.org/cms/scripts/page.php?item_id=entry_detail&uid=xnfaqyzcku
*/
; (function ($) {
$.fn.datepicker.dates['sw'] = {
days: ["Jumapili", "Jumatatu", "Jumanne", "Jumatano", "Alhamisi", "Ijumaa", "Jumamosi", "Jumapili"],
daysShort: ["J2", "J3", "J4", "J5", "Alh", "Ij", "J1", "J2"],
daysMin: ["2", "3", "4", "5", "A", "I", "1", "2"],
months: ["Januari", "Februari", "Machi", "Aprili", "Mei", "Juni", "Julai", "Agosti", "Septemba", "Oktoba", "Novemba", "Desemba"],
monthsShort: ["Jan", "Feb", "Mac", "Apr", "Mei", "Jun", "Jul", "Ago", "Sep", "Okt", "Nov", "Des"],
today: "Leo"
};
}(jQuery));
/**
* Thai translation for bootstrap-datepicker
* Suchau Jiraprapot <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['th'] = {
days: ["อาทิตย์", "จันทร์", "อังคาร", "พุธ", "พฤหัส", "ศุกร์", "เสาร์", "อาทิตย์"],
daysShort: ["อา", "จ", "อ", "พ", "พฤ", "ศ", "ส", "อา"],
daysMin: ["อา", "จ", "อ", "พ", "พฤ", "ศ", "ส", "อา"],
months: ["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"],
monthsShort: ["ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค."],
today: "วันนี้"
};
}(jQuery));
/**
* Turkish translation for bootstrap-datepicker
* Serkan Algur <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['tr'] = {
days: ["Pazar", "Pazartesi", "Salı", "Çarşamba", "Perşembe", "Cuma", "Cumartesi", "Pazar"],
daysShort: ["Pz", "Pzt", "Sal", "Çrş", "Prş", "Cu", "Cts", "Pz"],
daysMin: ["Pz", "Pzt", "Sa", "Çr", "Pr", "Cu", "Ct", "Pz"],
months: ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"],
monthsShort: ["Oca", "Şub", "Mar", "Nis", "May", "Haz", "Tem", "Ağu", "Eyl", "Eki", "Kas", "Ara"],
today: "Bugün",
format: "dd.mm.yyyy"
};
}(jQuery));
/**
* Ukrainian translation for bootstrap-datepicker
* Andrey Vityuk <andrey [dot] vityuk [at] gmail.com>
*/
; (function ($) {
$.fn.datepicker.dates['uk'] = {
days: ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота", "Неділя"],
daysShort: ["Нед", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Суб", "Нед"],
daysMin: ["Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб", "Нд"],
months: ["Січень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень"],
monthsShort: ["Січ", "Лют", "Бер", "Кві", "Тра", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Гру"],
today: "Сьогодні"
};
}(jQuery));
/**
* Simplified Chinese translation for bootstrap-datepicker
* Yuan Cheung <[email protected]>
*/
; (function ($) {
$.fn.datepicker.dates['zh-CN'] = {
days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
today: "今日",
format: "yyyy年mm月dd日",
weekStart: 1
};
}(jQuery));
/**
* Traditional Chinese translation for bootstrap-datepicker
* Rung-Sheng Jang <[email protected]>
* FrankWu <[email protected]> Fix more appropriate use of Traditional Chinese habit
*/
; (function ($) {
$.fn.datepicker.dates['zh-TW'] = {
days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
daysShort: ["週日", "週一", "週二", "週三", "週四", "週五", "週六", "週日"],
daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
today: "今天",
format: "yyyy年mm月dd日",
weekStart: 1
};
}(jQuery));
var dp;
dp = angular.module('ng-bootstrap-datepicker', []);
dp.directive('ngDatepicker', function () {
return {
restrict: 'A',
replace: true,
scope: {
ngOptions: '=',
ngModel: '='
},
template: "<div class=\"input-append date\">\n <input type=\"text\"><span class=\"add-on\"><i class=\"icon-th\"></i></span>\n</div>",
link: function (scope, element) {
scope.inputHasFocus = false;
element.datepicker(scope.ngOptions).on('changeDate', function (e) {
var defaultFormat, defaultLanguage, format, language;
defaultFormat = $.fn.datepicker.defaults.format;
format = scope.ngOptions.format || defaultFormat;
defaultLanguage = $.fn.datepicker.defaults.language;
language = scope.ngOptions.language || defaultLanguage;
return scope.$apply(function () {
return scope.ngModel = $.fn.datepicker.DPGlobal.formatDate(e.date, format, language);
});
});
element.find('input').on('focus', function () {
return scope.inputHasFocus = true;
}).on('blur', function () {
return scope.inputHasFocus = false;
});
return scope.$watch('ngModel', function (newValue) {
if (!scope.inputHasFocus) {
return element.datepicker('update', newValue);
}
});
}
};
}); |
// Insert your JS here |
'use strict';
const path = require('path');
// This is a custom Jest transformer turning file imports into filenames.
// https://facebook.github.io/jest/docs/en/webpack.html
module.exports = {
process(src, filename) {
const assetFilename = JSON.stringify(path.basename(filename));
if (filename.match(/\.svg$/)) {
return `const React = require('react');
module.exports = {
__esModule: true,
default: ${assetFilename},
ReactComponent: React.forwardRef((props, ref) => ({
$$typeof: Symbol.for('react.element'),
type: 'svg',
ref: ref,
key: null,
props: Object.assign({}, props, {
children: ${assetFilename}
})
})),
};`;
}
return `module.exports = ${assetFilename};`;
},
};
|
var colors = require('colors');
colors.enabled = true;
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['../nodejs/jasmine-custom-message.spec.js', './test-jasmine-custom-message.js']
}; |
import { Increment, Decrement } from '../actions'
export default (state = 0, action) => {
switch (action.constructor) {
case Increment:
return state + 1
case Decrement:
return state - 1
default:
return state
}
}
|
import {
RECEIVE_ALL_JOBS, RECEIVE_JOB, REQUEST_ALL_JOBS, REQUEST_JOB,
RECEIVE_FILTERED_JOBS, REQUEST_FILTERED_JOBS, CREATE_JOBS,
PAGINATE_JOBS, UPDATE_JOB, DELETE_JOB } from './constants'
const initialState = {
fetchingSelected: false,
selected: null,
fetchingAll: false,
all: null,
filteredJobs: null,
filtered: false,
filter: null, // we persist user's search parameters between navigations to/from home and job detail pages
offset: 0,
pageNum: 1
}
const jobsReducer = (state = initialState, action) => {
switch (action.type) {
case REQUEST_ALL_JOBS: return {
fetchingSelected: false,
selected: null,
fetchingAll: true,
all: null,
filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null,
filtered: false,
filter: null,
offset: 0,
pageNum: 1
}
case RECEIVE_ALL_JOBS: return {
fetchingSelected: false,
selected: null,
fetchingAll: false,
all: action.jobs,
filteredJobs: null,
filtered: false,
filter: null,
offset: 0,
pageNum: 1
}
case REQUEST_FILTERED_JOBS: return {
fetchingSelected: false,
selected: null,
fetchingAll: true,
all: state.all ? [...state.all] : null,
filteredJobs: null,
filtered: state.filteredJobs !== null,
filter: action.filter,
offset: 0,
pageNum: 1
}
case RECEIVE_FILTERED_JOBS: return {
fetchingSelected: false,
selected: null,
fetchingAll: false,
all: state.all ? [...state.all] : null,
filteredJobs: action.jobs,
filtered: true,
filter: {...state.filter},
offset: 0,
pageNum: 1
}
case PAGINATE_JOBS: return {
fetchingSelected: false,
selected: null,
fetchingAll: false,
all: state.all ? [...state.all] : null,
filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null,
filtered: state.filteredJobs !== null,
filter: state.filter ? {...state.filter} : null,
offset: action.offset,
pageNum: action.pageNum
}
case REQUEST_JOB: return {
fetchingSelected: true,
selected: null,
fetchingAll: false,
all: state.all ? [...state.all] : null,
filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null,
filtered: state.filteredJobs !== null,
filter: state.filter ? {...state.filter} : null,
offset: state.offset,
pageNum: state.pageNum
}
case RECEIVE_JOB: return {
fetchingSelected: false,
selected: action.job,
fetchingAll: false,
all: state.all ? [...state.all] : null,
filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null,
filtered: state.filteredJobs !== null,
filter: state.filter ? {...state.filter} : null,
offset: state.offset,
pageNum: state.pageNum
}
case CREATE_JOBS: return {
fetchingSelected: false,
selected: state.selected ? {...state.selected} : null,
fetchingAll: true,
all: state.all ? [...state.all] : null,
filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null,
filtered: false,
filter: null,
offset: 0,
pageNum: 1
}
case UPDATE_JOB: return {
fetchingSelected: true,
selected: state.selected ? {...state.selected} : null,
fetchingAll: false,
all: state.all ? [...state.all] : null,
filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null,
filtered: false,
filter: null,
offset: 0,
pageNum: 1
}
case DELETE_JOB: return {
fetchingSelected: true,
selected: state.selected ? {...state.selected} : null,
fetchingAll: false,
all: state.all ? [...state.all] : null,
filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null,
filtered: false,
filter: null,
offset: 0,
pageNum: 1
}
default: return state
}
}
export default jobsReducer
|
module.exports = {
createUser: require('./create-user')
};
|
/* global logger, processWebhookMessage */
import moment from 'moment';
RocketChat.integrations.triggerHandler = new class RocketChatIntegrationHandler {
constructor() {
this.vm = Npm.require('vm');
this.successResults = [200, 201, 202];
this.compiledScripts = {};
this.triggers = {};
RocketChat.models.Integrations.find({type: 'webhook-outgoing'}).observe({
added: (record) => {
this.addIntegration(record);
},
changed: (record) => {
this.removeIntegration(record);
this.addIntegration(record);
},
removed: (record) => {
this.removeIntegration(record);
}
});
}
addIntegration(record) {
logger.outgoing.debug(`Adding the integration ${ record.name } of the event ${ record.event }!`);
let channels;
if (record.event && !RocketChat.integrations.outgoingEvents[record.event].use.channel) {
logger.outgoing.debug('The integration doesnt rely on channels.');
//We don't use any channels, so it's special ;)
channels = ['__any'];
} else if (_.isEmpty(record.channel)) {
logger.outgoing.debug('The integration had an empty channel property, so it is going on all the public channels.');
channels = ['all_public_channels'];
} else {
logger.outgoing.debug('The integration is going on these channels:', record.channel);
channels = [].concat(record.channel);
}
for (const channel of channels) {
if (!this.triggers[channel]) {
this.triggers[channel] = {};
}
this.triggers[channel][record._id] = record;
}
}
removeIntegration(record) {
for (const trigger of Object.values(this.triggers)) {
delete trigger[record._id];
}
}
isTriggerEnabled(trigger) {
for (const trig of Object.values(this.triggers)) {
if (trig[trigger._id]) {
return trig[trigger._id].enabled;
}
}
return false;
}
updateHistory({ historyId, step, integration, event, data, triggerWord, ranPrepareScript, prepareSentMessage, processSentMessage, resultMessage, finished, url, httpCallData, httpError, httpResult, error, errorStack }) {
const history = {
type: 'outgoing-webhook',
step
};
// Usually is only added on initial insert
if (integration) {
history.integration = integration;
}
// Usually is only added on initial insert
if (event) {
history.event = event;
}
if (data) {
history.data = data;
if (data.user) {
history.data.user = _.omit(data.user, ['meta', '$loki', 'services']);
}
if (data.room) {
history.data.room = _.omit(data.room, ['meta', '$loki', 'usernames']);
history.data.room.usernames = ['this_will_be_filled_in_with_usernames_when_replayed'];
}
}
if (triggerWord) {
history.triggerWord = triggerWord;
}
if (typeof ranPrepareScript !== 'undefined') {
history.ranPrepareScript = ranPrepareScript;
}
if (prepareSentMessage) {
history.prepareSentMessage = prepareSentMessage;
}
if (processSentMessage) {
history.processSentMessage = processSentMessage;
}
if (resultMessage) {
history.resultMessage = resultMessage;
}
if (typeof finished !== 'undefined') {
history.finished = finished;
}
if (url) {
history.url = url;
}
if (typeof httpCallData !== 'undefined') {
history.httpCallData = httpCallData;
}
if (httpError) {
history.httpError = httpError;
}
if (typeof httpResult !== 'undefined') {
history.httpResult = httpResult;
}
if (typeof error !== 'undefined') {
history.error = error;
}
if (typeof errorStack !== 'undefined') {
history.errorStack = errorStack;
}
if (historyId) {
RocketChat.models.IntegrationHistory.update({ _id: historyId }, { $set: history });
return historyId;
} else {
history._createdAt = new Date();
return RocketChat.models.IntegrationHistory.insert(Object.assign({ _id: Random.id() }, history));
}
}
//Trigger is the trigger, nameOrId is a string which is used to try and find a room, room is a room, message is a message, and data contains "user_name" if trigger.impersonateUser is truthful.
sendMessage({ trigger, nameOrId = '', room, message, data }) {
let user;
//Try to find the user who we are impersonating
if (trigger.impersonateUser) {
user = RocketChat.models.Users.findOneByUsername(data.user_name);
}
//If they don't exist (aka the trigger didn't contain a user) then we set the user based upon the
//configured username for the integration since this is required at all times.
if (!user) {
user = RocketChat.models.Users.findOneByUsername(trigger.username);
}
let tmpRoom;
if (nameOrId || trigger.targetRoom) {
tmpRoom = RocketChat.getRoomByNameOrIdWithOptionToJoin({ currentUserId: user._id, nameOrId: nameOrId || trigger.targetRoom, errorOnEmpty: false }) || room;
} else {
tmpRoom = room;
}
//If no room could be found, we won't be sending any messages but we'll warn in the logs
if (!tmpRoom) {
logger.outgoing.warn(`The Integration "${ trigger.name }" doesn't have a room configured nor did it provide a room to send the message to.`);
return;
}
logger.outgoing.debug(`Found a room for ${ trigger.name } which is: ${ tmpRoom.name } with a type of ${ tmpRoom.t }`);
message.bot = { i: trigger._id };
const defaultValues = {
alias: trigger.alias,
avatar: trigger.avatar,
emoji: trigger.emoji
};
if (tmpRoom.t === 'd') {
message.channel = `@${ tmpRoom._id }`;
} else {
message.channel = `#${ tmpRoom._id }`;
}
message = processWebhookMessage(message, user, defaultValues);
return message;
}
buildSandbox(store = {}) {
const sandbox = {
_, s, console, moment,
Store: {
set: (key, val) => store[key] = val,
get: (key) => store[key]
},
HTTP: (method, url, options) => {
try {
return {
result: HTTP.call(method, url, options)
};
} catch (error) {
return { error };
}
}
};
Object.keys(RocketChat.models).filter(k => !k.startsWith('_')).forEach(k => {
sandbox[k] = RocketChat.models[k];
});
return { store, sandbox };
}
getIntegrationScript(integration) {
const compiledScript = this.compiledScripts[integration._id];
if (compiledScript && +compiledScript._updatedAt === +integration._updatedAt) {
return compiledScript.script;
}
const script = integration.scriptCompiled;
const { store, sandbox } = this.buildSandbox();
let vmScript;
try {
logger.outgoing.info('Will evaluate script of Trigger', integration.name);
logger.outgoing.debug(script);
vmScript = this.vm.createScript(script, 'script.js');
vmScript.runInNewContext(sandbox);
if (sandbox.Script) {
this.compiledScripts[integration._id] = {
script: new sandbox.Script(),
store,
_updatedAt: integration._updatedAt
};
return this.compiledScripts[integration._id].script;
}
} catch (e) {
logger.outgoing.error(`Error evaluating Script in Trigger ${ integration.name }:`);
logger.outgoing.error(script.replace(/^/gm, ' '));
logger.outgoing.error('Stack Trace:');
logger.outgoing.error(e.stack.replace(/^/gm, ' '));
throw new Meteor.Error('error-evaluating-script');
}
if (!sandbox.Script) {
logger.outgoing.error(`Class "Script" not in Trigger ${ integration.name }:`);
throw new Meteor.Error('class-script-not-found');
}
}
hasScriptAndMethod(integration, method) {
if (integration.scriptEnabled !== true || !integration.scriptCompiled || integration.scriptCompiled.trim() === '') {
return false;
}
let script;
try {
script = this.getIntegrationScript(integration);
} catch (e) {
return false;
}
return typeof script[method] !== 'undefined';
}
executeScript(integration, method, params, historyId) {
let script;
try {
script = this.getIntegrationScript(integration);
} catch (e) {
this.updateHistory({ historyId, step: 'execute-script-getting-script', error: true, errorStack: e });
return;
}
if (!script[method]) {
logger.outgoing.error(`Method "${ method }" no found in the Integration "${ integration.name }"`);
this.updateHistory({ historyId, step: `execute-script-no-method-${ method }` });
return;
}
try {
const { sandbox } = this.buildSandbox(this.compiledScripts[integration._id].store);
sandbox.script = script;
sandbox.method = method;
sandbox.params = params;
this.updateHistory({ historyId, step: `execute-script-before-running-${ method }` });
const result = this.vm.runInNewContext('script[method](params)', sandbox, { timeout: 3000 });
logger.outgoing.debug(`Script method "${ method }" result of the Integration "${ integration.name }" is:`);
logger.outgoing.debug(result);
return result;
} catch (e) {
this.updateHistory({ historyId, step: `execute-script-error-running-${ method }`, error: true, errorStack: e.stack.replace(/^/gm, ' ') });
logger.outgoing.error(`Error running Script in the Integration ${ integration.name }:`);
logger.outgoing.debug(integration.scriptCompiled.replace(/^/gm, ' ')); // Only output the compiled script if debugging is enabled, so the logs don't get spammed.
logger.outgoing.error('Stack:');
logger.outgoing.error(e.stack.replace(/^/gm, ' '));
return;
}
}
eventNameArgumentsToObject() {
const argObject = {
event: arguments[0]
};
switch (argObject.event) {
case 'sendMessage':
if (arguments.length >= 3) {
argObject.message = arguments[1];
argObject.room = arguments[2];
}
break;
case 'fileUploaded':
if (arguments.length >= 2) {
const arghhh = arguments[1];
argObject.user = arghhh.user;
argObject.room = arghhh.room;
argObject.message = arghhh.message;
}
break;
case 'roomArchived':
if (arguments.length >= 3) {
argObject.room = arguments[1];
argObject.user = arguments[2];
}
break;
case 'roomCreated':
if (arguments.length >= 3) {
argObject.owner = arguments[1];
argObject.room = arguments[2];
}
break;
case 'roomJoined':
case 'roomLeft':
if (arguments.length >= 3) {
argObject.user = arguments[1];
argObject.room = arguments[2];
}
break;
case 'userCreated':
if (arguments.length >= 2) {
argObject.user = arguments[1];
}
break;
default:
logger.outgoing.warn(`An Unhandled Trigger Event was called: ${ argObject.event }`);
argObject.event = undefined;
break;
}
logger.outgoing.debug(`Got the event arguments for the event: ${ argObject.event }`, argObject);
return argObject;
}
mapEventArgsToData(data, { event, message, room, owner, user }) {
switch (event) {
case 'sendMessage':
data.channel_id = room._id;
data.channel_name = room.name;
data.message_id = message._id;
data.timestamp = message.ts;
data.user_id = message.u._id;
data.user_name = message.u.username;
data.text = message.msg;
if (message.alias) {
data.alias = message.alias;
}
if (message.bot) {
data.bot = message.bot;
}
break;
case 'fileUploaded':
data.channel_id = room._id;
data.channel_name = room.name;
data.message_id = message._id;
data.timestamp = message.ts;
data.user_id = message.u._id;
data.user_name = message.u.username;
data.text = message.msg;
data.user = user;
data.room = room;
data.message = message;
if (message.alias) {
data.alias = message.alias;
}
if (message.bot) {
data.bot = message.bot;
}
break;
case 'roomCreated':
data.channel_id = room._id;
data.channel_name = room.name;
data.timestamp = room.ts;
data.user_id = owner._id;
data.user_name = owner.username;
data.owner = owner;
data.room = room;
break;
case 'roomArchived':
case 'roomJoined':
case 'roomLeft':
data.timestamp = new Date();
data.channel_id = room._id;
data.channel_name = room.name;
data.user_id = user._id;
data.user_name = user.username;
data.user = user;
data.room = room;
if (user.type === 'bot') {
data.bot = true;
}
break;
case 'userCreated':
data.timestamp = user.createdAt;
data.user_id = user._id;
data.user_name = user.username;
data.user = user;
if (user.type === 'bot') {
data.bot = true;
}
break;
default:
break;
}
}
executeTriggers() {
logger.outgoing.debug('Execute Trigger:', arguments[0]);
const argObject = this.eventNameArgumentsToObject(...arguments);
const { event, message, room } = argObject;
//Each type of event should have an event and a room attached, otherwise we
//wouldn't know how to handle the trigger nor would we have anywhere to send the
//result of the integration
if (!event) {
return;
}
const triggersToExecute = [];
logger.outgoing.debug('Starting search for triggers for the room:', room ? room._id : '__any');
if (room) {
switch (room.t) {
case 'd':
const id = room._id.replace(message.u._id, '');
const username = _.without(room.usernames, message.u.username)[0];
if (this.triggers[`@${ id }`]) {
for (const trigger of Object.values(this.triggers[`@${ id }`])) {
triggersToExecute.push(trigger);
}
}
if (this.triggers.all_direct_messages) {
for (const trigger of Object.values(this.triggers.all_direct_messages)) {
triggersToExecute.push(trigger);
}
}
if (id !== username && this.triggers[`@${ username }`]) {
for (const trigger of Object.values(this.triggers[`@${ username }`])) {
triggersToExecute.push(trigger);
}
}
break;
case 'c':
if (this.triggers.all_public_channels) {
for (const trigger of Object.values(this.triggers.all_public_channels)) {
triggersToExecute.push(trigger);
}
}
if (this.triggers[`#${ room._id }`]) {
for (const trigger of Object.values(this.triggers[`#${ room._id }`])) {
triggersToExecute.push(trigger);
}
}
if (room._id !== room.name && this.triggers[`#${ room.name }`]) {
for (const trigger of Object.values(this.triggers[`#${ room.name }`])) {
triggersToExecute.push(trigger);
}
}
break;
default:
if (this.triggers.all_private_groups) {
for (const trigger of Object.values(this.triggers.all_private_groups)) {
triggersToExecute.push(trigger);
}
}
if (this.triggers[`#${ room._id }`]) {
for (const trigger of Object.values(this.triggers[`#${ room._id }`])) {
triggersToExecute.push(trigger);
}
}
if (room._id !== room.name && this.triggers[`#${ room.name }`]) {
for (const trigger of Object.values(this.triggers[`#${ room.name }`])) {
triggersToExecute.push(trigger);
}
}
break;
}
}
if (this.triggers.__any) {
//For outgoing integration which don't rely on rooms.
for (const trigger of Object.values(this.triggers.__any)) {
triggersToExecute.push(trigger);
}
}
logger.outgoing.debug(`Found ${ triggersToExecute.length } to iterate over and see if the match the event.`);
for (const triggerToExecute of triggersToExecute) {
logger.outgoing.debug(`Is "${ triggerToExecute.name }" enabled, ${ triggerToExecute.enabled }, and what is the event? ${ triggerToExecute.event }`);
if (triggerToExecute.enabled === true && triggerToExecute.event === event) {
this.executeTrigger(triggerToExecute, argObject);
}
}
}
executeTrigger(trigger, argObject) {
for (const url of trigger.urls) {
this.executeTriggerUrl(url, trigger, argObject, 0);
}
}
executeTriggerUrl(url, trigger, { event, message, room, owner, user }, theHistoryId, tries = 0) {
if (!this.isTriggerEnabled(trigger)) {
logger.outgoing.warn(`The trigger "${ trigger.name }" is no longer enabled, stopping execution of it at try: ${ tries }`);
return;
}
logger.outgoing.debug(`Starting to execute trigger: ${ trigger.name } (${ trigger._id })`);
let word;
//Not all triggers/events support triggerWords
if (RocketChat.integrations.outgoingEvents[event].use.triggerWords) {
if (trigger.triggerWords && trigger.triggerWords.length > 0) {
for (const triggerWord of trigger.triggerWords) {
if (!trigger.triggerWordAnywhere && message.msg.indexOf(triggerWord) === 0) {
word = triggerWord;
break;
} else if (trigger.triggerWordAnywhere && message.msg.includes(triggerWord)) {
word = triggerWord;
break;
}
}
// Stop if there are triggerWords but none match
if (!word) {
logger.outgoing.debug(`The trigger word which "${ trigger.name }" was expecting could not be found, not executing.`);
return;
}
}
}
const historyId = this.updateHistory({ step: 'start-execute-trigger-url', integration: trigger, event });
const data = {
token: trigger.token,
bot: false
};
if (word) {
data.trigger_word = word;
}
this.mapEventArgsToData(data, { trigger, event, message, room, owner, user });
this.updateHistory({ historyId, step: 'mapped-args-to-data', data, triggerWord: word });
logger.outgoing.info(`Will be executing the Integration "${ trigger.name }" to the url: ${ url }`);
logger.outgoing.debug(data);
let opts = {
params: {},
method: 'POST',
url,
data,
auth: undefined,
npmRequestOptions: {
rejectUnauthorized: !RocketChat.settings.get('Allow_Invalid_SelfSigned_Certs'),
strictSSL: !RocketChat.settings.get('Allow_Invalid_SelfSigned_Certs')
},
headers: {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36'
}
};
if (this.hasScriptAndMethod(trigger, 'prepare_outgoing_request')) {
opts = this.executeScript(trigger, 'prepare_outgoing_request', { request: opts }, historyId);
}
this.updateHistory({ historyId, step: 'after-maybe-ran-prepare', ranPrepareScript: true });
if (!opts) {
this.updateHistory({ historyId, step: 'after-prepare-no-opts', finished: true });
return;
}
if (opts.message) {
const prepareMessage = this.sendMessage({ trigger, room, message: opts.message, data });
this.updateHistory({ historyId, step: 'after-prepare-send-message', prepareSentMessage: prepareMessage });
}
if (!opts.url || !opts.method) {
this.updateHistory({ historyId, step: 'after-prepare-no-url_or_method', finished: true });
return;
}
this.updateHistory({ historyId, step: 'pre-http-call', url: opts.url, httpCallData: opts.data });
HTTP.call(opts.method, opts.url, opts, (error, result) => {
if (!result) {
logger.outgoing.warn(`Result for the Integration ${ trigger.name } to ${ url } is empty`);
} else {
logger.outgoing.info(`Status code for the Integration ${ trigger.name } to ${ url } is ${ result.statusCode }`);
}
this.updateHistory({ historyId, step: 'after-http-call', httpError: error, httpResult: result });
if (this.hasScriptAndMethod(trigger, 'process_outgoing_response')) {
const sandbox = {
request: opts,
response: {
error,
status_code: result ? result.statusCode : undefined, //These values will be undefined to close issues #4175, #5762, and #5896
content: result ? result.data : undefined,
content_raw: result ? result.content : undefined,
headers: result ? result.headers : {}
}
};
const scriptResult = this.executeScript(trigger, 'process_outgoing_response', sandbox, historyId);
if (scriptResult && scriptResult.content) {
const resultMessage = this.sendMessage({ trigger, room, message: scriptResult.content, data });
this.updateHistory({ historyId, step: 'after-process-send-message', processSentMessage: resultMessage, finished: true });
return;
}
if (scriptResult === false) {
this.updateHistory({ historyId, step: 'after-process-false-result', finished: true });
return;
}
}
// if the result contained nothing or wasn't a successful statusCode
if (!result || !this.successResults.includes(result.statusCode)) {
if (error) {
logger.outgoing.error(`Error for the Integration "${ trigger.name }" to ${ url } is:`);
logger.outgoing.error(error);
}
if (result) {
logger.outgoing.error(`Error for the Integration "${ trigger.name }" to ${ url } is:`);
logger.outgoing.error(result);
if (result.statusCode === 410) {
this.updateHistory({ historyId, step: 'after-process-http-status-410', error: true });
logger.outgoing.error(`Disabling the Integration "${ trigger.name }" because the status code was 401 (Gone).`);
RocketChat.models.Integrations.update({ _id: trigger._id }, { $set: { enabled: false }});
return;
}
if (result.statusCode === 500) {
this.updateHistory({ historyId, step: 'after-process-http-status-500', error: true });
logger.outgoing.error(`Error "500" for the Integration "${ trigger.name }" to ${ url }.`);
logger.outgoing.error(result.content);
return;
}
}
if (trigger.retryFailedCalls) {
if (tries < trigger.retryCount && trigger.retryDelay) {
this.updateHistory({ historyId, error: true, step: `going-to-retry-${ tries + 1 }` });
let waitTime;
switch (trigger.retryDelay) {
case 'powers-of-ten':
// Try again in 0.1s, 1s, 10s, 1m40s, 16m40s, 2h46m40s, 27h46m40s, etc
waitTime = Math.pow(10, tries + 2);
break;
case 'powers-of-two':
// 2 seconds, 4 seconds, 8 seconds
waitTime = Math.pow(2, tries + 1) * 1000;
break;
case 'increments-of-two':
// 2 second, 4 seconds, 6 seconds, etc
waitTime = (tries + 1) * 2 * 1000;
break;
default:
const er = new Error('The integration\'s retryDelay setting is invalid.');
this.updateHistory({ historyId, step: 'failed-and-retry-delay-is-invalid', error: true, errorStack: er.stack });
return;
}
logger.outgoing.info(`Trying the Integration ${ trigger.name } to ${ url } again in ${ waitTime } milliseconds.`);
Meteor.setTimeout(() => {
this.executeTriggerUrl(url, trigger, { event, message, room, owner, user }, historyId, tries + 1);
}, waitTime);
} else {
this.updateHistory({ historyId, step: 'too-many-retries', error: true });
}
} else {
this.updateHistory({ historyId, step: 'failed-and-not-configured-to-retry', error: true });
}
return;
}
//process outgoing webhook response as a new message
if (result && this.successResults.includes(result.statusCode)) {
if (result && result.data && (result.data.text || result.data.attachments)) {
const resultMsg = this.sendMessage({ trigger, room, message: result.data, data });
this.updateHistory({ historyId, step: 'url-response-sent-message', resultMessage: resultMsg, finished: true });
}
}
});
}
replay(integration, history) {
if (!integration || integration.type !== 'webhook-outgoing') {
throw new Meteor.Error('integration-type-must-be-outgoing', 'The integration type to replay must be an outgoing webhook.');
}
if (!history || !history.data) {
throw new Meteor.Error('history-data-must-be-defined', 'The history data must be defined to replay an integration.');
}
const event = history.event;
const message = RocketChat.models.Messages.findOneById(history.data.message_id);
const room = RocketChat.models.Rooms.findOneById(history.data.channel_id);
const user = RocketChat.models.Users.findOneById(history.data.user_id);
let owner;
if (history.data.owner && history.data.owner._id) {
owner = RocketChat.models.Users.findOneById(history.data.owner._id);
}
this.executeTriggerUrl(history.url, integration, { event, message, room, owner, user });
}
};
|
'use strict';
module.exports = function (t, a) {
t(document.createElement('p'));
};
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M11 17h10v-2H11v2zm-8-5l4 4V8l-4 4zm0 9h18v-2H3v2zM3 3v2h18V3H3zm8 6h10V7H11v2zm0 4h10v-2H11v2z" /></React.Fragment>
, 'FormatIndentDecreaseSharp');
|
import { Button } from './button';
export { Button };
export default null;
|
/**
* @author Richard Davey <[email protected]>
* @copyright 2019 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var imageHeight = 0;
/**
* @function addFrame
* @private
* @since 3.0.0
*/
var addFrame = function (texture, sourceIndex, name, frame)
{
// The frame values are the exact coordinates to cut the frame out of the atlas from
var y = imageHeight - frame.y - frame.height;
texture.add(name, sourceIndex, frame.x, y, frame.width, frame.height);
// These are the original (non-trimmed) sprite values
/*
if (src.trimmed)
{
newFrame.setTrim(
src.sourceSize.w,
src.sourceSize.h,
src.spriteSourceSize.x,
src.spriteSourceSize.y,
src.spriteSourceSize.w,
src.spriteSourceSize.h
);
}
*/
};
/**
* Parses a Unity YAML File and creates Frames in the Texture.
* For more details about Sprite Meta Data see https://docs.unity3d.com/ScriptReference/SpriteMetaData.html
*
* @function Phaser.Textures.Parsers.UnityYAML
* @memberof Phaser.Textures.Parsers
* @private
* @since 3.0.0
*
* @param {Phaser.Textures.Texture} texture - The Texture to add the Frames to.
* @param {integer} sourceIndex - The index of the TextureSource.
* @param {object} yaml - The YAML data.
*
* @return {Phaser.Textures.Texture} The Texture modified by this parser.
*/
var UnityYAML = function (texture, sourceIndex, yaml)
{
// Add in a __BASE entry (for the entire atlas)
var source = texture.source[sourceIndex];
texture.add('__BASE', sourceIndex, 0, 0, source.width, source.height);
imageHeight = source.height;
var data = yaml.split('\n');
var lineRegExp = /^[ ]*(- )*(\w+)+[: ]+(.*)/;
var prevSprite = '';
var currentSprite = '';
var rect = { x: 0, y: 0, width: 0, height: 0 };
// var pivot = { x: 0, y: 0 };
// var border = { x: 0, y: 0, z: 0, w: 0 };
for (var i = 0; i < data.length; i++)
{
var results = data[i].match(lineRegExp);
if (!results)
{
continue;
}
var isList = (results[1] === '- ');
var key = results[2];
var value = results[3];
if (isList)
{
if (currentSprite !== prevSprite)
{
addFrame(texture, sourceIndex, currentSprite, rect);
prevSprite = currentSprite;
}
rect = { x: 0, y: 0, width: 0, height: 0 };
}
if (key === 'name')
{
// Start new list
currentSprite = value;
continue;
}
switch (key)
{
case 'x':
case 'y':
case 'width':
case 'height':
rect[key] = parseInt(value, 10);
break;
// case 'pivot':
// pivot = eval('var obj = ' + value);
// break;
// case 'border':
// border = eval('var obj = ' + value);
// break;
}
}
if (currentSprite !== prevSprite)
{
addFrame(texture, sourceIndex, currentSprite, rect);
}
return texture;
};
module.exports = UnityYAML;
/*
Example data:
TextureImporter:
spritePivot: {x: .5, y: .5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
spriteSheet:
sprites:
- name: asteroids_0
rect:
serializedVersion: 2
x: 5
y: 328
width: 65
height: 82
alignment: 0
pivot: {x: 0, y: 0}
border: {x: 0, y: 0, z: 0, w: 0}
- name: asteroids_1
rect:
serializedVersion: 2
x: 80
y: 322
width: 53
height: 88
alignment: 0
pivot: {x: 0, y: 0}
border: {x: 0, y: 0, z: 0, w: 0}
spritePackingTag: Asteroids
*/
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M12 5.9c1.16 0 2.1.94 2.1 2.1s-.94 2.1-2.1 2.1S9.9 9.16 9.9 8s.94-2.1 2.1-2.1m0 9c2.97 0 6.1 1.46 6.1 2.1v1.1H5.9V17c0-.64 3.13-2.1 6.1-2.1M12 4C9.79 4 8 5.79 8 8s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 9c-2.67 0-8 1.34-8 4v2c0 .55.45 1 1 1h14c.55 0 1-.45 1-1v-2c0-2.66-5.33-4-8-4z" /></g></React.Fragment>
, 'PersonOutlineRounded');
|
'use strict';
var element = require('../element');
module.exports = function(node) {
var el = element('phpdbg');
el.innerHTML = node.nodeValue;
return el;
};
|
$(function () {
// Prepare demo data
var data = [
{
"hc-key": "dm-lu",
"value": 0
},
{
"hc-key": "dm-ma",
"value": 1
},
{
"hc-key": "dm-pk",
"value": 2
},
{
"hc-key": "dm-da",
"value": 3
},
{
"hc-key": "dm-pl",
"value": 4
},
{
"hc-key": "dm-pr",
"value": 5
},
{
"hc-key": "dm-an",
"value": 6
},
{
"hc-key": "dm-go",
"value": 7
},
{
"hc-key": "dm-jn",
"value": 8
},
{
"hc-key": "dm-jh",
"value": 9
}
];
// Initiate the chart
$('#container').highcharts('Map', {
title : {
text : 'Highmaps basic demo'
},
subtitle : {
text : 'Source map: <a href="http://code.highcharts.com/mapdata/countries/dm/dm-all.js">Dominica</a>'
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
colorAxis: {
min: 0
},
series : [{
data : data,
mapData: Highcharts.maps['countries/dm/dm-all'],
joinBy: 'hc-key',
name: 'Random data',
states: {
hover: {
color: '#BADA55'
}
},
dataLabels: {
enabled: true,
format: '{point.name}'
}
}]
});
});
|
/*global require: false, module: false, process: false */
"use strict";
var mod = function(
_,
Promise,
Options,
Logger
) {
var Log = Logger.create("AppContainer");
var WebAppContainer = function() {
this.initialize.apply(this, arguments);
};
_.extend(WebAppContainer.prototype, {
initialize: function(opts) {
opts = Options.fromObject(opts)
this._app = opts.getOrError("app");
},
start: Promise.method(function() {
return Promise
.bind(this)
.then(function() {
return this._app.start();
});
}),
stop: Promise.method(function(reason) {
return this._app.stop().then(function() {
if (reason) {
Log.error("Stopping due to reason:", reason);
}
});
})
});
return WebAppContainer;
};
module.exports = mod(
require("underscore"),
require("bluebird"),
require("../core/options"),
require("../core/logging/logger")
);
|
"use strict";
const Base = require('yeoman-generator');
const generatorArguments = require('./arguments');
const generatorOptions = require('./options');
const generatorSteps = require('./steps');
module.exports = class ResponseGenerator extends Base {
constructor(args, options) {
super(args, options);
Object.keys(generatorArguments).forEach(key => this.argument(key, generatorArguments[key]));
Object.keys(generatorOptions).forEach(key => this.option(key, generatorOptions[key]));
this.description = 'Scaffold a new response';
}
get configuring() {
return generatorSteps.configuring;
}
get conflicts() {
return generatorSteps.conflicts;
}
get default() {
return generatorSteps.default;
}
get end() {
return generatorSteps.end;
}
get initializing() {
return generatorSteps.initializing
}
get install() {
return generatorSteps.install;
}
get prompting() {
return generatorSteps.prompting
}
get writing() {
return generatorSteps.writing;
}
};
|
var _extend = function(obj, source) {
for (var prop in source) {
obj[prop] = source[prop];
}
return obj;
};
var STATUS = {
blank: 'blank',
booked: 'booked',
overflowing: 'overflowing'
};
var ACTION = {
initialBook: 'initialBook',
book: 'book'
};
/**
* SequenceObject
*/
var SequenceObject, so;
SequenceObject = so = function(o){
this.registry = o.registry;
this.config = o.config;
this.store = this.registry.store;
this.logger = this.registry.logger;
this.state = {};
this.state.key = this.config.key;
this.state.segment = this.config.segment;
this.state.prebook = this.config.prebook;
this.state.initialCursor = this.config.initialCursor;
this.state.cursor = null;
this.state.valve = null;
this.state.prebookValve = null;
this.state.nextValve = null;
this.state.status = STATUS.blank;
this.state.ready = false;
this.state.actioning = false;
};
so.STATUS = STATUS;
so.ACTION = ACTION;
so.build = function(o){
var config = _extend({}, so.defaults);
o.config = _extend(config, o.config);
return new so(o);
};
so.prototype.init = function(cb){
var seq = this;
this.store.book(this.state, function(action){
seq.update(action);
cb(action.successful);
});
};
so.prototype.book = function(){
var seq = this;
this.store.book(this.state, function(action){
seq.update(action);
});
};
so.prototype.update = function(action){
if(action.successful){
if(action.name==ACTION.initialBook){
this.state.cursor = this.config.initialCursor;
this.state.valve = action.valve;
this.state.prebookValve = this.state.cursor + this.config.prebook;
this.state.nextValve = null;
}
else{
if(this.state.status==STATUS.blank || this.state.status==STATUS.overflowing ){
this.state.cursor = action.valve - this.config.segment;
this.state.valve = action.valve;
this.state.prebookValve = this.state.cursor + this.config.prebook;
this.state.nextValve = null;
}
else{
this.state.nextValve = action.valve;
}
}
this.state.ready = true;
this.state.status = STATUS.booked;
this.logger.info('Process ' + process.pid + ': The sequence [' + this.state.key + '] successfully booked a new valve ' + action.valve);
}
else{
if(action.name==ACTION.initialBook){
this.state.ready = false;
}
else{
//leave state as it was
}
this.logger.warn('Process ' + process.pid + ': The sequence [' + this.state.key + '] failed to book a new valve. ' +
'And currently, its valve is ' + this.state.valve + ', and its cursor is ' + this.state.cursor);
}
this.state.actioning = false;
};
so.prototype.check = function(){
if(this.state.status==STATUS.booked){
if(!this.state.nextValve){
if(this.state.cursor < this.state.prebookValve){
//Do nothing
}
else if(this.state.cursor < this.state.valve){
this.book();
}
else{
this.onOverflow();
this.book();
}
}
else{
if(this.state.cursor < this.state.valve){
//Do nothing
}
else if(this.state.cursor == this.state.valve){
this.onStep();
}
else{
this.logger.warn('Process ' + process.pid + ': The sequence [' + this.state.key + '] is in a illegal status ' + this.state.status);
this.onOverflow();
this.book();
}
}
}
else if(this.state.status==STATUS.overflowing){
if(!this.state.nextValve){
this.book();
}
else{
this.onStep();
}
}
else{
this.logger.error('unknown status: ' + this.state.status);
this.book();
}
};
so.prototype.onStep = function(){
this.logger.info('Process ' + process.pid + ': The sequence [' + this.state.key + '] stepped in status ' + this.state.status);
this.state.cursor = this.state.nextValve - this.config.segment;
this.state.valve = this.state.nextValve;
this.state.prebookValve = this.state.cursor + this.config.prebook;
this.state.nextValve = null;
};
so.prototype.onOverflow = function(){
this.logger.info('Process ' + process.pid + ': The sequence [' + this.state.key + '] is ' + STATUS.overflowing);
this.state.status = STATUS.overflowing;
var base = (new Date().getTime())*1000;
this.state.cursor = base;
this.state.valve = base + this.config.segment;
this.state.nextValve = null;
this.logger.warn('Process ' + process.pid + ': overflow value ' + this.state.cursor);
};
so.prototype.next = function(){
if(this.state.ready){
this.val = this.state.cursor++;
////debug
//if(this.val>10000000){
// console.error('Process ' + process.pid + ': overflowed value: ' + this.val);
//}
this.check();
return this;
}
else{
throw new Error('Process ' + process.pid + ': The sequence [' + this.state.key + '] is not ready for generating value');
}
};
module.exports = so;
|
'use strict';
const _ = require('lodash');
const moment = require('moment-timezone');
module.exports = BaseTypes => {
BaseTypes.ABSTRACT.prototype.dialectTypes = 'https://mariadb.com/kb/en/library/resultset/#field-types';
/**
* types: [buffer_type, ...]
* @see documentation : https://mariadb.com/kb/en/library/resultset/#field-types
* @see connector implementation : https://github.com/MariaDB/mariadb-connector-nodejs/blob/master/lib/const/field-type.js
*/
BaseTypes.DATE.types.mariadb = ['DATETIME'];
BaseTypes.STRING.types.mariadb = ['VAR_STRING'];
BaseTypes.CHAR.types.mariadb = ['STRING'];
BaseTypes.TEXT.types.mariadb = ['BLOB'];
BaseTypes.TINYINT.types.mariadb = ['TINY'];
BaseTypes.SMALLINT.types.mariadb = ['SHORT'];
BaseTypes.MEDIUMINT.types.mariadb = ['INT24'];
BaseTypes.INTEGER.types.mariadb = ['LONG'];
BaseTypes.BIGINT.types.mariadb = ['LONGLONG'];
BaseTypes.FLOAT.types.mariadb = ['FLOAT'];
BaseTypes.TIME.types.mariadb = ['TIME'];
BaseTypes.DATEONLY.types.mariadb = ['DATE'];
BaseTypes.BOOLEAN.types.mariadb = ['TINY'];
BaseTypes.BLOB.types.mariadb = ['TINYBLOB', 'BLOB', 'LONGBLOB'];
BaseTypes.DECIMAL.types.mariadb = ['NEWDECIMAL'];
BaseTypes.UUID.types.mariadb = false;
BaseTypes.ENUM.types.mariadb = false;
BaseTypes.REAL.types.mariadb = ['DOUBLE'];
BaseTypes.DOUBLE.types.mariadb = ['DOUBLE'];
BaseTypes.GEOMETRY.types.mariadb = ['GEOMETRY'];
BaseTypes.JSON.types.mariadb = ['JSON'];
class DECIMAL extends BaseTypes.DECIMAL {
toSql() {
let definition = super.toSql();
if (this._unsigned) {
definition += ' UNSIGNED';
}
if (this._zerofill) {
definition += ' ZEROFILL';
}
return definition;
}
}
class DATE extends BaseTypes.DATE {
toSql() {
return `DATETIME${this._length ? `(${this._length})` : ''}`;
}
_stringify(date, options) {
date = this._applyTimezone(date, options);
return date.format('YYYY-MM-DD HH:mm:ss.SSS');
}
static parse(value, options) {
value = value.string();
if (value === null) {
return value;
}
if (moment.tz.zone(options.timezone)) {
value = moment.tz(value, options.timezone).toDate();
}
else {
value = new Date(`${value} ${options.timezone}`);
}
return value;
}
}
class DATEONLY extends BaseTypes.DATEONLY {
static parse(value) {
return value.string();
}
}
class UUID extends BaseTypes.UUID {
toSql() {
return 'CHAR(36) BINARY';
}
}
class GEOMETRY extends BaseTypes.GEOMETRY {
constructor(type, srid) {
super(type, srid);
if (_.isEmpty(this.type)) {
this.sqlType = this.key;
}
else {
this.sqlType = this.type;
}
}
toSql() {
return this.sqlType;
}
}
class ENUM extends BaseTypes.ENUM {
toSql(options) {
return `ENUM(${this.values.map(value => options.escape(value)).join(', ')})`;
}
}
class JSONTYPE extends BaseTypes.JSON {
_stringify(value, options) {
return options.operation === 'where' && typeof value === 'string' ? value
: JSON.stringify(value);
}
}
return {
ENUM,
DATE,
DATEONLY,
UUID,
GEOMETRY,
DECIMAL,
JSON: JSONTYPE
};
};
|
module.exports = function () {
var faker = require('faker');
var _ = require('lodash');
var getUserInfo = require('./mocks/getUserInfo.js');
var productName = function () {
return faker.commerce.productAdjective() +
' ' +
faker.commerce.productMaterial() +
' Widget';
};
var productImage = function () {
return faker.image.imageUrl();
};
// This is your json structurn each named object below can match a remote call
return {
getUserInfo: getUserInfo,
getSidebar: _.times(3, function (id) {
return {
id: id + 1,
name: 'Home',
icon: 'home',
iconBackground: faker.internet.color(),
sequence: id + 1
};
}),
products: _.times(9, function (id) {
var title = productName();
return {
id: id + 1,
title: title,
image: productImage(),
price: faker.commerce.price(),
description: faker.lorem.paragraph(),
summary: faker.lorem.paragraph()
};
}),
products6: _.times(6, function (id) {
var title = productName();
return {
id: id + 1,
title: title,
image: productImage(),
price: faker.commerce.price(),
description: faker.lorem.paragraph(),
summary: faker.lorem.paragraph()
};
})
};
};
|
/*jshint esversion: 6 */
import Service from '@ember/service';
export default Service.extend({
createCustomBlock(name, options, callback_to_change_block) {
options.colour = options.colour || '#4453ff';
if (Blockly.Blocks[name]) {
//console.warn(`Redefiniendo el bloque ${name}`);
}
Blockly.Blocks[name] = {
init: function () {
this.jsonInit(options);
if (callback_to_change_block) {
callback_to_change_block.call(this);
}
}
};
Blockly.Blocks[name].isCustomBlock = true;
if (!Blockly.MyLanguage) {
Blockly.MyLanguage = Blockly.JavaScript;
}
if (options.code) {
Blockly.MyLanguage[name] = function (block) {
let variables = options.code.match(/\$(\w+)/g);
let code = options.code;
if (variables) {
variables.forEach((v) => {
let regex = new RegExp('\\' + v, "g");
let variable_name = v.slice(1);
var variable_object = null;
if (variable_name === "DO") {
variable_object = Blockly.JavaScript.statementToCode(block, variable_name);
} else {
variable_object = Blockly.MyLanguage.valueToCode(block, variable_name) || block.getFieldValue(variable_name) || null;
}
code = code.replace(regex, variable_object);
});
}
return code;
};
}
return Blockly.Blocks[name];
},
createBlockWithAsyncDropdown(name, options) {
function callback_to_change_block() {
this.
appendDummyInput().
appendField(options.label || "").
appendField(new Blockly.FieldDropdown(options.callbackDropdown), 'DROPDOWN_VALUE');
}
return this.createCustomBlock(name, options, callback_to_change_block);
},
createCustomBlockWithHelper(name, options) {
let block_def = {
message0: options.descripcion,
colour: options.colour || '#4a6cd4',
previousStatement: true,
nextStatement: true,
args0: [],
code: options.code || `hacer(actor_id, "${options.comportamiento}", ${options.argumentos});`,
};
if (options.icono) {
block_def.message0 = `%1 ${options.descripcion}`;
block_def.args0.push({
"type": "field_image",
"src": `iconos/${options.icono}`,
"width": 16,
"height": 16,
"alt": "*"
});
}
return this.createCustomBlock(name, block_def);
},
createBlockValue(name, options) {
let block = this.createCustomBlock(name, {
message0: `%1 ${options.descripcion}`,
colour: options.colour || '#4a6cd4',
output: 'String',
args0: [
{
"type": "field_image",
"src": `iconos/${options.icono}`,
"width": 16,
"height": 16,
"alt": "*"
}
],
});
Blockly.MyLanguage[name] = function () {
return [`'${options.valor}'`, Blockly.JavaScript.ORDER_ATOMIC];
};
return block;
},
getBlocksList() {
return Object.keys(Blockly.Blocks);
},
getCustomBlocksList() {
return Object.keys(Blockly.Blocks).filter((e) => {
return Blockly.Blocks[e].isCustomBlock;
}
);
},
createAlias(new_name, original_block_name) {
let original_block = Blockly.Blocks[original_block_name];
Blockly.Blocks[new_name] = Object.assign({}, original_block);
let new_block = Blockly.Blocks[new_name];
new_block.isCustomBlock = true;
new_block.aliases = [original_block_name];
if (!original_block.aliases)
original_block.aliases = [];
original_block.aliases.push(new_name);
if (!Blockly.MyLanguage) {
Blockly.MyLanguage = Blockly.JavaScript;
}
Blockly.MyLanguage[new_name] = Blockly.JavaScript[original_block_name];
return Blockly.Blocks[new_name];
},
setStartHat(state) {
Blockly.BlockSvg.START_HAT = state;
}
});
|
webpackJsonp([0],{
/***/ 109:
/***/ (function(module, exports) {
function webpackEmptyAsyncContext(req) {
// Here Promise.resolve().then() is used instead of new Promise() to prevent
// uncatched exception popping up in devtools
return Promise.resolve().then(function() {
throw new Error("Cannot find module '" + req + "'.");
});
}
webpackEmptyAsyncContext.keys = function() { return []; };
webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext;
module.exports = webpackEmptyAsyncContext;
webpackEmptyAsyncContext.id = 109;
/***/ }),
/***/ 150:
/***/ (function(module, exports) {
function webpackEmptyAsyncContext(req) {
// Here Promise.resolve().then() is used instead of new Promise() to prevent
// uncatched exception popping up in devtools
return Promise.resolve().then(function() {
throw new Error("Cannot find module '" + req + "'.");
});
}
webpackEmptyAsyncContext.keys = function() { return []; };
webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext;
module.exports = webpackEmptyAsyncContext;
webpackEmptyAsyncContext.id = 150;
/***/ }),
/***/ 193:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return TabsPage; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__home_home__ = __webpack_require__(194);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__about_about__ = __webpack_require__(196);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__contact_contact__ = __webpack_require__(197);
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var TabsPage = /** @class */ (function () {
function TabsPage() {
// this tells the tabs component which Pages
// should be each tab's root Page
this.tab1Root = __WEBPACK_IMPORTED_MODULE_1__home_home__["a" /* HomePage */];
this.tab2Root = __WEBPACK_IMPORTED_MODULE_2__about_about__["a" /* AboutPage */];
this.tab3Root = __WEBPACK_IMPORTED_MODULE_3__contact_contact__["a" /* ContactPage */];
}
TabsPage = __decorate([
Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({template:/*ion-inline-start:"/home/marcus/ionic2-camera-demo/src/pages/tabs/tabs.html"*/'<ion-tabs>\n <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home"></ion-tab>\n <ion-tab [root]="tab2Root" tabTitle="About" tabIcon="information-circle"></ion-tab>\n <ion-tab [root]="tab3Root" tabTitle="Contact" tabIcon="contacts"></ion-tab>\n</ion-tabs>\n'/*ion-inline-end:"/home/marcus/ionic2-camera-demo/src/pages/tabs/tabs.html"*/
}),
__metadata("design:paramtypes", [])
], TabsPage);
return TabsPage;
}());
//# sourceMappingURL=tabs.js.map
/***/ }),
/***/ 194:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return HomePage; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(33);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__ionic_native_camera__ = __webpack_require__(195);
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var HomePage = /** @class */ (function () {
function HomePage(navCtrl, camera) {
this.navCtrl = navCtrl;
this.camera = camera;
this.images = [];
}
HomePage.prototype.takePhoto = function () {
var _this = this;
var options = {
quality: 80,
destinationType: this.camera.DestinationType.DATA_URL,
sourceType: this.camera.PictureSourceType.CAMERA,
allowEdit: false,
encodingType: this.camera.EncodingType.JPEG,
saveToPhotoAlbum: false
};
this.camera.getPicture(options).then(function (imageData) {
// imageData is either a base64 encoded string or a file URI
// If it's base64:
var base64Image = 'data:image/jpeg;base64,' + imageData;
_this.images.unshift({
src: base64Image
});
}, function (err) {
// Handle error
});
};
HomePage = __decorate([
Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({
selector: 'page-home',template:/*ion-inline-start:"/home/marcus/ionic2-camera-demo/src/pages/home/home.html"*/'<ion-header>\n <ion-navbar>\n <ion-title>Home</ion-title>\n </ion-navbar>\n</ion-header>\n<ion-content>\n <ion-slides style="height: 50vh">\n <ion-slide *ngFor="let image of images">\n <ion-card>\n <img [src]="image.src"/>\n </ion-card>\n </ion-slide>\n </ion-slides>\n <p>\n <button ion-button round icon-only block (click)="takePhoto()">\n <ion-icon name="camera"></ion-icon>\n </button>\n </p>\n</ion-content>\n'/*ion-inline-end:"/home/marcus/ionic2-camera-demo/src/pages/home/home.html"*/
}),
__metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["d" /* NavController */], __WEBPACK_IMPORTED_MODULE_2__ionic_native_camera__["a" /* Camera */]])
], HomePage);
return HomePage;
}());
//# sourceMappingURL=home.js.map
/***/ }),
/***/ 196:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AboutPage; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(33);
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var AboutPage = /** @class */ (function () {
function AboutPage(navCtrl) {
this.navCtrl = navCtrl;
}
AboutPage = __decorate([
Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({
selector: 'page-about',template:/*ion-inline-start:"/home/marcus/ionic2-camera-demo/src/pages/about/about.html"*/'<ion-header>\n <ion-navbar>\n <ion-title>\n About\n </ion-title>\n </ion-navbar>\n</ion-header>\n\n<ion-content padding>\n\n</ion-content>\n'/*ion-inline-end:"/home/marcus/ionic2-camera-demo/src/pages/about/about.html"*/
}),
__metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["d" /* NavController */]])
], AboutPage);
return AboutPage;
}());
//# sourceMappingURL=about.js.map
/***/ }),
/***/ 197:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ContactPage; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(33);
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var ContactPage = /** @class */ (function () {
function ContactPage(navCtrl) {
this.navCtrl = navCtrl;
}
ContactPage = __decorate([
Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({
selector: 'page-contact',template:/*ion-inline-start:"/home/marcus/ionic2-camera-demo/src/pages/contact/contact.html"*/'<ion-header>\n <ion-navbar>\n <ion-title>\n Contact\n </ion-title>\n </ion-navbar>\n</ion-header>\n\n<ion-content>\n <ion-list>\n <ion-list-header>Follow us on Twitter</ion-list-header>\n <ion-item>\n <ion-icon name="ionic" item-left></ion-icon>\n @ionicframework\n </ion-item>\n </ion-list>\n</ion-content>\n'/*ion-inline-end:"/home/marcus/ionic2-camera-demo/src/pages/contact/contact.html"*/
}),
__metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["d" /* NavController */]])
], ContactPage);
return ContactPage;
}());
//# sourceMappingURL=contact.js.map
/***/ }),
/***/ 198:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_platform_browser_dynamic__ = __webpack_require__(199);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__app_module__ = __webpack_require__(221);
Object(__WEBPACK_IMPORTED_MODULE_0__angular_platform_browser_dynamic__["a" /* platformBrowserDynamic */])().bootstrapModule(__WEBPACK_IMPORTED_MODULE_1__app_module__["a" /* AppModule */]);
//# sourceMappingURL=main.js.map
/***/ }),
/***/ 221:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AppModule; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(33);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__app_component__ = __webpack_require__(264);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__pages_about_about__ = __webpack_require__(196);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__pages_contact_contact__ = __webpack_require__(197);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__pages_home_home__ = __webpack_require__(194);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__pages_tabs_tabs__ = __webpack_require__(193);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__angular_platform_browser__ = __webpack_require__(29);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__ionic_native_status_bar__ = __webpack_require__(190);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__ionic_native_splash_screen__ = __webpack_require__(192);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__ionic_native_camera__ = __webpack_require__(195);
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var AppModule = /** @class */ (function () {
function AppModule() {
}
AppModule = __decorate([
Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["I" /* NgModule */])({
declarations: [
__WEBPACK_IMPORTED_MODULE_2__app_component__["a" /* MyApp */],
__WEBPACK_IMPORTED_MODULE_3__pages_about_about__["a" /* AboutPage */],
__WEBPACK_IMPORTED_MODULE_4__pages_contact_contact__["a" /* ContactPage */],
__WEBPACK_IMPORTED_MODULE_5__pages_home_home__["a" /* HomePage */],
__WEBPACK_IMPORTED_MODULE_6__pages_tabs_tabs__["a" /* TabsPage */]
],
imports: [
__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["c" /* IonicModule */].forRoot(__WEBPACK_IMPORTED_MODULE_2__app_component__["a" /* MyApp */], {}, {
links: []
}),
__WEBPACK_IMPORTED_MODULE_7__angular_platform_browser__["a" /* BrowserModule */]
],
bootstrap: [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["a" /* IonicApp */]],
entryComponents: [
__WEBPACK_IMPORTED_MODULE_2__app_component__["a" /* MyApp */],
__WEBPACK_IMPORTED_MODULE_3__pages_about_about__["a" /* AboutPage */],
__WEBPACK_IMPORTED_MODULE_4__pages_contact_contact__["a" /* ContactPage */],
__WEBPACK_IMPORTED_MODULE_5__pages_home_home__["a" /* HomePage */],
__WEBPACK_IMPORTED_MODULE_6__pages_tabs_tabs__["a" /* TabsPage */]
],
providers: [
__WEBPACK_IMPORTED_MODULE_8__ionic_native_status_bar__["a" /* StatusBar */],
__WEBPACK_IMPORTED_MODULE_9__ionic_native_splash_screen__["a" /* SplashScreen */],
__WEBPACK_IMPORTED_MODULE_10__ionic_native_camera__["a" /* Camera */],
{ provide: __WEBPACK_IMPORTED_MODULE_0__angular_core__["u" /* ErrorHandler */], useClass: __WEBPACK_IMPORTED_MODULE_1_ionic_angular__["b" /* IonicErrorHandler */] }
]
})
], AppModule);
return AppModule;
}());
//# sourceMappingURL=app.module.js.map
/***/ }),
/***/ 264:
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return MyApp; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__angular_core__ = __webpack_require__(0);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_ionic_angular__ = __webpack_require__(33);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__ionic_native_status_bar__ = __webpack_require__(190);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__ionic_native_splash_screen__ = __webpack_require__(192);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__pages_tabs_tabs__ = __webpack_require__(193);
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var MyApp = /** @class */ (function () {
function MyApp(platform, statusBar, splashScreen) {
this.rootPage = __WEBPACK_IMPORTED_MODULE_4__pages_tabs_tabs__["a" /* TabsPage */];
platform.ready().then(function () {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
});
}
MyApp = __decorate([
Object(__WEBPACK_IMPORTED_MODULE_0__angular_core__["m" /* Component */])({template:/*ion-inline-start:"/home/marcus/ionic2-camera-demo/src/app/app.html"*/'<ion-nav [root]="rootPage"></ion-nav>\n'/*ion-inline-end:"/home/marcus/ionic2-camera-demo/src/app/app.html"*/
}),
__metadata("design:paramtypes", [__WEBPACK_IMPORTED_MODULE_1_ionic_angular__["e" /* Platform */], __WEBPACK_IMPORTED_MODULE_2__ionic_native_status_bar__["a" /* StatusBar */], __WEBPACK_IMPORTED_MODULE_3__ionic_native_splash_screen__["a" /* SplashScreen */]])
], MyApp);
return MyApp;
}());
//# sourceMappingURL=app.component.js.map
/***/ })
},[198]);
//# sourceMappingURL=main.js.map |
mf.include("chat_commands.js");
mf.include("assert.js");
mf.include("arrays.js");
/**
* Example:
* var id;
* var count = 0;
* task_manager.doLater(new task_manager.Task(function start() {
* id = mf.setInterval(function() {
* mf.debug("hello");
* if (++count === 10) {
* task_manager.done();
* }
* }, 1000);
* }, function stop() {
* mf.clearInterval(id);
* }, "saying hello 10 times");
*/
var task_manager = {};
(function() {
/**
* Constructor.
* @param start_func() called when the job starts or resumes
* @param stop_func() called when the job should pause or abort
* @param string either a toString function or a string used to display the task in a list
*/
task_manager.Task = function(start_func, stop_func, string, resume_func) {
assert.isFunction(start_func);
this.start = start_func;
assert.isFunction(stop_func);
this.stop = stop_func;
if (typeof string === "string") {
var old_string = string;
string = function() { return old_string; };
}
assert.isFunction(string);
this.toString = string;
if (resume_func !== undefined) {
assert.isFunction(resume_func);
this.resume = resume_func;
}
this.started = false;
};
var tasks = [];
function runNextCommand() {
if (tasks.length === 0) {
return;
}
if (tasks[0].started && tasks[0].resume !== undefined) {
tasks[0].resume();
} else {
tasks[0].started = true;
tasks[0].begin_time = new Date().getTime();
tasks[0].start();
}
};
task_manager.doLater = function(task) {
tasks.push(task);
task.started = false;
if (tasks.length === 1) {
runNextCommand();
}
};
task_manager.doNow = function(task) {
if (tasks.length !== 0) {
tasks[0].stop();
}
tasks.remove(task);
tasks.unshift(task);
runNextCommand();
};
task_manager.done = function() {
assert.isTrue(tasks.length !== 0);
var length = tasks.length;
tasks[0].started = false;
tasks.shift();
assert.isTrue(length !== tasks.length);
runNextCommand();
};
task_manager.postpone = function(min_timeout) {
var task = tasks[0];
tasks.remove(task);
if (min_timeout > 0) {
task.postponed = mf.setTimeout(function resume() {
task.postponed = undefined;
tasks.push(task);
if (tasks.length === 1) {
runNextCommand();
}
}, min_timeout);
} else {
tasks.push(task);
}
runNextCommand();
};
task_manager.remove = function(task) {
if (task === tasks[0]) {
task.stop();
tasks.remove(task);
runNextCommand();
} else {
tasks.remove(task);
if (task.postponed !== undefined) {
mf.clearTimeout(task.postponed);
task.postponed = undefined;
task.stop();
}
}
}
chat_commands.registerCommand("stop", function() {
if (tasks.length === 0) {
return;
}
tasks[0].stop();
tasks = [];
});
chat_commands.registerCommand("tasks",function(speaker,args,responder_fun) {
responder_fun("Tasks: " + tasks.join(", "));
});
chat_commands.registerCommand("reboot", function(speaker, args, responder_fun) {
if (tasks.length === 0) {
responder_fun("no tasks");
return;
}
tasks[0].stop();
tasks[0].start();
}),
})();
|
/**
* Adds a new plugin to plugin.json, based on user prompts
*/
(function(){
var fs = require("fs"),
inquirer = require("inquirer"),
chalk = require("chalk"),
plugins = require("../plugins.json"),
banner = require("./banner.js"),
tags = require("./tags.js")(),
tagChoices = tags.getTags().map(function(tag){
return { name: tag };
}),
questions = [
{
type: "input",
name: "name",
message: "What is the name of your postcss plugin?",
validate: function( providedName ){
if( providedName.length < 1 ){
return "Please provide an actual name for your plugin."
}
var exists = plugins.filter(function( plugin ){
return plugin.name === providedName;
}).length;
if( exists ) {
return "This plugin has already been added to the list.";
}
if( providedName.indexOf("postcss-") === -1 ){
console.log( chalk.red("\nFYI: Plugin names usually start with 'postcss-' so they can easily be found on NPM.") );
}
return true;
}
},{
type: "input",
name: "description",
message: "Describe your plugin by finishing this sentence:\nPostCSS plugin...",
default: "eg: \"...that transforms your CSS.\""
},{
type: "input",
name: "url",
message: "What is the GitHub URL for your plugin?",
validate: function( providedName ){
if( providedName.indexOf("https://github.com/") > -1 )
return true;
else
return "Please provide a valid GitHub URL";
}
},{
type: "checkbox",
name: "tags",
message: "Choose at least one tag that describes your plugin.\nFor descriptions of the tags, please see the list in full:\nhttps://github.com/himynameisdave/postcss-plugins/blob/master/docs/tags.md",
choices: tagChoices,
validate: function( answer ) {
if ( answer.length < 1 ) {
return "You must choose at least one tag.";
}
return true;
}
}
];
// START DA SCRIPT
// 1. Hello
console.log( banner );
// 2. Da Questions
inquirer.prompt( questions, function(answers){
console.log( chalk.yellow("Adding a postcss plugin with the following properties:") );
console.log( chalk.cyan("name:\n ")+chalk.green(answers.name) );
console.log( chalk.cyan("description:\n ")+chalk.green(answers.description) );
console.log( chalk.cyan("url:\n ")+chalk.green(answers.url) );
console.log( chalk.cyan("tags:") );
answers.tags.forEach(function( tag ){
console.log( chalk.green(" - "+tag) );
});
// sets the author here
var newPlug = answers;
newPlug.author = newPlug.url.split("/")[3];
// push the new plugin right on there because it's formatted 👌👌👌
plugins.push( newPlug )
// write the plugins.json
fs.writeFile( "plugins.json", JSON.stringify( plugins, null, 2 ), function(err){
if(err) throw err;
console.log("Added the new plugin to plugins.json!");
require("./versionBump.js")(answers);
});
});
})();
|
$(function() {
/* We're going to use these elements a lot, so let's save references to them
* here. All of these elements are already created by the HTML code produced
* by the items page. */
var $orderPanel = $('#order-panel');
var $orderPanelCloseButton = $('#order-panel-close-button');
var $itemName = $('#item-name');
var $itemDescription = $('#item-description');
var $itemQuantity = $('#item-quantity-input');
var $itemId = $('#item-id-input');
/* Show or hide the side panel. We do this by animating its `left` CSS
* property, causing it to slide off screen with a negative value when
* we want to hide it. */
var togglePanel = function(show) {
$orderPanel.animate({ right: show ? 0 : -$orderPanel.outerWidth()});
};
/* A function to show an alert box at the top of the page. */
var showAlert = function(message, type) {
/* This stuctured mess of code creates a Bootstrap-style alert box.
* Note the use of chainable jQuery methods. */
var $alert = (
$('<div>') // create a <div> element
.text(message) // set its text
.addClass('alert') // add some CSS classes and attributes
.addClass('alert-' + type)
.addClass('alert-dismissible')
.attr('role', 'alert')
.prepend( // prepend a close button to the inner HTML
$('<button>') // create a <button> element
.attr('type', 'button') // and so on...
.addClass('close')
.attr('data-dismiss', 'alert')
.html('×') // × is code for the x-symbol
)
.hide() // initially hide the alert so it will slide into view
);
/* Add the alert to the alert container. */
$('#alerts').append($alert);
/* Slide the alert into view with an animation. */
$alert.slideDown();
};
/* Close the panel when the close button is clicked. */
$('#order-panel-close-button').click(function() {
togglePanel(false);
});
/* Whenever an element with class `item-link` is clicked, copy over the item
* information to the side panel, then show the side panel. */
$('.item-link').click(function(event) {
// Prevent default link navigation
event.preventDefault();
var $this = $(this);
$itemName.text($this.find('.item-name').text());
$itemDescription.text($this.find('.item-description').text());
$itemId.val($this.attr('data-id'));
togglePanel(true);
});
/* A boring detail but an important one. When the size of the window changes,
* update the `left` property of the side menu so that it remains fully
* hidden. */
$(window).resize(function() {
if($orderPanel.offset().right < 0) {
$orderPanel.offset({ right: -$orderPanel.outerWidth() });
}
});
/* When the form is submitted (button is pressed or enter key is pressed),
* make the Ajax call to add the item to the current order. */
$('#item-add-form').submit(function(event) {
// Prevent default form submission
event.preventDefault();
/* No input validation... yet. */
var quantity = $itemQuantity.val();
//get orderid
var orderID;
$.ajax({
type: 'PUT',
url: '/orders/',
contentType: 'application/json',
data:JSON.stringify({
userID: 1
}),
async: false,
dataType: 'json'
}).done(function(data) {
orderID = data.orderID
//showAlert('Order created successfully', 'success');
}).fail(function() {
showAlert('Fail to get orderID', 'danger');
});
/* Send the data to `PUT /orders/:orderid/items/:itemid`. */
$.ajax({
/* The HTTP method. */
type: 'PUT',
/* The URL. Use a dummy order ID for now. */
url: '/orders/'+orderID+'/items/' + $itemId.val(),
/* The `Content-Type` header. This tells the server what format the body
* of our request is in. This sets the header as
* `Content-Type: application/json`. */
contentType: 'application/json',
/* The request body. `JSON.stringify` formats it as JSON. */
data: JSON.stringify({
quantity: quantity
}),
/* The `Accept` header. This tells the server that we want to receive
* JSON. This sets the header as something like
* `Accept: application/json`. */
dataType: 'json'
}).done(function() {
/* This is called if and when the server responds with a 2XX (success)
* status code. */
/* Show a success message. */
showAlert('Posted the order with id ' + orderID, 'success');
/* Close the side panel while we're at it. */
togglePanel(false);
}).fail(function() {
showAlert('Something went wrong.', 'danger');
});
});
});
|
// @flow
/* eslint-disable react/no-danger */
// $FlowMeteor
import { find, propEq } from "ramda";
import { Link } from "react-router";
import Split, {
Left,
Right,
} from "../../../components/@primitives/layout/split";
import Meta from "../../../components/shared/meta";
import AddToCart from "../../../components/giving/add-to-cart";
type ILayout = {
account: Object,
};
const Layout = ({ account }: ILayout) => (
<div>
<Split nav classes={["background--light-primary"]}>
<Meta
title={account.name}
description={account.summary}
image={
account.images
? find(propEq("fileLabel", "2:1"), account.images).cloudfront
: account.image
}
meta={[{ property: "og:type", content: "article" }]}
/>
<Right
background={
account.images
? find(propEq("fileLabel", "2:1"), account.images).cloudfront
: account.image
}
mobile
/>
<Right
background={
account.images
? find(propEq("fileLabel", "2:1"), account.images).cloudfront
: account.image
}
mobile={false}
/>
</Split>
<Left scroll classes={["background--light-primary"]}>
<Link
to="/give/now"
className={
"locked-top locked-left soft-double@lap-and-up soft " +
"h7 text-dark-secondary plain visuallyhidden@handheld"
}
>
<i
className="icon-arrow-back soft-half-right display-inline-block"
style={{ verticalAlign: "middle" }}
/>
<span
className="display-inline-block"
style={{ verticalAlign: "middle", marginTop: "5px" }}
>
Back
</span>
</Link>
<div className="soft@lap-and-up soft-double-top@lap-and-up">
<div className="soft soft-double-bottom soft-double-top@lap-and-up">
<h2>{account.name}</h2>
<div dangerouslySetInnerHTML={{ __html: account.description }} />
</div>
</div>
<div className="background--light-secondary">
<div className="constrain-copy soft-double@lap-and-up">
<div className="soft soft-double-bottom soft-double-top@lap-and-up">
<AddToCart accounts={[account]} donate />
</div>
</div>
</div>
</Left>
</div>
);
export default Layout;
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M22 5.18 10.59 16.6l-4.24-4.24 1.41-1.41 2.83 2.83 10-10L22 5.18zm-2.21 5.04c.13.57.21 1.17.21 1.78 0 4.42-3.58 8-8 8s-8-3.58-8-8 3.58-8 8-8c1.58 0 3.04.46 4.28 1.25l1.44-1.44C16.1 2.67 14.13 2 12 2 6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10c0-1.19-.22-2.33-.6-3.39l-1.61 1.61z"
}), 'TaskAltSharp');
exports.default = _default; |
var API_PHP ="http://devtucompass.tk/pici/BackEnd/Clases/chatAdmin.php";
var API_REST = "http://devtucompass.tk/pici/API/";
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
function enviarInfo(){
$("#enviarInfo").click(function(){
$.ajax({
type: "POST",
url: API_PHP,
data: $("#info").serialize(), // serializes the form's elements.
error: function(jqXHR, textStatus, errorThrown){
console.log("hi");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
//do stuff
},
cache:false
}).done( function (data){
localStorage.cedula= $("#cedula").val();
$("#cedulaH").attr('value',localStorage.cedula);
localStorage.useradmin = -1;
$.mobile.navigate( "#chat");
sendMessage();
});
});
}
function sendMessage(){
$("#send").click(function(){
$.ajax({
type: "POST",
url: API_PHP,
data: $("#messagechat").serialize(), // serializes the form's elements.
error: function(jqXHR, textStatus, errorThrown){
alert("hi");
alert(jqXHR);
alert(textStatus);
alert(errorThrown);
//do stuff
},
cache:false
}).done( function (data){
console.log("la informacion es: "+data);
});
});
$("#message").val("");
}
function getLogMessages() {
var cedula= localStorage.cedula ;
//alert("la Cedula es: "+cedula);
var content = "";
$.ajax({
type: "GET",
url: API_REST+"lastLogChat?cedula="+cedula,
error: function(jqXHR, textStatus, errorThrown){
console.log("hi");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
//do stuff
},
cache:false,
format:"jsonp",
crossDomain: true,
async: true
}).done( function (data){
$.each( data, function ( i, item ){
//alert(item.id);
if(item.por ==='si'){
content+='<li data-theme="c">'+
'<a href="#">'+
'<h2>Consulta Sena PICI Dice: </h2>'+
'<p>'+item.mensaje+'</p>'+
'<p class="ui-li-aside"></p>'+
'</a>'+
'</li>';
}else{
content+='<li data-theme="e">'+
'<a href="#">'+
'<h2>Tu Dices: </h2>'+
'<p>'+item.mensaje+'</p>'+
'<p class="ui-li-aside"></p>'+
'</a>'+
'</li>';
}
});
$("#logMensajes").html(content);
$( "#logMensajes" ).listview( "refresh" );
});
}
|
(function(jiglib) {
var MaterialProperties = jiglib.MaterialProperties;
var CachedImpulse = jiglib.CachedImpulse;
var PhysicsState = jiglib.PhysicsState;
var RigidBody = jiglib.RigidBody;
var HingeJoint = jiglib.HingeJoint;
var BodyPair = jiglib.BodyPair;
var PhysicsSystem = jiglib.PhysicsSystem;
var PhysicsController = function()
{
this._controllerEnabled = null; // Boolean
this._controllerEnabled = false;
}
PhysicsController.prototype.updateController = function(dt)
{
}
PhysicsController.prototype.enableController = function()
{
}
PhysicsController.prototype.disableController = function()
{
}
PhysicsController.prototype.get_controllerEnabled = function()
{
return this._controllerEnabled;
}
jiglib.PhysicsController = PhysicsController;
})(jiglib);
|
/*
* SameValue() (E5 Section 9.12).
*
* SameValue() is difficult to test indirectly. It appears in E5 Section
* 8.12.9, [[DefineOwnProperty]] several times.
*
* One relatively simple approach is to create a non-configurable, non-writable
* property, and attempt to use Object.defineProperty() to set a new value for
* the property. If SameValue(oldValue,newValue), no exception is thrown.
* Otherwise, reject (TypeError); see E5 Section 8.12.9, step 10.a.ii.1.
*/
function sameValue(x,y) {
var obj = {};
try {
Object.defineProperty(obj, 'test', {
writable: false,
enumerable: false,
configurable: false,
value: x
});
Object.defineProperty(obj, 'test', {
value: y
});
} catch (e) {
if (e.name === 'TypeError') {
return false;
} else {
throw e;
}
}
return true;
}
function test(x,y) {
print(sameValue(x,y));
}
/*===
test: different types, first undefined
false
false
false
false
false
false
===*/
/* Different types, first is undefined */
print('test: different types, first undefined')
test(undefined, null);
test(undefined, true);
test(undefined, false);
test(undefined, 123.0);
test(undefined, 'foo');
test(undefined, {});
/*===
test: different types, first null
false
false
false
false
false
false
===*/
/* Different types, first is null */
print('test: different types, first null')
test(null, undefined);
test(null, true);
test(null, false);
test(null, 123.0);
test(null, 'foo');
test(null, {});
/*===
test: different types, first boolean
false
false
false
false
false
false
false
false
false
false
===*/
/* Different types, first is boolean */
print('test: different types, first boolean')
test(true, undefined);
test(true, null);
test(true, 123.0);
test(true, 'foo');
test(true, {});
test(false, undefined);
test(false, null);
test(false, 123.0);
test(false, 'foo');
test(false, {});
/*===
test: different types, first number
false
false
false
false
false
false
===*/
/* Different types, first is number */
print('test: different types, first number')
test(123.0, undefined);
test(123.0, null);
test(123.0, true);
test(123.0, false);
test(123.0, 'foo');
test(123.0, {});
/*===
test: different types, first string
false
false
false
false
false
false
===*/
/* Different types, first is string */
print('test: different types, first string')
test('foo', undefined);
test('foo', null);
test('foo', true);
test('foo', false);
test('foo', 123.0);
test('foo', {});
/*===
test: different types, first object
false
false
false
false
false
false
===*/
/* Different types, first is object */
print('test: different types, first object')
test({}, undefined);
test({}, null);
test({}, true);
test({}, false);
test({}, 123.0);
test({}, 'foo');
/*===
test: same types, undefined
true
===*/
/* Same types: undefined */
print('test: same types, undefined')
test(undefined, undefined);
/*===
test: same types, null
true
===*/
/* Same types: null */
print('test: same types, null')
test(null, null);
/*===
test: same types, boolean
true
false
false
true
===*/
/* Same types: boolean */
print('test: same types, boolean')
test(true, true);
test(true, false);
test(false, true);
test(false, false);
/*===
test: same types, number
true
true
false
false
true
true
false
false
true
true
true
===*/
/* Same types: number */
print('test: same types, number')
test(NaN, NaN);
test(-0, -0);
test(-0, +0);
test(+0, -0);
test(+0, +0);
test(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY);
test(Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY);
test(Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY);
test(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
test(-123.0, -123.0);
test(123.0, 123.0);
/*===
test: same types, string
true
false
false
true
===*/
/* Same types: string */
print('test: same types, string')
test('', '');
test('foo', '')
test('', 'foo');
test('foo', 'foo');
/*===
test: same types, object
true
false
false
true
===*/
/* Same types: object */
var obj1 = {};
var obj2 = {};
print('test: same types, object')
test(obj1, obj1);
test(obj1, obj2);
test(obj2, obj1);
test(obj2, obj2);
|
/**
* marked - a markdown parser
* Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
* https://github.com/chjj/marked
*/
(function () {
var block = {
newline: /^\n+/,
code: /^( {4}[^\n]+\n*)+/,
fences: noop,
hr: /^( *[-*_]){3,} *(?:\n+|$)/,
heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
nptable: noop,
lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
html: /^ *(?:comment|closed|closing) *(?:\n{2,}|\s*$)/,
def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
table: noop,
paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
text: /^[^\n]+/
};
block.bullet = /(?:[*+-]|\d+\.)/;
block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
block.item = replace(block.item, "gm")(/bull/g, block.bullet)();
block.list = replace(block.list)(/bull/g, block.bullet)("hr", "\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))")("def", "\\n+(?=" + block.def.source + ")")();
block.blockquote = replace(block.blockquote)("def", block.def)();
block._tag = "(?!(?:" + "a|em|strong|small|s|cite|q|dfn|abbr|data|time|code" + "|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo" + "|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b";
block.html = replace(block.html)("comment", /<!--[\s\S]*?-->/)("closed", /<(tag)[\s\S]+?<\/\1>/)("closing", /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)(/tag/g, block._tag)();
block.paragraph = replace(block.paragraph)("hr", block.hr)("heading", block.heading)("lheading", block.lheading)("blockquote", block.blockquote)("tag", "<" + block._tag)("def", block.def)();
block.normal = merge({}, block);
block.gfm = merge({}, block.normal, {
fences: /^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/,
paragraph: /^/
});
block.gfm.paragraph = replace(block.paragraph)("(?!", "(?!" + block.gfm.fences.source.replace("\\1", "\\2") + "|" + block.list.source.replace("\\1", "\\3") + "|")();
block.tables = merge({}, block.gfm, {
nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
});
function Lexer(options) {
this.tokens = [];
this.tokens.links = {};
this.options = options || marked.defaults;
this.rules = block.normal;
if (this.options.gfm) {
if (this.options.tables) {
this.rules = block.tables
} else {
this.rules = block.gfm
}
}
}
Lexer.rules = block;
Lexer.lex = function (src, options) {
var lexer = new Lexer(options);
return lexer.lex(src)
};
Lexer.prototype.lex = function (src) {
src = src.replace(/\r\n|\r/g, "\n").replace(/\t/g, " ").replace(/\u00a0/g, " ").replace(/\u2424/g, "\n");
return this.token(src, true)
};
Lexer.prototype.token = function (src, top, bq) {
var src = src.replace(/^ +$/gm, ""), next, loose, cap, bull, b, item, space, i, l;
while (src) {
if (cap = this.rules.newline.exec(src)) {
src = src.substring(cap[0].length);
if (cap[0].length > 1) {
this.tokens.push({type: "space"})
}
}
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
cap = cap[0].replace(/^ {4}/gm, "");
this.tokens.push({type: "code", text: !this.options.pedantic ? cap.replace(/\n+$/, "") : cap});
continue
}
if (cap = this.rules.fences.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({type: "code", lang: cap[2], text: cap[3]});
continue
}
if (cap = this.rules.heading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({type: "heading", depth: cap[1].length, text: cap[2]});
continue
}
if (top && (cap = this.rules.nptable.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: "table",
header: cap[1].replace(/^ *| *\| *$/g, "").split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, "").split(/ *\| */),
cells: cap[3].replace(/\n$/, "").split("\n")
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = "right"
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = "center"
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = "left"
} else {
item.align[i] = null
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i].split(/ *\| */)
}
this.tokens.push(item);
continue
}
if (cap = this.rules.lheading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({type: "heading", depth: cap[2] === "=" ? 1 : 2, text: cap[1]});
continue
}
if (cap = this.rules.hr.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({type: "hr"});
continue
}
if (cap = this.rules.blockquote.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({type: "blockquote_start"});
cap = cap[0].replace(/^ *> ?/gm, "");
this.token(cap, top, true);
this.tokens.push({type: "blockquote_end"});
continue
}
if (cap = this.rules.list.exec(src)) {
src = src.substring(cap[0].length);
bull = cap[2];
this.tokens.push({type: "list_start", ordered: bull.length > 1});
cap = cap[0].match(this.rules.item);
next = false;
l = cap.length;
i = 0;
for (; i < l; i++) {
item = cap[i];
space = item.length;
item = item.replace(/^ *([*+-]|\d+\.) +/, "");
if (~item.indexOf("\n ")) {
space -= item.length;
item = !this.options.pedantic ? item.replace(new RegExp("^ {1," + space + "}", "gm"), "") : item.replace(/^ {1,4}/gm, "")
}
if (this.options.smartLists && i !== l - 1) {
b = block.bullet.exec(cap[i + 1])[0];
if (bull !== b && !(bull.length > 1 && b.length > 1)) {
src = cap.slice(i + 1).join("\n") + src;
i = l - 1
}
}
loose = next || /\n\n(?!\s*$)/.test(item);
if (i !== l - 1) {
next = item.charAt(item.length - 1) === "\n";
if (!loose)loose = next
}
this.tokens.push({type: loose ? "loose_item_start" : "list_item_start"});
this.token(item, false, bq);
this.tokens.push({type: "list_item_end"})
}
this.tokens.push({type: "list_end"});
continue
}
if (cap = this.rules.html.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: this.options.sanitize ? "paragraph" : "html",
pre: cap[1] === "pre" || cap[1] === "script" || cap[1] === "style",
text: cap[0]
});
continue
}
if (!bq && top && (cap = this.rules.def.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.links[cap[1].toLowerCase()] = {href: cap[2], title: cap[3]};
continue
}
if (top && (cap = this.rules.table.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: "table",
header: cap[1].replace(/^ *| *\| *$/g, "").split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, "").split(/ *\| */),
cells: cap[3].replace(/(?: *\| *)?\n$/, "").split("\n")
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = "right"
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = "center"
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = "left"
} else {
item.align[i] = null
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i].replace(/^ *\| *| *\| *$/g, "").split(/ *\| */)
}
this.tokens.push(item);
continue
}
if (top && (cap = this.rules.paragraph.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.push({
type: "paragraph",
text: cap[1].charAt(cap[1].length - 1) === "\n" ? cap[1].slice(0, -1) : cap[1]
});
continue
}
if (cap = this.rules.text.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({type: "text", text: cap[0]});
continue
}
if (src) {
throw new Error("Infinite loop on byte: " + src.charCodeAt(0))
}
}
return this.tokens
};
var inline = {
escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
url: noop,
tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
link: /^!?\[(inside)\]\(href\)/,
reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
br: /^ {2,}\n(?!\s*$)/,
del: noop,
text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
};
inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
inline.link = replace(inline.link)("inside", inline._inside)("href", inline._href)();
inline.reflink = replace(inline.reflink)("inside", inline._inside)();
inline.normal = merge({}, inline);
inline.pedantic = merge({}, inline.normal, {
strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
});
inline.gfm = merge({}, inline.normal, {
escape: replace(inline.escape)("])", "~|])")(),
url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
del: /^~~(?=\S)([\s\S]*?\S)~~/,
text: replace(inline.text)("]|", "~]|")("|", "|https?://|")()
});
inline.breaks = merge({}, inline.gfm, {
br: replace(inline.br)("{2,}", "*")(),
text: replace(inline.gfm.text)("{2,}", "*")()
});
function InlineLexer(links, options) {
this.options = options || marked.defaults;
this.links = links;
this.rules = inline.normal;
this.renderer = this.options.renderer || new Renderer;
this.renderer.options = this.options;
if (!this.links) {
throw new Error("Tokens array requires a `links` property.")
}
if (this.options.gfm) {
if (this.options.breaks) {
this.rules = inline.breaks
} else {
this.rules = inline.gfm
}
} else if (this.options.pedantic) {
this.rules = inline.pedantic
}
}
InlineLexer.rules = inline;
InlineLexer.output = function (src, links, options) {
var inline = new InlineLexer(links, options);
return inline.output(src)
};
InlineLexer.prototype.output = function (src) {
var out = "", link, text, href, cap;
while (src) {
if (cap = this.rules.escape.exec(src)) {
src = src.substring(cap[0].length);
out += cap[1];
continue
}
if (cap = this.rules.autolink.exec(src)) {
src = src.substring(cap[0].length);
if (cap[2] === "@") {
text = cap[1].charAt(6) === ":" ? this.mangle(cap[1].substring(7)) : this.mangle(cap[1]);
href = this.mangle("mailto:") + text
} else {
text = escape(cap[1]);
href = text
}
out += this.renderer.link(href, null, text);
continue
}
if (!this.inLink && (cap = this.rules.url.exec(src))) {
src = src.substring(cap[0].length);
text = escape(cap[1]);
href = text;
out += this.renderer.link(href, null, text);
continue
}
if (cap = this.rules.tag.exec(src)) {
if (!this.inLink && /^<a /i.test(cap[0])) {
this.inLink = true
} else if (this.inLink && /^<\/a>/i.test(cap[0])) {
this.inLink = false
}
src = src.substring(cap[0].length);
out += this.options.sanitize ? escape(cap[0]) : cap[0];
continue
}
if (cap = this.rules.link.exec(src)) {
src = src.substring(cap[0].length);
this.inLink = true;
out += this.outputLink(cap, {href: cap[2], title: cap[3]});
this.inLink = false;
continue
}
if ((cap = this.rules.reflink.exec(src)) || (cap = this.rules.nolink.exec(src))) {
src = src.substring(cap[0].length);
link = (cap[2] || cap[1]).replace(/\s+/g, " ");
link = this.links[link.toLowerCase()];
if (!link || !link.href) {
out += cap[0].charAt(0);
src = cap[0].substring(1) + src;
continue
}
this.inLink = true;
out += this.outputLink(cap, link);
this.inLink = false;
continue
}
if (cap = this.rules.strong.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.strong(this.output(cap[2] || cap[1]));
continue
}
if (cap = this.rules.em.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.em(this.output(cap[2] || cap[1]));
continue
}
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.codespan(escape(cap[2], true));
continue
}
if (cap = this.rules.br.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.br();
continue
}
if (cap = this.rules.del.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.del(this.output(cap[1]));
continue
}
if (cap = this.rules.text.exec(src)) {
src = src.substring(cap[0].length);
out += escape(this.smartypants(cap[0]));
continue
}
if (src) {
throw new Error("Infinite loop on byte: " + src.charCodeAt(0))
}
}
return out
};
InlineLexer.prototype.outputLink = function (cap, link) {
var href = escape(link.href), title = link.title ? escape(link.title) : null;
return cap[0].charAt(0) !== "!" ? this.renderer.link(href, title, this.output(cap[1])) : this.renderer.image(href, title, escape(cap[1]))
};
InlineLexer.prototype.smartypants = function (text) {
if (!this.options.smartypants)return text;
return text.replace(/--/g, "—").replace(/(^|[-\u2014/(\[{"\s])'/g, "$1‘").replace(/'/g, "’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g, "$1“").replace(/"/g, "”").replace(/\.{3}/g, "…")
};
InlineLexer.prototype.mangle = function (text) {
var out = "", l = text.length, i = 0, ch;
for (; i < l; i++) {
ch = text.charCodeAt(i);
if (Math.random() > .5) {
ch = "x" + ch.toString(16)
}
out += "&#" + ch + ";"
}
return out
};
function Renderer(options) {
this.options = options || {}
}
Renderer.prototype.code = function (code, lang, escaped) {
if (this.options.highlight) {
var out = this.options.highlight(code, lang);
if (out != null && out !== code) {
escaped = true;
code = out
}
}
if (!lang) {
return "<pre><code>" + (escaped ? code : escape(code, true)) + "\n</code></pre>"
}
return '<pre><code class="' + this.options.langPrefix + escape(lang, true) + '">' + (escaped ? code : escape(code, true)) + "\n</code></pre>\n"
};
Renderer.prototype.blockquote = function (quote) {
return "<blockquote>\n" + quote + "</blockquote>\n"
};
Renderer.prototype.html = function (html) {
return html
};
Renderer.prototype.heading = function (text, level, raw) {
return "<h" + level + ' id="' + this.options.headerPrefix + raw.toLowerCase().replace(/[^\w]+/g, "-") + '">' + text + "</h" + level + ">\n"
};
Renderer.prototype.hr = function () {
return this.options.xhtml ? "<hr/>\n" : "<hr>\n"
};
Renderer.prototype.list = function (body, ordered) {
var type = ordered ? "ol" : "ul";
return "<" + type + ">\n" + body + "</" + type + ">\n"
};
Renderer.prototype.listitem = function (text) {
return "<li>" + text + "</li>\n"
};
Renderer.prototype.paragraph = function (text) {
return "<p>" + text + "</p>\n"
};
Renderer.prototype.table = function (header, body) {
return "<table>\n" + "<thead>\n" + header + "</thead>\n" + "<tbody>\n" + body + "</tbody>\n" + "</table>\n"
};
Renderer.prototype.tablerow = function (content) {
return "<tr>\n" + content + "</tr>\n"
};
Renderer.prototype.tablecell = function (content, flags) {
var type = flags.header ? "th" : "td";
var tag = flags.align ? "<" + type + ' style="text-align:' + flags.align + '">' : "<" + type + ">";
return tag + content + "</" + type + ">\n"
};
Renderer.prototype.strong = function (text) {
return "<strong>" + text + "</strong>"
};
Renderer.prototype.em = function (text) {
return "<em>" + text + "</em>"
};
Renderer.prototype.codespan = function (text) {
return "<code>" + text + "</code>"
};
Renderer.prototype.br = function () {
return this.options.xhtml ? "<br/>" : "<br>"
};
Renderer.prototype.del = function (text) {
return "<del>" + text + "</del>"
};
Renderer.prototype.link = function (href, title, text) {
if (this.options.sanitize) {
try {
var prot = decodeURIComponent(unescape(href)).replace(/[^\w:]/g, "").toLowerCase()
} catch (e) {
return ""
}
if (prot.indexOf("javascript:") === 0) {
return ""
}
}
var out = '<a href="' + href + '"';
if (title) {
out += ' title="' + title + '"'
}
out += ">" + text + "</a>";
return out
};
Renderer.prototype.image = function (href, title, text) {
var out = '<img src="' + href + '" alt="' + text + '"';
if (title) {
out += ' title="' + title + '"'
}
out += this.options.xhtml ? "/>" : ">";
return out
};
function Parser(options) {
this.tokens = [];
this.token = null;
this.options = options || marked.defaults;
this.options.renderer = this.options.renderer || new Renderer;
this.renderer = this.options.renderer;
this.renderer.options = this.options
}
Parser.parse = function (src, options, renderer) {
var parser = new Parser(options, renderer);
return parser.parse(src)
};
Parser.prototype.parse = function (src) {
this.inline = new InlineLexer(src.links, this.options, this.renderer);
this.tokens = src.reverse();
var out = "";
while (this.next()) {
out += this.tok()
}
return out
};
Parser.prototype.next = function () {
return this.token = this.tokens.pop()
};
Parser.prototype.peek = function () {
return this.tokens[this.tokens.length - 1] || 0
};
Parser.prototype.parseText = function () {
var body = this.token.text;
while (this.peek().type === "text") {
body += "\n" + this.next().text
}
return this.inline.output(body)
};
Parser.prototype.tok = function () {
switch (this.token.type) {
case"space":
{
return ""
}
case"hr":
{
return this.renderer.hr()
}
case"heading":
{
return this.renderer.heading(this.inline.output(this.token.text), this.token.depth, this.token.text)
}
case"code":
{
return this.renderer.code(this.token.text, this.token.lang, this.token.escaped)
}
case"table":
{
var header = "", body = "", i, row, cell, flags, j;
cell = "";
for (i = 0; i < this.token.header.length; i++) {
flags = {header: true, align: this.token.align[i]};
cell += this.renderer.tablecell(this.inline.output(this.token.header[i]), {
header: true,
align: this.token.align[i]
})
}
header += this.renderer.tablerow(cell);
for (i = 0; i < this.token.cells.length; i++) {
row = this.token.cells[i];
cell = "";
for (j = 0; j < row.length; j++) {
cell += this.renderer.tablecell(this.inline.output(row[j]), {
header: false,
align: this.token.align[j]
})
}
body += this.renderer.tablerow(cell)
}
return this.renderer.table(header, body)
}
case"blockquote_start":
{
var body = "";
while (this.next().type !== "blockquote_end") {
body += this.tok()
}
return this.renderer.blockquote(body)
}
case"list_start":
{
var body = "", ordered = this.token.ordered;
while (this.next().type !== "list_end") {
body += this.tok()
}
return this.renderer.list(body, ordered)
}
case"list_item_start":
{
var body = "";
while (this.next().type !== "list_item_end") {
body += this.token.type === "text" ? this.parseText() : this.tok()
}
return this.renderer.listitem(body)
}
case"loose_item_start":
{
var body = "";
while (this.next().type !== "list_item_end") {
body += this.tok()
}
return this.renderer.listitem(body)
}
case"html":
{
var html = !this.token.pre && !this.options.pedantic ? this.inline.output(this.token.text) : this.token.text;
return this.renderer.html(html)
}
case"paragraph":
{
return this.renderer.paragraph(this.inline.output(this.token.text))
}
case"text":
{
return this.renderer.paragraph(this.parseText())
}
}
};
function escape(html, encode) {
return html.replace(!encode ? /&(?!#?\w+;)/g : /&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'")
}
function unescape(html) {
return html.replace(/&([#\w]+);/g, function (_, n) {
n = n.toLowerCase();
if (n === "colon")return ":";
if (n.charAt(0) === "#") {
return n.charAt(1) === "x" ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1))
}
return ""
})
}
function replace(regex, opt) {
regex = regex.source;
opt = opt || "";
return function self(name, val) {
if (!name)return new RegExp(regex, opt);
val = val.source || val;
val = val.replace(/(^|[^\[])\^/g, "$1");
regex = regex.replace(name, val);
return self
}
}
function noop() {
}
noop.exec = noop;
function merge(obj) {
var i = 1, target, key;
for (; i < arguments.length; i++) {
target = arguments[i];
for (key in target) {
if (Object.prototype.hasOwnProperty.call(target, key)) {
obj[key] = target[key]
}
}
}
return obj
}
function marked(src, opt, callback) {
if (callback || typeof opt === "function") {
if (!callback) {
callback = opt;
opt = null
}
opt = merge({}, marked.defaults, opt || {});
var highlight = opt.highlight, tokens, pending, i = 0;
try {
tokens = Lexer.lex(src, opt)
} catch (e) {
return callback(e)
}
pending = tokens.length;
var done = function (err) {
if (err) {
opt.highlight = highlight;
return callback(err)
}
var out;
try {
out = Parser.parse(tokens, opt)
} catch (e) {
err = e
}
opt.highlight = highlight;
return err ? callback(err) : callback(null, out)
};
if (!highlight || highlight.length < 3) {
return done()
}
delete opt.highlight;
if (!pending)return done();
for (; i < tokens.length; i++) {
(function (token) {
if (token.type !== "code") {
return --pending || done()
}
return highlight(token.text, token.lang, function (err, code) {
if (err)return done(err);
if (code == null || code === token.text) {
return --pending || done()
}
token.text = code;
token.escaped = true;
--pending || done()
})
})(tokens[i])
}
return
}
try {
if (opt)opt = merge({}, marked.defaults, opt);
return Parser.parse(Lexer.lex(src, opt), opt)
} catch (e) {
e.message += "\nPlease report this to https://github.com/chjj/marked.";
if ((opt || marked.defaults).silent) {
return "<p>An error occured:</p><pre>" + escape(e.message + "", true) + "</pre>"
}
throw e
}
}
marked.options = marked.setOptions = function (opt) {
merge(marked.defaults, opt);
return marked
};
marked.defaults = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: false,
silent: false,
highlight: null,
langPrefix: "lang-",
smartypants: false,
headerPrefix: "",
renderer: new Renderer,
xhtml: false
};
marked.Parser = Parser;
marked.parser = Parser.parse;
marked.Renderer = Renderer;
marked.Lexer = Lexer;
marked.lexer = Lexer.lex;
marked.InlineLexer = InlineLexer;
marked.inlineLexer = InlineLexer.output;
marked.parse = marked;
if (typeof module !== "undefined" && typeof exports === "object") {
module.exports = marked
} else if (typeof define === "function" && define.amd) {
define(function () {
return marked
})
} else {
this.marked = marked
}
}).call(function () {
return this || (typeof window !== "undefined" ? window : global)
}()); |
/*
* @name शेक बॉल बाउंस
* @description एक बॉल क्लास बनाएं, कई ऑब्जेक्ट्स को इंस्टेंट करें, इसे स्क्रीन के चारों ओर घुमाएं, और कैनवास के किनारे को छूने पर बाउंस करें।
* त्वरणX और त्वरण में कुल परिवर्तन के आधार पर शेक घटना का पता लगाएं और पता लगाने के आधार पर वस्तुओं को गति दें या धीमा करें।
*/
let balls = [];
let threshold = 30;
let accChangeX = 0;
let accChangeY = 0;
let accChangeT = 0;
function setup() {
createCanvas(displayWidth, displayHeight);
for (let i = 0; i < 20; i++) {
balls.push(new Ball());
}
}
function draw() {
background(0);
for (let i = 0; i < balls.length; i++) {
balls[i].move();
balls[i].display();
}
checkForShake();
}
function checkForShake() {
// Calculate total change in accelerationX and accelerationY
accChangeX = abs(accelerationX - pAccelerationX);
accChangeY = abs(accelerationY - pAccelerationY);
accChangeT = accChangeX + accChangeY;
// If shake
if (accChangeT >= threshold) {
for (let i = 0; i < balls.length; i++) {
balls[i].shake();
balls[i].turn();
}
}
// If not shake
else {
for (let i = 0; i < balls.length; i++) {
balls[i].stopShake();
balls[i].turn();
balls[i].move();
}
}
}
// Ball class
class Ball {
constructor() {
this.x = random(width);
this.y = random(height);
this.diameter = random(10, 30);
this.xspeed = random(-2, 2);
this.yspeed = random(-2, 2);
this.oxspeed = this.xspeed;
this.oyspeed = this.yspeed;
this.direction = 0.7;
}
move() {
this.x += this.xspeed * this.direction;
this.y += this.yspeed * this.direction;
}
// Bounce when touch the edge of the canvas
turn() {
if (this.x < 0) {
this.x = 0;
this.direction = -this.direction;
} else if (this.y < 0) {
this.y = 0;
this.direction = -this.direction;
} else if (this.x > width - 20) {
this.x = width - 20;
this.direction = -this.direction;
} else if (this.y > height - 20) {
this.y = height - 20;
this.direction = -this.direction;
}
}
// Add to xspeed and yspeed based on
// the change in accelerationX value
shake() {
this.xspeed += random(5, accChangeX / 3);
this.yspeed += random(5, accChangeX / 3);
}
// Gradually slows down
stopShake() {
if (this.xspeed > this.oxspeed) {
this.xspeed -= 0.6;
} else {
this.xspeed = this.oxspeed;
}
if (this.yspeed > this.oyspeed) {
this.yspeed -= 0.6;
} else {
this.yspeed = this.oyspeed;
}
}
display() {
ellipse(this.x, this.y, this.diameter, this.diameter);
}
}
|
import { removeFromArray } from '../../../utils/array';
import fireEvent from '../../../events/fireEvent';
import Fragment from '../../Fragment';
import createFunction from '../../../shared/createFunction';
import { unbind } from '../../../shared/methodCallers';
import noop from '../../../utils/noop';
import resolveReference from '../../resolvers/resolveReference';
const eventPattern = /^event(?:\.(.+))?$/;
const argumentsPattern = /^arguments\.(\d*)$/;
const dollarArgsPattern = /^\$(\d*)$/;
export default class EventDirective {
constructor ( owner, event, template ) {
this.owner = owner;
this.event = event;
this.template = template;
this.ractive = owner.parentFragment.ractive;
this.parentFragment = owner.parentFragment;
this.context = null;
this.passthru = false;
// method calls
this.method = null;
this.resolvers = null;
this.models = null;
this.argsFn = null;
// handler directive
this.action = null;
this.args = null;
}
bind () {
this.context = this.parentFragment.findContext();
const template = this.template;
if ( template.m ) {
this.method = template.m;
if ( this.passthru = template.g ) {
// on-click="foo(...arguments)"
// no models or args, just pass thru values
}
else {
this.resolvers = [];
this.models = template.a.r.map( ( ref, i ) => {
if ( eventPattern.test( ref ) ) {
// on-click="foo(event.node)"
return {
event: true,
keys: ref.length > 5 ? ref.slice( 6 ).split( '.' ) : [],
unbind: noop
};
}
const argMatch = argumentsPattern.exec( ref );
if ( argMatch ) {
// on-click="foo(arguments[0])"
return {
argument: true,
index: argMatch[1]
};
}
const dollarMatch = dollarArgsPattern.exec( ref );
if ( dollarMatch ) {
// on-click="foo($1)"
return {
argument: true,
index: dollarMatch[1] - 1
};
}
let resolver;
const model = resolveReference( this.parentFragment, ref );
if ( !model ) {
resolver = this.parentFragment.resolve( ref, model => {
this.models[i] = model;
removeFromArray( this.resolvers, resolver );
});
this.resolvers.push( resolver );
}
return model;
});
this.argsFn = createFunction( template.a.s, template.a.r.length );
}
}
else {
// TODO deprecate this style of directive
this.action = typeof template === 'string' ? // on-click='foo'
template :
typeof template.n === 'string' ? // on-click='{{dynamic}}'
template.n :
new Fragment({
owner: this,
template: template.n
});
this.args = template.a ? // static arguments
( typeof template.a === 'string' ? [ template.a ] : template.a ) :
template.d ? // dynamic arguments
new Fragment({
owner: this,
template: template.d
}) :
[]; // no arguments
}
if ( this.template.n && typeof this.template.n !== 'string' ) this.action.bind();
if ( this.template.d ) this.args.bind();
}
bubble () {
if ( !this.dirty ) {
this.dirty = true;
this.owner.bubble();
}
}
fire ( event, passedArgs ) {
// augment event object
if ( event ) {
event.keypath = this.context.getKeypath();
event.context = this.context.get();
event.index = this.parentFragment.indexRefs;
if ( passedArgs ) passedArgs.unshift( event );
}
if ( this.method ) {
if ( typeof this.ractive[ this.method ] !== 'function' ) {
throw new Error( `Attempted to call a non-existent method ("${this.method}")` );
}
let args;
if ( this.passthru ) {
args = passedArgs;
}
else {
const values = this.models.map( model => {
if ( !model ) return undefined;
if ( model.event ) {
let obj = event;
let keys = model.keys.slice();
while ( keys.length ) obj = obj[ keys.shift() ];
return obj;
}
if ( model.argument ) {
return passedArgs ? passedArgs[ model.index ] : void 0;
}
if ( model.wrapper ) {
return model.wrapper.value;
}
return model.get();
});
args = this.argsFn.apply( null, values );
}
// make event available as `this.event`
const ractive = this.ractive;
const oldEvent = ractive.event;
ractive.event = event;
ractive[ this.method ].apply( ractive, args );
ractive.event = oldEvent;
}
else {
const action = this.action.toString();
let args = this.template.d ? this.args.getArgsList() : this.args;
if ( event ) event.name = action;
fireEvent( this.ractive, action, {
event,
args
});
}
}
rebind () {
throw new Error( 'EventDirective$rebind not yet implemented!' ); // TODO add tests
}
render () {
this.event.listen( this );
}
unbind () {
const template = this.template;
if ( template.m ) {
this.resolvers.forEach( unbind );
this.resolvers = [];
this.models.forEach( model => {
if ( model ) model.unbind();
});
}
else {
// TODO this is brittle and non-explicit, fix it
if ( this.action.unbind ) this.action.unbind();
if ( this.args.unbind ) this.args.unbind();
}
}
unrender () {
this.event.unlisten();
}
update () {
if ( this.method ) return; // nothing to do
// ugh legacy
if ( this.action.update ) this.action.update();
if ( this.template.d ) this.args.update();
this.dirty = false;
}
}
|
module.exports={"title":"TYPO3","hex":"FF8700","source":"https://typo3.com/fileadmin/assets/typo3logos/typo3_bullet_01.svg","svg":"<svg role=\"img\" viewBox=\"0 0 24 24\" xmlns=\"http://www.w3.org/2000/svg\"><title>TYPO3 icon</title><path d=\"M18.08 16.539c-.356.105-.64.144-1.012.144-3.048 0-7.524-10.652-7.524-14.197 0-1.305.31-1.74.745-2.114C6.56.808 2.082 2.177.651 3.917c-.31.436-.497 1.12-.497 1.99C.154 11.442 6.06 24 10.228 24c1.928 0 5.178-3.168 7.852-7.46M16.134 0c3.855 0 7.713.622 7.713 2.798 0 4.415-2.8 9.765-4.23 9.765-2.549 0-5.72-7.09-5.72-10.635C13.897.31 14.518 0 16.134 0\"/></svg>","path":"M18.08 16.539c-.356.105-.64.144-1.012.144-3.048 0-7.524-10.652-7.524-14.197 0-1.305.31-1.74.745-2.114C6.56.808 2.082 2.177.651 3.917c-.31.436-.497 1.12-.497 1.99C.154 11.442 6.06 24 10.228 24c1.928 0 5.178-3.168 7.852-7.46M16.134 0c3.855 0 7.713.622 7.713 2.798 0 4.415-2.8 9.765-4.23 9.765-2.549 0-5.72-7.09-5.72-10.635C13.897.31 14.518 0 16.134 0"}; |
!function(){"use strict";!function(){if(void 0===window.Reflect||void 0===window.customElements||window.customElements.polyfillWrapFlushCallback)return;const t=HTMLElement;window.HTMLElement={HTMLElement:function(){return Reflect.construct(t,[],this.constructor)}}.HTMLElement,HTMLElement.prototype=t.prototype,HTMLElement.prototype.constructor=HTMLElement,Object.setPrototypeOf(HTMLElement,t)}()}(); |
/*
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['sap/ui/base/EventProvider','./Serializer','./delegate/HTML','sap/ui/thirdparty/vkbeautify'],function(E,S,H,v){"use strict";var a=E.extend("sap.ui.core.util.serializer.HTMLViewSerializer",{constructor:function(V,w,g,G){E.apply(this);this._oView=V;this._oWindow=w;this._fnGetControlId=g;this._fnGetEventHandlerName=G;}});a.prototype.serialize=function(){var s=function(C){return(C instanceof this._oWindow.sap.ui.core.mvc.View);};var c=new S(this._oView,new H(this._fnGetControlId,this._fnGetEventHandlerName),true,this._oWindow,s);var r=c.serialize();var V=[];V.push('<template');if(this._oView.getControllerName&&this._oView.getControllerName()){V.push(' data-controller-name="'+this._oView.getControllerName()+'"');}V.push(" >");V.push(r);V.push("</template>");return v.xml(V.join(""));};return a;});
|
'use strict';
var _ = require('lodash');
var helpers = require('./helpers');
var responseParser = require('./responseparser');
var request = require('./request');
// A resource on the API, instances of this are used as the prototype of
// instances of each API resource. This constructor will build up a method
// for each action that can be performed on the resource.
//
// - @param {Object} options
// - @param {Object} schema
//
// The `options` argument should have the following properties:
//
// - `resourceDefinition` - the definition of the resource and its actions from
// the schema definition.
// - `consumerkey` - the oauth consumerkey
// - `consumersecret` the oauth consumersecret
// - `schema` - the schema defintion
// - `format` - the desired response format
// - `logger` - for logging output
function Resource(options, schema) {
this.logger = options.logger;
this.resourceName = options.resourceDefinition.resource;
this.host = options.resourceDefinition.host || schema.host;
this.sslHost = options.resourceDefinition.sslHost || schema.sslHost;
this.port = options.resourceDefinition.port || schema.port;
this.prefix = options.resourceDefinition.prefix || schema.prefix;
this.consumerkey = options.consumerkey;
this.consumersecret = options.consumersecret;
if(this.logger.silly) {
this.logger.silly('Creating constructor for resource: ' + this.resourceName);
}
_.each(options.resourceDefinition.actions,
function processAction(action) {
this.createAction(action, options.userManagement);
}, this);
}
// Figure out the appropriate method name for an action on a resource on
// the API
//
// - @param {Mixed} - actionDefinition - Either a string if the action method
// name is the same as the action path component on the underlying API call
// or a hash if they differ.
// - @return {String}
Resource.prototype.chooseMethodName = function (actionDefinition) {
var fnName;
// Default the action name to getXXX if we only have the URL slug as the
// action definition.
if (_.isString(actionDefinition)) {
fnName = 'get' + helpers.capitalize(actionDefinition);
} else {
fnName = actionDefinition.methodName;
}
return fnName;
};
// Utility method for creating the necessary methods on the Resource for
// dispatching the request to the 7digital API.
//
// - @param {Mixed} actionDefinition - Either a string if the action method
// name is the same as the action path component on the underlying API call
// or a hash if they differ.
Resource.prototype.createAction = function (actionDefinition, isManaged) {
var url;
var fnName = this.chooseMethodName(actionDefinition);
var action = typeof actionDefinition.apiCall === 'undefined' ?
actionDefinition : actionDefinition.apiCall;
var httpMethod = (actionDefinition.method || 'GET').toUpperCase();
var host = actionDefinition.host || this.host;
var sslHost = actionDefinition.sslHost || this.sslHost;
var port = actionDefinition.port || this.port;
var prefix = actionDefinition.prefix || this.prefix;
var authType = (actionDefinition.oauth
&& actionDefinition.oauth === '3-legged' && isManaged)
? '2-legged'
: actionDefinition.oauth;
if(this.logger.silly) {
this.logger.silly(
'Creating method: ' + fnName + ' for ' + action +
' action with ' + httpMethod + ' HTTP verb');
}
/*jshint validthis: true */
function invokeAction(requestData, callback) {
var self = this;
var endpointInfo = {
host: invokeAction.host,
sslHost: invokeAction.sslHost || sslHost,
port: invokeAction.port,
prefix: invokeAction.prefix,
authtype: authType,
url: helpers.formatPath(invokeAction.prefix, this.resourceName,
action)
};
var credentials = {
consumerkey: this.consumerkey,
consumersecret: this.consumersecret
};
if (_.isFunction(requestData)) {
callback = requestData;
requestData = {};
}
function checkAndParse(err, data, response) {
if (err) {
return callback(err);
}
return responseParser.parse(data, {
format: self.format,
logger: self.logger,
url: endpointInfo.url,
params: requestData,
contentType: response.headers['content-type']
}, getLocationForRedirectsAndCallback);
function getLocationForRedirectsAndCallback(err, parsed) {
if (err) {
return callback(err);
}
if (response && response.headers['location']) {
parsed.location = response.headers['location'];
}
return callback(null, parsed);
}
}
_.defaults(requestData, this.defaultParams);
if (httpMethod === 'GET') {
// Add the default parameters to the request data
return request.get(endpointInfo, requestData, this.headers,
credentials, this.logger, checkAndParse);
}
if (httpMethod === 'POST' || httpMethod === 'PUT') {
return request.postOrPut(httpMethod, endpointInfo, requestData,
this.headers, credentials, this.logger, checkAndParse);
}
return callback(new Error('Unsupported HTTP verb: ' + httpMethod));
}
invokeAction.action = action;
invokeAction.authtype = authType;
invokeAction.host = host;
invokeAction.sslHost = sslHost;
invokeAction.port = port;
invokeAction.prefix = prefix;
this[fnName] = invokeAction;
};
module.exports = Resource;
|
/**
* Custom events to control showing and hiding of tooltip
*
* @attributes
* - `event` {String}
* - `eventOff` {String}
*/
export const checkStatus = function(dataEventOff, e) {
const { show } = this.state;
const { id } = this.props;
const isCapture = this.isCapture(e.currentTarget);
const currentItem = e.currentTarget.getAttribute('currentItem');
if (!isCapture) e.stopPropagation();
if (show && currentItem === 'true') {
if (!dataEventOff) this.hideTooltip(e);
} else {
e.currentTarget.setAttribute('currentItem', 'true');
setUntargetItems(e.currentTarget, this.getTargetArray(id));
this.showTooltip(e);
}
};
const setUntargetItems = function(currentTarget, targetArray) {
for (let i = 0; i < targetArray.length; i++) {
if (currentTarget !== targetArray[i]) {
targetArray[i].setAttribute('currentItem', 'false');
} else {
targetArray[i].setAttribute('currentItem', 'true');
}
}
};
const customListeners = {
id: '9b69f92e-d3fe-498b-b1b4-c5e63a51b0cf',
set(target, event, listener) {
if (this.id in target) {
const map = target[this.id];
map[event] = listener;
} else {
// this is workaround for WeakMap, which is not supported in older browsers, such as IE
Object.defineProperty(target, this.id, {
configurable: true,
value: { [event]: listener }
});
}
},
get(target, event) {
const map = target[this.id];
if (map !== undefined) {
return map[event];
}
}
};
export default function(target) {
target.prototype.isCustomEvent = function(ele) {
const { event } = this.state;
return event || !!ele.getAttribute('data-event');
};
/* Bind listener for custom event */
target.prototype.customBindListener = function(ele) {
const { event, eventOff } = this.state;
const dataEvent = ele.getAttribute('data-event') || event;
const dataEventOff = ele.getAttribute('data-event-off') || eventOff;
dataEvent.split(' ').forEach(event => {
ele.removeEventListener(event, customListeners.get(ele, event));
const customListener = checkStatus.bind(this, dataEventOff);
customListeners.set(ele, event, customListener);
ele.addEventListener(event, customListener, false);
});
if (dataEventOff) {
dataEventOff.split(' ').forEach(event => {
ele.removeEventListener(event, this.hideTooltip);
ele.addEventListener(event, this.hideTooltip, false);
});
}
};
/* Unbind listener for custom event */
target.prototype.customUnbindListener = function(ele) {
const { event, eventOff } = this.state;
const dataEvent = event || ele.getAttribute('data-event');
const dataEventOff = eventOff || ele.getAttribute('data-event-off');
ele.removeEventListener(dataEvent, customListeners.get(ele, event));
if (dataEventOff) ele.removeEventListener(dataEventOff, this.hideTooltip);
};
}
|
var Request = require('request');
function NewsFetcher() {
this._newsLink = 'http://kaku.rocks/news.json';
}
NewsFetcher.prototype.get = function() {
var promise = new Promise((resolve, reject) => {
Request.get(this._newsLink, (error, response, body) => {
if (error) {
reject(error);
console.log(error);
}
else {
var result = JSON.parse(body);
resolve(result.news);
}
});
});
return promise;
};
module.exports = new NewsFetcher();
|
/**
* @fileoverview Tests for max-depth.
* @author Ian Christian Myers
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var eslintTester = require("eslint-tester");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
eslintTester.addRuleTest("lib/rules/max-depth", {
valid: [
{ code: "function foo() { if (true) { if (false) { if (true) { } } } }", args: [1, 3] },
"function foo() { if (true) { if (false) { if (true) { } } } }"
],
invalid: [
{ code: "function foo() { if (true) { if (false) { if (true) { } } } }", args: [1, 2], errors: [{ message: "Blocks are nested too deeply (3).", type: "IfStatement"}] },
{ code: "function foo() { if (true) {} else { for(;;) {} } }", args: [1, 1], errors: [{ message: "Blocks are nested too deeply (2).", type: "ForStatement"}] },
{ code: "function foo() { while (true) { if (true) {} } }", args: [1, 1], errors: [{ message: "Blocks are nested too deeply (2).", type: "IfStatement"}] },
{ code: "function foo() { while (true) { if (true) { if (false) { } } } }", args: [1, 1], errors: [{ message: "Blocks are nested too deeply (2).", type: "IfStatement"}, { message: "Blocks are nested too deeply (3).", type: "IfStatement"}] }
]
});
|
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports.isReactChildren = isReactChildren;
exports.createRouteFromReactElement = createRouteFromReactElement;
exports.createRoutesFromReactChildren = createRoutesFromReactChildren;
exports.createRoutes = createRoutes;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _warning = require('warning');
var _warning2 = _interopRequireDefault(_warning);
function isValidChild(object) {
return object == null || (0, _react.isValidElement)(object);
}
function isReactChildren(object) {
return isValidChild(object) || Array.isArray(object) && object.every(isValidChild);
}
function checkPropTypes(componentName, propTypes, props) {
componentName = componentName || 'UnknownComponent';
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error = propTypes[propName](props, propName, componentName);
if (error instanceof Error) (0, _warning2['default'])(false, error.message);
}
}
}
function createRouteFromReactElement(element) {
var type = element.type;
var route = _extends({}, type.defaultProps, element.props);
if (type.propTypes) checkPropTypes(type.displayName || type.name, type.propTypes, route);
if (route.children) {
route.childRoutes = createRoutesFromReactChildren(route.children);
delete route.children;
}
return route;
}
/**
* Creates and returns a routes object from the given ReactChildren. JSX
* provides a convenient way to visualize how routes in the hierarchy are
* nested.
*
* import { Route, createRoutesFromReactChildren } from 'react-router';
*
* var routes = createRoutesFromReactChildren(
* <Route component={App}>
* <Route path="home" component={Dashboard}/>
* <Route path="news" component={NewsFeed}/>
* </Route>
* );
*
* Note: This method is automatically used when you provide <Route> children
* to a <Router> component.
*/
function createRoutesFromReactChildren(children) {
var routes = [];
_react2['default'].Children.forEach(children, function (element) {
if ((0, _react.isValidElement)(element)) {
// Component classes may have a static create* method.
if (element.type.createRouteFromReactElement) {
routes.push(element.type.createRouteFromReactElement(element));
} else {
routes.push(createRouteFromReactElement(element));
}
}
});
return routes;
}
/**
* Creates and returns an array of routes from the given object which
* may be a JSX route, a plain object route, or an array of either.
*/
function createRoutes(routes) {
if (isReactChildren(routes)) {
routes = createRoutesFromReactChildren(routes);
} else if (!Array.isArray(routes)) {
routes = [routes];
}
return routes;
} |
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import ReactDOM from 'react-dom';
import Nav from '../src/Nav';
import NavItem from '../src/NavItem';
import Tab from '../src/Tab';
import TabPane from '../src/TabPane';
import Tabs from '../src/Tabs';
import ValidComponentChildren from '../src/utils/ValidComponentChildren';
import { render } from './helpers';
describe('<Tabs>', () => {
it('Should show the correct tab', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Tabs id="test" defaultActiveKey={1}>
<Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab>
<Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab>
</Tabs>
);
const panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane);
assert.ok(ReactDOM.findDOMNode(panes[0]).className.match(/\bactive\b/));
assert.ok(!ReactDOM.findDOMNode(panes[1]).className.match(/\bactive\b/));
const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav);
assert.equal(nav.context.$bs_tabContainer.activeKey, 1);
});
it('Should only show the tabs with `Tab.props.title` set', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Tabs id="test" defaultActiveKey={3}>
<Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab>
<Tab eventKey={2}>Tab 2 content</Tab>
<Tab title="Tab 2" eventKey={3}>Tab 3 content</Tab>
</Tabs>
);
const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav);
assert.equal(ValidComponentChildren.count(nav.props.children), 2);
});
it('Should allow tab to have React components', () => {
const tabTitle = (
<strong className="special-tab">Tab 2</strong>
);
const instance = ReactTestUtils.renderIntoDocument(
<Tabs id="test" defaultActiveKey={2}>
<Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab>
<Tab title={tabTitle} eventKey={2}>Tab 2 content</Tab>
</Tabs>
);
const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(nav, 'special-tab'));
});
it('Should call onSelect when tab is selected', (done) => {
function onSelect(key) {
assert.equal(key, '2');
done();
}
const tab2 = <span className="tab2">Tab2</span>;
const instance = ReactTestUtils.renderIntoDocument(
<Tabs id="test" onSelect={onSelect} activeKey={1}>
<Tab title="Tab 1" eventKey="1">Tab 1 content</Tab>
<Tab title={tab2} eventKey="2">Tab 2 content</Tab>
</Tabs>
);
ReactTestUtils.Simulate.click(
ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'tab2')
);
});
it('Should have children with the correct DOM properties', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Tabs id="test" defaultActiveKey={1}>
<Tab title="Tab 1" className="custom" eventKey={1}>Tab 1 content</Tab>
<Tab title="Tab 2" tabClassName="tcustom" eventKey={2}>Tab 2 content</Tab>
</Tabs>
);
const panes = ReactTestUtils.scryRenderedComponentsWithType(instance, Tab);
const navs = ReactTestUtils.scryRenderedComponentsWithType(instance, NavItem);
assert.ok(ReactDOM.findDOMNode(panes[0]).className.match(/\bcustom\b/));
assert.ok(ReactDOM.findDOMNode(navs[1]).className.match(/\btcustom\b/));
assert.equal(ReactDOM.findDOMNode(panes[0]).id, 'test-pane-1');
});
it('Should show the correct first tab with no active key value', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Tabs id="test">
<Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab>
<Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab>
</Tabs>
);
const panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane);
assert.ok(ReactDOM.findDOMNode(panes[0]).className.match(/\bactive\b/));
assert.ok(!ReactDOM.findDOMNode(panes[1]).className.match(/\bactive\b/));
const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav);
assert.equal(nav.context.$bs_tabContainer.activeKey, 1);
});
it('Should show the correct first tab with children array', () => {
const panes = [0, 1].map(index => (
<Tab
key={index}
eventKey={index}
title={`Tab #${index}`}
>
<div>
content
</div>
</Tab>
));
let instance = ReactTestUtils.renderIntoDocument(
<Tabs id="test">
{panes}
{null}
</Tabs>
);
const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav);
assert.equal(nav.context.$bs_tabContainer.activeKey, 0);
});
it('Should show the correct tab when selected', () => {
const tab1 = <span className="tab1">Tab 1</span>;
const instance = ReactTestUtils.renderIntoDocument(
<Tabs id="test" defaultActiveKey={2} animation={false}>
<Tab title={tab1} eventKey={1}>Tab 1 content</Tab>
<Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab>
</Tabs>
);
const panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane);
ReactTestUtils.Simulate.click(
ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'tab1')
);
assert.ok(ReactDOM.findDOMNode(panes[0]).className.match(/\bactive\b/));
assert.ok(!ReactDOM.findDOMNode(panes[1]).className.match(/\bactive\b/));
const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav);
assert.equal(nav.context.$bs_tabContainer.activeKey, 1);
});
it('Should mount initial tab and no others when unmountOnExit is true and animation is false', () => {
const tab1 = <span className="tab1">Tab 1</span>;
const instance = ReactTestUtils.renderIntoDocument(
<Tabs id="test" defaultActiveKey={1} animation={false} unmountOnExit>
<Tab title={tab1} eventKey={1}>Tab 1 content</Tab>
<Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab>
<Tab title="Tab 3" eventKey={3}>Tab 3 content</Tab>
</Tabs>
);
const panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane);
expect(ReactDOM.findDOMNode(panes[0])).to.exist;
expect(ReactDOM.findDOMNode(panes[1])).to.not.exist;
expect(ReactDOM.findDOMNode(panes[2])).to.not.exist;
});
it('Should mount the correct tab when selected and unmount the previous when unmountOnExit is true and animation is false', () => {
const tab1 = <span className="tab1">Tab 1</span>;
const instance = ReactTestUtils.renderIntoDocument(
<Tabs id="test" defaultActiveKey={2} animation={false} unmountOnExit>
<Tab title={tab1} eventKey={1}>Tab 1 content</Tab>
<Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab>
</Tabs>
);
const panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane);
ReactTestUtils.Simulate.click(
ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'tab1')
);
expect(ReactDOM.findDOMNode(panes[0])).to.exist;
expect(ReactDOM.findDOMNode(panes[1])).to.not.exist;
const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav);
assert.equal(nav.context.$bs_tabContainer.activeKey, 1);
});
it('Should treat active key of null as nothing selected', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Tabs id="test" activeKey={null} onSelect={()=>{}}>
<Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab>
<Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab>
</Tabs>
);
const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav);
expect(nav.context.$bs_tabContainer.activeKey).to.not.exist;
});
it('Should pass default bsStyle (of "tabs") to Nav', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Tabs id="test" defaultActiveKey={1} animation={false}>
<Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab>
<Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab>
</Tabs>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'nav-tabs'));
});
it('Should pass bsStyle to Nav', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Tabs id="test" bsStyle="pills" defaultActiveKey={1} animation={false}>
<Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab>
<Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab>
</Tabs>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'nav-pills'));
});
it('Should pass disabled to Nav', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Tabs id="test" defaultActiveKey={1}>
<Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab>
<Tab title="Tab 2" eventKey={2} disabled>Tab 2 content</Tab>
</Tabs>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'disabled'));
});
it('Should not show content when clicking disabled tab', () => {
const tab1 = <span className="tab1">Tab 1</span>;
const instance = ReactTestUtils.renderIntoDocument(
<Tabs id="test" defaultActiveKey={2} animation={false}>
<Tab title={tab1} eventKey={1} disabled>Tab 1 content</Tab>
<Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab>
</Tabs>
);
const panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane);
ReactTestUtils.Simulate.click(
ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'tab1')
);
assert.ok(!ReactDOM.findDOMNode(panes[0]).className.match(/\bactive\b/));
assert.ok(ReactDOM.findDOMNode(panes[1]).className.match(/\bactive\b/));
const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav);
assert.equal(nav.context.$bs_tabContainer.activeKey, 2);
});
describe('active state invariants', () => {
let mountPoint;
beforeEach(() => {
mountPoint = document.createElement('div');
document.body.appendChild(mountPoint);
});
afterEach(() => {
ReactDOM.unmountComponentAtNode(mountPoint);
document.body.removeChild(mountPoint);
});
[true, false].forEach(animation => {
it(`should correctly set "active" after Tab is removed with "animation=${animation}"`, () => {
const instance = render(
<Tabs
id="test"
activeKey={2}
animation={animation}
onSelect={() => {}}
>
<Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab>
<Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab>
</Tabs>
, mountPoint);
const panes = ReactTestUtils.scryRenderedComponentsWithType(instance, TabPane);
assert.ok(!ReactDOM.findDOMNode(panes[0]).className.match(/\bactive\b/));
assert.ok(ReactDOM.findDOMNode(panes[1]).className.match(/\bactive\b/));
// second tab has been removed
render(
<Tabs
id="test"
activeKey={1}
animation={animation}
onSelect={() => {}}
>
<Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab>
</Tabs>
, mountPoint).refs.inner;
assert.ok(ReactDOM.findDOMNode(panes[0]).className.match(/\bactive\b/));
});
});
});
describe('Web Accessibility', () => {
let instance;
beforeEach(() => {
instance = ReactTestUtils.renderIntoDocument(
<Tabs defaultActiveKey={2} id="test">
<Tab title="Tab 1" eventKey={1}>Tab 1 content</Tab>
<Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab>
</Tabs>
);
});
it('Should generate ids from parent id', () => {
const tabs = ReactTestUtils.scryRenderedComponentsWithType(instance, NavItem);
tabs.every(tab =>
assert.ok(tab.props['aria-controls'] && tab.props.id));
});
it('Should add aria-labelledby', () => {
const panes = ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'tab-pane');
assert.equal(panes[0].getAttribute('aria-labelledby'), 'test-tab-1');
assert.equal(panes[1].getAttribute('aria-labelledby'), 'test-tab-2');
});
it('Should add aria-controls', () => {
const tabs = ReactTestUtils.scryRenderedComponentsWithType(instance, NavItem);
assert.equal(tabs[0].props['aria-controls'], 'test-pane-1');
assert.equal(tabs[1].props['aria-controls'], 'test-pane-2');
});
it('Should add role=tablist to the nav', () => {
const nav = ReactTestUtils.findRenderedComponentWithType(instance, Nav);
assert.equal(nav.props.role, 'tablist');
});
it('Should add aria-selected to the nav item for the selected tab', () => {
const tabs = ReactTestUtils.scryRenderedComponentsWithType(instance, NavItem);
const link1 = ReactTestUtils.findRenderedDOMComponentWithTag(tabs[0], 'a');
const link2 = ReactTestUtils.findRenderedDOMComponentWithTag(tabs[1], 'a');
assert.equal(link1.getAttribute('aria-selected'), 'false');
assert.equal(link2.getAttribute('aria-selected'), 'true');
});
});
it('Should not pass className to Nav', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Tabs id="test" bsStyle="pills" defaultActiveKey={1} animation={false}>
<Tab title="Tab 1" eventKey={1} className="my-tab-class">Tab 1 content</Tab>
<Tab title="Tab 2" eventKey={2}>Tab 2 content</Tab>
</Tabs>
);
const myTabClass = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'my-tab-class');
const myNavItem = ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'nav-pills')[0];
assert.notDeepEqual(myTabClass, myNavItem);
});
it('Should pass className, Id, and style to Tabs', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Tabs
bsStyle="pills"
defaultActiveKey={1}
animation={false}
className="my-tabs-class"
id="my-tabs-id"
style={{ opacity: 0.5 }}
/>
);
assert.equal(ReactDOM.findDOMNode(instance).getAttribute('class'), 'my-tabs-class');
assert.equal(ReactDOM.findDOMNode(instance).getAttribute('id'), 'my-tabs-id');
// Decimal point string depends on locale
assert.equal(parseFloat(ReactDOM.findDOMNode(instance).style.opacity), 0.5);
});
it('should derive bsClass from parent', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Tabs id="test" bsClass="my-tabs">
<Tab eventKey={1} title="Tab 1" />
<Tab eventKey={2} title="Tab 2" bsClass="my-pane" />
</Tabs>
);
assert.lengthOf(ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'my-tabs-pane'), 2);
assert.lengthOf(ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'my-pane'), 0);
});
});
|
'use strict';
const gulp = require('gulp');
const sequence = require('run-sequence');
gulp.task('start', cb => {
sequence('configure', 'build', 'install', cb);
});
|
semantic.dropdown = {};
// ready event
semantic.dropdown.ready = function() {
// selector cache
var
// alias
handler
;
// event handlers
handler = {
};
$('.first.example .menu .item')
.tab({
context: '.first.example'
})
;
$('.history.example .menu .item')
.tab({
context : '.history.example',
history : true,
path : '/modules/tab.html'
})
;
$('.dynamic.example .menu .item')
.tab({
context : '.dynamic.example',
auto : true,
path : '/modules/tab.html'
})
;
};
// attach ready event
$(document)
.ready(semantic.dropdown.ready)
; |
Subsets and Splits