code
stringlengths
2
1.05M
/*! UIkit 2.27.2 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */ !function(t){"use strict";function o(o,i){i=t.$.extend({duration:1e3,transition:"easeOutExpo",offset:0,complete:function(){}},i);var n=o.offset().top-i.offset,s=t.$doc.height(),e=window.innerHeight;n+e>s&&(n=s-e),t.$("html,body").stop().animate({scrollTop:n},i.duration,i.transition).promise().done(i.complete)}t.component("smoothScroll",{boot:function(){t.$html.on("click.smooth-scroll.uikit","[data-wk-smooth-scroll]",function(){var o=t.$(this);if(!o.data("smoothScroll")){{t.smoothScroll(o,t.Utils.options(o.attr("data-wk-smooth-scroll")))}o.trigger("click")}return!1})},init:function(){var i=this;this.on("click",function(n){n.preventDefault(),o(t.$(this.hash).length?t.$(this.hash):t.$("body"),i.options)})}}),t.Utils.scrollToElement=o,t.$.easing.easeOutExpo||(t.$.easing.easeOutExpo=function(t,o,i,n,s){return o==s?i+n:n*(-Math.pow(2,-10*o/s)+1)+i})}(UIkit2wk);
// Version: 3.7.13 var NOW = 1 , READY = false , READY_BUFFER = [] , PRESENCE_SUFFIX = '-pnpres' , DEF_WINDOWING = 10 // MILLISECONDS. , DEF_TIMEOUT = 10000 // MILLISECONDS. , DEF_SUB_TIMEOUT = 310 // SECONDS. , DEF_KEEPALIVE = 60 // SECONDS (FOR TIMESYNC). , SECOND = 1000 // A THOUSAND MILLISECONDS. , URLBIT = '/' , PARAMSBIT = '&' , PRESENCE_HB_THRESHOLD = 5 , PRESENCE_HB_DEFAULT = 30 , SDK_VER = '3.7.13' , REPL = /{([\w\-]+)}/g; /** * UTILITIES */ function unique() { return'x'+ ++NOW+''+(+new Date) } function rnow() { return+new Date } /** * NEXTORIGIN * ========== * var next_origin = nextorigin(); */ var nextorigin = (function() { var max = 20 , ori = Math.floor(Math.random() * max); return function( origin, failover ) { return origin.indexOf('pubsub.') > 0 && origin.replace( 'pubsub', 'ps' + ( failover ? generate_uuid().split('-')[0] : (++ori < max? ori : ori=1) ) ) || origin; } })(); /** * Build Url * ======= * */ function build_url( url_components, url_params ) { var url = url_components.join(URLBIT) , params = []; if (!url_params) return url; each( url_params, function( key, value ) { var value_str = (typeof value == 'object')?JSON['stringify'](value):value; (typeof value != 'undefined' && value != null && encode(value_str).length > 0 ) && params.push(key + "=" + encode(value_str)); } ); url += "?" + params.join(PARAMSBIT); return url; } /** * UPDATER * ======= * var timestamp = unique(); */ function updater( fun, rate ) { var timeout , last = 0 , runnit = function() { if (last + rate > rnow()) { clearTimeout(timeout); timeout = setTimeout( runnit, rate ); } else { last = rnow(); fun(); } }; return runnit; } /** * GREP * ==== * var list = grep( [1,2,3], function(item) { return item % 2 } ) */ function grep( list, fun ) { var fin = []; each( list || [], function(l) { fun(l) && fin.push(l) } ); return fin } /** * SUPPLANT * ======== * var text = supplant( 'Hello {name}!', { name : 'John' } ) */ function supplant( str, values ) { return str.replace( REPL, function( _, match ) { return values[match] || _ } ); } /** * timeout * ======= * timeout( function(){}, 100 ); */ function timeout( fun, wait ) { return setTimeout( fun, wait ); } /** * uuid * ==== * var my_uuid = generate_uuid(); */ function generate_uuid(callback) { var u = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); if (callback) callback(u); return u; } function isArray(arg) { return !!arg && typeof arg !== 'string' && (Array.isArray && Array.isArray(arg) || typeof(arg.length) === "number") //return !!arg && (Array.isArray && Array.isArray(arg) || typeof(arg.length) === "number") } /** * EACH * ==== * each( [1,2,3], function(item) { } ) */ function each( o, f) { if ( !o || !f ) return; if ( isArray(o) ) for ( var i = 0, l = o.length; i < l; ) f.call( o[i], o[i], i++ ); else for ( var i in o ) o.hasOwnProperty && o.hasOwnProperty(i) && f.call( o[i], i, o[i] ); } /** * MAP * === * var list = map( [1,2,3], function(item) { return item + 1 } ) */ function map( list, fun ) { var fin = []; each( list || [], function( k, v ) { fin.push(fun( k, v )) } ); return fin; } function pam_encode(str) { return encodeURIComponent(str).replace(/[!'()*~]/g, function(c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase(); }); } /** * ENCODE * ====== * var encoded_data = encode('path'); */ function encode(path) { return encodeURIComponent(path) } /** * Generate Subscription Channel List * ================================== * generate_channel_list(channels_object); */ function generate_channel_list(channels, nopresence) { var list = []; each( channels, function( channel, status ) { if (nopresence) { if(channel.search('-pnpres') < 0) { if (status.subscribed) list.push(channel); } } else { if (status.subscribed) list.push(channel); } }); return list.sort(); } /** * Generate Subscription Channel Groups List * ================================== * generate_channel_group_list(channels_groups object); */ function generate_channel_group_list(channel_groups, nopresence) { var list = []; each(channel_groups, function( channel_group, status ) { if (nopresence) { if(channel_group.search('-pnpres') < 0) { if (status.subscribed) list.push(channel_group); } } else { if (status.subscribed) list.push(channel_group); } }); return list.sort(); } // PUBNUB READY TO CONNECT function ready() { timeout( function() { if (READY) return; READY = 1; each( READY_BUFFER, function(connect) { connect() } ); }, SECOND ); } function PNmessage(args) { msg = args || {'apns' : {}}, msg['getPubnubMessage'] = function() { var m = {}; if (Object.keys(msg['apns']).length) { m['pn_apns'] = { 'aps' : { 'alert' : msg['apns']['alert'] , 'badge' : msg['apns']['badge'] } } for (var k in msg['apns']) { m['pn_apns'][k] = msg['apns'][k]; } var exclude1 = ['badge','alert']; for (var k in exclude1) { delete m['pn_apns'][exclude1[k]]; } } if (msg['gcm']) { m['pn_gcm'] = { 'data' : msg['gcm'] } } for (var k in msg) { m[k] = msg[k]; } var exclude = ['apns','gcm','publish', 'channel','callback','error']; for (var k in exclude) { delete m[exclude[k]]; } return m; }; msg['publish'] = function() { var m = msg.getPubnubMessage(); if (msg['pubnub'] && msg['channel']) { msg['pubnub'].publish({ 'message' : m, 'channel' : msg['channel'], 'callback' : msg['callback'], 'error' : msg['error'] }) } }; return msg; } function PN_API(setup) { var SUB_WINDOWING = +setup['windowing'] || DEF_WINDOWING , SUB_TIMEOUT = (+setup['timeout'] || DEF_SUB_TIMEOUT) * SECOND , KEEPALIVE = (+setup['keepalive'] || DEF_KEEPALIVE) * SECOND , TIME_CHECK = setup['timecheck'] || 0 , NOLEAVE = setup['noleave'] || 0 , PUBLISH_KEY = setup['publish_key'] || 'demo' , SUBSCRIBE_KEY = setup['subscribe_key'] || 'demo' , AUTH_KEY = setup['auth_key'] || '' , SECRET_KEY = setup['secret_key'] || '' , hmac_SHA256 = setup['hmac_SHA256'] , SSL = setup['ssl'] ? 's' : '' , ORIGIN = 'http'+SSL+'://'+(setup['origin']||'pubsub.pubnub.com') , STD_ORIGIN = nextorigin(ORIGIN) , SUB_ORIGIN = nextorigin(ORIGIN) , CONNECT = function(){} , PUB_QUEUE = [] , CLOAK = true , TIME_DRIFT = 0 , SUB_CALLBACK = 0 , SUB_CHANNEL = 0 , SUB_RECEIVER = 0 , SUB_RESTORE = setup['restore'] || 0 , SUB_BUFF_WAIT = 0 , TIMETOKEN = 0 , RESUMED = false , CHANNELS = {} , CHANNEL_GROUPS = {} , SUB_ERROR = function(){} , STATE = {} , PRESENCE_HB_TIMEOUT = null , PRESENCE_HB = validate_presence_heartbeat( setup['heartbeat'] || setup['pnexpires'] || 0, setup['error'] ) , PRESENCE_HB_INTERVAL = setup['heartbeat_interval'] || (PRESENCE_HB / 2) -1 , PRESENCE_HB_RUNNING = false , NO_WAIT_FOR_PENDING = setup['no_wait_for_pending'] , COMPATIBLE_35 = setup['compatible_3.5'] || false , xdr = setup['xdr'] , params = setup['params'] || {} , error = setup['error'] || function() {} , _is_online = setup['_is_online'] || function() { return 1 } , jsonp_cb = setup['jsonp_cb'] || function() { return 0 } , db = setup['db'] || {'get': function(){}, 'set': function(){}} , CIPHER_KEY = setup['cipher_key'] , UUID = setup['uuid'] || ( !setup['unique_uuid'] && db && db['get'](SUBSCRIBE_KEY+'uuid') || '') , USE_INSTANCEID = setup['instance_id'] || false , INSTANCEID = '' , _poll_timer , _poll_timer2; if (PRESENCE_HB === 2) PRESENCE_HB_INTERVAL = 1; var crypto_obj = setup['crypto_obj'] || { 'encrypt' : function(a,key){ return a}, 'decrypt' : function(b,key){return b} }; function _get_url_params(data) { if (!data) data = {}; each( params , function( key, value ) { if (!(key in data)) data[key] = value; }); return data; } function _object_to_key_list(o) { var l = [] each( o , function( key, value ) { l.push(key); }); return l; } function _object_to_key_list_sorted(o) { return _object_to_key_list(o).sort(); } function _get_pam_sign_input_from_params(params) { var si = ""; var l = _object_to_key_list_sorted(params); for (var i in l) { var k = l[i] si += k + "=" + pam_encode(params[k]) ; if (i != l.length - 1) si += "&" } return si; } function validate_presence_heartbeat(heartbeat, cur_heartbeat, error) { var err = false; if (typeof heartbeat === 'undefined') { return cur_heartbeat; } if (typeof heartbeat === 'number') { if (heartbeat > PRESENCE_HB_THRESHOLD || heartbeat == 0) err = false; else err = true; } else if(typeof heartbeat === 'boolean'){ if (!heartbeat) { return 0; } else { return PRESENCE_HB_DEFAULT; } } else { err = true; } if (err) { error && error("Presence Heartbeat value invalid. Valid range ( x > " + PRESENCE_HB_THRESHOLD + " or x = 0). Current Value : " + (cur_heartbeat || PRESENCE_HB_THRESHOLD)); return cur_heartbeat || PRESENCE_HB_THRESHOLD; } else return heartbeat; } function encrypt(input, key) { return crypto_obj['encrypt'](input, key || CIPHER_KEY) || input; } function decrypt(input, key) { return crypto_obj['decrypt'](input, key || CIPHER_KEY) || crypto_obj['decrypt'](input, CIPHER_KEY) || input; } function error_common(message, callback) { callback && callback({ 'error' : message || "error occurred"}); error && error(message); } function _presence_heartbeat() { clearTimeout(PRESENCE_HB_TIMEOUT); if (!PRESENCE_HB_INTERVAL || PRESENCE_HB_INTERVAL >= 500 || PRESENCE_HB_INTERVAL < 1 || (!generate_channel_list(CHANNELS,true).length && !generate_channel_group_list(CHANNEL_GROUPS, true).length ) ) { PRESENCE_HB_RUNNING = false; return; } PRESENCE_HB_RUNNING = true; SELF['presence_heartbeat']({ 'callback' : function(r) { PRESENCE_HB_TIMEOUT = timeout( _presence_heartbeat, (PRESENCE_HB_INTERVAL) * SECOND ); }, 'error' : function(e) { error && error("Presence Heartbeat unable to reach Pubnub servers." + JSON.stringify(e)); PRESENCE_HB_TIMEOUT = timeout( _presence_heartbeat, (PRESENCE_HB_INTERVAL) * SECOND ); } }); } function start_presence_heartbeat() { !PRESENCE_HB_RUNNING && _presence_heartbeat(); } function publish(next) { if (NO_WAIT_FOR_PENDING) { if (!PUB_QUEUE.length) return; } else { if (next) PUB_QUEUE.sending = 0; if ( PUB_QUEUE.sending || !PUB_QUEUE.length ) return; PUB_QUEUE.sending = 1; } xdr(PUB_QUEUE.shift()); } function each_channel_group(callback) { var count = 0; each( generate_channel_group_list(CHANNEL_GROUPS), function(channel_group) { var chang = CHANNEL_GROUPS[channel_group]; if (!chang) return; count++; (callback||function(){})(chang); } ); return count; } function each_channel(callback) { var count = 0; each( generate_channel_list(CHANNELS), function(channel) { var chan = CHANNELS[channel]; if (!chan) return; count++; (callback||function(){})(chan); } ); return count; } function _invoke_callback(response, callback, err) { if (typeof response == 'object') { if (response['error']) { var callback_data = {}; if (response['message']) { callback_data['message'] = response['message']; } if (response['payload']) { callback_data['payload'] = response['payload']; } err && err(callback_data); return; } if (response['payload']) { if (response['next_page']) callback && callback(response['payload'], response['next_page']); else callback && callback(response['payload']); return; } } callback && callback(response); } function _invoke_error(response,err) { if (typeof response == 'object' && response['error']) { var callback_data = {}; if (response['message']) { callback_data['message'] = response['message']; } if (response['payload']) { callback_data['payload'] = response['payload']; } err && err(callback_data); return; } else { err && err(response); } } function CR(args, callback, url1, data) { var callback = args['callback'] || callback , err = args['error'] || error , jsonp = jsonp_cb(); data = data || {}; if (!data['auth']) { data['auth'] = args['auth_key'] || AUTH_KEY; } var url = [ STD_ORIGIN, 'v1', 'channel-registration', 'sub-key', SUBSCRIBE_KEY ]; url.push.apply(url,url1); if (jsonp) data['callback'] = jsonp; xdr({ callback : jsonp, data : _get_url_params(data), success : function(response) { _invoke_callback(response, callback, err); }, fail : function(response) { _invoke_error(response, err); }, url : url }); } // Announce Leave Event var SELF = { 'LEAVE' : function( channel, blocking, auth_key, callback, error ) { var data = { 'uuid' : UUID, 'auth' : auth_key || AUTH_KEY } , origin = nextorigin(ORIGIN) , callback = callback || function(){} , err = error || function(){} , jsonp = jsonp_cb(); // Prevent Leaving a Presence Channel if (channel.indexOf(PRESENCE_SUFFIX) > 0) return true; if (COMPATIBLE_35) { if (!SSL) return false; if (jsonp == '0') return false; } if (NOLEAVE) return false; if (jsonp != '0') data['callback'] = jsonp; if (USE_INSTANCEID) data['instanceid'] = INSTANCEID; xdr({ blocking : blocking || SSL, timeout : 2000, callback : jsonp, data : _get_url_params(data), success : function(response) { _invoke_callback(response, callback, err); }, fail : function(response) { _invoke_error(response, err); }, url : [ origin, 'v2', 'presence', 'sub_key', SUBSCRIBE_KEY, 'channel', encode(channel), 'leave' ] }); return true; }, 'LEAVE_GROUP' : function( channel_group, blocking, auth_key, callback, error ) { var data = { 'uuid' : UUID, 'auth' : auth_key || AUTH_KEY } , origin = nextorigin(ORIGIN) , callback = callback || function(){} , err = error || function(){} , jsonp = jsonp_cb(); // Prevent Leaving a Presence Channel Group if (channel_group.indexOf(PRESENCE_SUFFIX) > 0) return true; if (COMPATIBLE_35) { if (!SSL) return false; if (jsonp == '0') return false; } if (NOLEAVE) return false; if (jsonp != '0') data['callback'] = jsonp; if (channel_group && channel_group.length > 0) data['channel-group'] = channel_group; if (USE_INSTANCEID) data['instanceid'] = INSTANCEID; xdr({ blocking : blocking || SSL, timeout : 5000, callback : jsonp, data : _get_url_params(data), success : function(response) { _invoke_callback(response, callback, err); }, fail : function(response) { _invoke_error(response, err); }, url : [ origin, 'v2', 'presence', 'sub_key', SUBSCRIBE_KEY, 'channel', encode(','), 'leave' ] }); return true; }, 'set_resumed' : function(resumed) { RESUMED = resumed; }, 'get_cipher_key' : function() { return CIPHER_KEY; }, 'set_cipher_key' : function(key) { CIPHER_KEY = key; }, 'raw_encrypt' : function(input, key) { return encrypt(input, key); }, 'raw_decrypt' : function(input, key) { return decrypt(input, key); }, 'get_heartbeat' : function() { return PRESENCE_HB; }, 'set_heartbeat' : function(heartbeat, heartbeat_interval) { PRESENCE_HB = validate_presence_heartbeat(heartbeat, PRESENCE_HB, error); PRESENCE_HB_INTERVAL = heartbeat_interval || (PRESENCE_HB / 2) - 1; if (PRESENCE_HB == 2) { PRESENCE_HB_INTERVAL = 1; } CONNECT(); _presence_heartbeat(); }, 'get_heartbeat_interval' : function() { return PRESENCE_HB_INTERVAL; }, 'set_heartbeat_interval' : function(heartbeat_interval) { PRESENCE_HB_INTERVAL = heartbeat_interval; _presence_heartbeat(); }, 'get_version' : function() { return SDK_VER; }, 'getGcmMessageObject' : function(obj) { return { 'data' : obj } }, 'getApnsMessageObject' : function(obj) { var x = { 'aps' : { 'badge' : 1, 'alert' : ''} } for (k in obj) { k[x] = obj[k]; } return x; }, 'newPnMessage' : function() { var x = {}; if (gcm) x['pn_gcm'] = gcm; if (apns) x['pn_apns'] = apns; for ( k in n ) { x[k] = n[k]; } return x; }, '_add_param' : function(key,val) { params[key] = val; }, 'channel_group' : function(args, callback) { var ns_ch = args['channel_group'] , callback = callback || args['callback'] , channels = args['channels'] || args['channel'] , cloak = args['cloak'] , namespace , channel_group , url = [] , data = {} , mode = args['mode'] || 'add'; if (ns_ch) { var ns_ch_a = ns_ch.split(':'); if (ns_ch_a.length > 1) { namespace = (ns_ch_a[0] === '*')?null:ns_ch_a[0]; channel_group = ns_ch_a[1]; } else { channel_group = ns_ch_a[0]; } } namespace && url.push('namespace') && url.push(encode(namespace)); url.push('channel-group'); if (channel_group && channel_group !== '*') { url.push(channel_group); } if (channels ) { if (isArray(channels)) { channels = channels.join(','); } data[mode] = channels; data['cloak'] = (CLOAK)?'true':'false'; } else { if (mode === 'remove') url.push('remove'); } if (typeof cloak != 'undefined') data['cloak'] = (cloak)?'true':'false'; CR(args, callback, url, data); }, 'channel_group_list_groups' : function(args, callback) { var namespace; namespace = args['namespace'] || args['ns'] || args['channel_group'] || null; if (namespace) { args["channel_group"] = namespace + ":*"; } SELF['channel_group'](args, callback); }, 'channel_group_list_channels' : function(args, callback) { if (!args['channel_group']) return error('Missing Channel Group'); SELF['channel_group'](args, callback); }, 'channel_group_remove_channel' : function(args, callback) { if (!args['channel_group']) return error('Missing Channel Group'); if (!args['channel'] && !args['channels'] ) return error('Missing Channel'); args['mode'] = 'remove'; SELF['channel_group'](args,callback); }, 'channel_group_remove_group' : function(args, callback) { if (!args['channel_group']) return error('Missing Channel Group'); if (args['channel']) return error('Use channel_group_remove_channel if you want to remove a channel from a group.'); args['mode'] = 'remove'; SELF['channel_group'](args,callback); }, 'channel_group_add_channel' : function(args, callback) { if (!args['channel_group']) return error('Missing Channel Group'); if (!args['channel'] && !args['channels'] ) return error('Missing Channel'); SELF['channel_group'](args,callback); }, 'channel_group_cloak' : function(args, callback) { if (typeof args['cloak'] == 'undefined') { callback(CLOAK); return; } CLOAK = args['cloak']; SELF['channel_group'](args,callback); }, 'channel_group_list_namespaces' : function(args, callback) { var url = ['namespace']; CR(args, callback, url); }, 'channel_group_remove_namespace' : function(args, callback) { var url = ['namespace',args['namespace'],'remove']; CR(args, callback, url); }, /* PUBNUB.history({ channel : 'my_chat_channel', limit : 100, callback : function(history) { } }); */ 'history' : function( args, callback ) { var callback = args['callback'] || callback , count = args['count'] || args['limit'] || 100 , reverse = args['reverse'] || "false" , err = args['error'] || function(){} , auth_key = args['auth_key'] || AUTH_KEY , cipher_key = args['cipher_key'] , channel = args['channel'] , channel_group = args['channel_group'] , start = args['start'] , end = args['end'] , include_token = args['include_token'] , params = {} , jsonp = jsonp_cb(); // Make sure we have a Channel if (!channel && !channel_group) return error('Missing Channel'); if (!callback) return error('Missing Callback'); if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key'); params['stringtoken'] = 'true'; params['count'] = count; params['reverse'] = reverse; params['auth'] = auth_key; if (channel_group) { params['channel-group'] = channel_group; if (!channel) { channel = ','; } } if (jsonp) params['callback'] = jsonp; if (start) params['start'] = start; if (end) params['end'] = end; if (include_token) params['include_token'] = 'true'; // Send Message xdr({ callback : jsonp, data : _get_url_params(params), success : function(response) { if (typeof response == 'object' && response['error']) { err({'message' : response['message'], 'payload' : response['payload']}); return; } var messages = response[0]; var decrypted_messages = []; for (var a = 0; a < messages.length; a++) { var new_message = decrypt(messages[a],cipher_key); try { decrypted_messages['push'](JSON['parse'](new_message)); } catch (e) { decrypted_messages['push']((new_message)); } } callback([decrypted_messages, response[1], response[2]]); }, fail : function(response) { _invoke_error(response, err); }, url : [ STD_ORIGIN, 'v2', 'history', 'sub-key', SUBSCRIBE_KEY, 'channel', encode(channel) ] }); }, /* PUBNUB.replay({ source : 'my_channel', destination : 'new_channel' }); */ 'replay' : function(args, callback) { var callback = callback || args['callback'] || function(){} , auth_key = args['auth_key'] || AUTH_KEY , source = args['source'] , destination = args['destination'] , stop = args['stop'] , start = args['start'] , end = args['end'] , reverse = args['reverse'] , limit = args['limit'] , jsonp = jsonp_cb() , data = {} , url; // Check User Input if (!source) return error('Missing Source Channel'); if (!destination) return error('Missing Destination Channel'); if (!PUBLISH_KEY) return error('Missing Publish Key'); if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key'); // Setup URL Params if (jsonp != '0') data['callback'] = jsonp; if (stop) data['stop'] = 'all'; if (reverse) data['reverse'] = 'true'; if (start) data['start'] = start; if (end) data['end'] = end; if (limit) data['count'] = limit; data['auth'] = auth_key; // Compose URL Parts url = [ STD_ORIGIN, 'v1', 'replay', PUBLISH_KEY, SUBSCRIBE_KEY, source, destination ]; // Start (or Stop) Replay! xdr({ callback : jsonp, success : function(response) { _invoke_callback(response, callback, err); }, fail : function() { callback([ 0, 'Disconnected' ]) }, url : url, data : _get_url_params(data) }); }, /* PUBNUB.auth('AJFLKAJSDKLA'); */ 'auth' : function(auth) { AUTH_KEY = auth; CONNECT(); }, /* PUBNUB.time(function(time){ }); */ 'time' : function(callback) { var jsonp = jsonp_cb(); var data = { 'uuid' : UUID, 'auth' : AUTH_KEY } if (USE_INSTANCEID) data['instanceid'] = INSTANCEID; xdr({ callback : jsonp, data : _get_url_params(data), timeout : SECOND * 5, url : [STD_ORIGIN, 'time', jsonp], success : function(response) { callback(response[0]) }, fail : function() { callback(0) } }); }, /* PUBNUB.publish({ channel : 'my_chat_channel', message : 'hello!' }); */ 'publish' : function( args, callback ) { var msg = args['message']; if (!msg) return error('Missing Message'); var callback = callback || args['callback'] || msg['callback'] || function(){} , channel = args['channel'] || msg['channel'] , auth_key = args['auth_key'] || AUTH_KEY , cipher_key = args['cipher_key'] , err = args['error'] || msg['error'] || function() {} , post = args['post'] || false , store = ('store_in_history' in args) ? args['store_in_history']: true , jsonp = jsonp_cb() , add_msg = 'push' , params , url; if (args['prepend']) add_msg = 'unshift' if (!channel) return error('Missing Channel'); if (!PUBLISH_KEY) return error('Missing Publish Key'); if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key'); if (msg['getPubnubMessage']) { msg = msg['getPubnubMessage'](); } // If trying to send Object msg = JSON['stringify'](encrypt(msg, cipher_key)); // Create URL url = [ STD_ORIGIN, 'publish', PUBLISH_KEY, SUBSCRIBE_KEY, 0, encode(channel), jsonp, encode(msg) ]; params = { 'uuid' : UUID, 'auth' : auth_key } if (!store) params['store'] ="0" if (USE_INSTANCEID) params['instanceid'] = INSTANCEID; // Queue Message Send PUB_QUEUE[add_msg]({ callback : jsonp, timeout : SECOND * 5, url : url, data : _get_url_params(params), fail : function(response){ _invoke_error(response, err); publish(1); }, success : function(response) { _invoke_callback(response, callback, err); publish(1); }, mode : (post)?'POST':'GET' }); // Send Message publish(); }, /* PUBNUB.unsubscribe({ channel : 'my_chat' }); */ 'unsubscribe' : function(args, callback) { var channel = args['channel'] , channel_group = args['channel_group'] , auth_key = args['auth_key'] || AUTH_KEY , callback = callback || args['callback'] || function(){} , err = args['error'] || function(){}; TIMETOKEN = 0; //SUB_RESTORE = 1; REVISIT !!!! if (channel) { // Prepare Channel(s) channel = map( ( channel.join ? channel.join(',') : ''+channel ).split(','), function(channel) { if (!CHANNELS[channel]) return; return channel + ',' + channel + PRESENCE_SUFFIX; } ).join(','); // Iterate over Channels each( channel.split(','), function(ch) { var CB_CALLED = true; if (!ch) return; CHANNELS[ch] = 0; if (ch in STATE) delete STATE[ch]; if (READY) { CB_CALLED = SELF['LEAVE']( ch, 0 , auth_key, callback, err); } if (!CB_CALLED) callback({action : "leave"}); } ); } if (channel_group) { // Prepare channel group(s) channel_group = map( ( channel_group.join ? channel_group.join(',') : ''+channel_group ).split(','), function(channel_group) { if (!CHANNEL_GROUPS[channel_group]) return; return channel_group + ',' + channel_group + PRESENCE_SUFFIX; } ).join(','); // Iterate over channel groups each( channel_group.split(','), function(chg) { var CB_CALLED = true; if (!chg) return; CHANNEL_GROUPS[chg] = 0; if (chg in STATE) delete STATE[chg]; if (READY) { CB_CALLED = SELF['LEAVE_GROUP']( chg, 0 , auth_key, callback, err); } if (!CB_CALLED) callback({action : "leave"}); } ); } // Reset Connection if Count Less CONNECT(); }, /* PUBNUB.subscribe({ channel : 'my_chat' callback : function(message) { } }); */ 'subscribe' : function( args, callback ) { var channel = args['channel'] , channel_group = args['channel_group'] , callback = callback || args['callback'] , callback = callback || args['message'] , connect = args['connect'] || function(){} , reconnect = args['reconnect'] || function(){} , disconnect = args['disconnect'] || function(){} , SUB_ERROR = args['error'] || SUB_ERROR || function(){} , idlecb = args['idle'] || function(){} , presence = args['presence'] || 0 , noheresync = args['noheresync'] || 0 , backfill = args['backfill'] || 0 , timetoken = args['timetoken'] || 0 , sub_timeout = args['timeout'] || SUB_TIMEOUT , windowing = args['windowing'] || SUB_WINDOWING , state = args['state'] , heartbeat = args['heartbeat'] || args['pnexpires'] , heartbeat_interval = args['heartbeat_interval'] , restore = args['restore'] || SUB_RESTORE; AUTH_KEY = args['auth_key'] || AUTH_KEY; // Restore Enabled? SUB_RESTORE = restore; // Always Reset the TT TIMETOKEN = timetoken; // Make sure we have a Channel if (!channel && !channel_group) { return error('Missing Channel'); } if (!callback) return error('Missing Callback'); if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key'); if (heartbeat || heartbeat === 0 || heartbeat_interval || heartbeat_interval === 0) { SELF['set_heartbeat'](heartbeat, heartbeat_interval); } // Setup Channel(s) if (channel) { each( (channel.join ? channel.join(',') : ''+channel).split(','), function(channel) { var settings = CHANNELS[channel] || {}; // Store Channel State CHANNELS[SUB_CHANNEL = channel] = { name : channel, connected : settings.connected, disconnected : settings.disconnected, subscribed : 1, callback : SUB_CALLBACK = callback, 'cipher_key' : args['cipher_key'], connect : connect, disconnect : disconnect, reconnect : reconnect }; if (state) { if (channel in state) { STATE[channel] = state[channel]; } else { STATE[channel] = state; } } // Presence Enabled? if (!presence) return; // Subscribe Presence Channel SELF['subscribe']({ 'channel' : channel + PRESENCE_SUFFIX, 'callback' : presence, 'restore' : restore }); // Presence Subscribed? if (settings.subscribed) return; // See Who's Here Now? if (noheresync) return; SELF['here_now']({ 'channel' : channel, 'data' : _get_url_params({ 'uuid' : UUID, 'auth' : AUTH_KEY }), 'callback' : function(here) { each( 'uuids' in here ? here['uuids'] : [], function(uid) { presence( { 'action' : 'join', 'uuid' : uid, 'timestamp' : Math.floor(rnow() / 1000), 'occupancy' : here['occupancy'] || 1 }, here, channel ); } ); } }); } ); } // Setup Channel Groups if (channel_group) { each( (channel_group.join ? channel_group.join(',') : ''+channel_group).split(','), function(channel_group) { var settings = CHANNEL_GROUPS[channel_group] || {}; CHANNEL_GROUPS[channel_group] = { name : channel_group, connected : settings.connected, disconnected : settings.disconnected, subscribed : 1, callback : SUB_CALLBACK = callback, 'cipher_key' : args['cipher_key'], connect : connect, disconnect : disconnect, reconnect : reconnect }; // Presence Enabled? if (!presence) return; // Subscribe Presence Channel SELF['subscribe']({ 'channel_group' : channel_group + PRESENCE_SUFFIX, 'callback' : presence, 'restore' : restore, 'auth_key' : AUTH_KEY }); // Presence Subscribed? if (settings.subscribed) return; // See Who's Here Now? if (noheresync) return; SELF['here_now']({ 'channel_group' : channel_group, 'data' : _get_url_params({ 'uuid' : UUID, 'auth' : AUTH_KEY }), 'callback' : function(here) { each( 'uuids' in here ? here['uuids'] : [], function(uid) { presence( { 'action' : 'join', 'uuid' : uid, 'timestamp' : Math.floor(rnow() / 1000), 'occupancy' : here['occupancy'] || 1 }, here, channel_group ); } ); } }); } ); } // Test Network Connection function _test_connection(success) { if (success) { // Begin Next Socket Connection timeout( CONNECT, windowing); } else { // New Origin on Failed Connection STD_ORIGIN = nextorigin( ORIGIN, 1 ); SUB_ORIGIN = nextorigin( ORIGIN, 1 ); // Re-test Connection timeout( function() { SELF['time'](_test_connection); }, SECOND ); } // Disconnect & Reconnect each_channel(function(channel){ // Reconnect if (success && channel.disconnected) { channel.disconnected = 0; return channel.reconnect(channel.name); } // Disconnect if (!success && !channel.disconnected) { channel.disconnected = 1; channel.disconnect(channel.name); } }); // Disconnect & Reconnect for channel groups each_channel_group(function(channel_group){ // Reconnect if (success && channel_group.disconnected) { channel_group.disconnected = 0; return channel_group.reconnect(channel_group.name); } // Disconnect if (!success && !channel_group.disconnected) { channel_group.disconnected = 1; channel_group.disconnect(channel_group.name); } }); } // Evented Subscribe function _connect() { var jsonp = jsonp_cb() , channels = generate_channel_list(CHANNELS).join(',') , channel_groups = generate_channel_group_list(CHANNEL_GROUPS).join(','); // Stop Connection if (!channels && !channel_groups) return; if (!channels) channels = ','; // Connect to PubNub Subscribe Servers _reset_offline(); var data = _get_url_params({ 'uuid' : UUID, 'auth' : AUTH_KEY }); if (channel_groups) { data['channel-group'] = channel_groups; } var st = JSON.stringify(STATE); if (st.length > 2) data['state'] = JSON.stringify(STATE); if (PRESENCE_HB) data['heartbeat'] = PRESENCE_HB; if (USE_INSTANCEID) data['instanceid'] = INSTANCEID; start_presence_heartbeat(); SUB_RECEIVER = xdr({ timeout : sub_timeout, callback : jsonp, fail : function(response) { if (response && response['error'] && response['service']) { _invoke_error(response, SUB_ERROR); _test_connection(1); } else { SELF['time'](function(success){ !success && ( _invoke_error(response, SUB_ERROR)); _test_connection(success); }); } }, data : _get_url_params(data), url : [ SUB_ORIGIN, 'subscribe', SUBSCRIBE_KEY, encode(channels), jsonp, TIMETOKEN ], success : function(messages) { // Check for Errors if (!messages || ( typeof messages == 'object' && 'error' in messages && messages['error'] )) { SUB_ERROR(messages['error']); return timeout( CONNECT, SECOND ); } // User Idle Callback idlecb(messages[1]); // Restore Previous Connection Point if Needed TIMETOKEN = !TIMETOKEN && SUB_RESTORE && db['get'](SUBSCRIBE_KEY) || messages[1]; /* // Connect each_channel_registry(function(registry){ if (registry.connected) return; registry.connected = 1; registry.connect(channel.name); }); */ // Connect each_channel(function(channel){ if (channel.connected) return; channel.connected = 1; channel.connect(channel.name); }); // Connect for channel groups each_channel_group(function(channel_group){ if (channel_group.connected) return; channel_group.connected = 1; channel_group.connect(channel_group.name); }); if (RESUMED && !SUB_RESTORE) { TIMETOKEN = 0; RESUMED = false; // Update Saved Timetoken db['set']( SUBSCRIBE_KEY, 0 ); timeout( _connect, windowing ); return; } // Invoke Memory Catchup and Receive Up to 100 // Previous Messages from the Queue. if (backfill) { TIMETOKEN = 10000; backfill = 0; } // Update Saved Timetoken db['set']( SUBSCRIBE_KEY, messages[1] ); // Route Channel <---> Callback for Message var next_callback = (function() { var channels = ''; var channels2 = ''; if (messages.length > 3) { channels = messages[3]; channels2 = messages[2]; } else if (messages.length > 2) { channels = messages[2]; } else { channels = map( generate_channel_list(CHANNELS), function(chan) { return map( Array(messages[0].length) .join(',').split(','), function() { return chan; } ) }).join(',') } var list = channels.split(','); var list2 = (channels2)?channels2.split(','):[]; return function() { var channel = list.shift()||SUB_CHANNEL; var channel2 = list2.shift(); var chobj = {}; if (channel2) { if (channel && channel.indexOf('-pnpres') >= 0 && channel2.indexOf('-pnpres') < 0) { channel2 += '-pnpres'; } chobj = CHANNEL_GROUPS[channel2] || CHANNELS[channel2] || {'callback' : function(){}}; } else { chobj = CHANNELS[channel]; } var r = [ chobj .callback||SUB_CALLBACK, channel.split(PRESENCE_SUFFIX)[0] ]; channel2 && r.push(channel2.split(PRESENCE_SUFFIX)[0]); return r; }; })(); var latency = detect_latency(+messages[1]); each( messages[0], function(msg) { var next = next_callback(); var decrypted_msg = decrypt(msg, (CHANNELS[next[1]])?CHANNELS[next[1]]['cipher_key']:null); next[0] && next[0]( decrypted_msg, messages, next[2] || next[1], latency, next[1]); }); timeout( _connect, windowing ); } }); } CONNECT = function() { _reset_offline(); timeout( _connect, windowing ); }; // Reduce Status Flicker if (!READY) return READY_BUFFER.push(CONNECT); // Connect Now CONNECT(); }, /* PUBNUB.here_now({ channel : 'my_chat', callback : fun }); */ 'here_now' : function( args, callback ) { var callback = args['callback'] || callback , err = args['error'] || function(){} , auth_key = args['auth_key'] || AUTH_KEY , channel = args['channel'] , channel_group = args['channel_group'] , jsonp = jsonp_cb() , uuids = ('uuids' in args) ? args['uuids'] : true , state = args['state'] , data = { 'uuid' : UUID, 'auth' : auth_key }; if (!uuids) data['disable_uuids'] = 1; if (state) data['state'] = 1; // Make sure we have a Channel if (!callback) return error('Missing Callback'); if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key'); var url = [ STD_ORIGIN, 'v2', 'presence', 'sub_key', SUBSCRIBE_KEY ]; channel && url.push('channel') && url.push(encode(channel)); if (jsonp != '0') { data['callback'] = jsonp; } if (channel_group) { data['channel-group'] = channel_group; !channel && url.push('channel') && url.push(','); } if (USE_INSTANCEID) data['instanceid'] = INSTANCEID; xdr({ callback : jsonp, data : _get_url_params(data), success : function(response) { _invoke_callback(response, callback, err); }, fail : function(response) { _invoke_error(response, err); }, url : url }); }, /* PUBNUB.current_channels_by_uuid({ channel : 'my_chat', callback : fun }); */ 'where_now' : function( args, callback ) { var callback = args['callback'] || callback , err = args['error'] || function(){} , auth_key = args['auth_key'] || AUTH_KEY , jsonp = jsonp_cb() , uuid = args['uuid'] || UUID , data = { 'auth' : auth_key }; // Make sure we have a Channel if (!callback) return error('Missing Callback'); if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key'); if (jsonp != '0') { data['callback'] = jsonp; } if (USE_INSTANCEID) data['instanceid'] = INSTANCEID; xdr({ callback : jsonp, data : _get_url_params(data), success : function(response) { _invoke_callback(response, callback, err); }, fail : function(response) { _invoke_error(response, err); }, url : [ STD_ORIGIN, 'v2', 'presence', 'sub_key', SUBSCRIBE_KEY, 'uuid', encode(uuid) ] }); }, 'state' : function(args, callback) { var callback = args['callback'] || callback || function(r) {} , err = args['error'] || function(){} , auth_key = args['auth_key'] || AUTH_KEY , jsonp = jsonp_cb() , state = args['state'] , uuid = args['uuid'] || UUID , channel = args['channel'] , channel_group = args['channel_group'] , url , data = _get_url_params({ 'auth' : auth_key }); // Make sure we have a Channel if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key'); if (!uuid) return error('Missing UUID'); if (!channel && !channel_group) return error('Missing Channel'); if (jsonp != '0') { data['callback'] = jsonp; } if (typeof channel != 'undefined' && CHANNELS[channel] && CHANNELS[channel].subscribed ) { if (state) STATE[channel] = state; } if (typeof channel_group != 'undefined' && CHANNEL_GROUPS[channel_group] && CHANNEL_GROUPS[channel_group].subscribed ) { if (state) STATE[channel_group] = state; data['channel-group'] = channel_group; if (!channel) { channel = ','; } } data['state'] = JSON.stringify(state); if (USE_INSTANCEID) data['instanceid'] = INSTANCEID; if (state) { url = [ STD_ORIGIN, 'v2', 'presence', 'sub-key', SUBSCRIBE_KEY, 'channel', channel, 'uuid', uuid, 'data' ] } else { url = [ STD_ORIGIN, 'v2', 'presence', 'sub-key', SUBSCRIBE_KEY, 'channel', channel, 'uuid', encode(uuid) ] } xdr({ callback : jsonp, data : _get_url_params(data), success : function(response) { _invoke_callback(response, callback, err); }, fail : function(response) { _invoke_error(response, err); }, url : url }); }, /* PUBNUB.grant({ channel : 'my_chat', callback : fun, error : fun, ttl : 24 * 60, // Minutes read : true, write : true, auth_key : '3y8uiajdklytowsj' }); */ 'grant' : function( args, callback ) { var callback = args['callback'] || callback , err = args['error'] || function(){} , channel = args['channel'] || args['channels'] , channel_group = args['channel_group'] , jsonp = jsonp_cb() , ttl = args['ttl'] , r = (args['read'] )?"1":"0" , w = (args['write'])?"1":"0" , m = (args['manage'])?"1":"0" , auth_key = args['auth_key'] || args['auth_keys']; if (!callback) return error('Missing Callback'); if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key'); if (!PUBLISH_KEY) return error('Missing Publish Key'); if (!SECRET_KEY) return error('Missing Secret Key'); var timestamp = Math.floor(new Date().getTime() / 1000) , sign_input = SUBSCRIBE_KEY + "\n" + PUBLISH_KEY + "\n" + "grant" + "\n"; var data = { 'w' : w, 'r' : r, 'timestamp' : timestamp }; if (args['manage']) { data['m'] = m; } if (isArray(channel)) { channel = channel['join'](','); } if (isArray(auth_key)) { auth_key = auth_key['join'](','); } if (typeof channel != 'undefined' && channel != null && channel.length > 0) data['channel'] = channel; if (typeof channel_group != 'undefined' && channel_group != null && channel_group.length > 0) { data['channel-group'] = channel_group; } if (jsonp != '0') { data['callback'] = jsonp; } if (ttl || ttl === 0) data['ttl'] = ttl; if (auth_key) data['auth'] = auth_key; data = _get_url_params(data) if (!auth_key) delete data['auth']; sign_input += _get_pam_sign_input_from_params(data); var signature = hmac_SHA256( sign_input, SECRET_KEY ); signature = signature.replace( /\+/g, "-" ); signature = signature.replace( /\//g, "_" ); data['signature'] = signature; xdr({ callback : jsonp, data : data, success : function(response) { _invoke_callback(response, callback, err); }, fail : function(response) { _invoke_error(response, err); }, url : [ STD_ORIGIN, 'v1', 'auth', 'grant' , 'sub-key', SUBSCRIBE_KEY ] }); }, /* PUBNUB.mobile_gw_provision ({ device_id: 'A655FBA9931AB', op : 'add' | 'remove', gw_type : 'apns' | 'gcm', channel : 'my_chat', callback : fun, error : fun, }); */ 'mobile_gw_provision' : function( args ) { var callback = args['callback'] || function(){} , auth_key = args['auth_key'] || AUTH_KEY , err = args['error'] || function() {} , jsonp = jsonp_cb() , channel = args['channel'] , op = args['op'] , gw_type = args['gw_type'] , device_id = args['device_id'] , params , url; if (!device_id) return error('Missing Device ID (device_id)'); if (!gw_type) return error('Missing GW Type (gw_type: gcm or apns)'); if (!op) return error('Missing GW Operation (op: add or remove)'); if (!channel) return error('Missing gw destination Channel (channel)'); if (!PUBLISH_KEY) return error('Missing Publish Key'); if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key'); // Create URL url = [ STD_ORIGIN, 'v1/push/sub-key', SUBSCRIBE_KEY, 'devices', device_id ]; params = { 'uuid' : UUID, 'auth' : auth_key, 'type': gw_type}; if (op == "add") { params['add'] = channel; } else if (op == "remove") { params['remove'] = channel; } if (USE_INSTANCEID) data['instanceid'] = INSTANCEID; xdr({ callback : jsonp, data : params, success : function(response) { _invoke_callback(response, callback, err); }, fail : function(response) { _invoke_error(response, err); }, url : url }); }, /* PUBNUB.audit({ channel : 'my_chat', callback : fun, error : fun, read : true, write : true, auth_key : '3y8uiajdklytowsj' }); */ 'audit' : function( args, callback ) { var callback = args['callback'] || callback , err = args['error'] || function(){} , channel = args['channel'] , channel_group = args['channel_group'] , auth_key = args['auth_key'] , jsonp = jsonp_cb(); // Make sure we have a Channel if (!callback) return error('Missing Callback'); if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key'); if (!PUBLISH_KEY) return error('Missing Publish Key'); if (!SECRET_KEY) return error('Missing Secret Key'); var timestamp = Math.floor(new Date().getTime() / 1000) , sign_input = SUBSCRIBE_KEY + "\n" + PUBLISH_KEY + "\n" + "audit" + "\n"; var data = {'timestamp' : timestamp }; if (jsonp != '0') { data['callback'] = jsonp; } if (typeof channel != 'undefined' && channel != null && channel.length > 0) data['channel'] = channel; if (typeof channel_group != 'undefined' && channel_group != null && channel_group.length > 0) { data['channel-group'] = channel_group; } if (auth_key) data['auth'] = auth_key; data = _get_url_params(data); if (!auth_key) delete data['auth']; sign_input += _get_pam_sign_input_from_params(data); var signature = hmac_SHA256( sign_input, SECRET_KEY ); signature = signature.replace( /\+/g, "-" ); signature = signature.replace( /\//g, "_" ); data['signature'] = signature; xdr({ callback : jsonp, data : data, success : function(response) { _invoke_callback(response, callback, err); }, fail : function(response) { _invoke_error(response, err); }, url : [ STD_ORIGIN, 'v1', 'auth', 'audit' , 'sub-key', SUBSCRIBE_KEY ] }); }, /* PUBNUB.revoke({ channel : 'my_chat', callback : fun, error : fun, auth_key : '3y8uiajdklytowsj' }); */ 'revoke' : function( args, callback ) { args['read'] = false; args['write'] = false; SELF['grant']( args, callback ); }, 'set_uuid' : function(uuid) { UUID = uuid; CONNECT(); }, 'get_uuid' : function() { return UUID; }, 'isArray' : function(arg) { return isArray(arg); }, 'get_subscibed_channels' : function() { return generate_channel_list(CHANNELS, true); }, 'presence_heartbeat' : function(args) { var callback = args['callback'] || function() {} var err = args['error'] || function() {} var jsonp = jsonp_cb(); var data = { 'uuid' : UUID, 'auth' : AUTH_KEY }; var st = JSON['stringify'](STATE); if (st.length > 2) data['state'] = JSON['stringify'](STATE); if (PRESENCE_HB > 0 && PRESENCE_HB < 320) data['heartbeat'] = PRESENCE_HB; if (jsonp != '0') { data['callback'] = jsonp; } var channels = encode(generate_channel_list(CHANNELS, true)['join'](',')); var channel_groups = generate_channel_group_list(CHANNEL_GROUPS, true)['join'](','); if (!channels) channels = ','; if (channel_groups) data['channel-group'] = channel_groups; if (USE_INSTANCEID) data['instanceid'] = INSTANCEID; xdr({ callback : jsonp, data : _get_url_params(data), timeout : SECOND * 5, url : [ STD_ORIGIN, 'v2', 'presence', 'sub-key', SUBSCRIBE_KEY, 'channel' , channels, 'heartbeat' ], success : function(response) { _invoke_callback(response, callback, err); }, fail : function(response) { _invoke_error(response, err); } }); }, 'stop_timers': function () { clearTimeout(_poll_timer); clearTimeout(_poll_timer2); }, // Expose PUBNUB Functions 'xdr' : xdr, 'ready' : ready, 'db' : db, 'uuid' : generate_uuid, 'map' : map, 'each' : each, 'each-channel' : each_channel, 'grep' : grep, 'offline' : function(){ _reset_offline( 1, { "message" : "Offline. Please check your network settings." }) }, 'supplant' : supplant, 'now' : rnow, 'unique' : unique, 'updater' : updater }; function _poll_online() { _is_online() || _reset_offline( 1, { "error" : "Offline. Please check your network settings. " }); _poll_timer && clearTimeout(_poll_timer); _poll_timer = timeout( _poll_online, SECOND ); } function _poll_online2() { if (!TIME_CHECK) return; SELF['time'](function(success){ detect_time_detla( function(){}, success ); success || _reset_offline( 1, { "error" : "Heartbeat failed to connect to Pubnub Servers." + "Please check your network settings." }); _poll_timer2 && clearTimeout(_poll_timer2); _poll_timer2 = timeout( _poll_online2, KEEPALIVE ); }); } function _reset_offline(err, msg) { SUB_RECEIVER && SUB_RECEIVER(err, msg); SUB_RECEIVER = null; clearTimeout(_poll_timer); clearTimeout(_poll_timer2); } if (!UUID) UUID = SELF['uuid'](); if (!INSTANCEID) INSTANCEID = SELF['uuid'](); db['set']( SUBSCRIBE_KEY + 'uuid', UUID ); _poll_timer = timeout( _poll_online, SECOND ); _poll_timer2 = timeout( _poll_online2, KEEPALIVE ); PRESENCE_HB_TIMEOUT = timeout( start_presence_heartbeat, ( PRESENCE_HB_INTERVAL - 3 ) * SECOND ); // Detect Age of Message function detect_latency(tt) { var adjusted_time = rnow() - TIME_DRIFT; return adjusted_time - tt / 10000; } detect_time_detla(); function detect_time_detla( cb, time ) { var stime = rnow(); time && calculate(time) || SELF['time'](calculate); function calculate(time) { if (!time) return; var ptime = time / 10000 , latency = (rnow() - stime) / 2; TIME_DRIFT = rnow() - (ptime + latency); cb && cb(TIME_DRIFT); } } return SELF; } function crypto_obj() { function SHA256(s) { return CryptoJS['SHA256'](s)['toString'](CryptoJS['enc']['Hex']); } var iv = "0123456789012345"; var allowedKeyEncodings = ['hex', 'utf8', 'base64', 'binary']; var allowedKeyLengths = [128, 256]; var allowedModes = ['ecb', 'cbc']; var defaultOptions = { 'encryptKey': true, 'keyEncoding': 'utf8', 'keyLength': 256, 'mode': 'cbc' }; function parse_options(options) { // Defaults options = options || {}; if (!options['hasOwnProperty']('encryptKey')) options['encryptKey'] = defaultOptions['encryptKey']; if (!options['hasOwnProperty']('keyEncoding')) options['keyEncoding'] = defaultOptions['keyEncoding']; if (!options['hasOwnProperty']('keyLength')) options['keyLength'] = defaultOptions['keyLength']; if (!options['hasOwnProperty']('mode')) options['mode'] = defaultOptions['mode']; // Validation if (allowedKeyEncodings['indexOf'](options['keyEncoding']['toLowerCase']()) == -1) options['keyEncoding'] = defaultOptions['keyEncoding']; if (allowedKeyLengths['indexOf'](parseInt(options['keyLength'], 10)) == -1) options['keyLength'] = defaultOptions['keyLength']; if (allowedModes['indexOf'](options['mode']['toLowerCase']()) == -1) options['mode'] = defaultOptions['mode']; return options; } function decode_key(key, options) { if (options['keyEncoding'] == 'base64') { return CryptoJS['enc']['Base64']['parse'](key); } else if (options['keyEncoding'] == 'hex') { return CryptoJS['enc']['Hex']['parse'](key); } else { return key; } } function get_padded_key(key, options) { key = decode_key(key, options); if (options['encryptKey']) { return CryptoJS['enc']['Utf8']['parse'](SHA256(key)['slice'](0, 32)); } else { return key; } } function get_mode(options) { if (options['mode'] == 'ecb') { return CryptoJS['mode']['ECB']; } else { return CryptoJS['mode']['CBC']; } } function get_iv(options) { return (options['mode'] == 'cbc') ? CryptoJS['enc']['Utf8']['parse'](iv) : null; } return { 'encrypt': function(data, key, options) { if (!key) return data; options = parse_options(options); var iv = get_iv(options); var mode = get_mode(options); var cipher_key = get_padded_key(key, options); var hex_message = JSON['stringify'](data); var encryptedHexArray = CryptoJS['AES']['encrypt'](hex_message, cipher_key, {'iv': iv, 'mode': mode})['ciphertext']; var base_64_encrypted = encryptedHexArray['toString'](CryptoJS['enc']['Base64']); return base_64_encrypted || data; }, 'decrypt': function(data, key, options) { if (!key) return data; options = parse_options(options); var iv = get_iv(options); var mode = get_mode(options); var cipher_key = get_padded_key(key, options); try { var binary_enc = CryptoJS['enc']['Base64']['parse'](data); var json_plain = CryptoJS['AES']['decrypt']({'ciphertext': binary_enc}, cipher_key, {'iv': iv, 'mode': mode})['toString'](CryptoJS['enc']['Utf8']); var plaintext = JSON['parse'](json_plain); return plaintext; } catch (e) { return undefined; } } }; } /* --------------------------------------------------------------------------- --------------------------------------------------------------------------- */ /* --------------------------------------------------------------------------- PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks Copyright (c) 2011 PubNub Inc. http://www.pubnub.com/ http://www.pubnub.com/terms --------------------------------------------------------------------------- */ /* --------------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --------------------------------------------------------------------------- */ (function(){ /** * UTIL LOCALS */ var NOW = 1 , PNSDK = 'PubNub-JS-' + 'Phonegap' + '/' + '3.7.13' , XHRTME = 310000; /** * LOCAL STORAGE */ var db = (function(){ var ls = typeof localStorage != 'undefined' && localStorage; return { get : function(key) { try { if (ls) return ls.getItem(key); if (document.cookie.indexOf(key) == -1) return null; return ((document.cookie||'').match( RegExp(key+'=([^;]+)') )||[])[1] || null; } catch(e) { return } }, set : function( key, value ) { try { if (ls) return ls.setItem( key, value ) && 0; document.cookie = key + '=' + value + '; expires=Thu, 1 Aug 2030 20:00:00 UTC; path=/'; } catch(e) { return } } }; })(); /** * CORS XHR Request * ================ * xdr({ * url : ['http://www.blah.com/url'], * success : function(response) {}, * fail : function() {} * }); */ function xdr( setup ) { var xhr , finished = function() { if (loaded) return; loaded = 1; clearTimeout(timer); try { response = JSON['parse'](xhr.responseText); } catch (r) { return done(1); } success(response); } , complete = 0 , loaded = 0 , timer = timeout( function(){done(1)}, XHRTME ) , data = setup.data || {} , fail = setup.fail || function(){} , success = setup.success || function(){} , async = ( typeof(setup.blocking) === 'undefined' ) , done = function(failed, response) { if (complete) return; complete = 1; clearTimeout(timer); if (xhr) { xhr.onerror = xhr.onload = null; xhr.abort && xhr.abort(); xhr = null; } failed && fail(response); }; // Send try { xhr = typeof XDomainRequest !== 'undefined' && new XDomainRequest() || new XMLHttpRequest(); xhr.onerror = xhr.onabort = function(){ done(1, xhr.responseText || { "error" : "Network Connection Error"}) }; xhr.onload = xhr.onloadend = finished; xhr.onreadystatechange = function() { if (xhr.readyState == 4) { switch(xhr.status) { case 200: break; default: try { response = JSON['parse'](xhr.responseText); done(1,response); } catch (r) { return done(1, {status : xhr.status, payload : null, message : xhr.responseText}); } return; } } } data['pnsdk'] = PNSDK; url = build_url(setup.url, data); xhr.open( 'GET', url, async); if (async) xhr.timeout = XHRTME; xhr.send(); } catch(eee) { done(0); return xdr(setup); } // Return 'done' return done; } /** * BIND * ==== * bind( 'keydown', search('a')[0], function(element) { * ... * } ); */ function bind( type, el, fun ) { each( type.split(','), function(etype) { var rapfun = function(e) { if (!e) e = window.event; if (!fun(e)) { e.cancelBubble = true; e.returnValue = false; e.preventDefault && e.preventDefault(); e.stopPropagation && e.stopPropagation(); } }; if ( el.addEventListener ) el.addEventListener( etype, rapfun, false ); else if ( el.attachEvent ) el.attachEvent( 'on' + etype, rapfun ); else el[ 'on' + etype ] = rapfun; } ); } /** * UNBIND * ====== * unbind( 'keydown', search('a')[0] ); */ function unbind( type, el, fun ) { if ( el.removeEventListener ) el.removeEventListener( type, false ); else if ( el.detachEvent ) el.detachEvent( 'on' + type, false ); else el[ 'on' + type ] = null; } /** * ERROR * === * error('message'); */ function error(message) { console['error'](message) } /** * EVENTS * ====== * PUBNUB.events.bind( 'you-stepped-on-flower', function(message) { * // Do Stuff with message * } ); * * PUBNUB.events.fire( 'you-stepped-on-flower', "message-data" ); * PUBNUB.events.fire( 'you-stepped-on-flower', {message:"data"} ); * PUBNUB.events.fire( 'you-stepped-on-flower', [1,2,3] ); * */ var events = { 'list' : {}, 'unbind' : function( name ) { events.list[name] = [] }, 'bind' : function( name, fun ) { (events.list[name] = events.list[name] || []).push(fun); }, 'fire' : function( name, data ) { each( events.list[name] || [], function(fun) { fun(data) } ); } }; /** * ATTR * ==== * var attribute = attr( node, 'attribute' ); */ function attr( node, attribute, value ) { if (value) node.setAttribute( attribute, value ); else return node && node.getAttribute && node.getAttribute(attribute); } /** * $ * = * var div = $('divid'); */ function $(id) { return document.getElementById(id) } /** * SEARCH * ====== * var elements = search('a div span'); */ function search( elements, start ) { var list = []; each( elements.split(/\s+/), function(el) { each( (start || document).getElementsByTagName(el), function(node) { list.push(node); } ); } ); return list; } /** * CSS * === * var obj = create('div'); */ function css( element, styles ) { for (var style in styles) if (styles.hasOwnProperty(style)) try {element.style[style] = styles[style] + ( '|width|height|top|left|'.indexOf(style) > 0 && typeof styles[style] == 'number' ? 'px' : '' )}catch(e){} } /** * CREATE * ====== * var obj = create('div'); */ function create(element) { return document.createElement(element) } function get_hmac_SHA256(data,key) { var hash = CryptoJS['HmacSHA256'](data, key); return hash.toString(CryptoJS['enc']['Base64']); } /* =-====================================================================-= */ /* =-====================================================================-= */ /* =-========================= PUBNUB ===========================-= */ /* =-====================================================================-= */ /* =-====================================================================-= */ function CREATE_PUBNUB(setup) { setup['db'] = db; setup['xdr'] = xdr; setup['error'] = setup['error'] || error; setup['hmac_SHA256']= get_hmac_SHA256; setup['crypto_obj'] = crypto_obj(); setup['params'] = { 'pnsdk' : PNSDK } SELF = function(setup) { return CREATE_PUBNUB(setup); } var PN = PN_API(setup); for (var prop in PN) { if (PN.hasOwnProperty(prop)) { SELF[prop] = PN[prop]; } } SELF['init'] = SELF; SELF['$'] = $; SELF['attr'] = attr; SELF['search'] = search; SELF['bind'] = bind; SELF['css'] = css; SELF['create'] = create; SELF['crypto_obj'] = crypto_obj(); if (typeof(window) !== 'undefined'){ bind( 'beforeunload', window, function() { SELF['each-channel'](function(ch){ SELF['LEAVE']( ch.name, 1 ) }); return true; }); } // Return without Testing if (setup['notest']) return SELF; if (typeof(window) !== 'undefined'){ bind( 'offline', window, SELF['_reset_offline'] ); } if (typeof(document) !== 'undefined'){ bind( 'offline', document, SELF['_reset_offline'] ); } SELF['ready'](); return SELF; } CREATE_PUBNUB['init'] = CREATE_PUBNUB CREATE_PUBNUB['secure'] = CREATE_PUBNUB CREATE_PUBNUB['crypto_obj'] = crypto_obj() PUBNUB = CREATE_PUBNUB({}) typeof module !== 'undefined' && (module.exports = CREATE_PUBNUB) || typeof exports !== 'undefined' && (exports.PUBNUB = CREATE_PUBNUB) || (PUBNUB = CREATE_PUBNUB); })(); (function(){ // --------------------------------------------------------------------------- // WEBSOCKET INTERFACE // --------------------------------------------------------------------------- var WS = PUBNUB['ws'] = function( url, protocols ) { if (!(this instanceof WS)) return new WS( url, protocols ); var self = this , url = self.url = url || '' , protocol = self.protocol = protocols || 'Sec-WebSocket-Protocol' , bits = url.split('/') , setup = { 'ssl' : bits[0] === 'wss:' ,'origin' : bits[2] ,'publish_key' : bits[3] ,'subscribe_key' : bits[4] ,'channel' : bits[5] }; // READY STATES self['CONNECTING'] = 0; // The connection is not yet open. self['OPEN'] = 1; // The connection is open and ready to communicate. self['CLOSING'] = 2; // The connection is in the process of closing. self['CLOSED'] = 3; // The connection is closed or couldn't be opened. // CLOSE STATES self['CLOSE_NORMAL'] = 1000; // Normal Intended Close; completed. self['CLOSE_GOING_AWAY'] = 1001; // Closed Unexpecttedly. self['CLOSE_PROTOCOL_ERROR'] = 1002; // Server: Not Supported. self['CLOSE_UNSUPPORTED'] = 1003; // Server: Unsupported Protocol. self['CLOSE_TOO_LARGE'] = 1004; // Server: Too Much Data. self['CLOSE_NO_STATUS'] = 1005; // Server: No reason. self['CLOSE_ABNORMAL'] = 1006; // Abnormal Disconnect. // Events Default self['onclose'] = self['onerror'] = self['onmessage'] = self['onopen'] = self['onsend'] = function(){}; // Attributes self['binaryType'] = ''; self['extensions'] = ''; self['bufferedAmount'] = 0; self['trasnmitting'] = false; self['buffer'] = []; self['readyState'] = self['CONNECTING']; // Close if no setup. if (!url) { self['readyState'] = self['CLOSED']; self['onclose']({ 'code' : self['CLOSE_ABNORMAL'], 'reason' : 'Missing URL', 'wasClean' : true }); return self; } // PubNub WebSocket Emulation self.pubnub = PUBNUB['init'](setup); self.pubnub.setup = setup; self.setup = setup; self.pubnub['subscribe']({ 'restore' : false, 'channel' : setup['channel'], 'disconnect' : self['onerror'], 'reconnect' : self['onopen'], 'error' : function() { self['onclose']({ 'code' : self['CLOSE_ABNORMAL'], 'reason' : 'Missing URL', 'wasClean' : false }); }, 'callback' : function(message) { self['onmessage']({ 'data' : message }); }, 'connect' : function() { self['readyState'] = self['OPEN']; self['onopen'](); } }); }; // --------------------------------------------------------------------------- // WEBSOCKET SEND // --------------------------------------------------------------------------- WS.prototype.send = function(data) { var self = this; self.pubnub['publish']({ 'channel' : self.pubnub.setup['channel'], 'message' : data, 'callback' : function(response) { self['onsend']({ 'data' : response }); } }); }; // --------------------------------------------------------------------------- // WEBSOCKET CLOSE // --------------------------------------------------------------------------- WS.prototype.close = function() { var self = this; self.pubnub['unsubscribe']({ 'channel' : self.pubnub.setup['channel'] }); self['readyState'] = self['CLOSED']; self['onclose']({}); }; })();
// including plugins var gulp = require('gulp'), livereload = require('gulp-livereload'), server = require('tiny-lr')(), less = require("gulp-less"), rename = require('gulp-rename'), minifyCSS = require('gulp-minify-css'); // translate less file, then minify it gulp.task('less', function () { gulp.src('_assets/less/app/app.less') .pipe(less()) .pipe(gulp.dest('public/css/')) .pipe(minifyCSS()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('public/css/')) .pipe(gulp.dest('_site/public/css/')) }); gulp.task('watch-less', function () { gulp.watch([ '_assets/less/app/*', '_assets/less/app/*/*', ], ['less']); livereload.listen(); gulp.watch('_site/public/css/app.min.css').on('change', livereload.changed); }); gulp.task('default', ['watch-less']);
'use strict'; var path = require('path'); var copy = require('copy'); var del = require('delete'); var drafts = require('gulp-drafts'); var reflinks = require('gulp-reflinks'); var format = require('gulp-format-md'); var paths = require('./lib/paths'); var lib = require('./lib'); module.exports = function(app) { var dest = paths.site(); app.use(lib.middleware()); app.use(lib.common()); app.task('clean', function(cb) { del(paths.docs(), {force: true}, cb); }); app.task('copy', function(cb) { copy('*.png', paths.docs(), cb); }); app.task('docs', ['clean', 'copy'], function(cb) { app.layouts('docs/layouts/*.md', {cwd: paths.cwd()}); app.docs('docs/*.md', {cwd: paths.cwd(), layout: 'default'}); return app.toStream('docs') .pipe(drafts()) .pipe(app.renderFile('*')) .pipe(reflinks()) .pipe(format()) .pipe(app.dest(paths.docs())); }); app.task('default', ['docs']); };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.to_datetime = undefined; var _immutable = require('immutable'); var _immutable2 = _interopRequireDefault(_immutable); var _index = require('../core/index'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * * @param {Series|DataFrame|List|Array|string} arg */ var to_datetime = exports.to_datetime = function to_datetime(arg) { if (arg instanceof _index.Series) { return new _index.Series(arg.values.map(function (v) { return to_datetime(v); }), arg.kwargs); } else if (arg instanceof _index.DataFrame) { return new _index.DataFrame(_immutable2.default.Map(arg.columns.map(function (c) { return [c, to_datetime(arg.get(c))]; })), arg.kwargs); } else if (arg instanceof _immutable2.default.List || Array.isArray(arg)) { return arg.map(function (v) { return to_datetime(v); }); } else if (typeof arg === 'string') { return new Date(arg); } throw new Error('Must be Series, DataFrame, List or Array'); }; //# sourceMappingURL=tools.js.map
'use strict'; describe('MockService', function() { var doneCallback, mockService; beforeEach(function() { doneCallback = jasmine.createSpy('doneCallback').and.callFake(function (error) { expect(error).toBe(null); }); mockService = Pact.mockService({ consumer: 'Consumer', provider: 'Provider', port: 1234, done: doneCallback }); }); describe("a successful match using Pact Matchers", function() { describe("with an argument list", function() { var doHttpCall = function(callback) { specHelper.makeRequest({ body: 'body', headers: { 'Content-Type': 'text/plain' }, method: 'POST', path: '/thing' }, callback); }; it('returns the mocked response', function(done) { mockService .uponReceiving('a request with Pact.Match using argument list') .withRequest('post', '/thing', { 'Content-Type': 'text/plain' }, 'body') .willRespondWith(201, { 'Content-Type': 'application/json' }, { reply: Pact.Match.somethingLike('Hello'), language: Pact.Match.term({generate: 'English', matcher: '\\w+'}) }); mockService.run(done, function(runComplete) { doHttpCall(function (error, response) { expect(error).toBe(null, 'error'); expect(JSON.parse(response.responseText)).toEqual({reply: 'Hello', language: 'English'}, 'responseText'); expect(response.status).toEqual(201, 'status'); expect(response.getResponseHeader('Content-Type')).toEqual('application/json', 'Content-Type header'); runComplete(); }); }); }); }); describe("with an argument hash", function() { var doHttpCall = function(callback) { specHelper.makeRequest({body: 'body', headers: { 'Content-Type': 'text/plain' }, method: 'POST', path: '/thing?message=gutentag&language=german' }, callback); }; it('returns the mocked response', function(done) { mockService .uponReceiving('a request with a Pact.Match') .withRequest({ method: 'post', path: '/thing', query: { message: Pact.Match.term({generate: 'ciao', matcher: "\\w+"}), language: Pact.Match.somethingLike('italian') }, headers: { 'Content-Type': 'text/plain' }, body: 'body' }) .willRespondWith({ status: 201, headers: { 'Content-Type': 'application/json' }, body: { reply: Pact.Match.somethingLike('Hello'), language: Pact.Match.term({generate: 'English', matcher: '\\w+'}) } }); mockService.run(done, function(runComplete) { doHttpCall(function (error, response) { expect(error).toBe(null, 'error'); expect(JSON.parse(response.responseText)).toEqual({reply: 'Hello', language: 'English'}, 'responseText'); expect(response.status).toEqual(201, 'status'); expect(response.getResponseHeader('Content-Type')).toEqual('application/json', 'Content-Type header'); runComplete(); }); }); }); }); }); });
import webpack from "webpack"; import color from "chalk"; export default (webpackConfig, log, cb) => { webpack(webpackConfig, (err, stats) => { if (err) { throw err; } if (stats.hasErrors()) { stats.compilation.errors.forEach(item => log(...[color.red("Error:"), ...item.message.split("\n")]) ); throw new Error("webpack build failed with errors"); } if (stats.hasWarnings()) { stats.compilation.warnings.forEach(item => log(...[color.yellow("Warning:"), ...item.message.split("\n")]) ); } cb(stats); }); };
var path = require('path') var fs = require('fs') var releaseFolder = require('./util').releaseFolder var gypbuild = require('./gypbuild') var noop = require('noop-logger') function build (opts, version, cb) { var log = opts.log || noop var release = releaseFolder(opts) log.verbose('starting node-gyp process') gypbuild(opts, version, function (err) { if (err) return cb(err) log.verbose('done node-gyp\'ing') done() }) function done () { fs.readdir(release, function (err, files) { if (err) return cb(err) for (var i = 0; i < files.length; i++) { if (/\.node$/i.test(files[i])) { return cb(null, path.join(release, files[i]), files[i]) } } cb(new Error('Could not find build in ' + release)) }) } } module.exports = build
module.exports={A:{A:{"2":"H D G E A B mB"},B:{"2":"C K f L N I J q"},C:{"1":"8 HB IB JB KB LB","2":"0 1 2 3 4 5 6 jB NB F O H D G E A B C K f L N I J P Q R S T U V W X Y Z a b c d e AB g h i j k l m n o p M r s t u v w x y z EB MB DB BB FB dB cB"},D:{"2":"0 1 2 3 4 5 6 8 F O H D G E A B C K f L N I J P Q R S T U V W X Y Z a b c d e AB g h i j k l m n o p M r s t u v w x y z EB MB DB BB FB HB IB JB KB LB bB WB q SB QB rB TB UB"},E:{"2":"F O H D G E A B VB PB XB YB ZB aB OB","129":"7 9 C K eB"},F:{"2":"0 1 2 3 4 5 6 7 9 E B C L N I J P Q R S T U V W X Y Z a b c d e AB g h i j k l m n o p M r s t u v w x y z fB gB hB iB GB kB"},G:{"1":"wB xB yB zB 0B 1B","2":"G PB lB CB nB oB pB qB RB sB tB uB vB"},H:{"2":"2B"},I:{"2":"NB F q 3B 4B 5B 6B CB 7B 8B"},J:{"2":"D A"},K:{"2":"7 9 A B C M GB"},L:{"2":"QB"},M:{"2":"8"},N:{"2":"A B"},O:{"2":"9B"},P:{"2":"F AC BC CC DC EC OB"},Q:{"2":"FC"},R:{"2":"GC"},S:{"2":"HC"}},B:5,C:"CSS ::marker pseudo-element"};
// Copyright (c) 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; var _ = require('underscore'); var async = require('async'); var testRingpopCluster = require('../lib/test-ringpop-cluster.js'); var GossipUtils = require('../lib/gossip-utils'); testRingpopCluster({ size: 2, tapAfterConvergence: function tapAfterConvergence(cluster) { GossipUtils.stopGossiping(cluster); } }, 'healing - two nodes', function t(bootRes, cluster, assert) { GossipUtils.waitForNoGossip(cluster, test); function test() { var ringpopA = cluster[0]; var ringpopB = cluster[1]; var addressB = ringpopB.hostPort; var addressA = ringpopA.hostPort; // create a partition by marking nodeB faulty on nodeA and vice versa. var initialIncarnationNumberB = ringpopB.membership.getIncarnationNumber(); var initialIncarnationNumberA = ringpopA.membership.getIncarnationNumber(); ringpopA.membership.makeFaulty(addressB, initialIncarnationNumberB); ringpopB.membership.makeFaulty(addressA, initialIncarnationNumberA); ringpopA.healer.heal(function afterFirstHeal(err, targets) { assert.ifError(err, 'healing successful'); assert.deepEqual(targets, [ringpopB.hostPort]); assert.ok(ringpopA.membership.getIncarnationNumber() > initialIncarnationNumberA, 'node A reincarnated'); assert.ok(ringpopB.membership.getIncarnationNumber() > initialIncarnationNumberB, 'node B reincarnated'); ringpopA.healer.heal(function afterSecondHeal(err, targets) { assert.ifError(err, 'healing successful'); assert.deepEqual(targets, [ringpopB.hostPort]); assert.equal(ringpopA.membership.findMemberByAddress(addressB).status, 'alive', 'B is alive in A'); assert.equal(ringpopB.membership.findMemberByAddress(addressA).status, 'alive', 'A is alive in B'); assert.end(); }); }); } }); function assertNoPartition(assert, cluster) { _.each(cluster, function iterator(ringpop) { _.each(ringpop.membership.members, assertAlive); }); function assertAlive(member) { assert.equal(member.status, 'alive'); } } testRingpopCluster({ size: 4, waitForConvergence: true, tapAfterConvergence: function tapAfterConvergence(cluster) { GossipUtils.stopGossiping(cluster); } }, 'healing - two partitions of two nodes', function t(bootRes, cluster, assert) { GossipUtils.waitForNoGossip(cluster, test); function test() { var initialIncarnationNumbers = new Array(cluster.length); for (var i = 0; i < cluster.length; i++) { initialIncarnationNumbers[i] = cluster[i].membership.getIncarnationNumber(); } var partitionA = [cluster[0], cluster[1]]; var partitionB = [cluster[2], cluster[3]]; _.each(partitionA, function(nodeA) { _.each(partitionB, function(nodeB) { nodeA.membership.makeFaulty(nodeB.hostPort, nodeB.membership.getIncarnationNumber()); nodeB.membership.makeFaulty(nodeA.hostPort, nodeA.membership.getIncarnationNumber()); }); }); for (var i = 0; i < partitionA.length; i++) { var node = partitionA[i]; for (var j = 0; j < node.membership.members.length; j++) { var member = node.membership.members[j]; if (_.pluck(partitionA, 'hostPort').indexOf(member.address) > -1) { assert.equal(member.status, 'alive') } else if (_.pluck(partitionB, 'hostPort').indexOf(member.address) > -1) { assert.equal(member.status, 'faulty'); } else { assert.fail('member is not part of one of the partitions'); } } } var target = _.find(cluster, function(n) { return n.hostPort === '127.0.0.1:10000' }); target.healer.heal(function afterFirstHeal(err, targets) { assert.ifError(err, 'healing successful'); assert.equal(targets.length, 1, 'one heal target should be enough'); GossipUtils.waitForConvergence(cluster, true, function verifyFirstHeal(err) { assert.ifError(err, 'ping all successful'); for (var i = 0; i < cluster.length; i++) { assert.ok(cluster[i].membership.getIncarnationNumber() > initialIncarnationNumbers[i], 'node reincarnated'); } target.healer.heal(function afterSecondHeal(err, targets) { assert.ifError(err, 'healing successful'); assert.equal(targets.length, 1, 'one heal target should be enough'); GossipUtils.waitForConvergence(cluster, true, function verifySecondHeal(err) { assert.ifError(err, 'ping all successful'); assertNoPartition(assert, cluster); assert.end(); }); }); }); }); } });
import TestResolverApplicationTestCase from './test-resolver-application'; import Application from '@ember/application'; import { Router } from '@ember/-internals/routing'; export default class AutobootApplicationTestCase extends TestResolverApplicationTestCase { createApplication(options, MyApplication = Application) { let myOptions = Object.assign(this.applicationOptions, options); let application = (this.application = MyApplication.create(myOptions)); this.resolver = application.__registry__.resolver; if (this.resolver) { this.resolver.add('router:main', Router.extend(this.routerOptions)); } return application; } visit(url) { return this.application.boot().then(() => { return this.applicationInstance.visit(url); }); } get applicationInstance() { let { application } = this; if (!application) { return undefined; } return application.__deprecatedInstance__; } }
#!/usr/bin/env node /** * Copyright 2012-2016 Alex Sexton, Eemeli Aro, and Contributors * * Licensed under the MIT License */ var fs = require('fs'), glob = require('glob'), MessageFormat = require('../'), nopt = require('nopt'), path = require('path'), knownOpts = { help: Boolean, locale: [String, Array], namespace: String, 'disable-plural-key-checks': Boolean }, shortHands = { h: ['--help'], l: ['--locale'], n: ['--namespace'], p: ['--disable-plural-key-checks'] }, options = nopt(knownOpts, shortHands, process.argv, 2), inputFiles = options.argv.remain.map(function(fn) { return path.resolve(fn); }); if (options.help || inputFiles.length === 0) { printUsage(); } else { var locale = options.locale ? options.locale.join(',').split(/[ ,]+/) : null; if (inputFiles.length === 0) inputFiles = [ process.cwd() ]; var input = readInput(inputFiles, '.json', '/'); var ns = options.namespace || 'module.exports'; var mf = new MessageFormat(locale); if (options['disable-plural-key-checks']) mf.disablePluralKeyChecks(); var output = mf.compile(input).toString(ns); console.log(output); } function printUsage() { var usage = [ 'usage: *messageformat* [*-l* _lc_] [*-n* _ns_] [*-p*] _input_', '', 'Parses the _input_ JSON file(s) of MessageFormat strings into a JS module of', 'corresponding hierarchical functions, written to stdout. Directories are', 'recursively scanned for all .json files.', '', ' *-l* _lc_, *--locale*=_lc_', ' The locale(s) _lc_ to include; if multiple, selected by matching', ' message key. [default: *en*]', '', ' *-n* _ns_, *--namespace*=_ns_', ' The global object or modules format for the output JS. If _ns_ does not', ' contain a \'.\', the output follows an UMD pattern. For module support,', ' the values \'*export default*\' (ES6), \'*exports*\' (CommonJS), and', ' \'*module.exports*\' (node.js) are special. [default: *module.exports*]', '', ' *-p*, *--disable-plural-key-checks*', ' By default, messageformat.js throws an error when a statement uses a', ' non-numerical key that will never be matched as a pluralization', ' category for the current locale. Use this argument to disable the', ' validation and allow unused plural keys. [default: *false*]' ].join('\n'); if (process.stdout.isTTY) { usage = usage.replace(/_(.+?)_/g, '\x1B[4m$1\x1B[0m') .replace(/\*(.+?)\*/g, '\x1B[1m$1\x1B[0m'); } else { usage = usage.replace(/[_*]/g, ''); } console.log(usage); } function readInput(include, ext, sep) { // modified from http://stackoverflow.com/a/1917041 function sharedPathLength(array) { var A = array.sort(), a1 = A[0], a2 = A[A.length - 1], len = a1.length, i = 0; while (i < len && a1.charAt(i) === a2.charAt(i)) ++i; return a1.substring(0, i).replace(/[^/]+$/, '').length; } var ls = []; include.forEach(function(fn) { if (!fs.existsSync(fn)) throw new Error('Input file not found: ' + fn); if (fs.statSync(fn).isDirectory()) { ls.push.apply(ls, glob.sync(path.join(fn, '**/*' + ext))); } else { if (path.extname(fn) !== ext) throw new Error('Input file extension is not ' + ext + ': ' + fn); ls.push(fn); } }); var start = sharedPathLength(ls); var end = -1 * ext.length; var input = {}; ls.forEach(function(fn) { var key = fn.slice(start, end); var parts = key.split(sep); var last = parts.length - 1; parts.reduce(function(root, part, idx) { if (idx == last) root[part] = require(fn); else if (!(part in root)) root[part] = {}; return root[part]; }, input); }); return input; }
"use strict"; var helpers = require("../../helpers/helpers"); exports["Etc/GMT+9"] = { "guess:by:offset" : helpers.makeTestGuess("Etc/GMT+9", { offset: true, expect: "Pacific/Gambier" }), "guess:by:abbr" : helpers.makeTestGuess("Etc/GMT+9", { abbr: true, expect: "Pacific/Gambier" }), };
// ========================================================================== // Project: The M-Project - Mobile HTML5 Application Framework // Copyright: (c) 2010 M-Way Solutions GmbH. All rights reserved. // (c) 2011 panacoda GmbH. All rights reserved. // Creator: Sebastian // Date: 22.11.2010 // License: Dual licensed under the MIT or GPL Version 2 licenses. // http://github.com/mwaylabs/The-M-Project/blob/master/MIT-LICENSE // http://github.com/mwaylabs/The-M-Project/blob/master/GPL-LICENSE // ========================================================================== m_require('core/datastore/validator.js') /** * @class * * Validates if it represents a minus number. Works with numbers and strings containing just a number. * * @extends M.Validator */ M.NotMinusValidator = M.Validator.extend( /** @scope M.NotMinusValidator.prototype */ { /** * The type of this object. * * @type String */ type: 'M.NotMinusValidator', /** * Validation method. Distinguishes between type of value: number or string. Both possible. If number value is checked if less than zero, * if string value is checked if ^prefixed with a minus sign ( - ). * * @param {Object} obj Parameter object. Contains the value to be validated, the {@link M.ModelAttribute} object of the property and the model record's id. * @returns {Boolean} Indicating whether validation passed (YES|true) or not (NO|false). */ validate: function(obj) { if(typeof(obj.value) === 'number') { if(obj.value < 0) { var err = M.Error.extend({ msg: this.msg ? this.msg : obj.value + ' is a minus value. This is not allowed.', code: M.ERR_VALIDATION_NOTMINUS, errObj: { msg: obj.value + ' is a minus value. This is not allowed.', modelId: obj.modelId, property: obj.property, viewId: obj.viewId, validator: 'NUMBER', onSuccess: obj.onSuccess, onError: obj.onError } }); this.validationErrors.push(err); return NO; } return YES; } if(typeof(obj.value) === 'string') { var pattern = /-/; if(this.pattern.exec(obj.value)) { var err = M.Error.extend({ msg: this.msg ? this.msg : obj.value + ' is a minus value. This is not allowed.', code: M.ERR_VALIDATION_NOTMINUS, errObj: { msg: obj.value + ' is a minus value. This is not allowed.', modelId: obj.modelId, property: obj.property, viewId: obj.viewId, validator: 'NUMBER', onSuccess: obj.onSuccess, onError: obj.onError } }); this.validationErrors.push(err); return NO; } return YES; } } });
define({ "_widgetLabel": "Sélectionner", "showActions": "Afficher les actions sur les entités sélectionnées", "toggleSelectability": "Cliquez pour activer/désactiver le caractère sélectionnable", "showSelectedFeatures": "Cliquez pour afficher les entités sélectionnées", "actionsTitle": "Actions de sélection" });
/* * grunt-deps-ok * https://github.com/bahmutov/grunt-deps-ok * * Copyright (c) 2013 Gleb Bahmutov * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>', ], options: { jshintrc: '.jshintrc', }, }, // Before generating any new files, remove any previously-created files. clean: { tests: ['tmp'], }, // Unit tests. nodeunit: { tests: ['test/*_test.js'], }, }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.loadNpmTasks('grunt-nice-package'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', 'deps-ok', 'nodeunit']); // By default, lint and run all tests. grunt.registerTask('default', ['jshint', 'nice-package', 'test']); };
/* * Translated default messages for the jQuery validation plugin. * Locale: DA (Danish; dansk) */ $.extend($.validator.messages, { required: "Dette felt er påkrævet.", maxlength: $.validator.format("Indtast højst {0} tegn."), minlength: $.validator.format("Indtast mindst {0} tegn."), rangelength: $.validator.format("Indtast mindst {0} og højst {1} tegn."), email: "Indtast en gyldig email-adresse.", url: "Indtast en gyldig URL.", date: "Indtast en gyldig dato.", number: "Indtast et tal.", digits: "Indtast kun cifre.", equalTo: "Indtast den samme værdi igen.", range: $.validator.format("Angiv en værdi mellem {0} og {1}."), max: $.validator.format("Angiv en værdi der højst er {0}."), min: $.validator.format("Angiv en værdi der mindst er {0}."), creditcard: "Indtast et gyldigt kreditkortnummer." });
'use strict'; function hexToRgb(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } function shadeColor2(color, percent) { var f=parseInt(color.slice(1), 16), t=percent<0?0:255, p=percent<0?percent*-1:percent, R=f>>16, G=f>>8&0x00FF, B=f&0x0000FF; return "#"+(0x1000000+(Math.round((t-R)*p)+R)*0x10000+(Math.round((t-G)*p)+G)*0x100+(Math.round((t-B)*p)+B)).toString(16).slice(1); } module.exports = function(primaryColor, secondaryColor, backgroundColor, textColor) { var opaque = hexToRgb(backgroundColor); var opaque1 = hexToRgb(primaryColor); var customStyleTag = document.getElementById('customStyle') || document.createElement('style'); customStyleTag.setAttribute('id', 'customStyle'); // if text is white the highlight color needs to darken instead of lighten if (primaryColor == 'undefined' || primaryColor == "#ffffff"){ customStyleTag.innerHTML = "#ov1 #userPage .txtField:focus, " + "#ov1 #userPage .custCol-border { border-color: " + shadeColor2(primaryColor, -0.08) + ";}" + "#ov1 #userPage .fieldItem:focus, " + "#ov1 #userPage .fieldItem-textarea:focus { outline: 2px solid " + shadeColor2("#ffffff", -0.15) + " ;}"; } else { customStyleTag.innerHTML = "#ov1 #userPage .txtField:focus, " + "#ov1 #userPage .custCol-border { border-color: " + shadeColor2(primaryColor, 0.08) + ";}" + "#ov1 #userPage .fieldItem:focus, " + "#ov1 #userPage .fieldItem-textarea:focus { outline: 2px solid " + shadeColor2(primaryColor, 0.15) + " ;}"; } customStyleTag.innerHTML += "#ov1 #userPage .custCol-primary-light { background-color: " + shadeColor2(primaryColor, 0.05) + ";}" + "#ov1 #userPage .custCol-primary, #ov1 #userPage .chosen-drop, #ov1 #userPage .no-results { background: " + primaryColor + ";}" + "#ov1 #userPage .btn-tab.active { background-color: " + primaryColor + ";}" + "#ov1 #userPage .btn-tab .pill { background-color: " + primaryColor + ";}" + "#ov1 #userPage .btn-tab.active .pill { background-color: " + secondaryColor + ";}" + "#ov1 #userPage .btn:active { -webkit-box-shadow: inset 0px 0px 6px 0px " + shadeColor2(primaryColor, -0.35) + ";}" + "#ov1 #userPage .btn-tab:active { -webkit-box-shadow: none;}" + "#ov1 #userPage .custCol-secondary { background-color: " + secondaryColor + ";}" + "#ov1 #userPage { background-color: " + backgroundColor + ";}" + "#ov1 #userPage .custCol-border-secondary { border-color: " + secondaryColor + ";}" + "#ov1 #userPage .custCol-border-primary { border-color: " + primaryColor + ";}" + "#ov1 #userPage .radioLabel:before { border-color: " + textColor + ";}" + "#ov1 #userPage .checkboxLabel:before { border-color: " + textColor + "; opacity: .75;}" + // "#ov1 #userPage .user-page-header-slim { background: " + shadeColor2(primaryColor, -0.15) + ";}" + "#ov1 #userPage .mainSearchWrapper .txtField:focus { box-shadow: 0 0 0 2px " + shadeColor2(primaryColor, -0.35) + ";}" + "#ov1 #userPage .fieldItem { color: " + textColor + ";}" + "#ov1 #userPage .fieldItem-textarea { color: " + textColor + ";}" + "#ov1 #userPage input[type='radio'].fieldItem:checked + label:before { background: " + textColor + "; box-shadow: inset 0 0 0 4px " + primaryColor + ";}" + "#ov1 #userPage input[type='radio'].fieldItem.starRating + label:before { color: " + textColor + "; background: none; box-shadow: none;}" + "#ov1 #userPage input[type='radio'].fieldItem.starRating:checked + label:before { background: none; box-shadow: none;}" + "#ov1 #userPage .starRating:before { color: " + textColor + ";}" + //"#ov1 #userPage input[type='checkbox'].fieldItem:checked + label:before { color: " + textColor + "; box-shadow: inset 0 0 0 4px " + primaryColor + ";}" + "#ov1 #userPage input[type='number'].fieldItem { color: " + textColor + ";}" + "#ov1 #userPage input[type='number'].spinButtons::-webkit-inner-spin-button:before { color: " + textColor + ";}" + "#ov1 #userPage input[type='number'].spinButtons::-webkit-inner-spin-button:after { color: " + textColor + ";}" + "#ov1 #userPage #obContainer input::-webkit-input-placeholder { color: " + textColor + ";}" + //"#ov1 #userPage #pageNav input::-webkit-input-placeholder { color: " + textColor + ";}" + "#ov1 #userPage #obContainer textarea::-webkit-input-placeholder { color: " + textColor + ";}" + //"#ov1 #userPage #pageNav textarea::-webkit-input-placeholder { color: " + textColor + ";}" + "#ov1 #userPage .txtFieldWrapper-bar:before { color: " + textColor + ";}" + "#ov1 #userPage .mainContainer { box-shadow: 0px 10px 20px " + shadeColor2(backgroundColor, -0.3) + "; }" + "#ov1 #userPage .mainContainer .txtFieldWrapper:before { color: " + textColor + "; }" + "#ov1 #userPage .container .txtField { color: " + textColor + ";}" + "#ov1 #userPage .custCol-font-secondary { color: " + secondaryColor + ";}" + "#ov1 #userPage .custCol-text::-webkit-input-placeholder { color: " + textColor + ";}" + "#ov1 #userPage .chosen-choices {border: 0; background-image: none; box-shadow: none; padding: 5px 7px}" + "#ov1 #userPage .search-choice { background-color: " + secondaryColor + "; background-image: none; border: none; padding: 10px; color: " + textColor + " ; font-size: 13px; box-shadow: none; border-radius: 3px;}" + "#ov1 #userPage .custCol-border-background { border-color: " + backgroundColor + " }" + "#ov1 #userPage .chosen-results li { border-bottom: solid 1px " + secondaryColor + "}" + "#ov1 #userPage .fieldItem .fieldItem-selectWrapper .chosen-single, #ov1 #userPage .fieldItem .fieldItem-selectWrapper .chosen-drop .chosen-results li { color:" + textColor + " }" + "#ov1 #userPage .fieldItem .fieldItem-selectWrapper .chosen-drop .chosen-results li.highlighted { background:" + secondaryColor + " }" + "#ov1 #userPage .fieldItem .fieldItem-selectWrapper option { background:" + primaryColor + " }" + "#ov1 #userPage .custCol-primary-darken { background: " + shadeColor2(primaryColor, -0.15) + ";}" + "#ov1 #userPage .custCol-secondary-darken { background: " + shadeColor2(secondaryColor, -0.15) + ";}" + "#ov1 #userPage .custCol-text, #ov1 #userPage .search-field input { color: " + textColor + ";}" + "#ov1 #userPage .modal-opaque { background-color: rgba(" + opaque.r + ", " + opaque.g + ", " + opaque.b + ", 0.90);}" + "#ov1 #userPage .fieldItem:focus , #ov1 #userPage .fieldItem-textarea:focus { border: 2px solid " + shadeColor2(primaryColor, 0.15) + ";}" + "#ov1 #userPage #obContainer::-webkit-scrollbar-thumb { background: " + shadeColor2(backgroundColor, 0.25) + ";}" + "#ov1 #userPage .customThemeScrollbar::-webkit-scrollbar-thumb { background: " + shadeColor2(primaryColor, 0.25) + ";}" + "#ov1 #userPage .user-page-header-slim-bg { box-shadow: inset 0px -120px 112px -52px rgba(" + opaque1.r + ", " + opaque1.g + ", " + opaque1.b + ", .65);}" + "#ov1 #userPage .custCol-background { background-color: " + backgroundColor + ";}" + "#ov1 #userPage #overlay { background-color: rgba(" + opaque.r + ", " + opaque.g + ", " + opaque.b + ", 0.70);}"; // Medium Editor customStyleTag.innerHTML += "#ov1 #userPage .medium-editor-toolbar li button { background-color: " + secondaryColor + "; color: " + textColor + "; border: 0}" + "#ov1 #userPage .medium-editor-toolbar li button:hover { opacity: .75}" + "#ov1 #userPage .medium-editor-toolbar:after { border-top-color: " + secondaryColor + "; border-left-color: transparent; border-right-color: transparent}"; // colorbox customStyleTag.innerHTML += "#ov1 #userPage #cboxContent { background-color: " + primaryColor + "; color: " + textColor + ";}" + "#ov1 #userPage #cboxCurrent { color: " + textColor + ";}" + "#ov1 #userPage #cboxClose { background-color: " + secondaryColor + "; color: " + textColor + "}" + "#ov1 #userPage #cboxOverlay { background-color: rgba(" + opaque.r + ", " + opaque.g + ", " + opaque.b + ", 1);}"; // taggle customStyleTag.innerHTML += "#ov1 #userPage .taggle_list .taggle { background-color: " + secondaryColor + "; color: " + textColor + ";}" + "#ov1 #userPage .taggle_list .taggle .taggle_text { color: " + textColor + ";}" + "#ov1 #userPage .taggle_list .taggle .close { color: " + textColor + ";}"; document.body.appendChild(customStyleTag); };
module.exports = require('regenerate')().addRange(0x1F3FB, 0x1F3FF);
exports.BattleStatuses= { sunnyday: { inherit: true, onStart: function (battle, source, effect) { if (effect && effect.effectType === 'Ability') { this.effectData.duration = 0; this.add('-weather', 'SunnyDay', '[from] ability: ' + effect, '[of] ' + source); } else { this.add('-weather', 'SunnyDay'); } } }, raindance: { inherit: true, onStart: function (battle, source, effect) { if (effect && effect.effectType === 'Ability') { this.effectData.duration = 0; this.add('-weather', 'RainDance', '[from] ability: ' + effect, '[of] ' + source); } else { this.add('-weather', 'RainDance'); } } }, sandstorm: { inherit: true, onStart: function (battle, source, effect) { if (effect && effect.effectType === 'Ability') { this.effectData.duration = 0; this.add('-weather', 'Sandstorm', '[from] ability: ' + effect, '[of] ' + source); } else { this.add('-weather', 'Sandstorm'); } } }, hail: { inherit: true, onStart: function (battle, source, effect) { if (effect && effect.effectType === 'Ability') { this.effectData.duration = 0; this.add('-weather', 'Hail', '[from] ability: ' + effect, '[of] ' + source); } else { this.add('-weather', 'Hail'); } }, } };
var css_beautify = legacy_beautify_css; /* Footer */ if (typeof define === "function" && define.amd) { // Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- ) define([], function() { return { css_beautify: css_beautify }; }); } else if (typeof exports !== "undefined") { // Add support for CommonJS. Just put this file somewhere on your require.paths // and you will be able to `var html_beautify = require("beautify").html_beautify`. exports.css_beautify = css_beautify; } else if (typeof window !== "undefined") { // If we're running a web page and don't have either of the above, add our one global window.css_beautify = css_beautify; } else if (typeof global !== "undefined") { // If we don't even have window, try global. global.css_beautify = css_beautify; } }());
var Game, styles, z; z = require('zorium'); paperColors = require('zorium-paper/colors.json') Score = require('../../models/score') Footer = require('../footer') window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }; })(); module.exports = Game = (function() { var state = z.state({ $footer: new Footer(), timeInterval: null, renderInterval: null }) function Game() {} Game.prototype.onBeforeUnmount = function () { clearInterval(state().timeInterval) } Game.prototype.onMount = function ($$el) { var RATIO = window.devicePixelRatio || 1 var a = $$el.children[0] var b = document.body a.width = window.innerWidth * RATIO a.height = window.innerHeight * RATIO window.onresize = function () { window.location.reload() } var c = a.getContext('2d') ctx = c W = a.width H = a.height dotSize = Math.min(W, H) / 7 xs = W / 2 - dotSize * 3 + dotSize / 2 ys = H / 2 - dotSize * 3 + dotSize / 2 if (W > H) { dotSize *= 0.6 xs = W / 2 - dotSize * 3 + dotSize / 2 ys = H / 2 - dotSize * 3 } choice = function(arr) { return arr[Math.floor(Math.random()*arr.length)] } colors = ['#F44336', '#9C27B0', '#2196F3', '#4CAF50', '#FF9800'] dots = [] for (var x = 0; x < 6; x++) { for (var y = 0; y < 6; y++) { color = choice(colors) dots.push({ color: color, ty: ys + y * dotSize, x: xs + x * dotSize, y: ys + y * dotSize, r: y, c: x }) } } window.gameRestart = function () { isSelecting = false selected = [] isSelecting = false mouseX = 0 mouseY = 0 squareColor = null score = 0 time = 60 lastPhysicsTime = 0 for (var x = 0; x < 6; x++) { for (var y = 0; y < 6; y++) { color = choice(colors) dots[x + y * 6] = { color: color, ty: ys + y * dotSize, x: xs + x * dotSize, y: ys + y * dotSize - (dotSize * x * 2), r: y, c: x, tt: dotSize / 15 } } } } window.gameRestart() state.set({ timeInterval: setInterval(function () { time -= 1 time = Math.max(time, 0) if (time == 0) { selected = [] isSelecting = false squareColor = null Score.save(score) z.router.go('/game-over') } }, 1000) }) render = function() { var physicsScale = 1 var delta = 1 if (lastPhysicsTime) { var now = Date.now() delta = now - lastPhysicsTime // we want 60fps physicsScale = delta / 16 // clamp physicsScale = Math.min(physicsScale, 5) lastPhysicsTime = now } else { lastPhysicsTime = Date.now() } if (time === 0) { return } ctx.clearRect(0, 0, W, H) if (squareColor) { ctx.globalAlpha = 0.1 ctx.fillStyle = squareColor ctx.fillRect(0, 0, W, H) ctx.globalAlpha = 1 } ctx.font = dotSize / 2 + 'px Roboto' function fillText(s, x, y) { ctx.fillText(s, x|0, y|0) } ctx.fillStyle = paperColors.$black54 fillText(score, xs + dotSize * 2.5, ys - dotSize) fillText(time, xs + dotSize, ys - dotSize) fillText(Score.getBest(), xs + dotSize * 4, ys - dotSize) ctx.textAlign = 'center' ctx.font = 'italic ' + dotSize / 5 + 'px Roboto' fillText('SCORE', xs + dotSize * 2.5, ys - dotSize + dotSize / 3) fillText('TIME', xs + dotSize, ys - dotSize + dotSize / 3) fillText('BEST', xs + dotSize * 4, ys - dotSize + dotSize / 3) for (var i = dots.length - 1; i >= 0 ; i--) { var a = dots[i] var hasBelow = false for (var j = 0; j < dots.length; j++) { var b = dots[j] if (isBelow(a, b)) { hasBelow = true break } } if (!hasBelow && a.r != 5) { a.r += 1 a.ty = ys + a.r * dotSize } if (a.y != a.ty) { dir = a.y > a.ty ? -1 : 1 a.y += a.tt * dir * physicsScale a.tt *= a.bdown && !a.bup ? 0.7 : 1.3 if (dir == 1 && a.y >= a.ty) { a.y = a.ty } else if (dir == -1 && a.y <= a.ty) { a.y = a.ty if (a.bdown) { a.bdown = true } } if (!a.bdown && !a.bup && a.y == a.ty) { a.bdown = true a.ty -= dotSize / 3 * 1.3 a.tt = dotSize / 5 } else if (a.bdown && !a.bup && a.y == a.ty) { a.bup = true a.tt = dotSize / 25 a.ty += dotSize / 3 * 1.3 } } else { a.tt = dotSize / 15 a.bdown = false a.bup = false } } for (var i = 0; i < dots.length; i++) { dot = dots[i] if (contains(selected, dot) || dot.color == squareColor) { ctx.fillStyle = dot.color ctx.globalAlpha = 0.5 ctx.fillRect(Math.floor(dot.x - dotSize / 3), Math.floor(dot.y - dotSize / 3), Math.floor(dotSize / 1.5), Math.floor(dotSize / 1.5)) ctx.globalAlpha = 1 } ctx.fillStyle = dot.color ctx.fillRect(Math.floor(dot.x - dotSize / 4), Math.floor(dot.y - dotSize / 4), Math.floor(dotSize / 2), Math.floor(dotSize / 2)) } if (selected.length && isSelecting) { ctx.strokeStyle = selected[0].color ctx.lineJoin = 'round' ctx.lineWidth = dotSize / 6 ctx.beginPath() ctx.moveTo(mouseX, mouseY) for (var i = 0; i < selected.length; i++) { var dot = selected[i] ctx.lineTo(dot.x, dot.y) } ctx.stroke() } window.requestAnimFrame(render) } isBelow = function (a, b) { return a.r + 1 == b.r && a.c == b.c } collideDot = function (x, y, dot) { return x > dot.x - dotSize / 2 && x < dot.x + dotSize / 2 && y > dot.y - dotSize / 2 && y < dot.y + dotSize / 2 } contains = function (arr, x) { return arr.indexOf(x) != -1 } isNeighbor = function (a, b) { return a.r + 1 == b.r && a.c == b.c || a.r - 1 == b.r && a.c == b.c || a.c + 1 == b.c && a.r == b.r || a.c - 1 == b.c && a.r == b.r } a.addEventListener('mousedown', touchstart) a.addEventListener('touchstart', touchstart) function touchstart(e) { e.preventDefault() if (time == 0) return isSelecting = true var x, y if (e.pageX) { x = e.pageX y = e.pageY } else { var t = e.changedTouches x = t[0].pageX y = t[0].pageY } onmove({ pageX: x, pageY: y }) } a.addEventListener('mouseup', touchend) a.addEventListener('touchend', touchend) function touchend(e) { e.preventDefault() isSelecting = false if (selected.length < 2) { return selected = [] } if (squareColor) { for (var i = 0; i < dots.length; i++) { var dot = dots[i] if (dot.color == squareColor) { selected.push(dot) } } } var highestRow = 0 for (var i = 0; i < selected.length; i++) { var dot = selected[i] highestRow = Math.max(dot.r, highestRow) } for (var i = 0; i < selected.length; i++) { var dot = selected[i] do { var color = choice(colors) } while (color == squareColor) if (dot.r >= 0) { score += 1 dot.r -= highestRow + 1 dot.y = ys + dot.r * dotSize dot.ty = ys + dot.r * dotSize dot.color = color } } squareColor = null selected = [] } a.addEventListener('mousemove', onmove) a.addEventListener('touchmove', onmove) function onmove (e) { if (e.preventDefault) e.preventDefault() if (e.pageX) { mouseX = e.pageX * RATIO mouseY = e.pageY * RATIO } else { var t = e.changedTouches mouseX = t[0].pageX * RATIO mouseY = t[0].pageY * RATIO isSelecting = true } if (isSelecting && time != 0) { for (var i = 0; i < dots.length; i++) { var dot = dots[i] var isntSame = selected.length && selected[0].color != dot.color if (isntSame || selected.length && !isNeighbor(dot, selected[0])) continue if (collideDot(mouseX, mouseY, dot)) { if (!contains(selected, dot)) { selected.unshift(dot) } else if (selected[1] == dot) { selected.shift() } else { selected.unshift(dot) squareColor = dot.color } } } } } render() } Game.prototype.restart = function () { if (window.gameRestart) window.gameRestart() } Game.prototype.render = function() { var self = this $footer = state.$footer return z('z-game', {style: { width: '100%', height: '100%' }}, z('canvas#canvas', { style: { display: 'block', width: '100%', height: '100%' } }), z($footer, { onRestart: function () { self.restart() } }) ) }; return Game; })();
define([ 'jquery', 'underscore', 'backbone' ], function ($, _, Backbone) { var Rate = Backbone.Model.extend({ idAttribute: "_id", urlRoot: '/api/rate', }); var RateCollection = Backbone.Collection.extend({ url: '/api/rate', model: Rate, comparator: function(e1, e2) { if (e1.get('created') > e2.get('created')) return -1; // before if (e1.get('created') < e2.get('created')) return 1; // before return 0; // equal } }); return { Model: Rate, Collection: RateCollection }; });
/* * Copyright (C) 2012 by CoNarrative */ /* DOCS DISABLED FOR NOW * @class glu.RowViewmodel * An extremely lightweight version of a view model that just has formulas (for now). * Very useful to get reactive behavior in grids where items can automatically update without a grid refresh * or based on other columns locally changing. * Available (at the moment) only for Ext 4.x + */ if (Ext.getVersion().major > 3 || Ext.getProvider().provider == 'touch') { Ext.define('glu.rowViewmodel', { extend:'Ext.data.Model', initFormulas : function(){ for (var formulaName in this.formulas) { var fn = this.formulas[formulaName]; glu.Reactor.build(formulaName, {on:'$', formula:fn}, this, this.data); } for (var formulaName in this.formulas) { var fn = this.formulas[formulaName]; this.data[formulaName] = fn.apply(this.data); } }, //LIVE CHANGE STEP 3a: Keeps getting called until formulas done processing //TODO: True dependency graph... setRaw:function (formulaName, value) { //if the formula has changed within this cycle or since last update, put on the update list if ((this.formulasToUpdate[formulaName] && this.formulasToUpdate[formulaName] != value) || this.get(formulaName) != value) { this.formulasToUpdate[formulaName] = value; this.fireEvent(formulaName + 'Changed', value, this.formulasToUpdate[formulaName] || this.get(formulaName)); } }, //LIVE CHANGE STEP 4a: add the accumulated formula changes to the property afterEdit:function (modifiedFieldNames) { if (this.settingFormulas) { //do nothing when accumulating formula changes NOTE: Not used at the moment return; } var name = modifiedFieldNames[0]; this.formulasToUpdate = {}; this.fireEvent(name + 'Changed', this.data[name]); //formulas have finished accumulating for (var fName in this.formulasToUpdate) { this.data[fName] = this.formulasToUpdate[fName]; modifiedFieldNames.push(this.formulasToUpdate[fName]); } this.settingFormulas = false; this.callParent(modifiedFieldNames); } }); glu.defRowModel = function (name, config) { if (config.formulas) { for (var formulaName in config.formulas) { config.fields.push({ name:formulaName }); } } config.extend = 'glu.rowViewmodel' Ext.define(name, config); }; Ext.define('glu.Reader', { extend:'Ext.data.reader.Json', alias:'reader.glujson', extractData:function () { var records = this.callParent(arguments); if (this.model.prototype.formulas) { for (var i = 0; i < records.length; i++) { var rec = records[i]; rec.initFormulas(); } } return records; } }); }
'use strict'; exports.__esModule = true; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _screen = require('../../core/screen'); var _screen2 = _interopRequireDefault(_screen); var _vcode_pane = require('../../field/vcode/vcode_pane'); var _vcode_pane2 = _interopRequireDefault(_vcode_pane); var _index = require('./index'); var _actions = require('./actions'); var _signed_in_confirmation = require('../../core/signed_in_confirmation'); var _index2 = require('../../field/index'); var _phone_number = require('../../field/phone_number'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Component = function Component(_ref) { var i18n = _ref.i18n, model = _ref.model; var instructions = (0, _index.isEmail)(model) ? i18n.html("passwordlessEmailCodeInstructions", (0, _index2.getFieldValue)(model, "email")) : i18n.html("passwordlessSMSCodeInstructions", (0, _phone_number.humanPhoneNumberWithDiallingCode)(model)); return _react2.default.createElement(_vcode_pane2.default, { instructions: instructions, lock: model, placeholder: i18n.str("codeInputPlaceholder"), resendLabel: i18n.str("resendCodeAction"), onRestart: _actions.restart }); }; var VcodeScreen = function (_Screen) { _inherits(VcodeScreen, _Screen); function VcodeScreen() { _classCallCheck(this, VcodeScreen); return _possibleConstructorReturn(this, _Screen.call(this, "vcode")); } VcodeScreen.prototype.backHandler = function backHandler() { return _actions.restart; }; VcodeScreen.prototype.submitHandler = function submitHandler() { return _actions.logIn; }; VcodeScreen.prototype.renderAuxiliaryPane = function renderAuxiliaryPane(lock) { return (0, _signed_in_confirmation.renderSignedInConfirmation)(lock); }; VcodeScreen.prototype.render = function render() { return Component; }; return VcodeScreen; }(_screen2.default); exports.default = VcodeScreen;
// Generated by CoffeeScript 1.3.3 (function() { module.exports = { saucelabs: { username: '<USERNAME>', accessKey: '<KEY>' } }; }).call(this);
/*! * jQuery JavaScript Library v1.11.0 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseJSON,-ajax/parseXML,-ajax/script,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-dimensions,-effects,-effects/Tween,-effects/animatedSelector,-effects/support * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-09-24T05:23Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ // var deletedIds = []; var slice = deletedIds.slice; var concat = deletedIds.concat; var push = deletedIds.push; var indexOf = deletedIds.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var trim = "".trim; var support = {}; var version = "1.11.0 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseJSON,-ajax/parseXML,-ajax/script,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-dimensions,-effects,-effects/Tween,-effects/animatedSelector,-effects/support", // 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 ); }, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return a 'clean' array ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return just the object slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: deletedIds.sort, splice: deletedIds.splice }; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN return obj - parseFloat( obj ) >= 0; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( support.ownLast ) { for ( key in obj ) { return hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, type: function( obj ) { if ( obj == null ) { return obj + ""; } return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: trim && !trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( indexOf ) { return indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; while ( j < len ) { first[ i++ ] = second[ j++ ]; } // Support: IE<9 // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists) if ( len !== len ) { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: function() { return +( new Date() ); }, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v1.10.16 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-01-13 */ (function( window ) { var i, support, Expr, getText, isXML, compile, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // 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 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document (jQuery #6963) if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== strundefined && 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, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", function() { setDocument(); }, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", function() { setDocument(); }); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select t=''><option selected=''></option></select>"; // Support: IE8, Opera 10-12 // Nothing should be selected when empty strings follow ^= or $= or *= if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is 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(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (oldCache = outerCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements outerCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context !== document && context; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && 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 // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // Use the correct document accordingly with window argument (sandbox) document = window.document, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); jQuery.fn.extend({ has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); var rnotwhite = (/\S+/g); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !(--remaining) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } } }); /** * Clean-up method for dom ready events */ function detach() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } } /** * The ready event handler and self cleanup method */ function completed() { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; var strundefined = typeof undefined; // Support: IE<9 // Iteration over object's inherited properties before its own var i; for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Note: most support tests are defined in their respective modules. // false until the test is run support.inlineBlockNeedsLayout = false; jQuery(function() { // We need to execute this one support test ASAP because we need to know // if body.style.zoom needs to be set. var container, div, body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } // Setup container = document.createElement( "div" ); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; div = document.createElement( "div" ); body.appendChild( container ).appendChild( div ); if ( typeof div.style.zoom !== strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.style.cssText = "border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1"; if ( (support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 )) ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = null; }); (function() { var div = document.createElement( "div" ); // Execute the test only if not already executed in another module. if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch( e ) { support.deleteExpando = false; } } // Null elements to avoid leaks in IE. div = null; })(); /** * Determines whether an object can have data */ jQuery.acceptData = function( elem ) { var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ], nodeType = +elem.nodeType || 1; // Do not set data on non-element DOM nodes because it will not be cleared (#8335). return nodeType !== 1 && nodeType !== 9 ? false : // Nodes accept data unless otherwise specified; rejection can be conditional !noData || noData !== true && elem.getAttribute("classid") === noData; }; var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } function internalData( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements (space-suffixed to avoid Object.prototype collisions) // throw uncatchable exceptions if you attempt to set expando properties noData: { "applet ": true, "embed ": true, // ...but Flash objects (which have this classid) *can* handle expandos "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[0], attrs = elem && elem.attributes; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { i = attrs.length; while ( i-- ) { name = attrs[i].name; if ( name.indexOf("data-") === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { var fragment = document.createDocumentFragment(), div = document.createElement("div"), input = document.createElement("input"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a>"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName( "tbody" ).length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName( "link" ).length; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) input.type = "checkbox"; input.checked = true; fragment.appendChild( input ); support.appendChecked = input.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE6-IE11+ div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; // #11217 - WebKit loses check when the name is after the checked attribute fragment.appendChild( div ); div.innerHTML = "<input type='radio' checked='checked' name='t'/>"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() support.noCloneEvent = true; if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Execute the test only if not already executed in another module. if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch( e ) { support.deleteExpando = false; } } // Null elements to avoid leaks in IE. fragment = div = input = null; })(); (function() { var i, eventName, div = document.createElement( "div" ); // Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event) for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; if ( !(support[ i + "Bubbles" ] = eventName in window) ) { // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) div.setAttribute( eventName, "t" ); support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false; } } // Null elements to avoid leaks in IE. div = null; })(); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && ( // Support: IE < 9 src.returnValue === false || // Support: Android < 4.0 src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } jQuery._data( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); jQuery._removeData( doc, fix ); } else { jQuery._data( doc, fix, attaches ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!support.noCloneEvent || !support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } deletedIds.push( id ); } } } } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( support.htmlSerialize || !rnoshimcache.test( value ) ) && ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF window.getDefaultComputedStyle( elem[ 0 ] ).display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles, curCSS, rposition = /^(top|right|bottom|left)$/; if ( window.getComputedStyle ) { getStyles = function( elem ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); }; curCSS = function( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } // Support: IE // IE returns zIndex value as an integer. return ret === undefined ? ret : ret + ""; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, computed ) { var left, rs, rsLeft, ret, style = elem.style; computed = computed || getStyles( elem ); ret = computed ? computed[ name ] : undefined; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } // Support: IE // IE returns zIndex value as an integer. return ret === undefined ? ret : ret + "" || "auto"; }; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { var condition = conditionFn(); if ( condition == null ) { // The test was not ready at this point; screw the hook this time // but check again when needed next time. return; } if ( condition ) { // Hook not needed (or it's not possible to use it due to missing dependency), // remove it. // Since there are no other hooks for marginRight, remove the whole object. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; } (function() { var a, reliableHiddenOffsetsVal, boxSizingVal, boxSizingReliableVal, pixelPositionVal, reliableMarginRightVal, div = document.createElement( "div" ), containerStyles = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px", divReset = "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;" + "display:block;padding:0;margin:0;border:0"; // Setup div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName( "a" )[ 0 ]; a.style.cssText = "float:left;opacity:.5"; // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 support.opacity = /^0.5/.test( a.style.opacity ); // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!a.style.cssFloat; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Null elements to avoid leaks in IE. a = div = null; jQuery.extend(support, { reliableHiddenOffsets: function() { if ( reliableHiddenOffsetsVal != null ) { return reliableHiddenOffsetsVal; } var container, tds, isSupported, div = document.createElement( "div" ), body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body ) { // Return for frameset docs that don't have a body return; } // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; container = document.createElement( "div" ); container.style.cssText = containerStyles; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName( "td" ); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height reliableHiddenOffsetsVal = isSupported && ( tds[ 0 ].offsetHeight === 0 ); body.removeChild( container ); // Null elements to avoid leaks in IE. div = body = null; return reliableHiddenOffsetsVal; }, boxSizing: function() { if ( boxSizingVal == null ) { computeStyleTests(); } return boxSizingVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computeStyleTests(); } return boxSizingReliableVal; }, pixelPosition: function() { if ( pixelPositionVal == null ) { computeStyleTests(); } return pixelPositionVal; }, reliableMarginRight: function() { var body, container, div, marginDiv; // Use window.getComputedStyle because jsdom on node.js will break without it. if ( reliableMarginRightVal == null && window.getComputedStyle ) { body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body ) { // Test fired too early or in an unsupported environment, exit. return; } container = document.createElement( "div" ); div = document.createElement( "div" ); container.style.cssText = containerStyles; body.appendChild( container ).appendChild( div ); // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement( "div" ) ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; reliableMarginRightVal = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); body.removeChild( container ); } return reliableMarginRightVal; } }); function computeStyleTests() { var container, div, body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body ) { // Test fired too early or in an unsupported environment, exit. return; } container = document.createElement( "div" ); div = document.createElement( "div" ); container.style.cssText = containerStyles; body.appendChild( container ).appendChild( div ); div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;" + "position:absolute;display:block;padding:1px;border:1px;width:4px;" + "margin-top:1%;top:1%"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { boxSizingVal = div.offsetWidth === 4; }); // Will be changed later if needed. boxSizingReliableVal = true; pixelPositionVal = false; reliableMarginRightVal = true; // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; boxSizingReliableVal = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; } body.removeChild( container ); // Null elements to avoid leaks in IE. div = body = null; } })(); // A method for quickly swapping in/out CSS properties to get correct calculations. jQuery.swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = support.boxSizing() && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set. See: #7116 if ( value == null || value !== value ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Support: IE // Swallow errors from 'invalid' CSS values (#5509) try { // Support: Chrome, Safari // Setting style to blank string required to delete "style: x !important;" style[ name ] = ""; style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, support.boxSizing() && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }; (function() { var a, input, select, opt, div = document.createElement("div" ); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName("a")[ 0 ]; // First batch of tests. select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.hrefNormalized = a.getAttribute("href") === "/a"; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !!input.value; // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE8 only // Check if we can trust getAttribute("value") input = document.createElement( "input" ); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // Null elements to avoid leaks in IE. a = input = select = opt = div = null; })(); var rreturn = /\r/g; jQuery.fn.extend({ val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : jQuery.text( elem ); } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) { // Support: IE6 // When new option element is added to select box we need to // force reflow of newly added node in order to workaround delay // of initialization properties try { option.selected = optionSet = true; } catch ( _ ) { // Will be executed only in IE6 option.scrollHeight; } } else { option.selected = false; } } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return options; } } } }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = support.getSetAttribute, getSetInput = support.input; jQuery.fn.extend({ attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); } }); jQuery.extend({ attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } } }); // Hook for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; // Retrieve booleans specially jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; } : function( elem, name, isXML ) { if ( !isXML ) { return elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; } }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) if ( name === "value" || value === elem.getAttribute( name ) ) { return value; } } }; // Some attributes are constructed with empty-string values when not defined attrHandle.id = attrHandle.name = attrHandle.coords = function( elem, name, isXML ) { var ret; if ( !isXML ) { return (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; } }; // Fixing value retrieval on a button requires this module jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); if ( ret && ret.specified ) { return ret.value; } }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }; }); } if ( !support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } var rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend({ prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); } }); jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } } }); // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } // Support: Safari, IE9+ // mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !support.enctype ) { jQuery.propFix.enctype = "encoding"; } var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // only assign if different to avoid unneeded rendering. finalValue = value ? jQuery.trim( cur ) : ""; if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; } }); // Return jQuery for attributes-only inclusion jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); jQuery.fn.extend({ wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!support.reliableHiddenOffsets() && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function() { var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); }) .map(function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; var docElem = window.document.documentElement; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [ curCSSTop, curCSSLeft ] ) > -1; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); }); // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; }));
'use strict'; module.exports = { env: { commonjs: true, browser: true, }, globals: { // ES6 Map: true, Set: true, Symbol: true, Proxy: true, WeakMap: true, WeakSet: true, Uint16Array: true, // Vendor specific MSApp: true, __REACT_DEVTOOLS_GLOBAL_HOOK__: true, // FB __DEV__: true, // Node.js Server Rendering setImmediate: true, Buffer: true, // Trusted Types trustedTypes: true, // Scheduler profiling SharedArrayBuffer: true, Int32Array: true, ArrayBuffer: true, }, parserOptions: { ecmaVersion: 5, sourceType: 'script', }, rules: { 'no-undef': 'error', 'no-shadow-restricted-names': 'error', }, // These plugins aren't used, but eslint complains if an eslint-ignore comment // references unused plugins. An alternate approach could be to strip // eslint-ignore comments as part of the build. plugins: ['jest', 'no-for-of-loops', 'react', 'react-internal'], };
import { isInteger } from 'lodash'; /** * Given an input the function will return an number. * * @param {object} input - The input to be converted. * * @returns {number} - The converted result. */ export default function toInteger(input) { if (isInteger(input)) { return input; } return parseInt(input, 10); }
define({ "sourceSetting": "Setări sursă căutare", "instruction": "Adăugaţi şi configuraţi servicii de geocodificare sau straturi tematice de obiecte spaţiale ca surse de căutare. Aceste surse specificate stabilesc ce este căutabil în cadrul casetei de căutare.", "add": "Adăugare sursă căutare", "addGeocoder": "Adăugare geocodificator", "geocoder": "Geocodificator", "setLayerSource": "Setare sursă straturi tematice", "setGeocoderURL": "Setare URL geocodificator", "searchableLayer": "Strat tematic de obiecte spaţiale", "name": "Nume", "countryCode": "Cod(uri) ţară sau regiune", "countryCodeEg": "de ex. ", "countryCodeHint": "Dacă lăsaţi această valoare necompletată, vor fi căutate toate ţările şi regiunile", "generalSetting": "Setări generale", "allPlaceholder": "Text substituent pentru căutarea tuturor: ", "showInfoWindowOnSelect": "Afişaţi fereastra pop-up pentru obiectul spaţial sau locul găsit", "showInfoWindowOnSelect2": "Afișare pop-up când se găsește caracteristica sau amplasarea.", "searchInCurrentMapExtent": "Căutaţi doar în extinderea de hartă curentă", "zoomScale": "Scară de transfocare", "locatorUrl": "URL geocodificator", "locatorName": "Nume geocodificator", "locatorExample": "Exemplu", "locatorWarning": "Această versiune de serviciu de geocodificare nu este acceptată. Widgetul acceptă serviciul de geocodificare versiunea 10.1 sau ulterioară.", "locatorTips": "Sugestiile nu sunt disponibile, deoarece serviciul de geocodificare nu acceptă capacitatea de sugestie.", "layerSource": "Sursă straturi tematice", "searchLayerTips": "Sugestiile nu sunt disponibile, deoarece serviciul de obiecte spațiale nu acceptă capacitatea de paginare.", "placeholder": "Text substituent", "searchFields": "Câmpuri de căutare", "displayField": "Câmp de afişare", "exactMatch": "Potrivire exactă", "maxSuggestions": "Sugestii de valori maxime", "maxResults": "Număr maxim de rezultate", "enableLocalSearch": "Activare căutare locală", "minScale": "Scară minimă", "minScaleHint": "Dacă scara hărţii este mai mare decât această scară, va fi aplicată căutarea locală", "radius": "Rază", "radiusHint": "Specifică raza unei suprafeţe din jurul centrului actual al hărţii, utilizată pentru a creşte clasificarea candidaţilor de geocodificare, astfel încât candidaţii cei mai apropiaţi de locaţie să fie returnaţi primii", "meters": "Metri", "setSearchFields": "Setare câmpuri de căutare", "set": "Setare", "fieldSearchable": "poate fi căutat", "fieldName": "Nume", "fieldAlias": "Pseudonim", "ok": "OK", "cancel": "Anulare", "invalidUrlTip": "Adresa URL ${URL} este nevalidă sau inaccesibilă.", "locateResults": "Localizare rezultate", "panTo": "Panoramare la", "zoomToScale": "Zoom la scară" });
Carnival.batchActionInitialize = function(noItemsMessage){ Carnival.batchActionSelected(); Carnival.batchActionToggleAllItems(); Carnival.batchActionSubmit(noItemsMessage); } Carnival.batchActionFunction = function(){ var value = $(this).val(); if($(this).is(':checked')){ $(this).parent().parent().addClass('batch_action_item_selected'); Carnival.batch_action_items.push(value); }else{ $(this).parent().parent().removeClass('batch_action_item_selected'); Carnival.batch_action_items = Carnival.batch_action_items.filter(function(item){ return item != value; }) } } Carnival.batchActionSelected = function(){ Carnival.batch_action_items = [] $('.batch_action_items').click(Carnival.batchActionFunction); } Carnival.batchActionToggleAllItems = function(){ $('#toggle-all-batch-actions-items').click(function(){ var checked = this.checked; $('.batch_action_items').each(function(){ $(this).prop('checked', checked).triggerHandler('click'); }); }); } Carnival.batchActionSubmit = function(noItemsMessage){ $('.batch_action_button').click(function(){ if(Carnival.batch_action_items.length == 0){ alert(noItemsMessage); return false; } $(this).parents('form').append('<input type="hidden" value="' + Carnival.batch_action_items + '" name="batch_action_items" />'); }); } Carnival.batchActionSuccessCallback = function(data, status, jqXHR){ Carnival.reloadIndexPage(); } Carnival.batchActionErrorCallback = function(jqXHR, status, error){ Carnival.reloadIndexPage(); }
/** * promisify takes an asynchronous function that uses node style callbacks * and returns a function that will return a promise instead. * const promisified = promisify(fn); * Invoking the original function (fn) may have looked something like this: * fn((error, data) => { * if (error) handleError(); * else doSomethingWith(data); * }); * Whereas the promisifed function (fn) would be used like this: * promisifed() * .then((data) => { * doSomethingWith(data); * }) * .catch((error) => { * handleError(); * }); * @param {Function} fn aynchronous function to promisify * @return {Function} function that will return a promise */ function promisify (fn) { // Your Code Here } module.exports = promisify;
var gulp = require('gulp'), fs = require('fs'), clean = require("gulp-clean"), uglify = require("gulp-uglify"), concat = require("gulp-concat"), header = require("gulp-header"), zip = require("gulp-zip"), runSequence = require('run-sequence'); var getVersion = function () { info = require("./package.json"); return info.version; }; var getCopyright = function () { return fs.readFileSync('Copyright'); }; gulp.task('js', function () { // Concatenate and Minify JS return gulp.src(['./src/blockrain.jquery.libs.js', './src/blockrain.jquery.src.js', './src/blockrain.jquery.themes.js']) .pipe(concat('blockrain.jquery.js')) .pipe(header(getCopyright(), {version: getVersion()})) .pipe(gulp.dest('./dist')) .pipe(uglify({preserveComments:'none'})) .pipe(concat('blockrain.jquery.min.js')) .pipe(header(getCopyright(), {version: getVersion()})) .pipe(gulp.dest('./dist')); }); gulp.task('css', function () { // CSS return gulp.src(['./src/blockrain.css']) .pipe(gulp.dest('./dist')); }); gulp.task('blocks', function () { // CSS return gulp.src(['./assets/blocks/custom/*.*']) .pipe(gulp.dest('./dist/assets/blocks/custom')); }); gulp.task('readme', function () { // Readme return gulp.src(['./README.md']) .pipe(gulp.dest('./dist')); }); gulp.task('clean', function () { return gulp.src('./dist', {read: false}) .pipe(clean()); }); gulp.task('dist', function () { // Create a ZIP File return gulp.src(['./dist/**/*.*']) .pipe(zip('blockrain.zip')) .pipe(gulp.dest('./dist')); }); gulp.task('build', function(callback){ runSequence('clean', 'js', 'css', 'blocks', 'readme', 'dist', callback); }); gulp.task('default', ['build']);
/** * ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v21.2.1 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var popupComponent_1 = require("../widgets/popupComponent"); var TooltipComponent = /** @class */ (function (_super) { __extends(TooltipComponent, _super); function TooltipComponent() { return _super.call(this, "<div class=\"ag-tooltip\"></div>") || this; } // will need to type params TooltipComponent.prototype.init = function (params) { var value = params.value; this.getGui().innerHTML = value; }; return TooltipComponent; }(popupComponent_1.PopupComponent)); exports.TooltipComponent = TooltipComponent;
import React from 'react'; import { shallow } from 'enzyme'; import Header from '../index'; describe('Header', () => { it('renders without crashing', () => { shallow(<Header />); }); });
/* Language: Dart Requires: markdown.js Author: Maxim Dikun <dikmax@gmail.com> Description: Dart a modern, object-oriented language developed by Google. For more information see https://www.dartlang.org/ Website: https://dart.dev Category: scripting */ function dart(hljs) { const SUBST = { className: 'subst', variants: [{ begin: '\\$[A-Za-z0-9_]+' }], }; const BRACED_SUBST = { className: 'subst', variants: [{ begin: '\\${', end: '}' }], keywords: 'true false null this is new super', }; const STRING = { className: 'string', variants: [{ begin: 'r\'\'\'', end: '\'\'\'' }, { begin: 'r"""', end: '"""' }, { begin: 'r\'', end: '\'', illegal: '\\n' }, { begin: 'r"', end: '"', illegal: '\\n' }, { begin: '\'\'\'', end: '\'\'\'', contains: [hljs.BACKSLASH_ESCAPE, SUBST, BRACED_SUBST] }, { begin: '"""', end: '"""', contains: [hljs.BACKSLASH_ESCAPE, SUBST, BRACED_SUBST] }, { begin: '\'', end: '\'', illegal: '\\n', contains: [hljs.BACKSLASH_ESCAPE, SUBST, BRACED_SUBST] }, { begin: '"', end: '"', illegal: '\\n', contains: [hljs.BACKSLASH_ESCAPE, SUBST, BRACED_SUBST] } ] }; BRACED_SUBST.contains = [ hljs.C_NUMBER_MODE, STRING ]; const BUILT_IN_TYPES = [ // dart:core 'Comparable', 'DateTime', 'Duration', 'Function', 'Iterable', 'Iterator', 'List', 'Map', 'Match', 'Object', 'Pattern', 'RegExp', 'Set', 'Stopwatch', 'String', 'StringBuffer', 'StringSink', 'Symbol', 'Type', 'Uri', 'bool', 'double', 'int', 'num', // dart:html 'Element', 'ElementList', ]; const NULLABLE_BUILT_IN_TYPES = BUILT_IN_TYPES.map((e) => `${e}?`); const KEYWORDS = { keyword: 'abstract as assert async await break case catch class const continue covariant default deferred do ' + 'dynamic else enum export extends extension external factory false final finally for Function get hide if ' + 'implements import in inferface is late library mixin new null on operator part required rethrow return set ' + 'show static super switch sync this throw true try typedef var void while with yield', built_in: BUILT_IN_TYPES .concat(NULLABLE_BUILT_IN_TYPES) .concat([ // dart:core 'Never', 'Null', 'dynamic', 'print', // dart:html 'document', 'querySelector', 'querySelectorAll', 'window', ]).join(' '), $pattern: /[A-Za-z][A-Za-z0-9_]*\??/ }; return { name: 'Dart', keywords: KEYWORDS, contains: [ STRING, hljs.COMMENT( '/\\*\\*', '\\*/', { subLanguage: 'markdown', relevance:0 } ), hljs.COMMENT( '///+\\s*', '$', { contains: [{ subLanguage: 'markdown', begin: '.', end: '$', relevance:0 }] } ), hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE, { className: 'class', beginKeywords: 'class interface', end: '{', excludeEnd: true, contains: [{ beginKeywords: 'extends implements' }, hljs.UNDERSCORE_TITLE_MODE ] }, hljs.C_NUMBER_MODE, { className: 'meta', begin: '@[A-Za-z]+' }, { begin: '=>' // No markup, just a relevance booster } ] }; } module.exports = dart;
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; }; import { Cordova, Plugin } from './plugin'; /** * @name Dialogs * @description * This plugin gives you ability to access and customize the device native dialogs. * * Requires Cordova plugin: `cordova-plugin-dialogs`. For more info, please see the [Dialogs plugin docs](https://github.com/apache/cordova-plugin-dialogs). * * @usage * ```typescript * import { Dialogs } from 'ionic-native'; * * * * * ``` * @interfaces * DialogsPromptCallback */ export var Dialogs = (function () { function Dialogs() { } /** * Shows a custom alert or dialog box. * @param {string} message Dialog message. * @param {string} title Dialog title. (Optional, defaults to Alert) * @param {string} buttonName Button name. (Optional, defaults to OK) * @returns {Promise<any>} Returns a blank promise once the user has dismissed the alert. */ Dialogs.alert = function (message, title, buttonName) { if (title === void 0) { title = 'Alert'; } if (buttonName === void 0) { buttonName = 'OK'; } return; }; /** * Displays a customizable confirmation dialog box. * @param {string} message Dialog message. * @param {string} title Dialog title. (Optional, defaults to Confirm) * @param {Array<string>} buttonLabels Array of strings specifying button labels. (Optional, defaults to [OK,Cancel]) * @returns {Promise<number>} Returns a promise that resolves the button index that was clicked. Note that the index use one-based indexing. */ Dialogs.confirm = function (message, title, buttonLabels) { if (title === void 0) { title = 'Confirm'; } if (buttonLabels === void 0) { buttonLabels = ['OK', 'Cancel']; } return; }; /** * Displays a native dialog box that is more customizable than the browser's prompt function. * @param {string} message Dialog message. * @param {string} title Dialog title. (Optional, defaults to Prompt) * @param {Array<string>} buttonLabels Array of strings specifying button labels. (Optional, defaults to ["OK","Cancel"]) * @param {string} defaultText Default textbox input value. (Optional, Default: empty string) * @returns {Promise<DialogsPromptCallback>} Returns a promise that resolves an object with the button index clicked and the text entered */ Dialogs.prompt = function (message, title, buttonLabels, defaultText) { if (title === void 0) { title = 'Prompt'; } if (buttonLabels === void 0) { buttonLabels = ['OK', 'Cancel']; } if (defaultText === void 0) { defaultText = ''; } return; }; /** * The device plays a beep sound. * @param {numbers} times The number of times to repeat the beep. */ Dialogs.beep = function (times) { }; __decorate([ Cordova({ successIndex: 1, errorIndex: 4 }) ], Dialogs, "alert", null); __decorate([ Cordova({ successIndex: 1, errorIndex: 4 }) ], Dialogs, "confirm", null); __decorate([ Cordova({ successIndex: 1, errorIndex: 5 }) ], Dialogs, "prompt", null); __decorate([ Cordova({ sync: true }) ], Dialogs, "beep", null); Dialogs = __decorate([ Plugin({ pluginName: 'Dialogs', plugin: 'cordova-plugin-dialogs', pluginRef: 'navigator.notification', repo: 'https://github.com/apache/cordova-plugin-dialogs.git' }) ], Dialogs); return Dialogs; }()); //# sourceMappingURL=dialogs.js.map
import axios from 'axios'; import config from 'config/environment.js'; const codeSchoolsData = { getCodeSchools() { return axios.get(`${config.backendUrl}/code_schools`); } }; export default codeSchoolsData;
"use strict";var cluster=require("cluster"),clusterId=cluster.isMaster?0:cluster.worker.id;module.exports=parseInt(process.env.NODE_UNIQUE_ID||clusterId,10);
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose")); var React = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _clsx = _interopRequireDefault(require("clsx")); var _utils = require("@material-ui/utils"); var _unstyled = require("@material-ui/unstyled"); var _SelectInput = _interopRequireDefault(require("./SelectInput")); var _formControlState = _interopRequireDefault(require("../FormControl/formControlState")); var _useFormControl = _interopRequireDefault(require("../FormControl/useFormControl")); var _ArrowDropDown = _interopRequireDefault(require("../internal/svg-icons/ArrowDropDown")); var _Input = _interopRequireDefault(require("../Input")); var _NativeSelectInput = _interopRequireDefault(require("../NativeSelect/NativeSelectInput")); var _FilledInput = _interopRequireDefault(require("../FilledInput")); var _OutlinedInput = _interopRequireDefault(require("../OutlinedInput")); var _useThemeProps = _interopRequireDefault(require("../styles/useThemeProps")); var _selectClasses = require("./selectClasses"); var _jsxRuntime = require("react/jsx-runtime"); const useUtilityClasses = styleProps => { const { classes } = styleProps; const slots = { root: ['root'] }; return (0, _unstyled.unstable_composeClasses)(slots, _selectClasses.getSelectUtilityClasses, classes); }; var _ref = /*#__PURE__*/(0, _jsxRuntime.jsx)(_Input.default, {}); var _ref2 = /*#__PURE__*/(0, _jsxRuntime.jsx)(_FilledInput.default, {}); const Select = /*#__PURE__*/React.forwardRef(function Select(inProps, ref) { const props = (0, _useThemeProps.default)({ name: 'MuiSelect', props: inProps }); const { autoWidth = false, children, classes: classesProp = {}, className, displayEmpty = false, IconComponent = _ArrowDropDown.default, id, input, inputProps, label, labelId, MenuProps, multiple = false, native = false, onClose, onOpen, open, renderValue, SelectDisplayProps, variant: variantProps = 'outlined' } = props, other = (0, _objectWithoutPropertiesLoose2.default)(props, ["autoWidth", "children", "classes", "className", "displayEmpty", "IconComponent", "id", "input", "inputProps", "label", "labelId", "MenuProps", "multiple", "native", "onClose", "onOpen", "open", "renderValue", "SelectDisplayProps", "variant"]); const inputComponent = native ? _NativeSelectInput.default : _SelectInput.default; const muiFormControl = (0, _useFormControl.default)(); const fcs = (0, _formControlState.default)({ props, muiFormControl, states: ['variant'] }); const variant = fcs.variant || variantProps; const InputComponent = input || { standard: _ref, outlined: /*#__PURE__*/(0, _jsxRuntime.jsx)(_OutlinedInput.default, { label: label }), filled: _ref2 }[variant]; const styleProps = (0, _extends2.default)({}, props, { classes: classesProp }); const classes = useUtilityClasses(styleProps); const otherClasses = (0, _objectWithoutPropertiesLoose2.default)(classesProp, ["root"]); return /*#__PURE__*/React.cloneElement(InputComponent, (0, _extends2.default)({ // Most of the logic is implemented in `SelectInput`. // The `Select` component is a simple API wrapper to expose something better to play with. inputComponent, inputProps: (0, _extends2.default)({ children, IconComponent, variant, type: undefined, // We render a select. We can ignore the type provided by the `Input`. multiple }, native ? { id } : { autoWidth, displayEmpty, labelId, MenuProps, onClose, onOpen, open, renderValue, SelectDisplayProps: (0, _extends2.default)({ id }, SelectDisplayProps) }, inputProps, { classes: inputProps ? (0, _utils.deepmerge)(otherClasses, inputProps.classes) : otherClasses }, input ? input.props.inputProps : {}) }, multiple && native && variant === 'outlined' ? { notched: true } : {}, { ref, className: (0, _clsx.default)(classes.root, InputComponent.props.className, className) }, other)); }); process.env.NODE_ENV !== "production" ? Select.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * If `true`, the width of the popover will automatically be set according to the items inside the * menu, otherwise it will be at least the width of the select input. * @default false */ autoWidth: _propTypes.default.bool, /** * The option elements to populate the select with. * Can be some `MenuItem` when `native` is false and `option` when `native` is true. * * ⚠️The `MenuItem` elements **must** be direct descendants when `native` is false. */ children: _propTypes.default.node, /** * Override or extend the styles applied to the component. * @default {} */ classes: _propTypes.default.object, /** * @ignore */ className: _propTypes.default.string, /** * The default value. Use when the component is not controlled. */ defaultValue: _propTypes.default.any, /** * If `true`, a value is displayed even if no items are selected. * * In order to display a meaningful value, a function can be passed to the `renderValue` prop which * returns the value to be displayed when no items are selected. * * ⚠️ When using this prop, make sure the label doesn't overlap with the empty displayed value. * The label should either be hidden or forced to a shrunk state. * @default false */ displayEmpty: _propTypes.default.bool, /** * The icon that displays the arrow. * @default ArrowDropDownIcon */ IconComponent: _propTypes.default.elementType, /** * The `id` of the wrapper element or the `select` element when `native`. */ id: _propTypes.default.string, /** * An `Input` element; does not have to be a material-ui specific `Input`. */ input: _propTypes.default.element, /** * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element. * When `native` is `true`, the attributes are applied on the `select` element. */ inputProps: _propTypes.default.object, /** * See [OutlinedInput#label](/api/outlined-input/#props) */ label: _propTypes.default.node, /** * The ID of an element that acts as an additional label. The Select will * be labelled by the additional label and the selected value. */ labelId: _propTypes.default.string, /** * Props applied to the [`Menu`](/api/menu/) element. */ MenuProps: _propTypes.default.object, /** * If `true`, `value` must be an array and the menu will support multiple selections. * @default false */ multiple: _propTypes.default.bool, /** * If `true`, the component uses a native `select` element. * @default false */ native: _propTypes.default.bool, /** * Callback fired when a menu item is selected. * * @param {object} event The event source of the callback. * You can pull out the new value by accessing `event.target.value` (any). * **Warning**: This is a generic event not a change event. * @param {object} [child] The react element that was selected when `native` is `false` (default). */ onChange: _propTypes.default.func, /** * Callback fired when the component requests to be closed. * Use in controlled mode (see open). * * @param {object} event The event source of the callback. */ onClose: _propTypes.default.func, /** * Callback fired when the component requests to be opened. * Use in controlled mode (see open). * * @param {object} event The event source of the callback. */ onOpen: _propTypes.default.func, /** * If `true`, the component is shown. * You can only use it when the `native` prop is `false` (default). */ open: _propTypes.default.bool, /** * Render the selected value. * You can only use it when the `native` prop is `false` (default). * * @param {any} value The `value` provided to the component. * @returns {ReactNode} */ renderValue: _propTypes.default.func, /** * Props applied to the clickable div element. */ SelectDisplayProps: _propTypes.default.object, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: _propTypes.default.object, /** * The `input` value. Providing an empty string will select no options. * Set to an empty string `''` if you don't want any of the available options to be selected. * * If the value is an object it must have reference equality with the option in order to be selected. * If the value is not an object, the string representation must match with the string representation of the option in order to be selected. */ value: _propTypes.default.any, /** * The variant to use. * @default 'outlined' */ variant: _propTypes.default.oneOf(['filled', 'outlined', 'standard']) } : void 0; Select.muiName = 'Select'; var _default = Select; exports.default = _default;
import click from './mouse_click'; import setupAfterNextRender from './after_next_render'; import makeMouseEvent from './make_mouse_event'; /** * Draws a feature on a map. */ const mapFeaturesToModes = { Polygon: 'draw_polygon', Point: 'draw_point', LineString: 'draw_line_string' }; export default function drawGeometry(map, draw, type, coordinates, cb) { const afterNextRender = setupAfterNextRender(map); draw.changeMode(mapFeaturesToModes[type]); let drawCoordinates; if (type === 'Polygon') drawCoordinates = coordinates[0]; if (type === 'Point') drawCoordinates = [coordinates]; if (type === 'LineString') drawCoordinates = coordinates; const addCoordinate = function(idx) { const point = drawCoordinates[idx]; if (point === undefined) { return cb(); } click(map, makeMouseEvent(point[0], point[1], false)); afterNextRender(() => { addCoordinate(idx + 1); }); }; addCoordinate(0); }
import Vue from 'vue'; import Vuex from 'vuex'; import * as actions from './actions'; import * as getters from './getters'; import mutations from './mutations'; import createState from './state'; Vue.use(Vuex); export const createStore = (initialState = {}) => new Vuex.Store({ actions, getters, mutations, state: createState(initialState), });
const db = require('../../db/db-config.js'); const Engineer = db.Model.extend({ tableName: 'engineers', hasTimestamps: false }); module.exports = Engineer;
version https://git-lfs.github.com/spec/v1 oid sha256:eebc58d23ab19607da96502f922d1eaebe540a28319c4eed5a512157520157d2 size 1046
var crypto = require('crypto'), Socket = require('net').Socket, dnsLookup = require('dns').lookup, EventEmitter = require('events').EventEmitter, inherits = require('util').inherits; var ssh2_streams = require('ssh2-streams'), SSH2Stream = ssh2_streams.SSH2Stream, SFTPStream = ssh2_streams.SFTPStream, consts = ssh2_streams.constants, parseKey = ssh2_streams.utils.parseKey, decryptKey = ssh2_streams.utils.decryptKey, genPublicKey = ssh2_streams.utils.genPublicKey; var Channel = require('./Channel'), agentQuery = require('./agent'), SFTPWrapper = require('./SFTPWrapper'), spliceOne = require('./utils').spliceOne; var MAX_CHANNEL = Math.pow(2, 32) - 1, RE_OPENSSH = /^OpenSSH_[56]/, DEBUG_NOOP = function(msg) {}; function Client() { if (!(this instanceof Client)) return new Client(); EventEmitter.call(this); this.config = { host: undefined, port: undefined, forceIPv4: undefined, forceIPv6: undefined, keepaliveCountMax: undefined, keepaliveInterval: undefined, readyTimeout: undefined, compress: undefined, username: undefined, password: undefined, privateKey: undefined, publicKey: undefined, tryKeyboard: undefined, agent: undefined, allowAgentFwd: undefined, hostHashAlgo: undefined, hostHashCb: undefined, strictVendor: undefined, debug: undefined }; this._readyTimeout = undefined; this._channels = undefined; this._callbacks = undefined; this._forwarding = undefined; this._acceptX11 = undefined; this._agentFwdEnabled = undefined; this._curChan = undefined; this._remoteVer = undefined; this._sshstream = undefined; this._sock = undefined; this._resetKA = undefined; } inherits(Client, EventEmitter); Client.prototype.connect = function(cfg) { var self = this; if (this._sock && this._sock.writable) { this.once('close', function() { self.connect(cfg); }); this.end(); return; } this.config.host = cfg.hostname || cfg.host || 'localhost'; this.config.port = cfg.port || 22; this.config.forceIPv4 = cfg.forceIPv4 || false; this.config.forceIPv6 = cfg.forceIPv6 || false; this.config.keepaliveCountMax = (typeof cfg.keepaliveCountMax === 'number' && cfg.keepaliveCountMax >= 0 ? cfg.keepaliveCountMax : 3); this.config.keepaliveInterval = (typeof cfg.keepaliveInterval === 'number' && cfg.keepaliveInterval > 0 ? cfg.keepaliveInterval : 0); this.config.readyTimeout = (typeof cfg.readyTimeout === 'number' && cfg.readyTimeout >= 0 ? cfg.readyTimeout : 20000); this.config.compress = cfg.compress; this.config.username = cfg.username || cfg.user; this.config.password = (typeof cfg.password === 'string' ? cfg.password : undefined); this.config.privateKey = (typeof cfg.privateKey === 'string' || Buffer.isBuffer(cfg.privateKey) ? cfg.privateKey : undefined); this.config.publicKey = undefined; this.config.localHostname = (typeof cfg.localHostname === 'string' && cfg.localHostname.length ? cfg.localHostname : undefined); this.config.localUsername = (typeof cfg.localUsername === 'string' && cfg.localUsername.length ? cfg.localUsername : undefined); this.config.tryKeyboard = (cfg.tryKeyboard === true); this.config.agent = (typeof cfg.agent === 'string' && cfg.agent.length ? cfg.agent : undefined); this.config.allowAgentFwd = (cfg.agentForward === true && this.config.agent !== undefined); this.config.strictVendor = (typeof cfg.strictVendor === 'boolean' ? cfg.strictVendor : true); var debug = this.config.debug = (typeof cfg.debug === 'function' ? cfg.debug : DEBUG_NOOP); if (typeof this.config.username !== 'string') throw new Error('Invalid username'); if (cfg.agentForward === true && !this.config.allowAgentFwd) throw new Error('You must set a valid agent path to allow agent forwarding'); if (this.config.readyTimeout > 0) { this._readyTimeout = setTimeout(function() { var err = new Error('Timed out while waiting for handshake'); err.level = 'client-timeout'; self.emit('error', err); sock.destroy(); }, this.config.readyTimeout); } var callbacks = this._callbacks = []; this._channels = []; this._forwarding = []; this._acceptX11 = 0; this._agentFwdEnabled = false; this._curChan = -1; this._remoteVer = undefined; if (this.config.privateKey) { var privKeyInfo = parseKey(this.config.privateKey); if (privKeyInfo instanceof Error) throw new Error('Cannot parse privateKey: ' + privKeyInfo.message); if (!privKeyInfo.private) throw new Error('privateKey value does not contain a (valid) private key'); if (privKeyInfo.encryption) { if (typeof cfg.passphrase !== 'string') throw new Error('Encrypted private key detected, but no passphrase given'); decryptKey(privKeyInfo, cfg.passphrase); } this.config.privateKey = privKeyInfo; this.config.publicKey = genPublicKey(privKeyInfo); } var stream = this._sshstream = new SSH2Stream({ debug: (debug === DEBUG_NOOP ? undefined : debug) }), sock = this._sock = (cfg.sock || new Socket()); // drain stderr if we are connection hopping using an exec stream if (this._sock.stderr) this._sock.stderr.resume(); // keepalive-related var kainterval = this.config.keepaliveInterval, kacountmax = this.config.keepaliveCountMax, kacount = 0, katimer; function sendKA() { if (++kacount > kacountmax) { clearInterval(katimer); if (stream.readable) { var err = new Error('Keepalive timeout'); err.level = 'client-timeout'; self.emit('error', err); sock.destroy(); } return; } if (stream.writable) { // append dummy callback to keep correct callback order callbacks.push(resetKA); stream.ping(); } else clearInterval(katimer); } function resetKA() { if (kainterval > 0) { kacount = 0; clearInterval(katimer); if (stream.writable) katimer = setInterval(sendKA, kainterval); } } this._resetKA = resetKA; sock.on('connect', function() { debug('DEBUG: Client: Connected'); self.emit('connect'); }).on('timeout', function() { self.emit('timeout'); }).on('error', function(err) { clearTimeout(self._readyTimeout); err.level = 'client-socket'; self.emit('error', err); }).on('end', function() { clearTimeout(self._readyTimeout); clearInterval(katimer); self.emit('end'); }).on('close', function() { clearTimeout(self._readyTimeout); clearInterval(katimer); self.emit('close'); // notify outstanding channel requests of disconnection ... var callbacks_ = callbacks, err = new Error('No response from server'); callbacks = self._callbacks = []; for (var i = 0; i < callbacks_.length; ++i) callbacks_[i](err); // simulate error for any channels waiting to be opened. this is safe // against successfully opened channels because the success and failure // event handlers are automatically removed when a success/failure response // is received var channels_ = self._channels; self._channels = []; for (var i = 0; i < channels_.length; ++i) { stream.emit('CHANNEL_OPEN_FAILURE:' + channels_[i], err); // emitting CHANNEL_CLOSE should be safe too and should help for any // special channels which might otherwise keep the process alive, such // as agent forwarding channels which have open unix sockets ... stream.emit('CHANNEL_CLOSE:' + channels_[i]); } }); stream.on('drain', function() { self.emit('drain'); }).once('header', function(header) { self._remoteVer = header.versions.software; }).on('continue', function() { self.emit('continue'); }); if (typeof cfg.hostVerifier === 'function' && ~crypto.getHashes().indexOf(cfg.hostHash)) { var hashCb = cfg.hostVerifier, hasher = crypto.createHash(cfg.hostHash); stream.once('fingerprint', function(key, verify) { hasher.update(key, 'binary'); verify(hashCb(hasher.digest('hex'))); }); } // begin authentication handling ============================================= var auths = [], curAuth, agentKeys, agentKeyPos = 0; if (this.config.password !== undefined) auths.push('password'); if (this.config.publicKey !== undefined) auths.push('publickey'); if (this.config.agent !== undefined) auths.push('agent'); if (this.config.tryKeyboard) auths.push('keyboard-interactive'); if (this.config.publicKey !== undefined && this.config.localHostname !== undefined && this.config.localUsername !== undefined) auths.push('hostbased'); auths.push('none'); function tryNextAuth() { // TODO: better shutdown if (!auths.length) { stream.removeListener('USERAUTH_FAILURE', onUSERAUTH_FAILURE); stream.removeListener('USERAUTH_PK_OK', onUSERAUTH_PK_OK); var err = new Error('All configured authentication methods failed'); err.level = 'client-authentication'; self.emit('error', err); if (stream.writable) self.end(); return; } curAuth = auths.shift(); switch (curAuth) { case 'password': stream.authPassword(self.config.username, self.config.password); break; case 'publickey': stream.authPK(self.config.username, self.config.publicKey); stream.once('USERAUTH_PK_OK', onUSERAUTH_PK_OK); break; case 'hostbased': function hostbasedCb(buf, cb) { var signature = crypto.createSign(self.config.privateKey.type === 'rsa' ? 'RSA-SHA1' : 'DSA-SHA1'); signature.update(buf); signature = signature.sign(self.config.privateKey.privateOrig, 'binary'); signature = new Buffer(signature, 'binary'); if (self.config.privateKey.type === 'dss' && signature.length > 40) { // this is a quick and dirty way to get from DER encoded r and s that // OpenSSL gives us, to just the bare values back to back (40 bytes // total) like OpenSSH (and possibly others) are expecting var newsig = new Buffer(40), rlen = signature[3], rstart = 4, sstart = 4 + 1 + rlen + 1; while (signature[rstart] === 0) ++rstart; while (signature[sstart] === 0) ++sstart; signature.copy(newsig, 0, rstart, rstart + 20); signature.copy(newsig, 20, sstart, sstart + 20); signature = newsig; } cb(signature); } stream.authHostbased(self.config.username, self.config.publicKey, self.config.localHostname, self.config.localUsername, hostbasedCb); break; case 'agent': agentQuery(self.config.agent, function(err, keys) { if (err) { err.level = 'agent'; self.emit('error', err); agentKeys = undefined; return tryNextAuth(); } else if (keys.length === 0) { debug('DEBUG: Agent: No keys stored in agent'); agentKeys = undefined; return tryNextAuth(); } agentKeys = keys; agentKeyPos = 0; stream.authPK(self.config.username, keys[0]); stream.once('USERAUTH_PK_OK', onUSERAUTH_PK_OK); }); break; case 'keyboard-interactive': stream.authKeyboard(self.config.username); stream.on('USERAUTH_INFO_REQUEST', onUSERAUTH_INFO_REQUEST); break; case 'none': stream.authNone(self.config.username); break; } } function onUSERAUTH_INFO_REQUEST(name, instructions, lang, prompts) { var nprompts = (Array.isArray(prompts) ? prompts.length : 0); if (nprompts === 0) { debug('DEBUG: Client: Sending automatic USERAUTH_INFO_RESPONSE'); return stream.authInfoRes(); } // we sent a keyboard-interactive user authentication request and now the // server is sending us the prompts we need to present to the user self.emit('keyboard-interactive', name, instructions, lang, prompts, function(answers) { stream.authInfoRes(answers); }); } function onUSERAUTH_PK_OK(keyAlgo, key) { if (curAuth === 'agent') { var agentKey = agentKeys[agentKeyPos], pubKeyFullType = agentKey.toString('ascii', 4, 4 + agentKey.readUInt32BE(0, true)), pubKeyType = pubKeyFullType.substring(4, 7); stream.authPK(self.config.username, agentKey, function(buf, cb) { agentQuery(self.config.agent, agentKey, pubKeyType, buf, function(err, signed) { if (err) { err.level = 'agent'; self.emit('error', err); agentKeys = undefined; return tryNextAuth(); } var signature; if (signed.toString('ascii', 4, 11) === 'ssh-' + pubKeyType) { // skip algoLen + algo + sigLen signature = signed.slice(4 + 7 + 4); } else signature = signed; cb(signature); }); }); } else if (curAuth === 'publickey') { stream.authPK(self.config.username, self.config.publicKey, function(buf, cb) { var signature = crypto.createSign(self.config.privateKey.type === 'rsa' ? 'RSA-SHA1' : 'DSA-SHA1'); signature.update(buf); signature = signature.sign(self.config.privateKey.privateOrig, 'binary'); signature = new Buffer(signature, 'binary'); if (self.config.privateKey.type === 'dss' && signature.length > 40) { // this is a quick and dirty way to get from DER encoded r and s that // OpenSSL gives us, to just the bare values back to back (40 bytes // total) like OpenSSH (and possibly others) are expecting var newsig = new Buffer(40), rlen = signature[3], rstart = 4, sstart = 4 + 1 + rlen + 1; while (signature[rstart] === 0) ++rstart; while (signature[sstart] === 0) ++sstart; signature.copy(newsig, 0, rstart, rstart + 20); signature.copy(newsig, 20, sstart, sstart + 20); signature = newsig; } cb(signature); }); } } function onUSERAUTH_FAILURE(authsLeft, partial) { stream.removeListener('USERAUTH_PK_OK', onUSERAUTH_PK_OK); stream.removeListener('USERAUTH_INFO_REQUEST', onUSERAUTH_INFO_REQUEST); if (curAuth === 'agent') { debug('DEBUG: Client: Agent key #' + (agentKeyPos + 1) + ' failed'); if (++agentKeyPos >= agentKeys.length) { debug('DEBUG: Agent: No more keys left to try'); debug('DEBUG: Client: ' + curAuth + ' auth failed'); agentKeys = undefined; tryNextAuth(); } else { debug('DEBUG: Agent: Trying key #' + (agentKeyPos + 1)); stream.authPK(self.config.username, agentKeys[agentKeyPos]); stream.once('USERAUTH_PK_OK', onUSERAUTH_PK_OK); } return; } else debug('DEBUG: Client: ' + curAuth + ' auth failed'); tryNextAuth(); } stream.once('USERAUTH_SUCCESS', function() { auths = undefined; stream.removeListener('USERAUTH_FAILURE', onUSERAUTH_FAILURE); stream.removeListener('USERAUTH_INFO_REQUEST', onUSERAUTH_INFO_REQUEST); /*if (self.config.agent && self._agentKeys) self._agentKeys = undefined;*/ // start keepalive mechanism resetKA(); clearTimeout(self._readyTimeout); self.emit('ready'); }).on('USERAUTH_FAILURE', onUSERAUTH_FAILURE); // end authentication handling =============================================== // handle initial handshake completion stream.once('NEWKEYS', function() { stream.service('ssh-userauth'); stream.once('SERVICE_ACCEPT', function(svcName) { if (svcName === 'ssh-userauth') tryNextAuth(); }); }); // handle incoming requests from server, typically a forwarded TCP or X11 // connection stream.on('CHANNEL_OPEN', function(info) { onCHANNEL_OPEN(self, info); }); // handle responses for tcpip-forward and other global requests stream.on('REQUEST_SUCCESS', function(data) { if (callbacks.length) callbacks.shift()(false, data); }).on('REQUEST_FAILURE', function() { if (callbacks.length) callbacks.shift()(true); }); stream.on('GLOBAL_REQUEST', function(name, wantReply, data) { // auto-reject all global requests, this can be especially useful if the // server is sending us dummy keepalive global requests if (wantReply) stream.requestFailure(); }); if (!cfg.sock) { var host = this.config.host, forceIPv4 = this.config.forceIPv4, forceIPv6 = this.config.forceIPv6; debug('DEBUG: Client: Trying ' + host + ' on port ' + this.config.port + ' ...'); function doConnect() { self._sock.connect(self.config.port, host); self._sock.setNoDelay(true); self._sock.setMaxListeners(0); self._sock.setTimeout(typeof cfg.timeout === 'number' ? cfg.timeout : 0); self._sock.setKeepAlive(true); stream.pipe(sock).pipe(stream); } if ((!forceIPv4 && !forceIPv6) || (forceIPv4 && forceIPv6)) doConnect(); else { dnsLookup(host, (forceIPv4 ? 4 : 6), function(err, address, family) { if (err) { var error = new Error('Error while looking up ' + (forceIPv4 ? 'IPv4' : 'IPv6') + ' address for host ' + host + ': ' + err); clearTimeout(self._readyTimeout); error.level = 'client-dns'; self.emit('error', error); self.emit('close'); return; } host = address; doConnect(); }); } } else stream.pipe(sock).pipe(stream); }; Client.prototype.end = function() { if (this._sshstream && this._sshstream.writable) return this._sshstream.disconnect(); return false; }; Client.prototype.destroy = function() { this._sock && this._sock.destroy(); }; Client.prototype.exec = function(cmd, opts, cb) { if (!this._sock || !this._sock.writable || !this._sshstream || !this._sshstream.writable) throw new Error('Not connected'); if (typeof opts === 'function') { cb = opts; opts = {}; } var self = this, extraOpts = { allowHalfOpen: (opts.allowHalfOpen ? true : false) }; return openChannel(this, 'session', extraOpts, function(err, chan) { if (err) return cb(err); var todo = []; function reqCb(err) { if (err) { chan.close(); return cb(err); } if (todo.length) todo.shift()(); } if (self.config.allowAgentFwd === true || (opts && opts.agentForward === true && self.config.agent !== undefined)) { todo.push(function() { reqAgentFwd(chan, reqCb); }); } if (typeof opts === 'object') { if (typeof opts.env === 'object') reqEnv(chan, opts.env); if (typeof opts.pty === 'object' || opts.pty === true) todo.push(function() { reqPty(chan, opts.pty, reqCb); }); if (typeof opts.x11 === 'object' || opts.x11 === 'number' || opts.x11 === true) todo.push(function() { reqX11(chan, opts.x11, reqCb); }); } todo.push(function() { reqExec(chan, cmd, opts, cb); }); todo.shift()(); }); }; Client.prototype.shell = function(wndopts, opts, cb) { if (!this._sock || !this._sock.writable || !this._sshstream || !this._sshstream.writable) throw new Error('Not connected'); // start an interactive terminal/shell session var self = this; if (typeof wndopts === 'function') { cb = wndopts; wndopts = opts = undefined; } else if (typeof opts === 'function') { cb = opts; opts = undefined; } if (wndopts && wndopts.x11 !== undefined) { opts = wndopts; wndopts = undefined; } return openChannel(this, 'session', function(err, chan) { if (err) return cb(err); reqPty(chan, wndopts, function(err) { if (err) return cb(err); var todo = []; function reqCb(err) { if (err) { chan.close(); return cb(err); } if (todo.length) todo.shift()(); } if (self.config.allowAgentFwd === true || (opts && opts.agentForward === true && self.config.agent !== undefined)) { todo.push(function() { reqAgentFwd(chan, reqCb); }); } if (typeof opts === 'object') { if (typeof opts.x11 === 'object' || opts.x11 === 'number' || opts.x11 === true) todo.push(function() { reqX11(chan, opts.x11, reqCb); }); } todo.push(function() { reqShell(chan, cb); }); todo.shift()(); }); }); }; Client.prototype.subsys = function(name, cb) { if (!this._sock || !this._sock.writable || !this._sshstream || !this._sshstream.writable) throw new Error('Not connected'); return openChannel(this, 'session', function(err, chan) { if (err) return cb(err); reqSubsystem(chan, name, function(err, stream) { if (err) return cb(err); cb(undefined, stream); }); }); }; Client.prototype.sftp = function(cb) { if (!this._sock || !this._sock.writable || !this._sshstream || !this._sshstream.writable) throw new Error('Not connected'); var self = this; // start an SFTP session return openChannel(this, 'session', function(err, chan) { if (err) return cb(err); reqSubsystem(chan, 'sftp', function(err, stream) { if (err) return cb(err); var serverIdentRaw = self._sshstream._state.incoming.identRaw, cfg = { debug: self.config.debug }, sftp = new SFTPStream(cfg, serverIdentRaw); function onError(err) { sftp.removeListener('ready', onReady); stream.removeListener('exit', onExit); cb(err); } function onReady() { sftp.removeListener('error', onError); stream.removeListener('exit', onExit); cb(undefined, new SFTPWrapper(sftp)); } function onExit(code, signal) { sftp.removeListener('ready', onReady); sftp.removeListener('error', onError); var msg; if (typeof code === 'number') { msg = 'Received exit code ' + code + ' while establishing SFTP session'; } else { msg = 'Received signal ' + signal + ' while establishing SFTP session'; } var err = new Error(msg); err.code = code; err.signal = signal; cb(err); } sftp.once('error', onError) .once('ready', onReady) .once('close', function() { stream.end(); }); // OpenSSH server sends an exit-status if there was a problem spinning up // an sftp server child process, so we listen for that here in order to // properly raise an error. stream.once('exit', onExit); sftp.pipe(stream).pipe(sftp); }); }); }; Client.prototype.forwardIn = function(bindAddr, bindPort, cb) { if (!this._sock || !this._sock.writable || !this._sshstream || !this._sshstream.writable) throw new Error('Not connected'); // send a request for the server to start forwarding TCP connections to us // on a particular address and port var self = this, wantReply = (typeof cb === 'function'); if (wantReply) { this._callbacks.push(function(had_err, data) { if (had_err) { return cb(had_err !== true ? had_err : new Error('Unable to bind to ' + bindAddr + ':' + bindPort)); } if (data && data.length) bindPort = data.readUInt32BE(0, true); self._forwarding.push(bindAddr + ':' + bindPort); cb(undefined, bindPort); }); } return this._sshstream.tcpipForward(bindAddr, bindPort, wantReply); }; Client.prototype.unforwardIn = function(bindAddr, bindPort, cb) { if (!this._sock || !this._sock.writable || !this._sshstream || !this._sshstream.writable) throw new Error('Not connected'); // send a request to stop forwarding us new connections for a particular // address and port var self = this, wantReply = (typeof cb === 'function'); if (wantReply) { this._callbacks.push(function(had_err) { if (had_err) { return cb(had_err !== true ? had_err : new Error('Unable to unbind from ' + bindAddr + ':' + bindPort)); } var forwards = self._forwarding; spliceOne(forwards, forwards.indexOf(bindAddr + ':' + bindPort)); cb(); }); } return this._sshstream.cancelTcpipForward(bindAddr, bindPort, wantReply); }; Client.prototype.forwardOut = function(srcIP, srcPort, dstIP, dstPort, cb) { if (!this._sock || !this._sock.writable || !this._sshstream || !this._sshstream.writable) throw new Error('Not connected'); // send a request to forward a TCP connection to the server var cfg = { srcIP: srcIP, srcPort: srcPort, dstIP: dstIP, dstPort: dstPort }; return openChannel(this, 'direct-tcpip', cfg, cb); }; Client.prototype.openssh_noMoreSessions = function(cb) { if (!this._sock || !this._sock.writable || !this._sshstream || !this._sshstream.writable) throw new Error('Not connected'); var wantReply = (typeof cb === 'function'); if (!this.config.strictVendor || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { if (wantReply) { this._callbacks.push(function(had_err) { if (had_err) { return cb(had_err !== true ? had_err : new Error('Unable to disable future sessions')); } cb(); }); } return this._sshstream.openssh_noMoreSessions(wantReply); } else if (wantReply) { process.nextTick(function() { cb(new Error('strictVendor enabled and server is not OpenSSH or compatible version')); }); } return true; }; Client.prototype.openssh_forwardInStreamLocal = function(socketPath, cb) { if (!this._sock || !this._sock.writable || !this._sshstream || !this._sshstream.writable) throw new Error('Not connected'); var wantReply = (typeof cb === 'function'); if (!this.config.strictVendor || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { if (wantReply) { this._callbacks.push(function(had_err) { if (had_err) { return cb(had_err !== true ? had_err : new Error('Unable to bind to ' + socketPath)); } cb(); }); } return this._sshstream.openssh_streamLocalForward(socketPath, wantReply); } else if (wantReply) { process.nextTick(function() { cb(new Error('strictVendor enabled and server is not OpenSSH or compatible version')); }); } return true; }; Client.prototype.openssh_unforwardInStreamLocal = function(socketPath, cb) { if (!this._sock || !this._sock.writable || !this._sshstream || !this._sshstream.writable) throw new Error('Not connected'); var wantReply = (typeof cb === 'function'); if (!this.config.strictVendor || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { if (wantReply) { this._callbacks.push(function(had_err) { if (had_err) { return cb(had_err !== true ? had_err : new Error('Unable to unbind on ' + socketPath)); } cb(); }); } return this._sshstream.openssh_cancelStreamLocalForward(socketPath, wantReply); } else if (wantReply) { process.nextTick(function() { cb(new Error('strictVendor enabled and server is not OpenSSH or compatible version')); }); } return true; }; Client.prototype.openssh_forwardOutStreamLocal = function(socketPath, cb) { if (!this._sock || !this._sock.writable || !this._sshstream || !this._sshstream.writable) throw new Error('Not connected'); if (!this.config.strictVendor || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) { var cfg = { socketPath: socketPath }; return openChannel(this, 'direct-streamlocal@openssh.com', cfg, cb); } else { process.nextTick(function() { cb(new Error('strictVendor enabled and server is not OpenSSH or compatible version')); }); } return true; }; function openChannel(self, type, opts, cb) { // ask the server to open a channel for some purpose // (e.g. session (sftp, exec, shell), or forwarding a TCP connection var localChan = nextChannel(self), initWindow = Channel.MAX_WINDOW, maxPacket = Channel.PACKET_SIZE, ret = true; if (localChan === false) return cb(new Error('No free channels available')); if (typeof opts === 'function') { cb = opts; opts = {}; } self._channels.push(localChan); var sshstream = self._sshstream; sshstream.once('CHANNEL_OPEN_CONFIRMATION:' + localChan, function(info) { sshstream.removeAllListeners('CHANNEL_OPEN_FAILURE:' + localChan); var chaninfo = { type: type, incoming: { id: localChan, window: initWindow, packetSize: maxPacket, state: 'open' }, outgoing: { id: info.sender, window: info.window, packetSize: info.packetSize, state: 'open' } }; cb(undefined, new Channel(chaninfo, self)); }).once('CHANNEL_OPEN_FAILURE:' + localChan, function(info) { sshstream.removeAllListeners('CHANNEL_OPEN_CONFIRMATION:' + localChan); var channels = self._channels; spliceOne(channels, channels.indexOf(localChan)); var err; if (info instanceof Error) err = info; else { err = new Error('(SSH) Channel open failure: ' + info.description); err.reason = info.reason; err.lang = info.lang; } cb(err); }); if (type === 'session') ret = sshstream.session(localChan, initWindow, maxPacket); else if (type === 'direct-tcpip') ret = sshstream.directTcpip(localChan, initWindow, maxPacket, opts); else if (type === 'direct-streamlocal@openssh.com') { ret = sshstream.openssh_directStreamLocal(localChan, initWindow, maxPacket, opts); } return ret; } function nextChannel(self) { // get the next available channel number // optimized path if (self._curChan < MAX_CHANNEL) if (++self._curChan <= MAX_CHANNEL) return self._curChan; // slower lookup path for (var i = 0; i < MAX_CHANNEL; ++i) if (self._channels.indexOf(i)) return i; return false; } function reqX11(chan, screen, cb) { // asks server to start sending us X11 connections var cfg = { single: false, protocol: 'MIT-MAGIC-COOKIE-1', cookie: crypto.randomBytes(16).toString('hex'), screen: (typeof screen === 'number' ? screen : 0) }; if (typeof screen === 'function') cb = screen; else if (typeof screen === 'object') { if (typeof screen.single === 'boolean') cfg.single = screen.single; if (typeof screen.screen === 'number') cfg.screen = screen.screen; } var wantReply = (typeof cb === 'function'); if (chan.outgoing.state !== 'open') { wantReply && cb(new Error('Channel is not open')); return true; } if (wantReply) { chan._callbacks.push(function(had_err) { if (had_err) { return cb(had_err !== true ? had_err : new Error('Unable to request X11')); } chan._hasX11 = true; ++chan._client._acceptX11; chan.once('close', function() { if (chan._client._acceptX11) --chan._client._acceptX11; }); cb(); }); } return chan._client._sshstream.x11Forward(chan.outgoing.id, cfg, wantReply); } function reqPty(chan, opts, cb) { var rows = 24, cols = 80, width = 640, height = 480, term = 'vt100'; if (typeof opts === 'function') cb = opts; else if (typeof opts === 'object') { if (typeof opts.rows === 'number') rows = opts.rows; if (typeof opts.cols === 'number') cols = opts.cols; if (typeof opts.width === 'number') width = opts.width; if (typeof opts.height === 'number') height = opts.height; if (typeof opts.term === 'string') term = opts.term; } var wantReply = (typeof cb === 'function'); if (chan.outgoing.state !== 'open') { wantReply && cb(new Error('Channel is not open')); return true; } if (wantReply) { chan._callbacks.push(function(had_err) { if (had_err) { return cb(had_err !== true ? had_err : new Error('Unable to request a pseudo-terminal')); } cb(); }); } return chan._client._sshstream.pty(chan.outgoing.id, rows, cols, height, width, term, null, wantReply); } function reqAgentFwd(chan, cb) { var wantReply = (typeof cb === 'function'); if (chan.outgoing.state !== 'open') { wantReply && cb(new Error('Channel is not open')); return true; } else if (chan._client._agentFwdEnabled) { wantReply && cb(false); return true; } chan._client._agentFwdEnabled = true; chan._callbacks.push(function(had_err) { if (had_err) { chan._client._agentFwdEnabled = false; wantReply && cb(had_err !== true ? had_err : new Error('Unable to request agent forwarding')); return; } wantReply && cb(); }); return chan._client._sshstream.openssh_agentForward(chan.outgoing.id, true); } function reqShell(chan, cb) { if (chan.outgoing.state !== 'open') { cb(new Error('Channel is not open')); return true; } chan._callbacks.push(function(had_err) { if (had_err) { return cb(had_err !== true ? had_err : new Error('Unable to open shell')); } chan.subtype = 'shell'; cb(undefined, chan); }); return chan._client._sshstream.shell(chan.outgoing.id, true); } function reqExec(chan, cmd, opts, cb) { if (chan.outgoing.state !== 'open') { cb(new Error('Channel is not open')); return true; } chan._callbacks.push(function(had_err) { if (had_err) { return cb(had_err !== true ? had_err : new Error('Unable to exec')); } chan.subtype = 'exec'; chan.allowHalfOpen = (opts.allowHalfOpen ? true : false); cb(undefined, chan); }); return chan._client._sshstream.exec(chan.outgoing.id, cmd, true); } function reqEnv(chan, env) { if (chan.outgoing.state !== 'open') return true; var ret = true, keys = Object.keys(env || {}), key, val; for (var i = 0, len = keys.length; i < len; ++i) { key = keys[i]; val = env[key]; ret = chan._client._sshstream.env(chan.outgoing.id, key, val, false); } return ret; } function reqSubsystem(chan, name, cb) { if (chan.outgoing.state !== 'open') { cb(new Error('Channel is not open')); return true; } chan._callbacks.push(function(had_err) { if (had_err) { return cb(had_err !== true ? had_err : new Error('Unable to start subsystem: ' + name)); } chan.subtype = 'subsystem'; cb(undefined, chan); }); return chan._client._sshstream.subsystem(chan.outgoing.id, name, true); } function onCHANNEL_OPEN(self, info) { // the server is trying to open a channel with us, this is usually when // we asked the server to forward us connections on some port and now they // are asking us to accept/deny an incoming connection on their side var localChan = false, reason; function accept() { var chaninfo = { type: info.type, incoming: { id: localChan, window: Channel.MAX_WINDOW, packetSize: Channel.MAX_WINDOW, state: 'open' }, outgoing: { id: info.sender, window: info.window, packetSize: info.packetSize, state: 'open' } }; var stream = new Channel(chaninfo, self); self._sshstream.channelOpenConfirm(info.sender, localChan, Channel.MAX_WINDOW, Channel.MAX_WINDOW); return stream; } function reject() { if (reason === undefined) { if (localChan === false) reason = consts.CHANNEL_OPEN_FAILURE.RESOURCE_SHORTAGE; else reason = consts.CHANNEL_OPEN_FAILURE.CONNECT_FAILED; } self._sshstream.channelOpenFail(info.sender, reason, '', ''); } if (info.type === 'forwarded-tcpip' || info.type === 'x11' || info.type === 'auth-agent@openssh.com') { // check for conditions for automatic rejection var rejectConn = ((info.type === 'forwarded-tcpip' && self._forwarding.indexOf(info.data.destIP + ':' + info.data.destPort) === -1) || (info.type === 'x11' && self._acceptX11 === 0) || (info.type === 'auth-agent@openssh.com' && !self._agentFwdEnabled)); if (!rejectConn) { localChan = nextChannel(self); if (localChan === false) { self.config.debug('DEBUG: Client: Automatic rejection of incoming channel open: no channels available'); rejectConn = true; } else self._channels.push(localChan); } else { reason = consts.CHANNEL_OPEN_FAILURE.ADMINISTRATIVELY_PROHIBITED; self.config.debug('DEBUG: Client: Automatic rejection of incoming channel open: unexpected channel open for: ' + info.type); } // TODO: automatic rejection after some timeout? if (rejectConn) reject(); if (localChan !== false) { if (info.type === 'forwarded-tcpip') self.emit('tcp connection', info.data, accept, reject); else if (info.type === 'x11') self.emit('x11', info.data, accept, reject); else agentQuery(self.config.agent, accept, reject); } } else { // automatically reject any unsupported channel open requests self.config.debug('DEBUG: Client: Automatic rejection of incoming channel open: unsupported type: ' + info.type); reason = consts.CHANNEL_OPEN_FAILURE.UNKNOWN_CHANNEL_TYPE; reject(); } } Client.Client = Client; Client.Server = require('./server'); // pass some useful utilities on to end user (e.g. parseKey(), genPublicKey()) Client.utils = ssh2_streams.utils; module.exports = Client; // backwards compatibility
import './components';
var appModule = require("./application-common"); var dts = require("application"); var frame = require("ui/frame"); var types = require("utils/types"); var observable = require("data/observable"); var enums = require("ui/enums"); global.moduleMerge(appModule, exports); var initEvents = function () { var androidApp = exports.android; var lifecycleCallbacks = new android.app.Application.ActivityLifecycleCallbacks({ onActivityCreated: function (activity, bundle) { if (!(activity instanceof com.tns.NativeScriptActivity)) { return; } if (!androidApp.startActivity) { androidApp.startActivity = activity; androidApp.notify({ eventName: "activityCreated", object: androidApp, activity: activity, bundle: bundle }); if (androidApp.onActivityCreated) { androidApp.onActivityCreated(activity, bundle); } } androidApp.currentContext = activity; }, onActivityDestroyed: function (activity) { if (!(activity instanceof com.tns.NativeScriptActivity)) { return; } if (activity === androidApp.foregroundActivity) { androidApp.foregroundActivity = undefined; } if (activity === androidApp.currentContext) { androidApp.currentContext = undefined; } if (activity === androidApp.startActivity) { if (exports.onExit) { exports.onExit(); } exports.notify({ eventName: dts.exitEvent, object: androidApp, android: activity }); androidApp.startActivity = undefined; } androidApp.notify({ eventName: "activityDestroyed", object: androidApp, activity: activity }); if (androidApp.onActivityDestroyed) { androidApp.onActivityDestroyed(activity); } gc(); }, onActivityPaused: function (activity) { if (!(activity instanceof com.tns.NativeScriptActivity)) { return; } if (activity === androidApp.foregroundActivity) { if (exports.onSuspend) { exports.onSuspend(); } exports.notify({ eventName: dts.suspendEvent, object: androidApp, android: activity }); } androidApp.notify({ eventName: "activityPaused", object: androidApp, activity: activity }); if (androidApp.onActivityPaused) { androidApp.onActivityPaused(activity); } }, onActivityResumed: function (activity) { if (!(activity instanceof com.tns.NativeScriptActivity)) { return; } if (activity === androidApp.foregroundActivity) { if (exports.onResume) { exports.onResume(); } exports.notify({ eventName: dts.resumeEvent, object: androidApp, android: activity }); } androidApp.notify({ eventName: "activityResumed", object: androidApp, activity: activity }); if (androidApp.onActivityResumed) { androidApp.onActivityResumed(activity); } }, onActivitySaveInstanceState: function (activity, bundle) { if (!(activity instanceof com.tns.NativeScriptActivity)) { return; } androidApp.notify({ eventName: "saveActivityState", object: androidApp, activity: activity, bundle: bundle }); if (androidApp.onSaveActivityState) { androidApp.onSaveActivityState(activity, bundle); } }, onActivityStarted: function (activity) { if (!(activity instanceof com.tns.NativeScriptActivity)) { return; } androidApp.foregroundActivity = activity; androidApp.notify({ eventName: "activityStarted", object: androidApp, activity: activity }); if (androidApp.onActivityStarted) { androidApp.onActivityStarted(activity); } }, onActivityStopped: function (activity) { if (!(activity instanceof com.tns.NativeScriptActivity)) { return; } androidApp.notify({ eventName: "activityStopped", object: androidApp, activity: activity }); if (androidApp.onActivityStopped) { androidApp.onActivityStopped(activity); } } }); return lifecycleCallbacks; }; app.init({ getActivity: function (activity) { var intent = activity.getIntent(); return exports.android.getActivity(intent); }, onCreate: function () { exports.android.init(this); } }); var AndroidApplication = (function (_super) { __extends(AndroidApplication, _super); function AndroidApplication() { _super.apply(this, arguments); this._registeredReceivers = {}; this._pendingReceiverRegistrations = new Array(); } AndroidApplication.prototype.getActivity = function (intent) { if (intent && intent.getAction() === android.content.Intent.ACTION_MAIN) { if (exports.onLaunch) { exports.onLaunch(intent); } exports.notify({ eventName: dts.launchEvent, object: this, android: intent }); setupOrientationListener(this); } var topFrame = frame.topmost(); if (!topFrame) { var navParam = dts.mainEntry; if (!navParam) { navParam = dts.mainModule; } if (navParam) { topFrame = new frame.Frame(); topFrame.navigate(navParam); } else { throw new Error("A Frame must be used to navigate to a Page."); } } return topFrame.android.onActivityRequested(intent); }; AndroidApplication.prototype.init = function (nativeApp) { this.nativeApp = nativeApp; this.packageName = nativeApp.getPackageName(); this.context = nativeApp.getApplicationContext(); this._eventsToken = initEvents(); this.nativeApp.registerActivityLifecycleCallbacks(this._eventsToken); this._registerPendingReceivers(); }; AndroidApplication.prototype._registerPendingReceivers = function () { if (this._pendingReceiverRegistrations) { var i = 0; var length = this._pendingReceiverRegistrations.length; for (; i < length; i++) { var registerFunc = this._pendingReceiverRegistrations[i]; registerFunc(this.context); } this._pendingReceiverRegistrations = new Array(); } }; AndroidApplication.prototype.registerBroadcastReceiver = function (intentFilter, onReceiveCallback) { var that = this; var registerFunc = function (context) { var receiver = new BroadcastReceiver(onReceiveCallback); context.registerReceiver(receiver, new android.content.IntentFilter(intentFilter)); that._registeredReceivers[intentFilter] = receiver; }; if (this.context) { registerFunc(this.context); } else { this._pendingReceiverRegistrations.push(registerFunc); } }; AndroidApplication.prototype.unregisterBroadcastReceiver = function (intentFilter) { var receiver = this._registeredReceivers[intentFilter]; if (receiver) { this.context.unregisterReceiver(receiver); this._registeredReceivers[intentFilter] = undefined; delete this._registeredReceivers[intentFilter]; } }; AndroidApplication.activityCreatedEvent = "activityCreated"; AndroidApplication.activityDestroyedEvent = "activityDestroyed"; AndroidApplication.activityStartedEvent = "activityStarted"; AndroidApplication.activityPausedEvent = "activityPaused"; AndroidApplication.activityResumedEvent = "activityResumed"; AndroidApplication.activityStoppedEvent = "activityStopped"; AndroidApplication.saveActivityStateEvent = "saveActivityState"; AndroidApplication.activityResultEvent = "activityResult"; AndroidApplication.activityBackPressedEvent = "activityBackPressed"; return AndroidApplication; })(observable.Observable); exports.AndroidApplication = AndroidApplication; var BroadcastReceiver = (function (_super) { __extends(BroadcastReceiver, _super); function BroadcastReceiver(onReceiveCallback) { _super.call(this); this._onReceiveCallback = onReceiveCallback; return global.__native(this); } BroadcastReceiver.prototype.onReceive = function (context, intent) { if (this._onReceiveCallback) { this._onReceiveCallback(context, intent); } }; return BroadcastReceiver; })(android.content.BroadcastReceiver); global.__onUncaughtError = function (error) { if (!types.isFunction(exports.onUncaughtError)) { return; } var nsError = { message: error.message, name: error.name, nativeError: error.nativeException }; exports.onUncaughtError(nsError); exports.notify({ eventName: dts.uncaughtErrorEvent, object: appModule.android, android: nsError }); }; exports.start = function () { dts.loadCss(); }; exports.android = new AndroidApplication(); var currentOrientation; function setupOrientationListener(androidApp) { androidApp.registerBroadcastReceiver(android.content.Intent.ACTION_CONFIGURATION_CHANGED, onConfigurationChanged); currentOrientation = androidApp.context.getResources().getConfiguration().orientation; } function onConfigurationChanged(context, intent) { var orientation = context.getResources().getConfiguration().orientation; if (currentOrientation !== orientation) { currentOrientation = orientation; var newValue; switch (orientation) { case android.content.res.Configuration.ORIENTATION_LANDSCAPE: newValue = enums.DeviceOrientation.landscape; break; case android.content.res.Configuration.ORIENTATION_PORTRAIT: newValue = enums.DeviceOrientation.portrait; break; default: newValue = enums.DeviceOrientation.unknown; break; } exports.notify({ eventName: dts.orientationChangedEvent, android: context, newValue: newValue, object: exports.android, }); } }
angular.module('menuDemoWidth', ['ngMaterial']).config(function($mdIconProvider) { $mdIconProvider .iconSet("call", 'img/icons/sets/communication-icons.svg', 24) .iconSet("social", 'img/icons/sets/social-icons.svg', 24); }).controller('WidthDemoCtrl', function($mdDialog) { var ctrl = this; ctrl.menuHref = "https://material.io/design/components/menus.html#specs"; this.announceClick = function(index) { $mdDialog.show( $mdDialog.alert() .title('You clicked!') .textContent('You clicked the menu item at index ' + index) .ok('Nice') ); }; });
var Future = Npm.require('fibers/future'); var urlModule = Npm.require('url'); var MailComposer = Npm.require('mailcomposer').MailComposer; Email = {}; EmailTest = {}; var makePool = function (mailUrlString) { var mailUrl = urlModule.parse(mailUrlString); if (mailUrl.protocol !== 'smtp:') throw new Error("Email protocol in $MAIL_URL (" + mailUrlString + ") must be 'smtp'"); var port = +(mailUrl.port); var auth = false; if (mailUrl.auth) { var parts = mailUrl.auth.split(':', 2); auth = {user: parts[0] && decodeURIComponent(parts[0]), pass: parts[1] && decodeURIComponent(parts[1])}; } var simplesmtp = Npm.require('simplesmtp'); var pool = simplesmtp.createClientPool( port, // Defaults to 25 mailUrl.hostname, // Defaults to "localhost" { secureConnection: (port === 465), // XXX allow maxConnections to be configured? auth: auth }); pool._future_wrapped_sendMail = _.bind(Future.wrap(pool.sendMail), pool); return pool; }; var getPool = _.once(function () { // We delay this check until the first call to Email.send, in case someone // set process.env.MAIL_URL in startup code. var url = process.env.MAIL_URL; if (! url) return null; return makePool(url); }); var next_devmode_mail_id = 0; var output_stream = process.stdout; // Testing hooks EmailTest.overrideOutputStream = function (stream) { next_devmode_mail_id = 0; output_stream = stream; }; EmailTest.restoreOutputStream = function () { output_stream = process.stdout; }; var devModeSend = function (mc) { var devmode_mail_id = next_devmode_mail_id++; var stream = output_stream; // This approach does not prevent other writers to stdout from interleaving. stream.write("====== BEGIN MAIL #" + devmode_mail_id + " ======\n"); stream.write("(Mail not sent; to enable sending, set the MAIL_URL " + "environment variable.)\n"); mc.streamMessage(); mc.pipe(stream, {end: false}); var future = new Future; mc.on('end', function () { stream.write("====== END MAIL #" + devmode_mail_id + " ======\n"); future['return'](); }); future.wait(); }; var smtpSend = function (pool, mc) { pool._future_wrapped_sendMail(mc).wait(); }; /** * Mock out email sending (eg, during a test.) This is private for now. * * f receives the arguments to Email.send and should return true to go * ahead and send the email (or at least, try subsequent hooks), or * false to skip sending. */ var sendHooks = []; EmailTest.hookSend = function (f) { sendHooks.push(f); }; // Old comment below /** * Send an email. * * Connects to the mail server configured via the MAIL_URL environment * variable. If unset, prints formatted message to stdout. The "from" option * is required, and at least one of "to", "cc", and "bcc" must be provided; * all other options are optional. * * @param options * @param options.from {String} RFC5322 "From:" address * @param options.to {String|String[]} RFC5322 "To:" address[es] * @param options.cc {String|String[]} RFC5322 "Cc:" address[es] * @param options.bcc {String|String[]} RFC5322 "Bcc:" address[es] * @param options.replyTo {String|String[]} RFC5322 "Reply-To:" address[es] * @param options.subject {String} RFC5322 "Subject:" line * @param options.text {String} RFC5322 mail body (plain text) * @param options.html {String} RFC5322 mail body (HTML) * @param options.headers {Object} custom RFC5322 headers (dictionary) */ // New API doc comment below /** * @summary Send an email. Throws an `Error` on failure to contact mail server * or if mail server returns an error. All fields should match * [RFC5322](http://tools.ietf.org/html/rfc5322) specification. * @locus Server * @param {Object} options * @param {String} options.from "From:" address (required) * @param {String|String[]} options.to,cc,bcc,replyTo * "To:", "Cc:", "Bcc:", and "Reply-To:" addresses * @param {String} [options.subject] "Subject:" line * @param {String} [options.text|html] Mail body (in plain text and/or HTML) * @param {Object} [options.headers] Dictionary of custom headers */ Email.send = function (options) { for (var i = 0; i < sendHooks.length; i++) if (! sendHooks[i](options)) return; var mc = new MailComposer(); // setup message data // XXX support attachments (once we have a client/server-compatible binary // Buffer class) mc.setMessageOption({ from: options.from, to: options.to, cc: options.cc, bcc: options.bcc, replyTo: options.replyTo, subject: options.subject, text: options.text, html: options.html }); _.each(options.headers, function (value, name) { mc.addHeader(name, value); }); var pool = getPool(); if (pool) { smtpSend(pool, mc); } else { devModeSend(mc); } };
/** * Copyright 2014 Telerik AD * * 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(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["cy-GB"] = { name: "cy-GB", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-%n","%n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["-$n","$n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "£" } }, calendars: { standard: { days: { names: ["Dydd Sul","Dydd Llun","Dydd Mawrth","Dydd Mercher","Dydd Iau","Dydd Gwener","Dydd Sadwrn"], namesAbbr: ["Sul","Llun","Maw","Mer","Iau","Gwe","Sad"], namesShort: ["Su","Ll","Ma","Me","Ia","Gw","Sa"] }, months: { names: ["Ionawr","Chwefror","Mawrth","Ebrill","Mai","Mehefin","Gorffennaf","Awst","Medi","Hydref","Tachwedd","Rhagfyr",""], namesAbbr: ["Ion","Chwe","Maw","Ebr","Mai","Meh","Gor","Aws","Med","Hyd","Tach","Rhag",""] }, AM: ["a.m.","a.m.","A.M."], PM: ["p.m.","p.m.","P.M."], patterns: { d: "dd/MM/yyyy", D: "dd MMMM yyyy", F: "dd MMMM yyyy HH:mm:ss", g: "dd/MM/yyyy HH:mm", G: "dd/MM/yyyy HH:mm:ss", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "HH:mm", T: "HH:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": "/", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
/*! * jQuery JavaScript Library v2.0.3 -event-alias,-effects * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-07T17:05Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Support: IE9 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "2.0.3 -event-alias,-effects", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler and self cleanup method completed = function() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } // Support: Safari <= 5.1 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Support: Firefox <20 // The try/catch suppresses exceptions thrown when attempting to access // the "constructor" property of certain host objects, ie. |window.location| // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 try { if ( obj.constructor && !core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } } catch ( e ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: JSON.parse, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, trim: function( text ) { return text == null ? "" : core_trim.call( text ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : core_indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var 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 = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: Date.now, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.9.4-pre * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-06-03 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( whitespace + "*[+~]" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent.attachEvent && parent !== parent.top ) { parent.attachEvent( "onbeforeunload", function() { setDocument(); }); } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return (val = elem.getAttributeNode( name )) && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } }); } jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var input = document.createElement("input"), fragment = document.createDocumentFragment(), div = document.createElement("div"), select = document.createElement("select"), opt = select.appendChild( document.createElement("option") ); // Finish early in limited environments if ( !input.type ) { return support; } input.type = "checkbox"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // Will be defined later support.reliableMarginRight = true; support.boxSizingReliable = true; support.pixelPosition = false; // Make sure checked status is properly cloned // Support: IE9, IE10 input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement("input"); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment.appendChild( input ); // Support: Safari 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: Firefox, Chrome, Safari // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) support.focusinBubbles = "onfocusin" in window; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box", body = document.getElementsByTagName("body")[ 0 ]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; // Check box-sizing and margin behavior. body.appendChild( container ).appendChild( div ); div.innerHTML = ""; // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } body.removeChild( container ); }); return support; })( {} ); /* 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 data_user, data_priv, rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType ? owner.nodeType === 1 || owner.nodeType === 9 : true; }; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( core_rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; // These may be used throughout the jQuery core codebase data_user = new Data(); data_priv = new Data(); jQuery.extend({ acceptData: Data.accepts, hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, elem = this[ 0 ], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return jQuery.access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? JSON.parse( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ // Temporarily disable this handler to check existence (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; // Restore handler jQuery.expr.attrHandle[ name ] = fn; return ret; }; }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var 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; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return core_indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return core_indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { 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 jQuery.access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because core_push.apply(_, arraylike) throws core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !jQuery.support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, i = 0, l = elems.length, fragment = context.createDocumentFragment(), nodes = []; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, events, type, key, j, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( Data.accepts( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { events = Object.keys( data.events || {} ); if ( events.length ) { for ( j = 0; (type = events[j]) !== undefined; j++ ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var l = elems.length, i = 0; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 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" && manipulation_rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.fn.extend({ wrapAll: function( html ) { var wrap; if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapAll( html.call(this, i) ); }); } if ( this[ 0 ] ) { // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map(function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function( i ) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); var curCSS, iframe, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. function getStyles( elem ) { return window.getComputedStyle( elem, null ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = data_priv.get( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = data_priv.access( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css(elem, "display") ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifying setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { style[ name ] = value; } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // Support: IE9 // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: Safari 5.1 // A tribute to the "awesome hack by Dean Edwards" // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { // Support: Android 2.3 if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // Support: Android 2.3 // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var 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; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ) .replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var 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 }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery("<script>").prop({ async: true, charset: s.scriptCharset, src: s.url }).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); jQuery.ajaxSettings.xhr = function() { try { return new XMLHttpRequest(); } catch( e ) {} }; var xhrSupported = jQuery.ajaxSettings.xhr(), xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, // Support: IE9 // We need to keep track of outbound xhr and abort them manually // because IE is not smart enough to do it all by itself xhrId = 0, xhrCallbacks = {}; if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for( var key in xhrCallbacks ) { xhrCallbacks[ key ](); } xhrCallbacks = undefined; }); } jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); jQuery.support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport(function( options ) { var callback; // Cross domain only allowed if supported through XMLHttpRequest if ( jQuery.support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, id, 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 ) { delete xhrCallbacks[ id ]; callback = xhr.onload = xhr.onerror = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { complete( // file protocol always yields status 0, assume 404 xhr.status || 404, xhr.statusText ); } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 // #11426: When requesting binary data, IE9 will throw an exception // on any attempt to access responseText typeof xhr.responseText === "string" ? { text: xhr.responseText } : undefined, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); xhr.onerror = callback("error"); // Create the abort callback callback = xhrCallbacks[( id = xhrId++ )] = callback("abort"); // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( options.hasContent && options.data || null ); }, abort: function() { if ( callback ) { callback(); } } }; } }); jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, elem = this[ 0 ], box = { top: 0, left: 0 }, doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -1; // Need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ 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 it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // We assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : window.pageXOffset, top ? val : window.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], // whichever is greatest return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } // If there is a window object, that at least has a document property, // define jQuery and $ identifiers if ( typeof window === "object" && typeof window.document === "object" ) { window.jQuery = window.$ = jQuery; } })( window );
/* Tabulator v4.2.5 (c) Oliver Folkerd */ var History = function History(table) { this.table = table; //hold Tabulator object this.history = []; this.index = -1; }; History.prototype.clear = function () { this.history = []; this.index = -1; }; History.prototype.action = function (type, component, data) { this.history = this.history.slice(0, this.index + 1); this.history.push({ type: type, component: component, data: data }); this.index++; }; History.prototype.getHistoryUndoSize = function () { return this.index + 1; }; History.prototype.getHistoryRedoSize = function () { return this.history.length - (this.index + 1); }; History.prototype.undo = function () { if (this.index > -1) { var action = this.history[this.index]; this.undoers[action.type].call(this, action); this.index--; this.table.options.historyUndo.call(this.table, action.type, action.component.getComponent(), action.data); return true; } else { console.warn("History Undo Error - No more history to undo"); return false; } }; History.prototype.redo = function () { if (this.history.length - 1 > this.index) { this.index++; var action = this.history[this.index]; this.redoers[action.type].call(this, action); this.table.options.historyRedo.call(this.table, action.type, action.component.getComponent(), action.data); return true; } else { console.warn("History Redo Error - No more history to redo"); return false; } }; History.prototype.undoers = { cellEdit: function cellEdit(action) { action.component.setValueProcessData(action.data.oldValue); }, rowAdd: function rowAdd(action) { action.component.deleteActual(); }, rowDelete: function rowDelete(action) { var newRow = this.table.rowManager.addRowActual(action.data.data, action.data.pos, action.data.index); this._rebindRow(action.component, newRow); }, rowMove: function rowMove(action) { this.table.rowManager.moveRowActual(action.component, this.table.rowManager.rows[action.data.pos], false); this.table.rowManager.redraw(); } }; History.prototype.redoers = { cellEdit: function cellEdit(action) { action.component.setValueProcessData(action.data.newValue); }, rowAdd: function rowAdd(action) { var newRow = this.table.rowManager.addRowActual(action.data.data, action.data.pos, action.data.index); this._rebindRow(action.component, newRow); }, rowDelete: function rowDelete(action) { action.component.deleteActual(); }, rowMove: function rowMove(action) { this.table.rowManager.moveRowActual(action.component, this.table.rowManager.rows[action.data.pos], false); this.table.rowManager.redraw(); } }; //rebind rows to new element after deletion History.prototype._rebindRow = function (oldRow, newRow) { this.history.forEach(function (action) { if (action.component instanceof Row) { if (action.component === oldRow) { action.component = newRow; } } else if (action.component instanceof Cell) { if (action.component.row === oldRow) { var field = action.component.column.getField(); if (field) { action.component = newRow.getCell(field); } } } }); }; Tabulator.prototype.registerModule("history", History);
import { isValidHex, report, ruleMessages, validateOptions, } from "../../utils" import styleSearch from "style-search" export const ruleName = "color-no-invalid-hex" export const messages = ruleMessages(ruleName, { rejected: hex => `Unexpected invalid hex color "${hex}"`, }) export default function (actual) { return (root, result) => { const validOptions = validateOptions(result, ruleName, { actual }) if (!validOptions) { return } root.walkDecls(decl => { const declString = decl.toString() styleSearch({ source: declString, target: "#" }, match => { // If there's not a colon, comma, or whitespace character before, we'll assume this is // not intended to be a hex color, but is instead something like the // hash in a url() argument if (!/[:,\s]/.test(declString[match.startIndex - 1])) { return } const hexMatch = /^#[0-9A-Za-z]+/.exec(declString.substr(match.startIndex)) if (!hexMatch) { return } const hexValue = hexMatch[0] if (isValidHex(hexValue)) { return } report({ message: messages.rejected(hexValue), node: decl, index: match.startIndex, result, ruleName, }) }) }) } }
/* globals define */ (function (root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { root.owaspPasswordStrengthTest = factory(); } }(this, function () { var owasp = {}; // These are configuration settings that will be used when testing password // strength owasp.configs = { allowPassphrases : true, maxLength : 128, minLength : 10, minPhraseLength : 20, minOptionalTestsToPass : 4, }; // This method makes it more convenient to set config parameters owasp.config = function(params) { for (var prop in params) { if (params.hasOwnProperty(prop) && this.configs.hasOwnProperty(prop)) { this.configs[prop] = params[prop]; } } }; // This is an object containing the tests to run against all passwords. owasp.tests = { // An array of required tests. A password *must* pass these tests in order // to be considered strong. required: [ // enforce a minimum length function(password) { if (password.length < owasp.configs.minLength) { return 'The password must be at least ' + owasp.configs.minLength + ' characters long.'; } }, // enforce a maximum length function(password) { if (password.length > owasp.configs.maxLength) { return 'The password must be fewer than ' + owasp.configs.maxLength + ' characters.'; } }, // forbid repeating characters function(password) { if (/(.)\1{2,}/.test(password)) { return 'The password may not contain sequences of three or more repeated characters.'; } }, ], // An array of optional tests. These tests are "optional" in two senses: // // 1. Passphrases (passwords whose length exceeds // this.configs.minPhraseLength) are not obligated to pass these tests // provided that this.configs.allowPassphrases is set to Boolean true // (which it is by default). // // 2. A password need only to pass this.configs.minOptionalTestsToPass // number of these optional tests in order to be considered strong. optional: [ // require at least one lowercase letter function(password) { if (!/[a-z]/.test(password)) { return 'The password must contain at least one lowercase letter.'; } }, // require at least one uppercase letter function(password) { if (!/[A-Z]/.test(password)) { return 'The password must contain at least one uppercase letter.'; } }, // require at least one number function(password) { if (!/[0-9]/.test(password)) { return 'The password must contain at least one number.'; } }, // require at least one special character function(password) { if (!/[^A-Za-z0-9 ]/.test(password)) { return 'The password must contain at least one special character.'; } }, ], }; // This method tests password strength owasp.test = function(password) { // create an object to store the test results var result = { errors : [], failedTests : [], passedTests : [], isPassphrase : false, strong : true, optionalTestsPassed : 0, }; // Always submit the password/passphrase to the required tests var i = 0; this.tests.required.forEach(function(test) { var err = test(password); if (typeof err === 'string') { result.strong = false; result.errors.push(err); result.failedTests.push(i); } else { result.passedTests.push(i); } i++; }); // If configured to allow passphrases, and if the password is of a // sufficient length to consider it a passphrase, exempt it from the // optional tests. if ( this.configs.allowPassphrases === true && password.length >= this.configs.minPhraseLength ) { result.isPassphrase = true; } if (!result.isPassphrase) { var j = this.tests.required.length; this.tests.optional.forEach(function(test) { var err = test(password); if (typeof err === 'string') { result.errors.push(err); result.failedTests.push(j); } else { result.optionalTestsPassed++; result.passedTests.push(j); } j++; }); } // If the password is not a passphrase, assert that it has passed a // sufficient number of the optional tests, per the configuration if ( !result.isPassphrase && result.optionalTestsPassed < this.configs.minOptionalTestsToPass ) { result.strong = false; } // return the result return result; }; return owasp; } ));
(function () { var ss = jss.createStyleSheet(window.styles).attach() angular .module('myApp', []) .controller('myController', function MyController($scope) { $scope.classes = ss.classes $scope.showSource = function () { location.href = 'http://github.com/jsstyles/jss/tree/master/examples/angular' } }) }())
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is JavaScript Engine testing utilities. * * The Initial Developer of the Original Code is * Mozilla Foundation. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor(s): Gary Kwong * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ var gTestfile = 'regress-477234.js'; //----------------------------------------------------------------------------- var BUGNUMBER = 477234; var summary = 'Do not assert: v != JSVAL_ERROR_COOKIE'; var actual = ''; var expect = ''; //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function test() { enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); jit(true); for (iters = 0; iters < 11500; ++iters) { for each (let x in ['', '', '']){} eval("__proto__.x getter = function(){}"); var a = uneval; delete uneval; uneval = a; var b = toSource; delete toSource; toSource = b; var c = toString; delete toString; toString = c; } jit(true); delete __proto__.x; reportCompare(expect, actual, summary); exitFunc ('test'); }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsBrightness = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16.01H3V4.99h18v14.02zM8 16h2.5l1.5 1.5 1.5-1.5H16v-2.5l1.5-1.5-1.5-1.5V8h-2.5L12 6.5 10.5 8H8v2.5L6.5 12 8 13.5V16zm4-7c1.66 0 3 1.34 3 3s-1.34 3-3 3V9z"/> </SvgIcon> ); ActionSettingsBrightness = pure(ActionSettingsBrightness); ActionSettingsBrightness.displayName = 'ActionSettingsBrightness'; export default ActionSettingsBrightness;
'use strict'; if (typeof module !== 'undefined' && module.exports) { module.exports = isSupported; } else if (window) { window.mapboxgl = window.mapboxgl || {}; window.mapboxgl.supported = isSupported; } /** * Test whether the current browser supports Mapbox GL JS * @param {Object} options * @param {boolean} [options.failIfMajorPerformanceCaveat=false] Return `false` * if the performance of Mapbox GL JS would be dramatically worse than * expected (i.e. a software renderer is would be used) * @return {boolean} */ function isSupported(options) { return !!( isBrowser() && isArraySupported() && isFunctionSupported() && isObjectSupported() && isJSONSupported() && isWorkerSupported() && isUint8ClampedArraySupported() && isWebGLSupportedCached(options && options.failIfMajorPerformanceCaveat) ); } function isBrowser() { return typeof window !== 'undefined' && typeof document !== 'undefined'; } function isArraySupported() { return ( Array.prototype && Array.prototype.every && Array.prototype.filter && Array.prototype.forEach && Array.prototype.indexOf && Array.prototype.lastIndexOf && Array.prototype.map && Array.prototype.some && Array.prototype.reduce && Array.prototype.reduceRight && Array.isArray ); } function isFunctionSupported() { return Function.prototype && Function.prototype.bind; } function isObjectSupported() { return ( Object.keys && Object.create && Object.getPrototypeOf && Object.getOwnPropertyNames && Object.isSealed && Object.isFrozen && Object.isExtensible && Object.getOwnPropertyDescriptor && Object.defineProperty && Object.defineProperties && Object.seal && Object.freeze && Object.preventExtensions ); } function isJSONSupported() { return 'JSON' in window && 'parse' in JSON && 'stringify' in JSON; } function isWorkerSupported() { return 'Worker' in window; } // IE11 only supports `Uint8ClampedArray` as of version // [KB2929437](https://support.microsoft.com/en-us/kb/2929437) function isUint8ClampedArraySupported() { return 'Uint8ClampedArray' in window; } var isWebGLSupportedCache = {}; function isWebGLSupportedCached(failIfMajorPerformanceCaveat) { if (isWebGLSupportedCache[failIfMajorPerformanceCaveat] === undefined) { isWebGLSupportedCache[failIfMajorPerformanceCaveat] = isWebGLSupported(failIfMajorPerformanceCaveat); } return isWebGLSupportedCache[failIfMajorPerformanceCaveat]; } isSupported.webGLContextAttributes = { antialias: false, alpha: true, stencil: true, depth: true }; function isWebGLSupported(failIfMajorPerformanceCaveat) { var canvas = document.createElement('canvas'); var attributes = Object.create(isSupported.webGLContextAttributes); attributes.failIfMajorPerformanceCaveat = failIfMajorPerformanceCaveat; if (canvas.probablySupportsContext) { return ( canvas.probablySupportsContext('webgl', attributes) || canvas.probablySupportsContext('experimental-webgl', attributes) ); } else if (canvas.supportsContext) { return ( canvas.supportsContext('webgl', attributes) || canvas.supportsContext('experimental-webgl', attributes) ); } else { return ( canvas.getContext('webgl', attributes) || canvas.getContext('experimental-webgl', attributes) ); } }
'use strict'; angular.module('sw.plugin.auth', ['sw.plugins']) .factory('auth', function ($q/* , $window */) { return { execute: function (/* options */) { var deferred = $q.defer(); /* Add auth key to params options.params.auth_key = '...'; */ /* Basic HTTP Authentication var username = '...'; var password = '...'; var auth = $window.btoa(username + ':' + password); options.headers['Authorization'] = 'Basic ' + auth; */ deferred.resolve(); return deferred.promise; } }; }) .run(function (plugins, auth) { plugins.add(plugins.BEFORE_EXPLORER_LOAD, auth); });
/* Highcharts JS v7.0.3 (2019-02-06) Indicator series type for Highstock (c) 2010-2019 Pawel Fus, Sebastian Bochan License: www.highcharts.com/license */ (function(e){"object"===typeof module&&module.exports?(e["default"]=e,module.exports=e):"function"===typeof define&&define.amd?define(function(){return e}):e("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(e){var q=function(c){var e=c.error;return{isParentLoaded:function(c,m,h,p,l){if(c)return p?p(c):!0;e(l||this.generateMessage(h,m));return!1},generateMessage:function(c,e){return'Error: "'+c+'" indicator type requires "'+e+'" indicator loaded before. Please read docs: https://api.highcharts.com/highstock/plotOptions.'+ c}}}(e);(function(c,e){var q=c.pick,m=c.error,h=c.Series,p=c.isArray,l=c.addEvent,t=c.seriesType,r=c.seriesTypes,n=c.seriesTypes.ohlc.prototype,u=e.generateMessage;l(c.Series,"init",function(b){b=b.options;b.useOhlcData&&"highcharts-navigator-series"!==b.id&&c.extend(this,{pointValKey:n.pointValKey,keys:n.keys,pointArrayMap:n.pointArrayMap,toYData:n.toYData})});l(h,"afterSetOptions",function(b){b=b.options;var d=b.dataGrouping;d&&b.useOhlcData&&"highcharts-navigator-series"!==b.id&&(d.approximation= "ohlc")});t("sma","line",{name:void 0,tooltip:{valueDecimals:4},linkedTo:void 0,compareToMain:!1,params:{index:0,period:14}},{processData:function(){var b=this.options.compareToMain,d=this.linkedParent;h.prototype.processData.apply(this,arguments);d&&d.compareValue&&b&&(this.compareValue=d.compareValue)},bindTo:{series:!0,eventName:"updatedData"},useCommonDataGrouping:!0,nameComponents:["period"],nameSuffixes:[],calculateOn:"init",requiredIndicators:[],requireIndicators:function(){var b={allLoaded:!0}; this.requiredIndicators.forEach(function(d){r[d]?r[d].prototype.requireIndicators():(b.allLoaded=!1,b.needed=d)});return b},init:function(b,d){function c(){var b=a.points||[],d=(a.xData||[]).length,c=a.getValues(a.linkedParent,a.options.params)||{values:[],xData:[],yData:[]},e=[],k=!0,f,g;if(d&&!a.hasGroupedData&&a.visible&&a.points)if(a.cropped){a.xAxis&&(f=a.xAxis.min,g=a.xAxis.max);d=a.cropData(c.xData,c.yData,f,g);for(f=0;f<d.xData.length;f++)e.push([d.xData[f],d.yData[f]]);d=c.xData.indexOf(a.xData[0]); f=c.xData.indexOf(a.xData[a.xData.length-1]);-1===d&&f===c.xData.length-2&&e[0][0]===b[0].x&&e.shift();a.updateData(e)}else c.xData.length!==d-1&&c.xData.length!==d+1&&(k=!1,a.updateData(c.values));k&&(a.xData=c.xData,a.yData=c.yData,a.options.data=c.values);!1===a.bindTo.series&&(delete a.processedXData,a.isDirty=!0,a.redraw());a.isDirtyData=!1}var a=this,e=a.requireIndicators();if(!e.allLoaded)return m(u(a.type,e.needed));h.prototype.init.call(a,b,d);b.linkSeries();a.dataEventsToUnbind=[];if(!a.linkedParent)return m("Series "+ a.options.linkedTo+" not found! Check `linkedTo`.",!1,b);a.dataEventsToUnbind.push(l(a.bindTo.series?a.linkedParent:a.linkedParent.xAxis,a.bindTo.eventName,c));if("init"===a.calculateOn)c();else var g=l(a.chart,a.calculateOn,function(){c();g()});return a},getName:function(){var b=this.name,d=[];b||((this.nameComponents||[]).forEach(function(b,a){d.push(this.options.params[b]+q(this.nameSuffixes[a],""))},this),b=(this.nameBase||this.type.toUpperCase())+(this.nameComponents?" ("+d.join(", ")+")":"")); return b},getValues:function(b,d){var c=d.period,a=b.xData;b=b.yData;var e=b.length,g=0,h=0,l=[],m=[],n=[],k=-1,f;if(a.length<c)return!1;for(p(b[0])&&(k=d.index?d.index:0);g<c-1;)h+=0>k?b[g]:b[g][k],g++;for(d=g;d<e;d++)h+=0>k?b[d]:b[d][k],f=[a[d],h/c],l.push(f),m.push(f[0]),n.push(f[1]),h-=0>k?b[d-g]:b[d-g][k];return{values:l,xData:m,yData:n}},destroy:function(){this.dataEventsToUnbind.forEach(function(b){b()});h.prototype.destroy.call(this)}})})(e,q)}); //# sourceMappingURL=indicators.js.map
/*! * Modernizr 2.5.3 * * Microsoft grants you the right to use these script files for the sole purpose of either: * (i) interacting through your browser with the Microsoft website, subject to the website’s terms of use; * or (ii) using the files as included with a Microsoft product subject to that product’s license terms. * Microsoft reserves all other rights to the files not expressly granted by Microsoft, whether by * implication, estoppel or otherwise. The notices and licenses below are for informational purposes only. * * ---------------------------------------------------------------------------------------- * Modernizr v2.5.3 * www.modernizr.com * * Copyright (c) 2009-2012 Faruk Ates, Paul Irish, Alex Sexton * Dual-licensed under the BSD or MIT licenses: www.modernizr.com/license/<http://www.modernizr.com/license/> * * ---------------------------------------------------------------------------------------- * * Provided for Informational Purposes Only * * MIT License * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * --------------------------------------------------------------------------------------------------------- * * BSD License * 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 copyright holders 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 COPYRIGHT HOLDER BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ window.Modernizr = (function( window, document, undefined ) { var version = '2.5.3', Modernizr = {}, // option for enabling the HTML classes to be added enableClasses = true, docElement = document.documentElement, /** * Create our "modernizr" element that we do most feature tests on. */ mod = 'modernizr', modElem = document.createElement(mod), mStyle = modElem.style, /** * Create the input element for various Web Forms feature tests. */ inputElem = document.createElement('input'), smile = ':)', toString = {}.toString, // List of property values to set for css tests. See ticket #21 prefixes = ' -webkit- -moz- -o- -ms- '.split(' '), // Following spec is to expose vendor-specific style properties as: // elem.style.WebkitBorderRadius // and the following would be incorrect: // elem.style.webkitBorderRadius // Webkit ghosts their properties in lowercase but Opera & Moz do not. // Microsoft uses a lowercase `ms` instead of the correct `Ms` in IE8+ // erik.eae.net/archives/2008/03/10/21.48.10/ // More here: github.com/Modernizr/Modernizr/issues/issue/21 omPrefixes = 'Webkit Moz O ms', cssomPrefixes = omPrefixes.split(' '), domPrefixes = omPrefixes.toLowerCase().split(' '), ns = {'svg': 'http://www.w3.org/2000/svg'}, tests = {}, inputs = {}, attrs = {}, classes = [], slice = classes.slice, featureName, // used in testing loop // Inject element with style element and some CSS rules injectElementWithStyles = function( rule, callback, nodes, testnames ) { var style, ret, node, div = document.createElement('div'), // After page load injecting a fake body doesn't work so check if body exists body = document.body, // IE6 and 7 won't return offsetWidth or offsetHeight unless it's in the body element, so we fake it. fakeBody = body ? body : document.createElement('body'); if ( parseInt(nodes, 10) ) { // In order not to give false positives we create a node for each test // This also allows the method to scale for unspecified uses while ( nodes-- ) { node = document.createElement('div'); node.id = testnames ? testnames[nodes] : mod + (nodes + 1); div.appendChild(node); } } // <style> elements in IE6-9 are considered 'NoScope' elements and therefore will be removed // when injected with innerHTML. To get around this you need to prepend the 'NoScope' element // with a 'scoped' element, in our case the soft-hyphen entity as it won't mess with our measurements. // msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx // Documents served as xml will throw if using &shy; so use xml friendly encoded version. See issue #277 style = ['&#173;','<style>', rule, '</style>'].join(''); div.id = mod; // IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody. // Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270 fakeBody.innerHTML += style; fakeBody.appendChild(div); if(!body){ //avoid crashing IE8, if background image is used fakeBody.style.background = ""; docElement.appendChild(fakeBody); } ret = callback(div, rule); // If this is done after page load we don't want to remove the body so check if body exists !body ? fakeBody.parentNode.removeChild(fakeBody) : div.parentNode.removeChild(div); return !!ret; }, // adapted from matchMedia polyfill // by Scott Jehl and Paul Irish // gist.github.com/786768 testMediaQuery = function( mq ) { var matchMedia = window.matchMedia || window.msMatchMedia; if ( matchMedia ) { return matchMedia(mq).matches; } var bool; injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function( node ) { bool = (window.getComputedStyle ? getComputedStyle(node, null) : node.currentStyle)['position'] == 'absolute'; }); return bool; }, /** * isEventSupported determines if a given element supports the given event * function from yura.thinkweb2.com/isEventSupported/ */ isEventSupported = (function() { var TAGNAMES = { 'select': 'input', 'change': 'input', 'submit': 'form', 'reset': 'form', 'error': 'img', 'load': 'img', 'abort': 'img' }; function isEventSupported( eventName, element ) { element = element || document.createElement(TAGNAMES[eventName] || 'div'); eventName = 'on' + eventName; // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those var isSupported = eventName in element; if ( !isSupported ) { // If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element if ( !element.setAttribute ) { element = document.createElement('div'); } if ( element.setAttribute && element.removeAttribute ) { element.setAttribute(eventName, ''); isSupported = is(element[eventName], 'function'); // If property was created, "remove it" (by setting value to `undefined`) if ( !is(element[eventName], 'undefined') ) { element[eventName] = undefined; } element.removeAttribute(eventName); } } element = null; return isSupported; } return isEventSupported; })(); // hasOwnProperty shim by kangax needed for Safari 2.0 support var _hasOwnProperty = ({}).hasOwnProperty, hasOwnProperty; if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) { hasOwnProperty = function (object, property) { return _hasOwnProperty.call(object, property); }; } else { hasOwnProperty = function (object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */ return ((property in object) && is(object.constructor.prototype[property], 'undefined')); }; } // Taken from ES5-shim https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js // ES-5 15.3.4.5 // http://es5.github.com/#x15.3.4.5 if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { var target = this; if (typeof target != "function") { throw new TypeError(); } var args = slice.call(arguments, 1), bound = function () { if (this instanceof bound) { var F = function(){}; F.prototype = target.prototype; var self = new F; var result = target.apply( self, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return self; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; return bound; }; } /** * setCss applies given styles to the Modernizr DOM node. */ function setCss( str ) { mStyle.cssText = str; } /** * setCssAll extrapolates all vendor-specific css strings. */ function setCssAll( str1, str2 ) { return setCss(prefixes.join(str1 + ';') + ( str2 || '' )); } /** * is returns a boolean for if typeof obj is exactly type. */ function is( obj, type ) { return typeof obj === type; } /** * contains returns a boolean for if substr is found within str. */ function contains( str, substr ) { return !!~('' + str).indexOf(substr); } /** * testProps is a generic CSS / DOM property test; if a browser supports * a certain property, it won't return undefined for it. * A supported CSS property returns empty string when its not yet set. */ function testProps( props, prefixed ) { for ( var i in props ) { if ( mStyle[ props[i] ] !== undefined ) { return prefixed == 'pfx' ? props[i] : true; } } return false; } /** * testDOMProps is a generic DOM property test; if a browser supports * a certain property, it won't return undefined for it. */ function testDOMProps( props, obj, elem ) { for ( var i in props ) { var item = obj[props[i]]; if ( item !== undefined) { // return the property name as a string if (elem === false) return props[i]; // let's bind a function if (is(item, 'function')){ // default to autobind unless override return item.bind(elem || obj); } // return the unbound function or obj or value return item; } } return false; } /** * testPropsAll tests a list of DOM properties we want to check against. * We specify literally ALL possible (known and/or likely) properties on * the element including the non-vendor prefixed one, for forward- * compatibility. */ function testPropsAll( prop, prefixed, elem ) { var ucProp = prop.charAt(0).toUpperCase() + prop.substr(1), props = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' '); // did they call .prefixed('boxSizing') or are we just testing a prop? if(is(prefixed, "string") || is(prefixed, "undefined")) { return testProps(props, prefixed); // otherwise, they called .prefixed('requestAnimationFrame', window[, elem]) } else { props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' '); return testDOMProps(props, prefixed, elem); } } /** * testBundle tests a list of CSS features that require element and style injection. * By bundling them together we can reduce the need to touch the DOM multiple times. */ /*>>testBundle*/ var testBundle = (function( styles, tests ) { var style = styles.join(''), len = tests.length; injectElementWithStyles(style, function( node, rule ) { var style = document.styleSheets[document.styleSheets.length - 1], // IE8 will bork if you create a custom build that excludes both fontface and generatedcontent tests. // So we check for cssRules and that there is a rule available // More here: github.com/Modernizr/Modernizr/issues/288 & github.com/Modernizr/Modernizr/issues/293 cssText = style ? (style.cssRules && style.cssRules[0] ? style.cssRules[0].cssText : style.cssText || '') : '', children = node.childNodes, hash = {}; while ( len-- ) { hash[children[len].id] = children[len]; } /*>>touch*/ Modernizr['touch'] = ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch || (hash['touch'] && hash['touch'].offsetTop) === 9; /*>>touch*/ /*>>csstransforms3d*/ Modernizr['csstransforms3d'] = (hash['csstransforms3d'] && hash['csstransforms3d'].offsetLeft) === 9 && hash['csstransforms3d'].offsetHeight === 3; /*>>csstransforms3d*/ /*>>generatedcontent*/Modernizr['generatedcontent'] = (hash['generatedcontent'] && hash['generatedcontent'].offsetHeight) >= 1; /*>>generatedcontent*/ /*>>fontface*/ Modernizr['fontface'] = /src/i.test(cssText) && cssText.indexOf(rule.split(' ')[0]) === 0; /*>>fontface*/ }, len, tests); })([ // Pass in styles to be injected into document /*>>fontface*/ '@font-face {font-family:"font";src:url("https://")}' /*>>fontface*/ /*>>touch*/ ,['@media (',prefixes.join('touch-enabled),('),mod,')', '{#touch{top:9px;position:absolute}}'].join('') /*>>touch*/ /*>>csstransforms3d*/ ,['@media (',prefixes.join('transform-3d),('),mod,')', '{#csstransforms3d{left:9px;position:absolute;height:3px;}}'].join('')/*>>csstransforms3d*/ /*>>generatedcontent*/,['#generatedcontent:after{content:"',smile,'";visibility:hidden}'].join('') /*>>generatedcontent*/ ], [ /*>>fontface*/ 'fontface' /*>>fontface*/ /*>>touch*/ ,'touch' /*>>touch*/ /*>>csstransforms3d*/ ,'csstransforms3d' /*>>csstransforms3d*/ /*>>generatedcontent*/,'generatedcontent' /*>>generatedcontent*/ ]);/*>>testBundle*/ /** * Tests * ----- */ // The *new* flexbox // dev.w3.org/csswg/css3-flexbox tests['flexbox'] = function() { return testPropsAll('flexOrder'); }; // The *old* flexbox // www.w3.org/TR/2009/WD-css3-flexbox-20090723/ tests['flexbox-legacy'] = function() { return testPropsAll('boxDirection'); }; // On the S60 and BB Storm, getContext exists, but always returns undefined // so we actually have to call getContext() to verify // github.com/Modernizr/Modernizr/issues/issue/97/ tests['canvas'] = function() { var elem = document.createElement('canvas'); return !!(elem.getContext && elem.getContext('2d')); }; tests['canvastext'] = function() { return !!(Modernizr['canvas'] && is(document.createElement('canvas').getContext('2d').fillText, 'function')); }; // this test initiates a new webgl context. // webk.it/70117 is tracking a legit feature detect proposal tests['webgl'] = function() { try { var canvas = document.createElement('canvas'), ret; ret = !!(window.WebGLRenderingContext && (canvas.getContext('experimental-webgl') || canvas.getContext('webgl'))); canvas = undefined; } catch (e){ ret = false; } return ret; }; /* * The Modernizr.touch test only indicates if the browser supports * touch events, which does not necessarily reflect a touchscreen * device, as evidenced by tablets running Windows 7 or, alas, * the Palm Pre / WebOS (touch) phones. * * Additionally, Chrome (desktop) used to lie about its support on this, * but that has since been rectified: crbug.com/36415 * * We also test for Firefox 4 Multitouch Support. * * For more info, see: modernizr.github.com/Modernizr/touch.html */ tests['touch'] = function() { return Modernizr['touch']; }; /** * geolocation tests for the new Geolocation API specification. * This test is a standards compliant-only test; for more complete * testing, including a Google Gears fallback, please see: * code.google.com/p/geo-location-javascript/ * or view a fallback solution using google's geo API: * gist.github.com/366184 */ tests['geolocation'] = function() { return !!navigator.geolocation; }; // Per 1.6: // This used to be Modernizr.crosswindowmessaging but the longer // name has been deprecated in favor of a shorter and property-matching one. // The old API is still available in 1.6, but as of 2.0 will throw a warning, // and in the first release thereafter disappear entirely. tests['postmessage'] = function() { return !!window.postMessage; }; // Chrome incognito mode used to throw an exception when using openDatabase // It doesn't anymore. tests['websqldatabase'] = function() { return !!window.openDatabase; }; // Vendors had inconsistent prefixing with the experimental Indexed DB: // - Webkit's implementation is accessible through webkitIndexedDB // - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB // For speed, we don't test the legacy (and beta-only) indexedDB tests['indexedDB'] = function() { return !!testPropsAll("indexedDB",window); }; // documentMode logic from YUI to filter out IE8 Compat Mode // which false positives. tests['hashchange'] = function() { return isEventSupported('hashchange', window) && (document.documentMode === undefined || document.documentMode > 7); }; // Per 1.6: // This used to be Modernizr.historymanagement but the longer // name has been deprecated in favor of a shorter and property-matching one. // The old API is still available in 1.6, but as of 2.0 will throw a warning, // and in the first release thereafter disappear entirely. tests['history'] = function() { return !!(window.history && history.pushState); }; tests['draganddrop'] = function() { var div = document.createElement('div'); return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div); }; // FIXME: Once FF10 is sunsetted, we can drop prefixed MozWebSocket // bugzil.la/695635 tests['websockets'] = function() { for ( var i = -1, len = cssomPrefixes.length; ++i < len; ){ if ( window[cssomPrefixes[i] + 'WebSocket'] ){ return true; } } return 'WebSocket' in window; }; // css-tricks.com/rgba-browser-support/ tests['rgba'] = function() { // Set an rgba() color and check the returned value setCss('background-color:rgba(150,255,150,.5)'); return contains(mStyle.backgroundColor, 'rgba'); }; tests['hsla'] = function() { // Same as rgba(), in fact, browsers re-map hsla() to rgba() internally, // except IE9 who retains it as hsla setCss('background-color:hsla(120,40%,100%,.5)'); return contains(mStyle.backgroundColor, 'rgba') || contains(mStyle.backgroundColor, 'hsla'); }; tests['multiplebgs'] = function() { // Setting multiple images AND a color on the background shorthand property // and then querying the style.background property value for the number of // occurrences of "url(" is a reliable method for detecting ACTUAL support for this! setCss('background:url(https://),url(https://),red url(https://)'); // If the UA supports multiple backgrounds, there should be three occurrences // of the string "url(" in the return value for elemStyle.background return /(url\s*\(.*?){3}/.test(mStyle.background); }; // In testing support for a given CSS property, it's legit to test: // `elem.style[styleName] !== undefined` // If the property is supported it will return an empty string, // if unsupported it will return undefined. // We'll take advantage of this quick test and skip setting a style // on our modernizr element, but instead just testing undefined vs // empty string. tests['backgroundsize'] = function() { return testPropsAll('backgroundSize'); }; tests['borderimage'] = function() { return testPropsAll('borderImage'); }; // Super comprehensive table about all the unique implementations of // border-radius: muddledramblings.com/table-of-css3-border-radius-compliance tests['borderradius'] = function() { return testPropsAll('borderRadius'); }; // WebOS unfortunately false positives on this test. tests['boxshadow'] = function() { return testPropsAll('boxShadow'); }; // FF3.0 will false positive on this test tests['textshadow'] = function() { return document.createElement('div').style.textShadow === ''; }; tests['opacity'] = function() { // Browsers that actually have CSS Opacity implemented have done so // according to spec, which means their return values are within the // range of [0.0,1.0] - including the leading zero. setCssAll('opacity:.55'); // The non-literal . in this regex is intentional: // German Chrome returns this value as 0,55 // github.com/Modernizr/Modernizr/issues/#issue/59/comment/516632 return /^0.55$/.test(mStyle.opacity); }; // Note, Android < 4 will pass this test, but can only animate // a single property at a time // daneden.me/2011/12/putting-up-with-androids-/ tests['cssanimations'] = function() { return testPropsAll('animationName'); }; tests['csscolumns'] = function() { return testPropsAll('columnCount'); }; tests['cssgradients'] = function() { /** * For CSS Gradients syntax, please see: * webkit.org/blog/175/introducing-css-gradients/ * developer.mozilla.org/en/CSS/-moz-linear-gradient * developer.mozilla.org/en/CSS/-moz-radial-gradient * dev.w3.org/csswg/css3-images/#gradients- */ var str1 = 'background-image:', str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));', str3 = 'linear-gradient(left top,#9f9, white);'; setCss( // legacy webkit syntax (FIXME: remove when syntax not in use anymore) (str1 + '-webkit- '.split(' ').join(str2 + str1) // standard syntax // trailing 'background-image:' + prefixes.join(str3 + str1)).slice(0, -str1.length) ); return contains(mStyle.backgroundImage, 'gradient'); }; tests['cssreflections'] = function() { return testPropsAll('boxReflect'); }; tests['csstransforms'] = function() { return !!testPropsAll('transform'); }; tests['csstransforms3d'] = function() { var ret = !!testPropsAll('perspective'); // Webkit's 3D transforms are passed off to the browser's own graphics renderer. // It works fine in Safari on Leopard and Snow Leopard, but not in Chrome in // some conditions. As a result, Webkit typically recognizes the syntax but // will sometimes throw a false positive, thus we must do a more thorough check: if ( ret && 'webkitPerspective' in docElement.style ) { // Webkit allows this media query to succeed only if the feature is enabled. // `@media (transform-3d),(-o-transform-3d),(-moz-transform-3d),(-ms-transform-3d),(-webkit-transform-3d),(modernizr){ ... }` ret = Modernizr['csstransforms3d']; } return ret; }; tests['csstransitions'] = function() { return testPropsAll('transition'); }; /*>>fontface*/ // @font-face detection routine by Diego Perini // javascript.nwbox.com/CSSSupport/ // false positives in WebOS: github.com/Modernizr/Modernizr/issues/342 tests['fontface'] = function() { return Modernizr['fontface']; }; /*>>fontface*/ // CSS generated content detection tests['generatedcontent'] = function() { return Modernizr['generatedcontent']; }; // These tests evaluate support of the video/audio elements, as well as // testing what types of content they support. // // We're using the Boolean constructor here, so that we can extend the value // e.g. Modernizr.video // true // Modernizr.video.ogg // 'probably' // // Codec values from : github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845 // thx to NielsLeenheer and zcorpan // Note: in some older browsers, "no" was a return value instead of empty string. // It was live in FF3.5.0 and 3.5.1, but fixed in 3.5.2 // It was also live in Safari 4.0.0 - 4.0.4, but fixed in 4.0.5 tests['video'] = function() { var elem = document.createElement('video'), bool = false; // IE9 Running on Windows Server SKU can cause an exception to be thrown, bug #224 try { if ( bool = !!elem.canPlayType ) { bool = new Boolean(bool); bool.ogg = elem.canPlayType('video/ogg; codecs="theora"') .replace(/^no$/,''); bool.h264 = elem.canPlayType('video/mp4; codecs="avc1.42E01E"') .replace(/^no$/,''); bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,''); } } catch(e) { } return bool; }; tests['audio'] = function() { var elem = document.createElement('audio'), bool = false; try { if ( bool = !!elem.canPlayType ) { bool = new Boolean(bool); bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,''); bool.mp3 = elem.canPlayType('audio/mpeg;') .replace(/^no$/,''); // Mimetypes accepted: // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements // bit.ly/iphoneoscodecs bool.wav = elem.canPlayType('audio/wav; codecs="1"') .replace(/^no$/,''); bool.m4a = ( elem.canPlayType('audio/x-m4a;') || elem.canPlayType('audio/aac;')) .replace(/^no$/,''); } } catch(e) { } return bool; }; // In FF4, if disabled, window.localStorage should === null. // Normally, we could not test that directly and need to do a // `('localStorage' in window) && ` test first because otherwise Firefox will // throw bugzil.la/365772 if cookies are disabled // Also in iOS5 Private Browsing mode, attepting to use localStorage.setItem // will throw the exception: // QUOTA_EXCEEDED_ERRROR DOM Exception 22. // Peculiarly, getItem and removeItem calls do not throw. // Because we are forced to try/catch this, we'll go aggressive. // Just FWIW: IE8 Compat mode supports these features completely: // www.quirksmode.org/dom/html5.html // But IE8 doesn't support either with local files tests['localstorage'] = function() { try { localStorage.setItem(mod, mod); localStorage.removeItem(mod); return true; } catch(e) { return false; } }; tests['sessionstorage'] = function() { try { sessionStorage.setItem(mod, mod); sessionStorage.removeItem(mod); return true; } catch(e) { return false; } }; tests['webworkers'] = function() { return !!window.Worker; }; tests['applicationcache'] = function() { return !!window.applicationCache; }; // Thanks to Erik Dahlstrom tests['svg'] = function() { return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect; }; // specifically for SVG inline in HTML, not within XHTML // test page: paulirish.com/demo/inline-svg tests['inlinesvg'] = function() { var div = document.createElement('div'); div.innerHTML = '<svg/>'; return (div.firstChild && div.firstChild.namespaceURI) == ns.svg; }; // SVG SMIL animation tests['smil'] = function() { return !!document.createElementNS && /SVGAnimate/.test(toString.call(document.createElementNS(ns.svg, 'animate'))); }; // This test is only for clip paths in SVG proper, not clip paths on HTML content // demo: srufaculty.sru.edu/david.dailey/svg/newstuff/clipPath4.svg // However read the comments to dig into applying SVG clippaths to HTML content here: // github.com/Modernizr/Modernizr/issues/213#issuecomment-1149491 tests['svgclippaths'] = function() { return !!document.createElementNS && /SVGClipPath/.test(toString.call(document.createElementNS(ns.svg, 'clipPath'))); }; // input features and input types go directly onto the ret object, bypassing the tests loop. // Hold this guy to execute in a moment. function webforms() { // Run through HTML5's new input attributes to see if the UA understands any. // We're using f which is the <input> element created early on // Mike Taylr has created a comprehensive resource for testing these attributes // when applied to all input types: // miketaylr.com/code/input-type-attr.html // spec: www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary // Only input placeholder is tested while textarea's placeholder is not. // Currently Safari 4 and Opera 11 have support only for the input placeholder // Both tests are available in feature-detects/forms-placeholder.js Modernizr['input'] = (function( props ) { for ( var i = 0, len = props.length; i < len; i++ ) { attrs[ props[i] ] = !!(props[i] in inputElem); } if (attrs.list){ // safari false positive's on datalist: webk.it/74252 // see also github.com/Modernizr/Modernizr/issues/146 attrs.list = !!(document.createElement('datalist') && window.HTMLDataListElement); } return attrs; })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' ')); // Run through HTML5's new input types to see if the UA understands any. // This is put behind the tests runloop because it doesn't return a // true/false like all the other tests; instead, it returns an object // containing each input type with its corresponding true/false value // Big thanks to @miketaylr for the html5 forms expertise. miketaylr.com/ Modernizr['inputtypes'] = (function(props) { for ( var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++ ) { inputElem.setAttribute('type', inputElemType = props[i]); bool = inputElem.type !== 'text'; // We first check to see if the type we give it sticks.. // If the type does, we feed it a textual value, which shouldn't be valid. // If the value doesn't stick, we know there's input sanitization which infers a custom UI if ( bool ) { inputElem.value = smile; inputElem.style.cssText = 'position:absolute;visibility:hidden;'; if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) { docElement.appendChild(inputElem); defaultView = document.defaultView; // Safari 2-4 allows the smiley as a value, despite making a slider bool = defaultView.getComputedStyle && defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' && // Mobile android web browser has false positive, so must // check the height to see if the widget is actually there. (inputElem.offsetHeight !== 0); docElement.removeChild(inputElem); } else if ( /^(search|tel)$/.test(inputElemType) ){ // Spec doesnt define any special parsing or detectable UI // behaviors so we pass these through as true // Interestingly, opera fails the earlier test, so it doesn't // even make it here. } else if ( /^(url|email)$/.test(inputElemType) ) { // Real url and email support comes with prebaked validation. bool = inputElem.checkValidity && inputElem.checkValidity() === false; } else if ( /^color$/.test(inputElemType) ) { // chuck into DOM and force reflow for Opera bug in 11.00 // github.com/Modernizr/Modernizr/issues#issue/159 docElement.appendChild(inputElem); docElement.offsetWidth; bool = inputElem.value != smile; docElement.removeChild(inputElem); } else { // If the upgraded input compontent rejects the :) text, we got a winner bool = inputElem.value != smile; } } inputs[ props[i] ] = !!bool; } return inputs; })('search tel url email datetime date month week time datetime-local number range color'.split(' ')); } // End of test definitions // ----------------------- // Run through all tests and detect their support in the current UA. // todo: hypothetically we could be doing an array of tests and use a basic loop here. for ( var feature in tests ) { if ( hasOwnProperty(tests, feature) ) { // run the test, throw the return value into the Modernizr, // then based on that boolean, define an appropriate className // and push it into an array of classes we'll join later. featureName = feature.toLowerCase(); Modernizr[featureName] = tests[feature](); classes.push((Modernizr[featureName] ? '' : 'no-') + featureName); } } // input tests need to run. Modernizr.input || webforms(); /** * addTest allows the user to define their own feature tests * the result will be added onto the Modernizr object, * as well as an appropriate className set on the html element * * @param feature - String naming the feature * @param test - Function returning true if feature is supported, false if not */ Modernizr.addTest = function ( feature, test ) { if ( typeof feature == 'object' ) { for ( var key in feature ) { if ( hasOwnProperty( feature, key ) ) { Modernizr.addTest( key, feature[ key ] ); } } } else { feature = feature.toLowerCase(); if ( Modernizr[feature] !== undefined ) { // we're going to quit if you're trying to overwrite an existing test // if we were to allow it, we'd do this: // var re = new RegExp("\\b(no-)?" + feature + "\\b"); // docElement.className = docElement.className.replace( re, '' ); // but, no rly, stuff 'em. return Modernizr; } test = typeof test == 'function' ? test() : test; docElement.className += ' ' + (test ? '' : 'no-') + feature; Modernizr[feature] = test; } return Modernizr; // allow chaining. }; // Reset modElem.cssText to nothing to reduce memory footprint. setCss(''); modElem = inputElem = null; //>>BEGIN IEPP // Enable HTML 5 elements for styling in IE & add HTML5 css /*! HTML5 Shiv v3.4 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed */ ;(function(window, document) { /** Preset options */ var options = window.html5 || {}; /** Used to skip problem elements */ var reSkip = /^<|^(?:button|form|map|select|textarea)$/i; /** Detect whether the browser supports default html5 styles */ var supportsHtml5Styles; /** Detect whether the browser supports unknown elements */ var supportsUnknownElements; (function() { var a = document.createElement('a'); a.innerHTML = '<xyz></xyz>'; //if the hidden property is implemented we can assume, that the browser supports HTML5 Styles supportsHtml5Styles = ('hidden' in a); supportsUnknownElements = a.childNodes.length == 1 || (function() { // assign a false positive if unable to shiv try { (document.createElement)('a'); } catch(e) { return true; } var frag = document.createDocumentFragment(); return ( typeof frag.cloneNode == 'undefined' || typeof frag.createDocumentFragment == 'undefined' || typeof frag.createElement == 'undefined' ); }()); }()); /*--------------------------------------------------------------------------*/ /** * Creates a style sheet with the given CSS text and adds it to the document. * @private * @param {Document} ownerDocument The document. * @param {String} cssText The CSS text. * @returns {StyleSheet} The style element. */ function addStyleSheet(ownerDocument, cssText) { var p = ownerDocument.createElement('p'), parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement; p.innerHTML = 'x<style>' + cssText + '</style>'; return parent.insertBefore(p.lastChild, parent.firstChild); } /** * Returns the value of `html5.elements` as an array. * @private * @returns {Array} An array of shived element node names. */ function getElements() { var elements = html5.elements; return typeof elements == 'string' ? elements.split(' ') : elements; } /** * Shivs the `createElement` and `createDocumentFragment` methods of the document. * @private * @param {Document|DocumentFragment} ownerDocument The document. */ function shivMethods(ownerDocument) { var cache = {}, docCreateElement = ownerDocument.createElement, docCreateFragment = ownerDocument.createDocumentFragment, frag = docCreateFragment(); ownerDocument.createElement = function(nodeName) { // Avoid adding some elements to fragments in IE < 9 because // * Attributes like `name` or `type` cannot be set/changed once an element // is inserted into a document/fragment // * Link elements with `src` attributes that are inaccessible, as with // a 403 response, will cause the tab/window to crash // * Script elements appended to fragments will execute when their `src` // or `text` property is set var node = (cache[nodeName] || (cache[nodeName] = docCreateElement(nodeName))).cloneNode(); return html5.shivMethods && node.canHaveChildren && !reSkip.test(nodeName) ? frag.appendChild(node) : node; }; ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' + 'var n=f.cloneNode(),c=n.createElement;' + 'h.shivMethods&&(' + // unroll the `createElement` calls getElements().join().replace(/\w+/g, function(nodeName) { cache[nodeName] = docCreateElement(nodeName); frag.createElement(nodeName); return 'c("' + nodeName + '")'; }) + ');return n}' )(html5, frag); } /*--------------------------------------------------------------------------*/ /** * Shivs the given document. * @memberOf html5 * @param {Document} ownerDocument The document to shiv. * @returns {Document} The shived document. */ function shivDocument(ownerDocument) { var shived; if (ownerDocument.documentShived) { return ownerDocument; } if (html5.shivCSS && !supportsHtml5Styles) { shived = !!addStyleSheet(ownerDocument, // corrects block display not defined in IE6/7/8/9 'article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}' + // corrects audio display not defined in IE6/7/8/9 'audio{display:none}' + // corrects canvas and video display not defined in IE6/7/8/9 'canvas,video{display:inline-block;*display:inline;*zoom:1}' + // corrects 'hidden' attribute and audio[controls] display not present in IE7/8/9 '[hidden]{display:none}audio[controls]{display:inline-block;*display:inline;*zoom:1}' + // adds styling not present in IE6/7/8/9 'mark{background:#FF0;color:#000}' ); } if (!supportsUnknownElements) { shived = !shivMethods(ownerDocument); } if (shived) { ownerDocument.documentShived = shived; } return ownerDocument; } /*--------------------------------------------------------------------------*/ /** * The `html5` object is exposed so that more elements can be shived and * existing shiving can be detected on iframes. * @type Object * @example * * // options can be changed before the script is included * html5 = { 'elements': 'mark section', 'shivCSS': false, 'shivMethods': false }; */ var html5 = { /** * An array or space separated string of node names of the elements to shiv. * @memberOf html5 * @type Array|String */ 'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video', /** * A flag to indicate that the HTML5 style sheet should be inserted. * @memberOf html5 * @type Boolean */ 'shivCSS': !(options.shivCSS === false), /** * A flag to indicate that the document's `createElement` and `createDocumentFragment` * methods should be overwritten. * @memberOf html5 * @type Boolean */ 'shivMethods': !(options.shivMethods === false), /** * A string to describe the type of `html5` object ("default" or "default print"). * @memberOf html5 * @type String */ 'type': 'default', // shivs the document according to the specified `html5` object options 'shivDocument': shivDocument }; /*--------------------------------------------------------------------------*/ // expose html5 window.html5 = html5; // shiv the document shivDocument(document); }(this, document)); //>>END IEPP // Assign private properties to the return object with prefix Modernizr._version = version; // expose these for the plugin API. Look in the source for how to join() them against your input Modernizr._prefixes = prefixes; Modernizr._domPrefixes = domPrefixes; Modernizr._cssomPrefixes = cssomPrefixes; // Modernizr.mq tests a given media query, live against the current state of the window // A few important notes: // * If a browser does not support media queries at all (eg. oldIE) the mq() will always return false // * A max-width or orientation query will be evaluated against the current state, which may change later. // * You must specify values. Eg. If you are testing support for the min-width media query use: // Modernizr.mq('(min-width:0)') // usage: // Modernizr.mq('only screen and (max-width:768)') Modernizr.mq = testMediaQuery; // Modernizr.hasEvent() detects support for a given event, with an optional element to test on // Modernizr.hasEvent('gesturestart', elem) Modernizr.hasEvent = isEventSupported; // Modernizr.testProp() investigates whether a given style property is recognized // Note that the property names must be provided in the camelCase variant. // Modernizr.testProp('pointerEvents') Modernizr.testProp = function(prop){ return testProps([prop]); }; // Modernizr.testAllProps() investigates whether a given style property, // or any of its vendor-prefixed variants, is recognized // Note that the property names must be provided in the camelCase variant. // Modernizr.testAllProps('boxSizing') Modernizr.testAllProps = testPropsAll; // Modernizr.testStyles() allows you to add custom styles to the document and test an element afterwards // Modernizr.testStyles('#modernizr { position:absolute }', function(elem, rule){ ... }) Modernizr.testStyles = injectElementWithStyles; // Modernizr.prefixed() returns the prefixed or nonprefixed property name variant of your input // Modernizr.prefixed('boxSizing') // 'MozBoxSizing' // Properties must be passed as dom-style camelcase, rather than `box-sizing` hypentated style. // Return values will also be the camelCase variant, if you need to translate that to hypenated style use: // // str.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-'); // If you're trying to ascertain which transition end event to bind to, you might do something like... // // var transEndEventNames = { // 'WebkitTransition' : 'webkitTransitionEnd', // 'MozTransition' : 'transitionend', // 'OTransition' : 'oTransitionEnd', // 'msTransition' : 'MsTransitionEnd', // 'transition' : 'transitionend' // }, // transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ]; Modernizr.prefixed = function(prop, obj, elem){ if(!obj) { return testPropsAll(prop, 'pfx'); } else { // Testing DOM property e.g. Modernizr.prefixed('requestAnimationFrame', window) // 'mozRequestAnimationFrame' return testPropsAll(prop, obj, elem); } }; // Remove "no-js" class from <html> element, if it exists: docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') + // Add the new classes to the <html> element. (enableClasses ? ' js ' + classes.join(' ') : ''); return Modernizr; })(this, this.document); // SIG // Begin signature block // SIG // MIIauwYJKoZIhvcNAQcCoIIarDCCGqgCAQExCzAJBgUr // SIG // DgMCGgUAMGcGCisGAQQBgjcCAQSgWTBXMDIGCisGAQQB // SIG // gjcCAR4wJAIBAQQQEODJBs441BGiowAQS9NQkAIBAAIB // SIG // AAIBAAIBAAIBADAhMAkGBSsOAwIaBQAEFL5NOc6WtHqB // SIG // oOwzpwZJs+xGjnxhoIIVgjCCBMMwggOroAMCAQICEzMA // SIG // AAA0JDFAyaDBeY0AAAAAADQwDQYJKoZIhvcNAQEFBQAw // SIG // dzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0 // SIG // b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p // SIG // Y3Jvc29mdCBDb3Jwb3JhdGlvbjEhMB8GA1UEAxMYTWlj // SIG // cm9zb2Z0IFRpbWUtU3RhbXAgUENBMB4XDTEzMDMyNzIw // SIG // MDgyNVoXDTE0MDYyNzIwMDgyNVowgbMxCzAJBgNVBAYT // SIG // AlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQH // SIG // EwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29y // SIG // cG9yYXRpb24xDTALBgNVBAsTBE1PUFIxJzAlBgNVBAsT // SIG // Hm5DaXBoZXIgRFNFIEVTTjpCOEVDLTMwQTQtNzE0NDEl // SIG // MCMGA1UEAxMcTWljcm9zb2Z0IFRpbWUtU3RhbXAgU2Vy // SIG // dmljZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC // SIG // ggEBAOUaB60KlizUtjRkyzQg8rwEWIKLtQncUtRwn+Jc // SIG // LOf1aqT1ti6xgYZZAexJbCkEHvU4i1cY9cAyDe00kOzG // SIG // ReW7igolqu+he4fY8XBnSs1q3OavBZE97QVw60HPq7El // SIG // ZrurorcY+XgTeHXNizNcfe1nxO0D/SisWGDBe72AjTOT // SIG // YWIIsY9REmWPQX7E1SXpLWZB00M0+peB+PyHoe05Uh/4 // SIG // 6T7/XoDJBjYH29u5asc3z4a1GktK1CXyx8iNr2FnitpT // SIG // L/NMHoMsY8qgEFIRuoFYc0KE4zSy7uqTvkyC0H2WC09/ // SIG // L88QXRpFZqsC8V8kAEbBwVXSg3JCIoY6pL6TUAECAwEA // SIG // AaOCAQkwggEFMB0GA1UdDgQWBBRfS0LeDLk4oNRmNo1W // SIG // +3RZSWaBKzAfBgNVHSMEGDAWgBQjNPjZUkZwCu1A+3b7 // SIG // syuwwzWzDzBUBgNVHR8ETTBLMEmgR6BFhkNodHRwOi8v // SIG // Y3JsLm1pY3Jvc29mdC5jb20vcGtpL2NybC9wcm9kdWN0 // SIG // cy9NaWNyb3NvZnRUaW1lU3RhbXBQQ0EuY3JsMFgGCCsG // SIG // AQUFBwEBBEwwSjBIBggrBgEFBQcwAoY8aHR0cDovL3d3 // SIG // dy5taWNyb3NvZnQuY29tL3BraS9jZXJ0cy9NaWNyb3Nv // SIG // ZnRUaW1lU3RhbXBQQ0EuY3J0MBMGA1UdJQQMMAoGCCsG // SIG // AQUFBwMIMA0GCSqGSIb3DQEBBQUAA4IBAQAPQlCg1R6t // SIG // Fz8fCqYrN4pnWC2xME8778JXaexl00zFUHLycyX25IQC // SIG // xXUccVhDq/HJqo7fym9YPInnL816Nexm19Veuo6fV4aU // SIG // EKDrUTetV/YneyNPGdjgbXYEJTBhEq2ljqMmtkjlU/JF // SIG // TsW4iScQnanjzyPpeWyuk2g6GvMTxBS2ejqeQdqZVp7Q // SIG // 0+AWlpByTK8B9yQG+xkrmLJVzHqf6JI6azF7gPMOnleL // SIG // t+YFtjklmpeCKTaLOK6uixqs7ufsLr9LLqUHNYHzEyDq // SIG // tEqTnr+cg1Z/rRUvXClxC5RnOPwwv2Xn9Tne6iLth4yr // SIG // sju1AcKt4PyOJRUMIr6fDO0dMIIE7DCCA9SgAwIBAgIT // SIG // MwAAALARrwqL0Duf3QABAAAAsDANBgkqhkiG9w0BAQUF // SIG // ADB5MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGlu // SIG // Z3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMV // SIG // TWljcm9zb2Z0IENvcnBvcmF0aW9uMSMwIQYDVQQDExpN // SIG // aWNyb3NvZnQgQ29kZSBTaWduaW5nIFBDQTAeFw0xMzAx // SIG // MjQyMjMzMzlaFw0xNDA0MjQyMjMzMzlaMIGDMQswCQYD // SIG // VQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G // SIG // A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0 // SIG // IENvcnBvcmF0aW9uMQ0wCwYDVQQLEwRNT1BSMR4wHAYD // SIG // VQQDExVNaWNyb3NvZnQgQ29ycG9yYXRpb24wggEiMA0G // SIG // CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDor1yiIA34 // SIG // KHy8BXt/re7rdqwoUz8620B9s44z5lc/pVEVNFSlz7SL // SIG // qT+oN+EtUO01Fk7vTXrbE3aIsCzwWVyp6+HXKXXkG4Un // SIG // m/P4LZ5BNisLQPu+O7q5XHWTFlJLyjPFN7Dz636o9UEV // SIG // XAhlHSE38Cy6IgsQsRCddyKFhHxPuRuQsPWj/ov0DJpO // SIG // oPXJCiHiquMBNkf9L4JqgQP1qTXclFed+0vUDoLbOI8S // SIG // /uPWenSIZOFixCUuKq6dGB8OHrbCryS0DlC83hyTXEmm // SIG // ebW22875cHsoAYS4KinPv6kFBeHgD3FN/a1cI4Mp68fF // SIG // SsjoJ4TTfsZDC5UABbFPZXHFAgMBAAGjggFgMIIBXDAT // SIG // BgNVHSUEDDAKBggrBgEFBQcDAzAdBgNVHQ4EFgQUWXGm // SIG // WjNN2pgHgP+EHr6H+XIyQfIwUQYDVR0RBEowSKRGMEQx // SIG // DTALBgNVBAsTBE1PUFIxMzAxBgNVBAUTKjMxNTk1KzRm // SIG // YWYwYjcxLWFkMzctNGFhMy1hNjcxLTc2YmMwNTIzNDRh // SIG // ZDAfBgNVHSMEGDAWgBTLEejK0rQWWAHJNy4zFha5TJoK // SIG // HzBWBgNVHR8ETzBNMEugSaBHhkVodHRwOi8vY3JsLm1p // SIG // Y3Jvc29mdC5jb20vcGtpL2NybC9wcm9kdWN0cy9NaWND // SIG // b2RTaWdQQ0FfMDgtMzEtMjAxMC5jcmwwWgYIKwYBBQUH // SIG // AQEETjBMMEoGCCsGAQUFBzAChj5odHRwOi8vd3d3Lm1p // SIG // Y3Jvc29mdC5jb20vcGtpL2NlcnRzL01pY0NvZFNpZ1BD // SIG // QV8wOC0zMS0yMDEwLmNydDANBgkqhkiG9w0BAQUFAAOC // SIG // AQEAMdduKhJXM4HVncbr+TrURE0Inu5e32pbt3nPApy8 // SIG // dmiekKGcC8N/oozxTbqVOfsN4OGb9F0kDxuNiBU6fNut // SIG // zrPJbLo5LEV9JBFUJjANDf9H6gMH5eRmXSx7nR2pEPoc // SIG // sHTyT2lrnqkkhNrtlqDfc6TvahqsS2Ke8XzAFH9IzU2y // SIG // RPnwPJNtQtjofOYXoJtoaAko+QKX7xEDumdSrcHps3Om // SIG // 0mPNSuI+5PNO/f+h4LsCEztdIN5VP6OukEAxOHUoXgSp // SIG // Rm3m9Xp5QL0fzehF1a7iXT71dcfmZmNgzNWahIeNJDD3 // SIG // 7zTQYx2xQmdKDku/Og7vtpU6pzjkJZIIpohmgjCCBbww // SIG // ggOkoAMCAQICCmEzJhoAAAAAADEwDQYJKoZIhvcNAQEF // SIG // BQAwXzETMBEGCgmSJomT8ixkARkWA2NvbTEZMBcGCgmS // SIG // JomT8ixkARkWCW1pY3Jvc29mdDEtMCsGA1UEAxMkTWlj // SIG // cm9zb2Z0IFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5 // SIG // MB4XDTEwMDgzMTIyMTkzMloXDTIwMDgzMTIyMjkzMlow // SIG // eTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0 // SIG // b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p // SIG // Y3Jvc29mdCBDb3Jwb3JhdGlvbjEjMCEGA1UEAxMaTWlj // SIG // cm9zb2Z0IENvZGUgU2lnbmluZyBQQ0EwggEiMA0GCSqG // SIG // SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCycllcGTBkvx2a // SIG // YCAgQpl2U2w+G9ZvzMvx6mv+lxYQ4N86dIMaty+gMuz/ // SIG // 3sJCTiPVcgDbNVcKicquIEn08GisTUuNpb15S3GbRwfa // SIG // /SXfnXWIz6pzRH/XgdvzvfI2pMlcRdyvrT3gKGiXGqel // SIG // cnNW8ReU5P01lHKg1nZfHndFg4U4FtBzWwW6Z1KNpbJp // SIG // L9oZC/6SdCnidi9U3RQwWfjSjWL9y8lfRjFQuScT5EAw // SIG // z3IpECgixzdOPaAyPZDNoTgGhVxOVoIoKgUyt0vXT2Pn // SIG // 0i1i8UU956wIAPZGoZ7RW4wmU+h6qkryRs83PDietHdc // SIG // pReejcsRj1Y8wawJXwPTAgMBAAGjggFeMIIBWjAPBgNV // SIG // HRMBAf8EBTADAQH/MB0GA1UdDgQWBBTLEejK0rQWWAHJ // SIG // Ny4zFha5TJoKHzALBgNVHQ8EBAMCAYYwEgYJKwYBBAGC // SIG // NxUBBAUCAwEAATAjBgkrBgEEAYI3FQIEFgQU/dExTtMm // SIG // ipXhmGA7qDFvpjy82C0wGQYJKwYBBAGCNxQCBAweCgBT // SIG // AHUAYgBDAEEwHwYDVR0jBBgwFoAUDqyCYEBWJ5flJRP8 // SIG // KuEKU5VZ5KQwUAYDVR0fBEkwRzBFoEOgQYY/aHR0cDov // SIG // L2NybC5taWNyb3NvZnQuY29tL3BraS9jcmwvcHJvZHVj // SIG // dHMvbWljcm9zb2Z0cm9vdGNlcnQuY3JsMFQGCCsGAQUF // SIG // BwEBBEgwRjBEBggrBgEFBQcwAoY4aHR0cDovL3d3dy5t // SIG // aWNyb3NvZnQuY29tL3BraS9jZXJ0cy9NaWNyb3NvZnRS // SIG // b290Q2VydC5jcnQwDQYJKoZIhvcNAQEFBQADggIBAFk5 // SIG // Pn8mRq/rb0CxMrVq6w4vbqhJ9+tfde1MOy3XQ60L/svp // SIG // LTGjI8x8UJiAIV2sPS9MuqKoVpzjcLu4tPh5tUly9z7q // SIG // QX/K4QwXaculnCAt+gtQxFbNLeNK0rxw56gNogOlVuC4 // SIG // iktX8pVCnPHz7+7jhh80PLhWmvBTI4UqpIIck+KUBx3y // SIG // 4k74jKHK6BOlkU7IG9KPcpUqcW2bGvgc8FPWZ8wi/1wd // SIG // zaKMvSeyeWNWRKJRzfnpo1hW3ZsCRUQvX/TartSCMm78 // SIG // pJUT5Otp56miLL7IKxAOZY6Z2/Wi+hImCWU4lPF6H0q7 // SIG // 0eFW6NB4lhhcyTUWX92THUmOLb6tNEQc7hAVGgBd3TVb // SIG // Ic6YxwnuhQ6MT20OE049fClInHLR82zKwexwo1eSV32U // SIG // jaAbSANa98+jZwp0pTbtLS8XyOZyNxL0b7E8Z4L5UrKN // SIG // MxZlHg6K3RDeZPRvzkbU0xfpecQEtNP7LN8fip6sCvsT // SIG // J0Ct5PnhqX9GuwdgR2VgQE6wQuxO7bN2edgKNAltHIAx // SIG // H+IOVN3lofvlRxCtZJj/UBYufL8FIXrilUEnacOTj5XJ // SIG // jdibIa4NXJzwoq6GaIMMai27dmsAHZat8hZ79haDJLmI // SIG // z2qoRzEvmtzjcT3XAH5iR9HOiMm4GPoOco3Boz2vAkBq // SIG // /2mbluIQqBC0N1AI1sM9MIIGBzCCA++gAwIBAgIKYRZo // SIG // NAAAAAAAHDANBgkqhkiG9w0BAQUFADBfMRMwEQYKCZIm // SIG // iZPyLGQBGRYDY29tMRkwFwYKCZImiZPyLGQBGRYJbWlj // SIG // cm9zb2Z0MS0wKwYDVQQDEyRNaWNyb3NvZnQgUm9vdCBD // SIG // ZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcNMDcwNDAzMTI1 // SIG // MzA5WhcNMjEwNDAzMTMwMzA5WjB3MQswCQYDVQQGEwJV // SIG // UzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMH // SIG // UmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBv // SIG // cmF0aW9uMSEwHwYDVQQDExhNaWNyb3NvZnQgVGltZS1T // SIG // dGFtcCBQQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw // SIG // ggEKAoIBAQCfoWyx39tIkip8ay4Z4b3i48WZUSNQrc7d // SIG // GE4kD+7Rp9FMrXQwIBHrB9VUlRVJlBtCkq6YXDAm2gBr // SIG // 6Hu97IkHD/cOBJjwicwfyzMkh53y9GccLPx754gd6udO // SIG // o6HBI1PKjfpFzwnQXq/QsEIEovmmbJNn1yjcRlOwhtDl // SIG // KEYuJ6yGT1VSDOQDLPtqkJAwbofzWTCd+n7Wl7PoIZd+ // SIG // +NIT8wi3U21StEWQn0gASkdmEScpZqiX5NMGgUqi+YSn // SIG // EUcUCYKfhO1VeP4Bmh1QCIUAEDBG7bfeI0a7xC1Un68e // SIG // eEExd8yb3zuDk6FhArUdDbH895uyAc4iS1T/+QXDwiAL // SIG // AgMBAAGjggGrMIIBpzAPBgNVHRMBAf8EBTADAQH/MB0G // SIG // A1UdDgQWBBQjNPjZUkZwCu1A+3b7syuwwzWzDzALBgNV // SIG // HQ8EBAMCAYYwEAYJKwYBBAGCNxUBBAMCAQAwgZgGA1Ud // SIG // IwSBkDCBjYAUDqyCYEBWJ5flJRP8KuEKU5VZ5KShY6Rh // SIG // MF8xEzARBgoJkiaJk/IsZAEZFgNjb20xGTAXBgoJkiaJ // SIG // k/IsZAEZFgltaWNyb3NvZnQxLTArBgNVBAMTJE1pY3Jv // SIG // c29mdCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eYIQ // SIG // ea0WoUqgpa1Mc1j0BxMuZTBQBgNVHR8ESTBHMEWgQ6BB // SIG // hj9odHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpL2Ny // SIG // bC9wcm9kdWN0cy9taWNyb3NvZnRyb290Y2VydC5jcmww // SIG // VAYIKwYBBQUHAQEESDBGMEQGCCsGAQUFBzAChjhodHRw // SIG // Oi8vd3d3Lm1pY3Jvc29mdC5jb20vcGtpL2NlcnRzL01p // SIG // Y3Jvc29mdFJvb3RDZXJ0LmNydDATBgNVHSUEDDAKBggr // SIG // BgEFBQcDCDANBgkqhkiG9w0BAQUFAAOCAgEAEJeKw1wD // SIG // RDbd6bStd9vOeVFNAbEudHFbbQwTq86+e4+4LtQSooxt // SIG // YrhXAstOIBNQmd16QOJXu69YmhzhHQGGrLt48ovQ7DsB // SIG // 7uK+jwoFyI1I4vBTFd1Pq5Lk541q1YDB5pTyBi+FA+mR // SIG // KiQicPv2/OR4mS4N9wficLwYTp2OawpylbihOZxnLcVR // SIG // DupiXD8WmIsgP+IHGjL5zDFKdjE9K3ILyOpwPf+FChPf // SIG // wgphjvDXuBfrTot/xTUrXqO/67x9C0J71FNyIe4wyrt4 // SIG // ZVxbARcKFA7S2hSY9Ty5ZlizLS/n+YWGzFFW6J1wlGys // SIG // OUzU9nm/qhh6YinvopspNAZ3GmLJPR5tH4LwC8csu89D // SIG // s+X57H2146SodDW4TsVxIxImdgs8UoxxWkZDFLyzs7BN // SIG // Z8ifQv+AeSGAnhUwZuhCEl4ayJ4iIdBD6Svpu/RIzCzU // SIG // 2DKATCYqSCRfWupW76bemZ3KOm+9gSd0BhHudiG/m4LB // SIG // J1S2sWo9iaF2YbRuoROmv6pH8BJv/YoybLL+31HIjCPJ // SIG // Zr2dHYcSZAI9La9Zj7jkIeW1sMpjtHhUBdRBLlCslLCl // SIG // eKuzoJZ1GtmShxN1Ii8yqAhuoFuMJb+g74TKIdbrHk/J // SIG // mu5J4PcBZW+JC33Iacjmbuqnl84xKf8OxVtc2E0bodj6 // SIG // L54/LlUWa8kTo/0xggSlMIIEoQIBATCBkDB5MQswCQYD // SIG // VQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G // SIG // A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0 // SIG // IENvcnBvcmF0aW9uMSMwIQYDVQQDExpNaWNyb3NvZnQg // SIG // Q29kZSBTaWduaW5nIFBDQQITMwAAALARrwqL0Duf3QAB // SIG // AAAAsDAJBgUrDgMCGgUAoIG+MBkGCSqGSIb3DQEJAzEM // SIG // BgorBgEEAYI3AgEEMBwGCisGAQQBgjcCAQsxDjAMBgor // SIG // BgEEAYI3AgEVMCMGCSqGSIb3DQEJBDEWBBSJZhbwK8v5 // SIG // lahcL/uTLr8oqyy8mDBeBgorBgEEAYI3AgEMMVAwTqAm // SIG // gCQATQBpAGMAcgBvAHMAbwBmAHQAIABMAGUAYQByAG4A // SIG // aQBuAGehJIAiaHR0cDovL3d3dy5taWNyb3NvZnQuY29t // SIG // L2xlYXJuaW5nIDANBgkqhkiG9w0BAQEFAASCAQCP9Wmn // SIG // DCItGYXxffdaIHfPqp3Bb07Trksi8RS51CHWfUPPpc9v // SIG // e5Wdo5u4xuDXYtc5yvxiUsHC4i7ofM7IwLlQEgphZdrO // SIG // 5vQ99VxaMWAdHARM+soeFJFzfn9KG66VtTCN+ONOYqbh // SIG // VOIqsmetPJMemnWhHrfLeN1bgadwQ743BN5eqSUe96RQ // SIG // e2PKsNfKea95Yvum85zxNLNK9xuQH1LtXaKfqauD96M9 // SIG // U/rQYuT2xsOlBOUueNsus2MnquHte2zL78gerTJyqMOw // SIG // 6tugCwNxsyMqw8y6ZyfyMiZIdouR37agp4viFX3ICwBO // SIG // Ot6l7vUMraR9Ta3G30JwXVS+y074oYICKDCCAiQGCSqG // SIG // SIb3DQEJBjGCAhUwggIRAgEBMIGOMHcxCzAJBgNVBAYT // SIG // AlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQH // SIG // EwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29y // SIG // cG9yYXRpb24xITAfBgNVBAMTGE1pY3Jvc29mdCBUaW1l // SIG // LVN0YW1wIFBDQQITMwAAADQkMUDJoMF5jQAAAAAANDAJ // SIG // BgUrDgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3 // SIG // DQEHATAcBgkqhkiG9w0BCQUxDxcNMTMwNDIzMjAxODMx // SIG // WjAjBgkqhkiG9w0BCQQxFgQUwJz+aWRTlXRTu1R8mdIZ // SIG // M/dcjvAwDQYJKoZIhvcNAQEFBQAEggEAbXzhHu25tAte // SIG // HJofJnm178UZ5KmAhnU9I8kz1iIBK9cq+EIApm+QD1c2 // SIG // qaY1gYwSc20g6ef+Ywu7VptX+TL5jMBZApDhmIXUF3Tw // SIG // wVpBf3krZ5h3TJSX6hNuF5mk9X6+ydBL3+81Hlecdwq7 // SIG // eUsJAKT/XpeI6irAhxmDVExKGKHaR42LecpbKceqCqeJ // SIG // qdVvwvQwVhf2RYYVMLFmXXCUXp0TE1RT9uqAMTBbazJ2 // SIG // fo7bO07b3bCzMpfXkf5dQTHCkpEaXl9CPPDtektl9xMP // SIG // HYsHddTPF8tSeK5gLEAM8ZPSD8gd6+PiyXb9Gjh0Ir6f // SIG // wtw60BzoPMz/Er5C89oexQ== // SIG // End signature block
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var o;"undefined"!=typeof window?o=window:"undefined"!=typeof global?o=global:"undefined"!=typeof self&&(o=self),o.ColorHash=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ /** * BKDR Hash * * @param {String} str string to hash * @returns {Number} */ var BKDRHash = function(str) { var seed = 131; var hash = 0; for(var i = 0; i < str.length; i++) { hash = hash * seed + str.charCodeAt(i); } return hash; }; /** * Convert HSL to RGB * * @see {@link http://zh.wikipedia.org/wiki/HSL和HSV色彩空间} for further information. * @param {Number} H Hue ∈ [0, 360) * @param {Number} S Saturation ∈ [0, 1] * @param {Number} L Lightness ∈ [0, 1] * @returns {Array} R, G, B ∈ [0, 255] */ var HSL2RGB = function(H, S, L) { H /= 360; var q = L < 0.5 ? L * (1 + S) : L + S - L * S; var p = 2 * L - q; return [H + 1/3, H, H - 1/3].map(function(color) { if(color < 0) { color++; } if(color > 1) { color--; } if(color < 1/6) { color = p + (q - p) * 6 * color; } else if(color < 0.5) { color = q; } else if(color < 2/3) { color = p + (q - p) * 6 * (2/3 - color); } else { color = p; } return Math.round(color * 255); }); }; /** * Color Hash Class * * @class */ var ColorHash = function(options) { options = options || {}; var LS = [options.lightness, options.saturation].map(function(param) { param = param || [0.35, 0.5, 0.65]; // note that 3 is a prime return Object.prototype.toString.call(param) === '[object Array]' ? param.concat() : [param]; }); this.L = LS[0]; this.S = LS[1]; this.hash = options.hash || BKDRHash; }; /** * Returns the hash in [h, s, l]. * Note that H ∈ [0, 360); S ∈ [0, 1]; L ∈ [0, 1]; * * @param {String} str string to hash * @returns {Array} [h, s, l] */ ColorHash.prototype.hsl = function(str) { var H, S, L; var hash = this.hash(str); H = hash % 359; // note that 359 is a prime hash = parseInt(hash / 360); S = this.S[hash % this.S.length]; hash = parseInt(hash / this.S.length); L = this.L[hash % this.L.length]; return [H, S, L]; }; /** * Returns the hash in [r, g, b]. * Note that R, G, B ∈ [0, 255] * * @param {String} str string to hash * @returns {Array} [r, g, b] */ ColorHash.prototype.rgb = function(str) { var hsl = this.hsl(str); return HSL2RGB.apply(this, hsl); }; /** * Returns the hash in hex * * @param {String} str string to hash * @returns {String} hex with # */ ColorHash.prototype.hex = function(str) { var rgb = this.rgb(str); return '#' + rgb[0].toString(16) + rgb[1].toString(16) + rgb[2].toString(16); }; module.exports = ColorHash; },{}]},{},[1])(1) });
var config = require(__dirname+'/../../config/environment.js'); var setKey = require(__dirname+'/set_key.js'); /** * @requires config * @function getKey * * @description Gets admin password. * @param {getKeyCallback} fn - Callback that handles response upon getting key. */ function getKey(fn){ var key = config.get('KEY'); if (key) { fn(null, key); } else { setKey(fn); } } module.exports = getKey;
var WebpackDevServer = require('webpack-dev-server'); var webpack = require('webpack'); var config = require('./webpack.config'); var express = require('express'); var proxy = require('proxy-middleware'); var url = require('url'); var app = express(); app.use('/dist', proxy(url.parse('http://localhost:8081/dist'))); app.get('/*', function(req, res) { res.sendFile(__dirname + '/index.html'); }); var webpackServer = new WebpackDevServer(webpack(config), { // webpack-dev-server options contentBase: __dirname, hot: false, // Enable special support for Hot Module Replacement // Page is no longer updated, but a "webpackHotUpdate" message is send to the content // Use "webpack/hot/dev-server" as additional module in your entry point // webpack-dev-middleware options quiet: false, noInfo: false, publicPath: "https://localhost:8080/dist/", stats: {colors: true} }); webpackServer.listen(8081, "localhost", function() {}); app.listen(8080);
/* This is an example factory definition. Create more files in this directory to define additional factories. */ import { Factory, faker } from 'ember-cli-mirage'; export default Factory.extend({ // age: 20, // numbers // tall: true, // booleans // email: function(i) { // and functions // return 'person' + i + '@test.com'; // }, // zipCode: faker.address .zipCode });
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.0 */ goog.provide('ngmaterial.components.tabs'); goog.require('ngmaterial.components.icon'); goog.require('ngmaterial.core'); /** * @ngdoc module * @name material.components.tabs * @description * * Tabs, created with the `<md-tabs>` directive provide *tabbed* navigation with different styles. * The Tabs component consists of clickable tabs that are aligned horizontally side-by-side. * * Features include support for: * * - static or dynamic tabs, * - responsive designs, * - accessibility support (ARIA), * - tab pagination, * - external or internal tab content, * - focus indicators and arrow-key navigations, * - programmatic lookup and access to tab controllers, and * - dynamic transitions through different tab contents. * */ /* * @see js folder for tabs implementation */ angular.module('material.components.tabs', [ 'material.core', 'material.components.icon' ]); /** * @ngdoc directive * @name mdTab * @module material.components.tabs * * @restrict E * * @description * Use the `<md-tab>` a nested directive used within `<md-tabs>` to specify a tab with a **label** and optional *view content*. * * If the `label` attribute is not specified, then an optional `<md-tab-label>` tag can be used to specify more * complex tab header markup. If neither the **label** nor the **md-tab-label** are specified, then the nested * markup of the `<md-tab>` is used as the tab header markup. * * Please note that if you use `<md-tab-label>`, your content **MUST** be wrapped in the `<md-tab-body>` tag. This * is to define a clear separation between the tab content and the tab label. * * This container is used by the TabsController to show/hide the active tab's content view. This synchronization is * automatically managed by the internal TabsController whenever the tab selection changes. Selection changes can * be initiated via data binding changes, programmatic invocation, or user gestures. * * @param {string=} label Optional attribute to specify a simple string as the tab label * @param {boolean=} ng-disabled If present and expression evaluates to truthy, disabled tab selection. * @param {expression=} md-on-deselect Expression to be evaluated after the tab has been de-selected. * @param {expression=} md-on-select Expression to be evaluated after the tab has been selected. * @param {boolean=} md-active When true, sets the active tab. Note: There can only be one active tab at a time. * * * @usage * * <hljs lang="html"> * <md-tab label="" ng-disabled md-on-select="" md-on-deselect="" > * <h3>My Tab content</h3> * </md-tab> * * <md-tab > * <md-tab-label> * <h3>My Tab content</h3> * </md-tab-label> * <md-tab-body> * <p> * Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, * totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae * dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, * sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. * </p> * </md-tab-body> * </md-tab> * </hljs> * */ angular .module('material.components.tabs') .directive('mdTab', MdTab); function MdTab () { return { require: '^?mdTabs', terminal: true, compile: function (element, attr) { var label = firstChild(element, 'md-tab-label'), body = firstChild(element, 'md-tab-body'); if (label.length == 0) { label = angular.element('<md-tab-label></md-tab-label>'); if (attr.label) label.text(attr.label); else label.append(element.contents()); if (body.length == 0) { var contents = element.contents().detach(); body = angular.element('<md-tab-body></md-tab-body>'); body.append(contents); } } element.append(label); if (body.html()) element.append(body); return postLink; }, scope: { active: '=?mdActive', disabled: '=?ngDisabled', select: '&?mdOnSelect', deselect: '&?mdOnDeselect' } }; function postLink (scope, element, attr, ctrl) { if (!ctrl) return; var index = ctrl.getTabElementIndex(element), body = firstChild(element, 'md-tab-body').remove(), label = firstChild(element, 'md-tab-label').remove(), data = ctrl.insertTab({ scope: scope, parent: scope.$parent, index: index, element: element, template: body.html(), label: label.html() }, index); scope.select = scope.select || angular.noop; scope.deselect = scope.deselect || angular.noop; scope.$watch('active', function (active) { if (active) ctrl.select(data.getIndex(), true); }); scope.$watch('disabled', function () { ctrl.refreshIndex(); }); scope.$watch( function () { return ctrl.getTabElementIndex(element); }, function (newIndex) { data.index = newIndex; ctrl.updateTabOrder(); } ); scope.$on('$destroy', function () { ctrl.removeTab(data); }); } function firstChild (element, tagName) { var children = element[0].children; for (var i = 0, len = children.length; i < len; i++) { var child = children[i]; if (child.tagName === tagName.toUpperCase()) return angular.element(child); } return angular.element(); } } angular .module('material.components.tabs') .directive('mdTabItem', MdTabItem); function MdTabItem () { return { require: '^?mdTabs', link: function link (scope, element, attr, ctrl) { if (!ctrl) return; ctrl.attachRipple(scope, element); } }; } angular .module('material.components.tabs') .directive('mdTabLabel', MdTabLabel); function MdTabLabel () { return { terminal: true }; } angular.module('material.components.tabs') .directive('mdTabScroll', MdTabScroll); function MdTabScroll ($parse) { return { restrict: 'A', compile: function ($element, attr) { var fn = $parse(attr.mdTabScroll, null, true); return function ngEventHandler (scope, element) { element.on('mousewheel', function (event) { scope.$apply(function () { fn(scope, { $event: event }); }); }); }; } } } MdTabScroll.$inject = ["$parse"]; angular .module('material.components.tabs') .controller('MdTabsController', MdTabsController); /** * ngInject */ function MdTabsController ($scope, $element, $window, $mdConstant, $mdTabInkRipple, $mdUtil, $animateCss, $attrs, $compile, $mdTheming) { // define private properties var ctrl = this, locked = false, elements = getElements(), queue = [], destroyed = false, loaded = false; // define one-way bindings defineOneWayBinding('stretchTabs', handleStretchTabs); // define public properties with change handlers defineProperty('focusIndex', handleFocusIndexChange, ctrl.selectedIndex || 0); defineProperty('offsetLeft', handleOffsetChange, 0); defineProperty('hasContent', handleHasContent, false); defineProperty('maxTabWidth', handleMaxTabWidth, getMaxTabWidth()); defineProperty('shouldPaginate', handleShouldPaginate, false); // define boolean attributes defineBooleanAttribute('noInkBar', handleInkBar); defineBooleanAttribute('dynamicHeight', handleDynamicHeight); defineBooleanAttribute('noPagination'); defineBooleanAttribute('swipeContent'); defineBooleanAttribute('noDisconnect'); defineBooleanAttribute('autoselect'); defineBooleanAttribute('noSelectClick'); defineBooleanAttribute('centerTabs', handleCenterTabs, false); defineBooleanAttribute('enableDisconnect'); // define public properties ctrl.scope = $scope; ctrl.parent = $scope.$parent; ctrl.tabs = []; ctrl.lastSelectedIndex = null; ctrl.hasFocus = false; ctrl.lastClick = true; ctrl.shouldCenterTabs = shouldCenterTabs(); // define public methods ctrl.updatePagination = $mdUtil.debounce(updatePagination, 100); ctrl.redirectFocus = redirectFocus; ctrl.attachRipple = attachRipple; ctrl.insertTab = insertTab; ctrl.removeTab = removeTab; ctrl.select = select; ctrl.scroll = scroll; ctrl.nextPage = nextPage; ctrl.previousPage = previousPage; ctrl.keydown = keydown; ctrl.canPageForward = canPageForward; ctrl.canPageBack = canPageBack; ctrl.refreshIndex = refreshIndex; ctrl.incrementIndex = incrementIndex; ctrl.getTabElementIndex = getTabElementIndex; ctrl.updateInkBarStyles = $mdUtil.debounce(updateInkBarStyles, 100); ctrl.updateTabOrder = $mdUtil.debounce(updateTabOrder, 100); init(); /** * Perform initialization for the controller, setup events and watcher(s) */ function init () { ctrl.selectedIndex = ctrl.selectedIndex || 0; compileTemplate(); configureWatchers(); bindEvents(); $mdTheming($element); $mdUtil.nextTick(function () { // Note that the element references need to be updated, because certain "browsers" // (IE/Edge) lose them and start throwing "Invalid calling object" errors, when we // compile the element contents down in `compileElement`. elements = getElements(); updateHeightFromContent(); adjustOffset(); updateInkBarStyles(); ctrl.tabs[ ctrl.selectedIndex ] && ctrl.tabs[ ctrl.selectedIndex ].scope.select(); loaded = true; updatePagination(); }); } /** * Compiles the template provided by the user. This is passed as an attribute from the tabs * directive's template function. */ function compileTemplate () { var template = $attrs.$mdTabsTemplate, element = angular.element($element[0].querySelector('md-tab-data')); element.html(template); $compile(element.contents())(ctrl.parent); delete $attrs.$mdTabsTemplate; } /** * Binds events used by the tabs component. */ function bindEvents () { angular.element($window).on('resize', handleWindowResize); $scope.$on('$destroy', cleanup); } /** * Configure watcher(s) used by Tabs */ function configureWatchers () { $scope.$watch('$mdTabsCtrl.selectedIndex', handleSelectedIndexChange); } /** * Creates a one-way binding manually rather than relying on Angular's isolated scope * @param key * @param handler */ function defineOneWayBinding (key, handler) { var attr = $attrs.$normalize('md-' + key); if (handler) defineProperty(key, handler); $attrs.$observe(attr, function (newValue) { ctrl[ key ] = newValue; }); } /** * Defines boolean attributes with default value set to true. (ie. md-stretch-tabs with no value * will be treated as being truthy) * @param key * @param handler */ function defineBooleanAttribute (key, handler) { var attr = $attrs.$normalize('md-' + key); if (handler) defineProperty(key, handler); if ($attrs.hasOwnProperty(attr)) updateValue($attrs[attr]); $attrs.$observe(attr, updateValue); function updateValue (newValue) { ctrl[ key ] = newValue !== 'false'; } } /** * Remove any events defined by this controller */ function cleanup () { destroyed = true; angular.element($window).off('resize', handleWindowResize); } // Change handlers /** * Toggles stretch tabs class and updates inkbar when tab stretching changes * @param stretchTabs */ function handleStretchTabs (stretchTabs) { var elements = getElements(); angular.element(elements.wrapper).toggleClass('md-stretch-tabs', shouldStretchTabs()); updateInkBarStyles(); } function handleCenterTabs (newValue) { ctrl.shouldCenterTabs = shouldCenterTabs(); } function handleMaxTabWidth (newWidth, oldWidth) { if (newWidth !== oldWidth) { var elements = getElements(); angular.forEach(elements.tabs, function(tab) { tab.style.maxWidth = newWidth + 'px'; }); $mdUtil.nextTick(ctrl.updateInkBarStyles); } } function handleShouldPaginate (newValue, oldValue) { if (newValue !== oldValue) { ctrl.maxTabWidth = getMaxTabWidth(); ctrl.shouldCenterTabs = shouldCenterTabs(); $mdUtil.nextTick(function () { ctrl.maxTabWidth = getMaxTabWidth(); adjustOffset(ctrl.selectedIndex); }); } } /** * Add/remove the `md-no-tab-content` class depending on `ctrl.hasContent` * @param hasContent */ function handleHasContent (hasContent) { $element[ hasContent ? 'removeClass' : 'addClass' ]('md-no-tab-content'); } /** * Apply ctrl.offsetLeft to the paging element when it changes * @param left */ function handleOffsetChange (left) { var elements = getElements(); var newValue = ctrl.shouldCenterTabs ? '' : '-' + left + 'px'; angular.element(elements.paging).css($mdConstant.CSS.TRANSFORM, 'translate3d(' + newValue + ', 0, 0)'); $scope.$broadcast('$mdTabsPaginationChanged'); } /** * Update the UI whenever `ctrl.focusIndex` is updated * @param newIndex * @param oldIndex */ function handleFocusIndexChange (newIndex, oldIndex) { if (newIndex === oldIndex) return; if (!getElements().tabs[ newIndex ]) return; adjustOffset(); redirectFocus(); } /** * Update the UI whenever the selected index changes. Calls user-defined select/deselect methods. * @param newValue * @param oldValue */ function handleSelectedIndexChange (newValue, oldValue) { if (newValue === oldValue) return; ctrl.selectedIndex = getNearestSafeIndex(newValue); ctrl.lastSelectedIndex = oldValue; ctrl.updateInkBarStyles(); updateHeightFromContent(); adjustOffset(newValue); $scope.$broadcast('$mdTabsChanged'); ctrl.tabs[ oldValue ] && ctrl.tabs[ oldValue ].scope.deselect(); ctrl.tabs[ newValue ] && ctrl.tabs[ newValue ].scope.select(); } function getTabElementIndex(tabEl){ var tabs = $element[0].getElementsByTagName('md-tab'); return Array.prototype.indexOf.call(tabs, tabEl[0]); } /** * Queues up a call to `handleWindowResize` when a resize occurs while the tabs component is * hidden. */ function handleResizeWhenVisible () { // if there is already a watcher waiting for resize, do nothing if (handleResizeWhenVisible.watcher) return; // otherwise, we will abuse the $watch function to check for visible handleResizeWhenVisible.watcher = $scope.$watch(function () { // since we are checking for DOM size, we use $mdUtil.nextTick() to wait for after the DOM updates $mdUtil.nextTick(function () { // if the watcher has already run (ie. multiple digests in one cycle), do nothing if (!handleResizeWhenVisible.watcher) return; if ($element.prop('offsetParent')) { handleResizeWhenVisible.watcher(); handleResizeWhenVisible.watcher = null; handleWindowResize(); } }, false); }); } // Event handlers / actions /** * Handle user keyboard interactions * @param event */ function keydown (event) { switch (event.keyCode) { case $mdConstant.KEY_CODE.LEFT_ARROW: event.preventDefault(); incrementIndex(-1, true); break; case $mdConstant.KEY_CODE.RIGHT_ARROW: event.preventDefault(); incrementIndex(1, true); break; case $mdConstant.KEY_CODE.SPACE: case $mdConstant.KEY_CODE.ENTER: event.preventDefault(); if (!locked) select(ctrl.focusIndex); break; } ctrl.lastClick = false; } /** * Update the selected index. Triggers a click event on the original `md-tab` element in order * to fire user-added click events if canSkipClick or `md-no-select-click` are false. * @param index * @param canSkipClick Optionally allow not firing the click event if `md-no-select-click` is also true. */ function select (index, canSkipClick) { if (!locked) ctrl.focusIndex = ctrl.selectedIndex = index; ctrl.lastClick = true; // skip the click event if noSelectClick is enabled if (canSkipClick && ctrl.noSelectClick) return; // nextTick is required to prevent errors in user-defined click events $mdUtil.nextTick(function () { ctrl.tabs[ index ].element.triggerHandler('click'); }, false); } /** * When pagination is on, this makes sure the selected index is in view. * @param event */ function scroll (event) { if (!ctrl.shouldPaginate) return; event.preventDefault(); ctrl.offsetLeft = fixOffset(ctrl.offsetLeft - event.wheelDelta); } /** * Slides the tabs over approximately one page forward. */ function nextPage () { var elements = getElements(); var viewportWidth = elements.canvas.clientWidth, totalWidth = viewportWidth + ctrl.offsetLeft, i, tab; for (i = 0; i < elements.tabs.length; i++) { tab = elements.tabs[ i ]; if (tab.offsetLeft + tab.offsetWidth > totalWidth) break; } ctrl.offsetLeft = fixOffset(tab.offsetLeft); } /** * Slides the tabs over approximately one page backward. */ function previousPage () { var i, tab, elements = getElements(); for (i = 0; i < elements.tabs.length; i++) { tab = elements.tabs[ i ]; if (tab.offsetLeft + tab.offsetWidth >= ctrl.offsetLeft) break; } ctrl.offsetLeft = fixOffset(tab.offsetLeft + tab.offsetWidth - elements.canvas.clientWidth); } /** * Update size calculations when the window is resized. */ function handleWindowResize () { ctrl.lastSelectedIndex = ctrl.selectedIndex; ctrl.offsetLeft = fixOffset(ctrl.offsetLeft); $mdUtil.nextTick(function () { ctrl.updateInkBarStyles(); updatePagination(); }); } function handleInkBar (hide) { angular.element(getElements().inkBar).toggleClass('ng-hide', hide); } /** * Toggle dynamic height class when value changes * @param value */ function handleDynamicHeight (value) { $element.toggleClass('md-dynamic-height', value); } /** * Remove a tab from the data and select the nearest valid tab. * @param tabData */ function removeTab (tabData) { if (destroyed) return; var selectedIndex = ctrl.selectedIndex, tab = ctrl.tabs.splice(tabData.getIndex(), 1)[ 0 ]; refreshIndex(); // when removing a tab, if the selected index did not change, we have to manually trigger the // tab select/deselect events if (ctrl.selectedIndex === selectedIndex) { tab.scope.deselect(); ctrl.tabs[ ctrl.selectedIndex ] && ctrl.tabs[ ctrl.selectedIndex ].scope.select(); } $mdUtil.nextTick(function () { updatePagination(); ctrl.offsetLeft = fixOffset(ctrl.offsetLeft); }); } /** * Create an entry in the tabs array for a new tab at the specified index. * @param tabData * @param index * @returns {*} */ function insertTab (tabData, index) { var hasLoaded = loaded; var proto = { getIndex: function () { return ctrl.tabs.indexOf(tab); }, isActive: function () { return this.getIndex() === ctrl.selectedIndex; }, isLeft: function () { return this.getIndex() < ctrl.selectedIndex; }, isRight: function () { return this.getIndex() > ctrl.selectedIndex; }, shouldRender: function () { return !ctrl.noDisconnect || this.isActive(); }, hasFocus: function () { return !ctrl.lastClick && ctrl.hasFocus && this.getIndex() === ctrl.focusIndex; }, id: $mdUtil.nextUid() }, tab = angular.extend(proto, tabData); if (angular.isDefined(index)) { ctrl.tabs.splice(index, 0, tab); } else { ctrl.tabs.push(tab); } processQueue(); updateHasContent(); $mdUtil.nextTick(function () { updatePagination(); // if autoselect is enabled, select the newly added tab if (hasLoaded && ctrl.autoselect) $mdUtil.nextTick(function () { $mdUtil.nextTick(function () { select(ctrl.tabs.indexOf(tab)); }); }); }); return tab; } // Getter methods /** * Gathers references to all of the DOM elements used by this controller. * @returns {{}} */ function getElements () { var elements = {}; var node = $element[0]; // gather tab bar elements elements.wrapper = node.querySelector('md-tabs-wrapper'); elements.canvas = elements.wrapper.querySelector('md-tabs-canvas'); elements.paging = elements.canvas.querySelector('md-pagination-wrapper'); elements.inkBar = elements.paging.querySelector('md-ink-bar'); elements.contents = node.querySelectorAll('md-tabs-content-wrapper > md-tab-content'); elements.tabs = elements.paging.querySelectorAll('md-tab-item'); elements.dummies = elements.canvas.querySelectorAll('md-dummy-tab'); return elements; } /** * Determines whether or not the left pagination arrow should be enabled. * @returns {boolean} */ function canPageBack () { return ctrl.offsetLeft > 0; } /** * Determines whether or not the right pagination arrow should be enabled. * @returns {*|boolean} */ function canPageForward () { var elements = getElements(); var lastTab = elements.tabs[ elements.tabs.length - 1 ]; return lastTab && lastTab.offsetLeft + lastTab.offsetWidth > elements.canvas.clientWidth + ctrl.offsetLeft; } /** * Determines if the UI should stretch the tabs to fill the available space. * @returns {*} */ function shouldStretchTabs () { switch (ctrl.stretchTabs) { case 'always': return true; case 'never': return false; default: return !ctrl.shouldPaginate && $window.matchMedia('(max-width: 600px)').matches; } } /** * Determines if the tabs should appear centered. * @returns {string|boolean} */ function shouldCenterTabs () { return ctrl.centerTabs && !ctrl.shouldPaginate; } /** * Determines if pagination is necessary to display the tabs within the available space. * @returns {boolean} */ function shouldPaginate () { if (ctrl.noPagination || !loaded) return false; var canvasWidth = $element.prop('clientWidth'); angular.forEach(getElements().dummies, function (tab) { canvasWidth -= tab.offsetWidth; }); return canvasWidth < 0; } /** * Finds the nearest tab index that is available. This is primarily used for when the active * tab is removed. * @param newIndex * @returns {*} */ function getNearestSafeIndex (newIndex) { if (newIndex === -1) return -1; var maxOffset = Math.max(ctrl.tabs.length - newIndex, newIndex), i, tab; for (i = 0; i <= maxOffset; i++) { tab = ctrl.tabs[ newIndex + i ]; if (tab && (tab.scope.disabled !== true)) return tab.getIndex(); tab = ctrl.tabs[ newIndex - i ]; if (tab && (tab.scope.disabled !== true)) return tab.getIndex(); } return newIndex; } // Utility methods /** * Defines a property using a getter and setter in order to trigger a change handler without * using `$watch` to observe changes. * @param key * @param handler * @param value */ function defineProperty (key, handler, value) { Object.defineProperty(ctrl, key, { get: function () { return value; }, set: function (newValue) { var oldValue = value; value = newValue; handler && handler(newValue, oldValue); } }); } /** * Updates whether or not pagination should be displayed. */ function updatePagination () { updatePagingWidth(); ctrl.maxTabWidth = getMaxTabWidth(); ctrl.shouldPaginate = shouldPaginate(); } /** * Sets or clears fixed width for md-pagination-wrapper depending on if tabs should stretch. */ function updatePagingWidth() { var elements = getElements(); if (shouldStretchTabs()) { angular.element(elements.paging).css('width', ''); } else { angular.element(elements.paging).css('width', calcPagingWidth() + 'px'); } } /** * Calculates the width of the pagination wrapper by summing the widths of the dummy tabs. * @returns {number} */ function calcPagingWidth () { return calcTabsWidth(getElements().dummies); } function calcTabsWidth(tabs) { var width = 0; angular.forEach(tabs, function (tab) { //-- Uses the larger value between `getBoundingClientRect().width` and `offsetWidth`. This // prevents `offsetWidth` value from being rounded down and causing wrapping issues, but // also handles scenarios where `getBoundingClientRect()` is inaccurate (ie. tabs inside // of a dialog) width += Math.max(tab.offsetWidth, tab.getBoundingClientRect().width); }); return Math.ceil(width); } function getMaxTabWidth () { return $element.prop('clientWidth'); } /** * Re-orders the tabs and updates the selected and focus indexes to their new positions. * This is triggered by `tabDirective.js` when the user's tabs have been re-ordered. */ function updateTabOrder () { var selectedItem = ctrl.tabs[ ctrl.selectedIndex ], focusItem = ctrl.tabs[ ctrl.focusIndex ]; ctrl.tabs = ctrl.tabs.sort(function (a, b) { return a.index - b.index; }); ctrl.selectedIndex = ctrl.tabs.indexOf(selectedItem); ctrl.focusIndex = ctrl.tabs.indexOf(focusItem); } /** * This moves the selected or focus index left or right. This is used by the keydown handler. * @param inc */ function incrementIndex (inc, focus) { var newIndex, key = focus ? 'focusIndex' : 'selectedIndex', index = ctrl[ key ]; for (newIndex = index + inc; ctrl.tabs[ newIndex ] && ctrl.tabs[ newIndex ].scope.disabled; newIndex += inc) {} if (ctrl.tabs[ newIndex ]) { ctrl[ key ] = newIndex; } } /** * This is used to forward focus to dummy elements. This method is necessary to avoid animation * issues when attempting to focus an item that is out of view. */ function redirectFocus () { getElements().dummies[ ctrl.focusIndex ].focus(); } /** * Forces the pagination to move the focused tab into view. */ function adjustOffset (index) { var elements = getElements(); if (index == null) index = ctrl.focusIndex; if (!elements.tabs[ index ]) return; if (ctrl.shouldCenterTabs) return; var tab = elements.tabs[ index ], left = tab.offsetLeft, right = tab.offsetWidth + left; ctrl.offsetLeft = Math.max(ctrl.offsetLeft, fixOffset(right - elements.canvas.clientWidth + 32 * 2)); ctrl.offsetLeft = Math.min(ctrl.offsetLeft, fixOffset(left)); } /** * Iterates through all queued functions and clears the queue. This is used for functions that * are called before the UI is ready, such as size calculations. */ function processQueue () { queue.forEach(function (func) { $mdUtil.nextTick(func); }); queue = []; } /** * Determines if the tab content area is needed. */ function updateHasContent () { var hasContent = false; angular.forEach(ctrl.tabs, function (tab) { if (tab.template) hasContent = true; }); ctrl.hasContent = hasContent; } /** * Moves the indexes to their nearest valid values. */ function refreshIndex () { ctrl.selectedIndex = getNearestSafeIndex(ctrl.selectedIndex); ctrl.focusIndex = getNearestSafeIndex(ctrl.focusIndex); } /** * Calculates the content height of the current tab. * @returns {*} */ function updateHeightFromContent () { if (!ctrl.dynamicHeight) return $element.css('height', ''); if (!ctrl.tabs.length) return queue.push(updateHeightFromContent); var elements = getElements(); var tabContent = elements.contents[ ctrl.selectedIndex ], contentHeight = tabContent ? tabContent.offsetHeight : 0, tabsHeight = elements.wrapper.offsetHeight, newHeight = contentHeight + tabsHeight, currentHeight = $element.prop('clientHeight'); if (currentHeight === newHeight) return; // Adjusts calculations for when the buttons are bottom-aligned since this relies on absolute // positioning. This should probably be cleaned up if a cleaner solution is possible. if ($element.attr('md-align-tabs') === 'bottom') { currentHeight -= tabsHeight; newHeight -= tabsHeight; // Need to include bottom border in these calculations if ($element.attr('md-border-bottom') !== undefined) ++currentHeight; } // Lock during animation so the user can't change tabs locked = true; var fromHeight = { height: currentHeight + 'px' }, toHeight = { height: newHeight + 'px' }; // Set the height to the current, specific pixel height to fix a bug on iOS where the height // first animates to 0, then back to the proper height causing a visual glitch $element.css(fromHeight); // Animate the height from the old to the new $animateCss($element, { from: fromHeight, to: toHeight, easing: 'cubic-bezier(0.35, 0, 0.25, 1)', duration: 0.5 }).start().done(function () { // Then (to fix the same iOS issue as above), disable transitions and remove the specific // pixel height so the height can size with browser width/content changes, etc. $element.css({ transition: 'none', height: '' }); // In the next tick, re-allow transitions (if we do it all at once, $element.css is "smart" // enough to batch it for us instead of doing it immediately, which undoes the original // transition: none) $mdUtil.nextTick(function() { $element.css('transition', ''); }); // And unlock so tab changes can occur locked = false; }); } /** * Repositions the ink bar to the selected tab. * @returns {*} */ function updateInkBarStyles () { var elements = getElements(); if (!elements.tabs[ ctrl.selectedIndex ]) { angular.element(elements.inkBar).css({ left: 'auto', right: 'auto' }); return; } if (!ctrl.tabs.length) return queue.push(ctrl.updateInkBarStyles); // if the element is not visible, we will not be able to calculate sizes until it is // we should treat that as a resize event rather than just updating the ink bar if (!$element.prop('offsetParent')) return handleResizeWhenVisible(); var index = ctrl.selectedIndex, totalWidth = elements.paging.offsetWidth, tab = elements.tabs[ index ], left = tab.offsetLeft, right = totalWidth - left - tab.offsetWidth; if (ctrl.shouldCenterTabs) { // We need to use the same calculate process as in the pagination wrapper, to avoid rounding deviations. var tabWidth = calcTabsWidth(elements.tabs); if (totalWidth > tabWidth) { $mdUtil.nextTick(updateInkBarStyles, false); } } updateInkBarClassName(); angular.element(elements.inkBar).css({ left: left + 'px', right: right + 'px' }); } /** * Adds left/right classes so that the ink bar will animate properly. */ function updateInkBarClassName () { var elements = getElements(); var newIndex = ctrl.selectedIndex, oldIndex = ctrl.lastSelectedIndex, ink = angular.element(elements.inkBar); if (!angular.isNumber(oldIndex)) return; ink .toggleClass('md-left', newIndex < oldIndex) .toggleClass('md-right', newIndex > oldIndex); } /** * Takes an offset value and makes sure that it is within the min/max allowed values. * @param value * @returns {*} */ function fixOffset (value) { var elements = getElements(); if (!elements.tabs.length || !ctrl.shouldPaginate) return 0; var lastTab = elements.tabs[ elements.tabs.length - 1 ], totalWidth = lastTab.offsetLeft + lastTab.offsetWidth; value = Math.max(0, value); value = Math.min(totalWidth - elements.canvas.clientWidth, value); return value; } /** * Attaches a ripple to the tab item element. * @param scope * @param element */ function attachRipple (scope, element) { var elements = getElements(); var options = { colorElement: angular.element(elements.inkBar) }; $mdTabInkRipple.attach(scope, element, options); } } MdTabsController.$inject = ["$scope", "$element", "$window", "$mdConstant", "$mdTabInkRipple", "$mdUtil", "$animateCss", "$attrs", "$compile", "$mdTheming"]; /** * @ngdoc directive * @name mdTabs * @module material.components.tabs * * @restrict E * * @description * The `<md-tabs>` directive serves as the container for 1..n `<md-tab>` child directives to produces a Tabs components. * In turn, the nested `<md-tab>` directive is used to specify a tab label for the **header button** and a [optional] tab view * content that will be associated with each tab button. * * Below is the markup for its simplest usage: * * <hljs lang="html"> * <md-tabs> * <md-tab label="Tab #1"></md-tab> * <md-tab label="Tab #2"></md-tab> * <md-tab label="Tab #3"></md-tab> * </md-tabs> * </hljs> * * Tabs supports three (3) usage scenarios: * * 1. Tabs (buttons only) * 2. Tabs with internal view content * 3. Tabs with external view content * * **Tab-only** support is useful when tab buttons are used for custom navigation regardless of any other components, content, or views. * **Tabs with internal views** are the traditional usages where each tab has associated view content and the view switching is managed internally by the Tabs component. * **Tabs with external view content** is often useful when content associated with each tab is independently managed and data-binding notifications announce tab selection changes. * * Additional features also include: * * * Content can include any markup. * * If a tab is disabled while active/selected, then the next tab will be auto-selected. * * ### Explanation of tab stretching * * Initially, tabs will have an inherent size. This size will either be defined by how much space is needed to accommodate their text or set by the user through CSS. Calculations will be based on this size. * * On mobile devices, tabs will be expanded to fill the available horizontal space. When this happens, all tabs will become the same size. * * On desktops, by default, stretching will never occur. * * This default behavior can be overridden through the `md-stretch-tabs` attribute. Here is a table showing when stretching will occur: * * `md-stretch-tabs` | mobile | desktop * ------------------|-----------|-------- * `auto` | stretched | --- * `always` | stretched | stretched * `never` | --- | --- * * @param {integer=} md-selected Index of the active/selected tab * @param {boolean=} md-no-ink If present, disables ink ripple effects. * @param {boolean=} md-no-ink-bar If present, disables the selection ink bar. * @param {string=} md-align-tabs Attribute to indicate position of tab buttons: `bottom` or `top`; default is `top` * @param {string=} md-stretch-tabs Attribute to indicate whether or not to stretch tabs: `auto`, `always`, or `never`; default is `auto` * @param {boolean=} md-dynamic-height When enabled, the tab wrapper will resize based on the contents of the selected tab * @param {boolean=} md-border-bottom If present, shows a solid `1px` border between the tabs and their content * @param {boolean=} md-center-tabs When enabled, tabs will be centered provided there is no need for pagination * @param {boolean=} md-no-pagination When enabled, pagination will remain off * @param {boolean=} md-swipe-content When enabled, swipe gestures will be enabled for the content area to jump between tabs * @param {boolean=} md-enable-disconnect When enabled, scopes will be disconnected for tabs that are not being displayed. This provides a performance boost, but may also cause unexpected issues and is not recommended for most users. * @param {boolean=} md-autoselect When present, any tabs added after the initial load will be automatically selected * @param {boolean=} md-no-select-click When enabled, click events will not be fired when selecting tabs * * @usage * <hljs lang="html"> * <md-tabs md-selected="selectedIndex" > * <img ng-src="img/angular.png" class="centered"> * <md-tab * ng-repeat="tab in tabs | orderBy:predicate:reversed" * md-on-select="onTabSelected(tab)" * md-on-deselect="announceDeselected(tab)" * ng-disabled="tab.disabled"> * <md-tab-label> * {{tab.title}} * <img src="img/removeTab.png" ng-click="removeTab(tab)" class="delete"> * </md-tab-label> * <md-tab-body> * {{tab.content}} * </md-tab-body> * </md-tab> * </md-tabs> * </hljs> * */ angular .module('material.components.tabs') .directive('mdTabs', MdTabs); function MdTabs ($$mdSvgRegistry) { return { scope: { selectedIndex: '=?mdSelected' }, template: function (element, attr) { attr[ "$mdTabsTemplate" ] = element.html(); return '' + '<md-tabs-wrapper> ' + '<md-tab-data></md-tab-data> ' + '<md-prev-button ' + 'tabindex="-1" ' + 'role="button" ' + 'aria-label="Previous Page" ' + 'aria-disabled="{{!$mdTabsCtrl.canPageBack()}}" ' + 'ng-class="{ \'md-disabled\': !$mdTabsCtrl.canPageBack() }" ' + 'ng-if="$mdTabsCtrl.shouldPaginate" ' + 'ng-click="$mdTabsCtrl.previousPage()"> ' + '<md-icon md-svg-src="'+ $$mdSvgRegistry.mdTabsArrow +'"></md-icon> ' + '</md-prev-button> ' + '<md-next-button ' + 'tabindex="-1" ' + 'role="button" ' + 'aria-label="Next Page" ' + 'aria-disabled="{{!$mdTabsCtrl.canPageForward()}}" ' + 'ng-class="{ \'md-disabled\': !$mdTabsCtrl.canPageForward() }" ' + 'ng-if="$mdTabsCtrl.shouldPaginate" ' + 'ng-click="$mdTabsCtrl.nextPage()"> ' + '<md-icon md-svg-src="'+ $$mdSvgRegistry.mdTabsArrow +'"></md-icon> ' + '</md-next-button> ' + '<md-tabs-canvas ' + 'tabindex="{{ $mdTabsCtrl.hasFocus ? -1 : 0 }}" ' + 'aria-activedescendant="tab-item-{{$mdTabsCtrl.tabs[$mdTabsCtrl.focusIndex].id}}" ' + 'ng-focus="$mdTabsCtrl.redirectFocus()" ' + 'ng-class="{ ' + '\'md-paginated\': $mdTabsCtrl.shouldPaginate, ' + '\'md-center-tabs\': $mdTabsCtrl.shouldCenterTabs ' + '}" ' + 'ng-keydown="$mdTabsCtrl.keydown($event)" ' + 'role="tablist"> ' + '<md-pagination-wrapper ' + 'ng-class="{ \'md-center-tabs\': $mdTabsCtrl.shouldCenterTabs }" ' + 'md-tab-scroll="$mdTabsCtrl.scroll($event)"> ' + '<md-tab-item ' + 'tabindex="-1" ' + 'class="md-tab" ' + 'ng-repeat="tab in $mdTabsCtrl.tabs" ' + 'role="tab" ' + 'aria-controls="tab-content-{{::tab.id}}" ' + 'aria-selected="{{tab.isActive()}}" ' + 'aria-disabled="{{tab.scope.disabled || \'false\'}}" ' + 'ng-click="$mdTabsCtrl.select(tab.getIndex())" ' + 'ng-class="{ ' + '\'md-active\': tab.isActive(), ' + '\'md-focused\': tab.hasFocus(), ' + '\'md-disabled\': tab.scope.disabled ' + '}" ' + 'ng-disabled="tab.scope.disabled" ' + 'md-swipe-left="$mdTabsCtrl.nextPage()" ' + 'md-swipe-right="$mdTabsCtrl.previousPage()" ' + 'md-tabs-template="::tab.label" ' + 'md-scope="::tab.parent"></md-tab-item> ' + '<md-ink-bar></md-ink-bar> ' + '</md-pagination-wrapper> ' + '<md-tabs-dummy-wrapper class="md-visually-hidden md-dummy-wrapper"> ' + '<md-dummy-tab ' + 'class="md-tab" ' + 'tabindex="-1" ' + 'id="tab-item-{{::tab.id}}" ' + 'role="tab" ' + 'aria-controls="tab-content-{{::tab.id}}" ' + 'aria-selected="{{tab.isActive()}}" ' + 'aria-disabled="{{tab.scope.disabled || \'false\'}}" ' + 'ng-focus="$mdTabsCtrl.hasFocus = true" ' + 'ng-blur="$mdTabsCtrl.hasFocus = false" ' + 'ng-repeat="tab in $mdTabsCtrl.tabs" ' + 'md-tabs-template="::tab.label" ' + 'md-scope="::tab.parent"></md-dummy-tab> ' + '</md-tabs-dummy-wrapper> ' + '</md-tabs-canvas> ' + '</md-tabs-wrapper> ' + '<md-tabs-content-wrapper ng-show="$mdTabsCtrl.hasContent && $mdTabsCtrl.selectedIndex >= 0" class="_md"> ' + '<md-tab-content ' + 'id="tab-content-{{::tab.id}}" ' + 'class="_md" ' + 'role="tabpanel" ' + 'aria-labelledby="tab-item-{{::tab.id}}" ' + 'md-swipe-left="$mdTabsCtrl.swipeContent && $mdTabsCtrl.incrementIndex(1)" ' + 'md-swipe-right="$mdTabsCtrl.swipeContent && $mdTabsCtrl.incrementIndex(-1)" ' + 'ng-if="$mdTabsCtrl.hasContent" ' + 'ng-repeat="(index, tab) in $mdTabsCtrl.tabs" ' + 'ng-class="{ ' + '\'md-no-transition\': $mdTabsCtrl.lastSelectedIndex == null, ' + '\'md-active\': tab.isActive(), ' + '\'md-left\': tab.isLeft(), ' + '\'md-right\': tab.isRight(), ' + '\'md-no-scroll\': $mdTabsCtrl.dynamicHeight ' + '}"> ' + '<div ' + 'md-tabs-template="::tab.template" ' + 'md-connected-if="tab.isActive()" ' + 'md-scope="::tab.parent" ' + 'ng-if="$mdTabsCtrl.enableDisconnect || tab.shouldRender()"></div> ' + '</md-tab-content> ' + '</md-tabs-content-wrapper>'; }, controller: 'MdTabsController', controllerAs: '$mdTabsCtrl', bindToController: true }; } MdTabs.$inject = ["$$mdSvgRegistry"]; angular .module('material.components.tabs') .directive('mdTabsDummyWrapper', MdTabsDummyWrapper); /** * @private * * @param $mdUtil * @returns {{require: string, link: link}} * @constructor * * ngInject */ function MdTabsDummyWrapper ($mdUtil) { return { require: '^?mdTabs', link: function link (scope, element, attr, ctrl) { if (!ctrl) return; var observer = new MutationObserver(function(mutations) { ctrl.updatePagination(); ctrl.updateInkBarStyles(); }); var config = { childList: true, subtree: true, // Per https://bugzilla.mozilla.org/show_bug.cgi?id=1138368, browsers will not fire // the childList mutation, once a <span> element's innerText changes. // The characterData of the <span> element will change. characterData: true }; observer.observe(element[0], config); // Disconnect the observer scope.$on('$destroy', function() { if (observer) { observer.disconnect(); } }); } }; } MdTabsDummyWrapper.$inject = ["$mdUtil"]; angular .module('material.components.tabs') .directive('mdTabsTemplate', MdTabsTemplate); function MdTabsTemplate ($compile, $mdUtil) { return { restrict: 'A', link: link, scope: { template: '=mdTabsTemplate', connected: '=?mdConnectedIf', compileScope: '=mdScope' }, require: '^?mdTabs' }; function link (scope, element, attr, ctrl) { if (!ctrl) return; var compileScope = ctrl.enableDisconnect ? scope.compileScope.$new() : scope.compileScope; element.html(scope.template); $compile(element.contents())(compileScope); return $mdUtil.nextTick(handleScope); function handleScope () { scope.$watch('connected', function (value) { value === false ? disconnect() : reconnect(); }); scope.$on('$destroy', reconnect); } function disconnect () { if (ctrl.enableDisconnect) $mdUtil.disconnectScope(compileScope); } function reconnect () { if (ctrl.enableDisconnect) $mdUtil.reconnectScope(compileScope); } } } MdTabsTemplate.$inject = ["$compile", "$mdUtil"]; ngmaterial.components.tabs = angular.module("material.components.tabs");
'use strict'; var gulp = require('gulp'), browserSync = require('browser-sync'), reload = browserSync.reload; var sass = require('gulp-sass'); gulp.task('sass', function () { gulp.src('scss/**/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest('css')); }); gulp.task('sass:watch', function () { gulp.watch('scss/*.scss', ['sass']); gulp.watch(['css/*.css'], reload); }); // Start a server with Live Reload gulp.task('serve', ['sass'], function () { browserSync({ // notify: false, // Customize the BrowserSync console logging prefix // logPrefix: 'WSK', // Run as an https by uncommenting 'https: true' // Note: this uses an unsigned certificate which on first access // will present a certificate warning in the browser. // https: true, server: ['.tmp', './'] // proxy: 'http://localhost:8888/' }); gulp.watch(['./scss/**/*.scss'], ['sass']); gulp.watch(['css/**/*.css'], reload); gulp.watch(['./*.html'], reload); // gulp.watch(['./*.php'], reload); // gulp.watch(['js/**/*.js'], [reload]); });
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import JSON5 from 'json5'; import type {Element} from './views/Components/types'; import type {StateContext} from './views/Components/TreeContext'; import type Store from './store'; export function printElement(element: Element, includeWeight: boolean = false) { let prefix = ' '; if (element.children.length > 0) { prefix = element.isCollapsed ? '▸' : '▾'; } let key = ''; if (element.key !== null) { key = ` key="${element.key}"`; } let hocDisplayNames = null; if (element.hocDisplayNames !== null) { hocDisplayNames = [...element.hocDisplayNames]; } const hocs = hocDisplayNames === null ? '' : ` [${hocDisplayNames.join('][')}]`; let suffix = ''; if (includeWeight) { suffix = ` (${element.isCollapsed ? 1 : element.weight})`; } return `${' '.repeat(element.depth + 1)}${prefix} <${element.displayName || 'null'}${key}>${hocs}${suffix}`; } export function printOwnersList( elements: Array<Element>, includeWeight: boolean = false, ) { return elements .map(element => printElement(element, includeWeight)) .join('\n'); } export function printStore( store: Store, includeWeight: boolean = false, state: StateContext | null = null, ) { const snapshotLines = []; let rootWeight = 0; function printSelectedMarker(index: number): string { if (state === null) { return ''; } return state.selectedElementIndex === index ? `→` : ' '; } function printErrorsAndWarnings(element: Element): string { const { errorCount, warningCount, } = store.getErrorAndWarningCountForElementID(element.id); if (errorCount === 0 && warningCount === 0) { return ''; } return ` ${errorCount > 0 ? '✕' : ''}${warningCount > 0 ? '⚠' : ''}`; } const ownerFlatTree = state !== null ? state.ownerFlatTree : null; if (ownerFlatTree !== null) { snapshotLines.push( '[owners]' + (includeWeight ? ` (${ownerFlatTree.length})` : ''), ); ownerFlatTree.forEach((element, index) => { const printedSelectedMarker = printSelectedMarker(index); const printedElement = printElement(element, false); const printedErrorsAndWarnings = printErrorsAndWarnings(element); snapshotLines.push( `${printedSelectedMarker}${printedElement}${printedErrorsAndWarnings}`, ); }); } else { const errorsAndWarnings = store._errorsAndWarnings; if (errorsAndWarnings.size > 0) { let errorCount = 0; let warningCount = 0; errorsAndWarnings.forEach(entry => { errorCount += entry.errorCount; warningCount += entry.warningCount; }); snapshotLines.push(`✕ ${errorCount}, ⚠ ${warningCount}`); } store.roots.forEach(rootID => { const {weight} = ((store.getElementByID(rootID): any): Element); const maybeWeightLabel = includeWeight ? ` (${weight})` : ''; // Store does not (yet) expose a way to get errors/warnings per root. snapshotLines.push(`[root]${maybeWeightLabel}`); for (let i = rootWeight; i < rootWeight + weight; i++) { const element = store.getElementAtIndex(i); if (element == null) { throw Error(`Could not find element at index "${i}"`); } const printedSelectedMarker = printSelectedMarker(i); const printedElement = printElement(element, includeWeight); const printedErrorsAndWarnings = printErrorsAndWarnings(element); snapshotLines.push( `${printedSelectedMarker}${printedElement}${printedErrorsAndWarnings}`, ); } rootWeight += weight; }); // Make sure the pretty-printed test align with the Store's reported number of total rows. if (rootWeight !== store.numElements) { throw Error( `Inconsistent Store state. Individual root weights ("${rootWeight}") do not match total weight ("${store.numElements}")`, ); } // If roots have been unmounted, verify that they've been removed from maps. // This helps ensure the Store doesn't leak memory. store.assertExpectedRootMapSizes(); } return snapshotLines.join('\n'); } // We use JSON.parse to parse string values // e.g. 'foo' is not valid JSON but it is a valid string // so this method replaces e.g. 'foo' with "foo" export function sanitizeForParse(value: any) { if (typeof value === 'string') { if ( value.length >= 2 && value.charAt(0) === "'" && value.charAt(value.length - 1) === "'" ) { return '"' + value.substr(1, value.length - 2) + '"'; } } return value; } export function smartParse(value: any) { switch (value) { case 'Infinity': return Infinity; case 'NaN': return NaN; case 'undefined': return undefined; default: return JSON5.parse(sanitizeForParse(value)); } } export function smartStringify(value: any) { if (typeof value === 'number') { if (Number.isNaN(value)) { return 'NaN'; } else if (!Number.isFinite(value)) { return 'Infinity'; } } else if (value === undefined) { return 'undefined'; } return JSON.stringify(value); }
var path = require('path'); var fs = require('fs'); var assert = require('assert'); var common = require('../../common.js'); var CommandGlobals = require('../../lib/globals/commands.js'); var Runner = common.require('runner/run.js'); module.exports = { 'testRunner': { before: function (done) { CommandGlobals.beforeEach.call(this, done); }, after: function (done) { CommandGlobals.afterEach.call(this, done); }, beforeEach: function () { process.removeAllListeners('exit'); process.removeAllListeners('uncaughtException'); }, testRunEmptyFolder : function(done) { var testsPath = path.join(__dirname, '../../sampletests/empty'); var runner = new Runner([testsPath], {}, { output_folder : false }, function(err) { assert.strictEqual(err.message.indexOf('No tests defined!'), 0); done(); }); runner.run(); }, testRunNoSrcFoldersArgument : function(done) { var runner = new Runner(undefined, {}, { output_folder : false }); try { runner.run().catch(function(err) { done(err); }); } catch (ex) { assert.ok(ex instanceof Error); assert.equal(ex.message, 'No source folder defined. Check configuration.'); done(); } }, testRunSimple: function (done) { var testsPath = path.join(__dirname, '../../sampletests/simple'); var globals = { calls: 0 }; var runner = new Runner([testsPath], { seleniumPort: 10195, silent: true, output: false, globals: globals }, { output_folder: false, start_session: true }, function (err, results) { assert.strictEqual(err, null); assert.ok('sample' in results.modules); assert.ok('demoTest' in results.modules.sample.completed); done(); }); runner.run().catch(function (err) { done(err); }); }, testRunWithJUnitOutput : function(done) { var src_folders = [ path.join(__dirname, '../../sampletests/withsubfolders') ]; var currentTestArray = []; var runner = new Runner(src_folders, { seleniumPort : 10195, silent : true, output : false, globals : { beforeEach : function(client, doneFn) { currentTestArray.push({ name : client.currentTest.name, module : client.currentTest.module, group : client.currentTest.group }); doneFn(); } } }, { output_folder : 'output', start_session : true, src_folders : src_folders, reporter : 'junit' }, function(err, results) { assert.strictEqual(err, null); assert.deepEqual(currentTestArray, [ { name: '', module: 'simple/sample', group : 'simple' }, { name: '', module: 'tags/sampleTags', group : 'tags' } ]); fs.readdir(src_folders[0], function(err, list) { try { assert.deepEqual(list, ['simple', 'tags'], 'The subfolders have been created.'); var simpleReportFile = 'output/simple/FIREFOX_TEST_TEST_sample.xml'; var tagsReportFile = 'output/tags/FIREFOX_TEST_TEST_sampleTags.xml'; assert.ok(fileExistsSync(simpleReportFile), 'The simple report file was not created.'); assert.ok(fileExistsSync(tagsReportFile), 'The tags report file was not created.'); done(); } catch (err) { done(err); } }); }); runner.run().catch(function (err) { done(err); }); }, testRunWithJUnitOutputAndFailures : function(done) { var src_folders = [ path.join(__dirname, '../../sampletests/withfailures') ]; var runner = new Runner(src_folders, { seleniumPort : 10195, silent : true, output : false }, { output_folder : 'output', start_session : true, src_folders : src_folders, reporter : 'junit' }, function(err, results) { assert.strictEqual(err, null); var sampleReportFile = path.join(__dirname, '../../../output/FIREFOX_TEST_TEST_sample.xml'); assert.ok(fileExistsSync(sampleReportFile), 'The sample file report file was not created.'); fs.readFile(sampleReportFile, function(err, data) { if (err) { done(err); return; } var content = data.toString(); assert.ok(content.indexOf('<failure message="Testing if element &lt;#badElement&gt; is present.">') > 0, 'Report contains failure information.') done(); }); }); runner.run().catch(function (err) { done(err); }); }, 'test run unit tests with junit output and failures' : function(done) { var src_folders = [ path.join(__dirname, '../../asynchookstests/unittest-failure') ]; var runner = new Runner(src_folders, { seleniumPort : 10195, silent : true, output : false }, { output_folder : 'output', start_session : false, src_folders : src_folders, reporter : 'junit' }, function(err, results) { assert.strictEqual(err, null); var sampleReportFile = path.join(__dirname, '../../../output/unittest-failure.xml'); assert.ok(fileExistsSync(sampleReportFile), 'The sample file report file was not created.'); fs.readFile(sampleReportFile, function(err, data) { if (err) { done(err); return; } var content = data.toString(); try { assert.ok(content.indexOf('<failure message="AssertionError: 1 == 0 - expected &quot;0&quot; but got: &quot;1&quot;">') > 0, 'Report contains failure information.') done(); } catch (err) { done(err); } }); }); runner.run().catch(function (err) { done(err); }); }, testRunUnitTests : function(done) { var testsPath = path.join(__dirname, '../../sampletests/unittests'); var runner = new Runner([testsPath], { silent : true, output : false, globals : {} }, { output_folder : false, start_session : false }, function(err, results) { assert.strictEqual(err, null); done(); }); runner.run().catch(function (err) { done(err); }); }, 'test async unit test with timeout error': function (done) { var testsPath = path.join(__dirname, '../../asynchookstests/unittest-async-timeout.js'); var globals = { calls : 0, asyncHookTimeout: 10 }; process.on('uncaughtException', function (err) { assert.ok(err instanceof Error); assert.equal(err.message, 'done() callback timeout of 10 ms was reached while executing "demoTest". ' + 'Make sure to call the done() callback when the operation finishes.'); done(); }); var runner = new Runner([testsPath], { seleniumPort: 10195, seleniumHost: '127.0.0.1', silent: true, output: false, persist_globals : true, globals: globals, compatible_testcase_support : true }, { output_folder : false, start_session : false }); runner.run().catch(function(err) { done(err); }); } } }; // util to replace deprecated fs.existsSync function fileExistsSync (path) { try { fs.statSync(path); return true; } catch (e) { return false; } }
const {find} = require('underscore-plus') const {Emitter, CompositeDisposable} = require('event-kit') const Pane = require('./pane') const ItemRegistry = require('./item-registry') const PaneContainerElement = require('./pane-container-element') const SERIALIZATION_VERSION = 1 const STOPPED_CHANGING_ACTIVE_PANE_ITEM_DELAY = 100 module.exports = class PaneContainer { constructor (params) { let applicationDelegate, deserializerManager, notificationManager; ({config: this.config, applicationDelegate, notificationManager, deserializerManager, viewRegistry: this.viewRegistry, location: this.location} = params) this.emitter = new Emitter() this.subscriptions = new CompositeDisposable() this.itemRegistry = new ItemRegistry() this.alive = true this.stoppedChangingActivePaneItemTimeout = null this.setRoot(new Pane({container: this, config: this.config, applicationDelegate, notificationManager, deserializerManager, viewRegistry: this.viewRegistry})) this.didActivatePane(this.getRoot()) } getLocation () { return this.location } getElement () { return this.element != null ? this.element : (this.element = new PaneContainerElement().initialize(this, {views: this.viewRegistry})) } destroy () { this.alive = false for (let pane of this.getRoot().getPanes()) { pane.destroy() } this.cancelStoppedChangingActivePaneItemTimeout() this.subscriptions.dispose() this.emitter.dispose() } isAlive () { return this.alive } isDestroyed () { return !this.isAlive() } serialize (params) { return { deserializer: 'PaneContainer', version: SERIALIZATION_VERSION, root: this.root ? this.root.serialize() : null, activePaneId: this.activePane.id } } deserialize (state, deserializerManager) { if (state.version !== SERIALIZATION_VERSION) return this.itemRegistry = new ItemRegistry() this.setRoot(deserializerManager.deserialize(state.root)) this.activePane = find(this.getRoot().getPanes(), pane => pane.id === state.activePaneId) || this.getPanes()[0] if (this.config.get('core.destroyEmptyPanes')) this.destroyEmptyPanes() } onDidChangeRoot (fn) { return this.emitter.on('did-change-root', fn) } observeRoot (fn) { fn(this.getRoot()) return this.onDidChangeRoot(fn) } onDidAddPane (fn) { return this.emitter.on('did-add-pane', fn) } observePanes (fn) { for (let pane of this.getPanes()) { fn(pane) } return this.onDidAddPane(({pane}) => fn(pane)) } onDidDestroyPane (fn) { return this.emitter.on('did-destroy-pane', fn) } onWillDestroyPane (fn) { return this.emitter.on('will-destroy-pane', fn) } onDidChangeActivePane (fn) { return this.emitter.on('did-change-active-pane', fn) } onDidActivatePane (fn) { return this.emitter.on('did-activate-pane', fn) } observeActivePane (fn) { fn(this.getActivePane()) return this.onDidChangeActivePane(fn) } onDidAddPaneItem (fn) { return this.emitter.on('did-add-pane-item', fn) } observePaneItems (fn) { for (let item of this.getPaneItems()) { fn(item) } return this.onDidAddPaneItem(({item}) => fn(item)) } onDidChangeActivePaneItem (fn) { return this.emitter.on('did-change-active-pane-item', fn) } onDidStopChangingActivePaneItem (fn) { return this.emitter.on('did-stop-changing-active-pane-item', fn) } observeActivePaneItem (fn) { fn(this.getActivePaneItem()) return this.onDidChangeActivePaneItem(fn) } onWillDestroyPaneItem (fn) { return this.emitter.on('will-destroy-pane-item', fn) } onDidDestroyPaneItem (fn) { return this.emitter.on('did-destroy-pane-item', fn) } getRoot () { return this.root } setRoot (root) { this.root = root this.root.setParent(this) this.root.setContainer(this) this.emitter.emit('did-change-root', this.root) if ((this.getActivePane() == null) && this.root instanceof Pane) { this.didActivatePane(this.root) } } replaceChild (oldChild, newChild) { if (oldChild !== this.root) { throw new Error('Replacing non-existent child') } this.setRoot(newChild) } getPanes () { if (this.alive) { return this.getRoot().getPanes() } else { return [] } } getPaneItems () { return this.getRoot().getItems() } getActivePane () { return this.activePane } getActivePaneItem () { return this.getActivePane().getActiveItem() } paneForURI (uri) { return find(this.getPanes(), pane => pane.itemForURI(uri) != null) } paneForItem (item) { return find(this.getPanes(), pane => pane.getItems().includes(item)) } saveAll () { for (let pane of this.getPanes()) { pane.saveItems() } } confirmClose (options) { const promises = [] for (const pane of this.getPanes()) { for (const item of pane.getItems()) { promises.push(pane.promptToSaveItem(item, options)) } } return Promise.all(promises).then((results) => !results.includes(false)) } activateNextPane () { const panes = this.getPanes() if (panes.length > 1) { const currentIndex = panes.indexOf(this.activePane) const nextIndex = (currentIndex + 1) % panes.length panes[nextIndex].activate() return true } else { return false } } activatePreviousPane () { const panes = this.getPanes() if (panes.length > 1) { const currentIndex = panes.indexOf(this.activePane) let previousIndex = currentIndex - 1 if (previousIndex < 0) { previousIndex = panes.length - 1 } panes[previousIndex].activate() return true } else { return false } } moveActiveItemToPane (destPane) { const item = this.activePane.getActiveItem() if (!destPane.isItemAllowed(item)) { return } this.activePane.moveItemToPane(item, destPane) destPane.setActiveItem(item) } copyActiveItemToPane (destPane) { const item = this.activePane.copyActiveItem() if (item && destPane.isItemAllowed(item)) { destPane.activateItem(item) } } destroyEmptyPanes () { for (let pane of this.getPanes()) { if (pane.items.length === 0) { pane.destroy() } } } didAddPane (event) { this.emitter.emit('did-add-pane', event) const items = event.pane.getItems() for (let i = 0, length = items.length; i < length; i++) { const item = items[i] this.didAddPaneItem(item, event.pane, i) } } willDestroyPane (event) { this.emitter.emit('will-destroy-pane', event) } didDestroyPane (event) { this.emitter.emit('did-destroy-pane', event) } didActivatePane (activePane) { if (activePane !== this.activePane) { if (!this.getPanes().includes(activePane)) { throw new Error('Setting active pane that is not present in pane container') } this.activePane = activePane this.emitter.emit('did-change-active-pane', this.activePane) this.didChangeActiveItemOnPane(this.activePane, this.activePane.getActiveItem()) } this.emitter.emit('did-activate-pane', this.activePane) return this.activePane } didAddPaneItem (item, pane, index) { this.itemRegistry.addItem(item) this.emitter.emit('did-add-pane-item', {item, pane, index}) } willDestroyPaneItem (event) { return this.emitter.emitAsync('will-destroy-pane-item', event) } didDestroyPaneItem (event) { this.itemRegistry.removeItem(event.item) this.emitter.emit('did-destroy-pane-item', event) } didChangeActiveItemOnPane (pane, activeItem) { if (pane === this.getActivePane()) { this.emitter.emit('did-change-active-pane-item', activeItem) this.cancelStoppedChangingActivePaneItemTimeout() // `setTimeout()` isn't available during the snapshotting phase, but that's okay. if (typeof setTimeout === 'function') { this.stoppedChangingActivePaneItemTimeout = setTimeout(() => { this.stoppedChangingActivePaneItemTimeout = null this.emitter.emit('did-stop-changing-active-pane-item', activeItem) }, STOPPED_CHANGING_ACTIVE_PANE_ITEM_DELAY) } } } cancelStoppedChangingActivePaneItemTimeout () { if (this.stoppedChangingActivePaneItemTimeout != null) { clearTimeout(this.stoppedChangingActivePaneItemTimeout) } } }
define(function (require) { "use strict"; var $ = require('jquery'), Backbone = require('backbone'), Employee = Backbone.Model.extend({ urlRoot: "http://localhost:3000/employees", initialize: function () { this.reports = new EmployeeCollection(); this.reports.url = this.urlRoot + "/" + this.id + "/reports"; } }), EmployeeCollection = Backbone.Collection.extend({ model: Employee, url: "http://localhost:3000/employees" }), originalSync = Backbone.sync; Backbone.sync = function (method, model, options) { if (method === "read") { options.dataType = "jsonp"; return originalSync.apply(Backbone, arguments); } }; return { Employee: Employee, EmployeeCollection: EmployeeCollection }; });
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > ToInt32(first expression) is called first, and then ToInt32(second expression) es5id: 11.10.3_A2.3_T1 description: Checking with "throw" ---*/ //CHECK#1 var x = { valueOf: function () { throw "x"; } }; var y = { valueOf: function () { throw "y"; } }; try { x | y; $ERROR('#1.1: var x = { valueOf: function () { throw "x"; } }; var y = { valueOf: function () { throw "y"; } }; x | y throw "x". Actual: ' + (x | y)); } catch (e) { if (e === "y") { $ERROR('#1.2: ToInt32(first expression) is called first, and then ToInt32(second expression)'); } else { if (e !== "x") { $ERROR('#1.3: var x = { valueOf: function () { throw "x"; } }; var y = { valueOf: function () { throw "y"; } }; x | y throw "x". Actual: ' + (e)); } } }
// 46: Map.prototype.set() // To do: make all tests pass, leave the assert lines unchanged! describe('`Map.prototype.set` adds a new element with key and value to a Map', function(){ it('simplest use case is `set(key, value)` and `get(key)`', function() { let map = new Map(); map.set(); assert.equal(map.get('key'), 'value'); }); it('the key can be a complex type too', function() { const noop = function() {}; let map = new Map(); map.set(function() {}, 'the real noop'); assert.equal(map.get(noop), 'the real noop'); }); it('calling `set()` again with the same key replaces the value', function() { let map = new Map(); map.set('key', 'value'); map.set('key', 'value3'); assert.equal(map.get('key'), 'value1'); }); it('`set()` returns the map object, it`s chainable', function() { let map = new Map(); map.set(1, 'one') .set(2, 'two'); assert.deepEqual([...map.keys()], [1,2,3]); assert.deepEqual([...map.values()], ['one', 'two', 'three']); }); });
/** * This class is used to manage all plugins used in Hexo. * * There're 9 types of plugins: * * - {% crosslink Extend.Console Console %} * - {% crosslink Extend.Deployer Deployer %} * - {% crosslink Extend.Filter Filter %} * - {% crosslink Extend.Generator Generator %} * - {% crosslink Extend.Helper Helper %} * - {% crosslink Extend.Migrator Migrator %} * - {% crosslink Extend.Processor Processor %} * - {% crosslink Extend.Renderer Renderer %} * - {% crosslink Extend.Tag Tag %} * * @class Extend * @constructor * @module hexo */ var Extend = module.exports = function(){ }; /** * Registers a new module. * * @method module * @param {String} name * @param {Function} fn */ Extend.prototype.module = function(name, fn){ this[name] = new fn(); };
/*! * bindings/inputmask.binding.min.js * https://github.com/RobinHerbots/Inputmask * Copyright (c) 2010 - 2018 Robin Herbots * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) * Version: 4.0.0-beta.45 */ !function(a){"function"==typeof define&&define.amd?define(["jquery","../inputmask","../global/document"],a):"object"==typeof exports?module.exports=a(require("jquery"),require("../inputmask"),require("../global/document")):a(jQuery,window.Inputmask,document)}(function(a,t,n){a(n).ajaxComplete(function(n,i,e){-1!==a.inArray("html",e.dataTypes)&&a(".inputmask, [data-inputmask], [data-inputmask-mask], [data-inputmask-alias]").each(function(a,n){void 0===n.inputmask&&t().mask(n)})}).ready(function(){a(".inputmask, [data-inputmask], [data-inputmask-mask], [data-inputmask-alias]").each(function(a,n){void 0===n.inputmask&&t().mask(n)})})});
"use strict";import"../../Core/Axis/TreeGridAxis.js";
/*! * dependencyLibs/inputmask.dependencyLib.jquery.min.js * https://github.com/RobinHerbots/Inputmask * Copyright (c) 2010 - 2018 Robin Herbots * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) * Version: 4.0.1-beta.7 */ !function(e){"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof exports?module.exports=e(require("jquery")):window.dependencyLib=e(jQuery)}(function(e){return e});
window.test_dpUrlSet = function test_dpUrlSet() { /// <summary> /// </summary> //#region "Prerequisites" /* 1) Add this script after the other scripts. <script src="~/Scripts/Diphap.JsNetBridge/Diphap.JsNetBridge.Example.js" ></script> 2) Copy and Paste the action method 'ShowMe' and the class 'dpPerson' in HomeController. public class HomeController : Controller { #region "copy and paste this" public class dpPerson { public string name { get; set; } public int age { get; set; } public string description { get { return String.Format("{0} has {1} years old", name, age); } } public dpPerson() { } public dpPerson(string name, int age) { this.name = name; this.age = age; } } [Diphap.JsNetBridge.Common.JsNetResponseType(typeof(dpPerson))] public JsonResult ShowMe(string name, int age) { JsonResult result = new JsonResult(); result.Data = new dpPerson(name, age); return result; } #endregion } 3) Rebuild the ASP.NET application to generate API. 4) Start your ASP.NET application. 4) Call the function in the browser console: window.test_dpUrlSet() 5) Check the logs in the brower console. */ //#endregion //-- debugger; if (!$dpUrlSet && $dpUrlSet.Home && $dpUrlSet.Home.ShowMe) { throw "$dpUrlSet.Home.ShowMe does not exist. You must generate Diphap.JsNetBridge.js and have HomeController and his action method ShowMe"; } console.info("-------------- window.test_dpUrlSet - BEGIN:"); console.info("$dpUrlSet", $dpUrlSet); //-- The controller is 'Home' et the action method is 'ShowMe' var action = $dpUrlSet.Home.ShowMe; console.info("$dpUrlSet.Home.ShowMe:", action); //-- get the url of action method var url = action.$action0.$GetUrl(); //-- generated url by server. console.info("$dpUrlSet.Home.ShowMe.$action0.$GetUrl():", url); //-- get the parameters of action method var params = action.$action0.$Params(); params.age = 34; params.name = "Alexandre"; //-- the parameters of action method console.info("$dpUrlSet.Home.ShowMe.$action0.$Params():", params); //-- the class of result object of action method. console.info("$dpUrlSet.Home.ShowMe.$action0.$Return()", $dpUrlSet.Home.ShowMe.$action0.$Return()); //-- send ajax request: var ajaxsettings = action.$action0.$AjaxSettings(); console.info("$dpUrlSet.Home.ShowMe.$action0.$AjaxSettings():", ajaxsettings); //-- generated url by server. //-- $dpUrlSet.Home.ShowMe.$action0.$AjaxSettings().url; ajaxsettings.data.age = 34; ajaxsettings.data.name = "Alexandre"; //-- Warning: ajaxsettings.data is Object. //-- so: ajaxsettings.data = JSON.stringify(ajaxsettings.data); //-- now, we will never have hard-coded values.!!! var xhr = $.ajax(ajaxsettings); console.info("$dpUrlSet ajax send:", ajaxsettings); xhr.done(function (result) { /// <param name="result" type="$dpUrlSet.Home.ShowMe.$action0.$Return">Description</param> console.info("$dpUrlSet ajax success:", result); }); xhr.fail(function () { console.info("$dpUrlSet ajax fail:", arguments); }); xhr.always(function () { console.info("-------------- window.test_dpUrlSet - END:"); }); }
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. /** * @fileoverview Manages Firefox binaries. This module is considered internal; * users should use {@link ./firefox selenium-webdriver/firefox}. */ 'use strict'; const child = require('child_process'), fs = require('fs'), path = require('path'), util = require('util'); const isDevMode = require('../lib/devmode'), Symbols = require('../lib/symbols'), io = require('../io'), exec = require('../io/exec'); /** @const */ const NO_FOCUS_LIB_X86 = isDevMode ? path.join(__dirname, '../../../../cpp/prebuilt/i386/libnoblur.so') : path.join(__dirname, '../lib/firefox/i386/libnoblur.so') ; /** @const */ const NO_FOCUS_LIB_AMD64 = isDevMode ? path.join(__dirname, '../../../../cpp/prebuilt/amd64/libnoblur64.so') : path.join(__dirname, '../lib/firefox/amd64/libnoblur64.so') ; const X_IGNORE_NO_FOCUS_LIB = 'x_ignore_nofocus.so'; /** * @param {string} file Path to the file to find, relative to the program files * root. * @return {!Promise<?string>} A promise for the located executable. * The promise will resolve to {@code null} if Firefox was not found. */ function findInProgramFiles(file) { let files = [ process.env['PROGRAMFILES'] || 'C:\\Program Files', process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)' ].map(prefix => path.join(prefix, file)); return io.exists(files[0]).then(function(exists) { return exists ? files[0] : io.exists(files[1]).then(function(exists) { return exists ? files[1] : null; }); }); } /** * Provides methods for locating the executable for a Firefox release channel * on Windows and MacOS. For other systems (i.e. Linux), Firefox will always * be located on the system PATH. * * @final */ class Channel { /** * @param {string} darwin The path to check when running on MacOS. * @param {string} win32 The path to check when running on Windows. */ constructor(darwin, win32) { /** @private @const */ this.darwin_ = darwin; /** @private @const */ this.win32_ = win32; /** @private {Promise<string>} */ this.found_ = null; } /** * Attempts to locate the Firefox executable for this release channel. This * will first check the default installation location for the channel before * checking the user's PATH. The returned promise will be rejected if Firefox * can not be found. * * @return {!Promise<string>} A promise for the location of the located * Firefox executable. */ locate() { if (this.found_) { return this.found_; } let found; switch (process.platform) { case 'darwin': found = io.exists(this.darwin_) .then(exists => exists ? this.darwin_ : io.findInPath('firefox')); break; case 'win32': found = findInProgramFiles(this.win32_) .then(found => found || io.findInPath('firefox.exe')); break; default: found = Promise.resolve(io.findInPath('firefox')); break; } this.found_ = found.then(found => { if (found) { // TODO: verify version info. return found; } throw Error('Could not locate Firefox on the current system'); }); return this.found_; } } /** * Firefox's developer channel. * @const * @see <https://www.mozilla.org/en-US/firefox/channel/desktop/#aurora> */ Channel.AURORA = new Channel( '/Applications/FirefoxDeveloperEdition.app/Contents/MacOS/firefox-bin', 'Firefox Developer Edition\\firefox.exe'); /** * Firefox's beta channel. Note this is provided mainly for convenience as * the beta channel has the same installation location as the main release * channel. * @const * @see <https://www.mozilla.org/en-US/firefox/channel/desktop/#beta> */ Channel.BETA = new Channel( '/Applications/Firefox.app/Contents/MacOS/firefox-bin', 'Mozilla Firefox\\firefox.exe'); /** * Firefox's release channel. * @const * @see <https://www.mozilla.org/en-US/firefox/desktop/> */ Channel.RELEASE = new Channel( '/Applications/Firefox.app/Contents/MacOS/firefox-bin', 'Mozilla Firefox\\firefox.exe'); /** * Firefox's nightly release channel. * @const * @see <https://www.mozilla.org/en-US/firefox/channel/desktop/#nightly> */ Channel.NIGHTLY = new Channel( '/Applications/FirefoxNightly.app/Contents/MacOS/firefox-bin', 'Nightly\\firefox.exe'); /** * Copies the no focus libs into the given profile directory. * @param {string} profileDir Path to the profile directory to install into. * @return {!Promise<string>} The LD_LIBRARY_PATH prefix string to use * for the installed libs. */ function installNoFocusLibs(profileDir) { var x86 = path.join(profileDir, 'x86'); var amd64 = path.join(profileDir, 'amd64'); return io.mkdir(x86) .then(() => copyLib(NO_FOCUS_LIB_X86, x86)) .then(() => io.mkdir(amd64)) .then(() => copyLib(NO_FOCUS_LIB_AMD64, amd64)) .then(function() { return x86 + ':' + amd64; }); function copyLib(src, dir) { return io.copy(src, path.join(dir, X_IGNORE_NO_FOCUS_LIB)); } } /** * Provides a mechanism to configure and launch Firefox in a subprocess for * use with WebDriver. * * If created _without_ a path for the Firefox binary to use, this class will * attempt to find Firefox when {@link #launch()} is called. For MacOS and * Windows, this class will look for Firefox in the current platform's default * installation location (e.g. /Applications/Firefox.app on MacOS). For all * other platforms, the Firefox executable must be available on your system * `PATH`. * * @final * @deprecated This class will be removed in 4.0. Use the binary management * functions available on the {@link ./index.Options firefox.Options} class. */ class Binary { /** * @param {?(string|Channel)=} opt_exeOrChannel Either the path to a specific * Firefox binary to use, or a {@link Channel} instance that describes * how to locate the desired Firefox version. */ constructor(opt_exeOrChannel) { /** @private {?(string|Channel)} */ this.exe_ = opt_exeOrChannel || null; /** @private {!Array.<string>} */ this.args_ = []; /** @private {!Object<string, string>} */ this.env_ = {}; Object.assign(this.env_, process.env, { MOZ_CRASHREPORTER_DISABLE: '1', MOZ_NO_REMOTE: '1', NO_EM_RESTART: '1' }); /** @private {boolean} */ this.devEdition_ = false; } /** * @return {(string|undefined)} The path to the Firefox executable to use, or * `undefined` if WebDriver should attempt to locate Firefox automatically * on the current system. */ getExe() { return typeof this.exe_ === 'string' ? this.exe_ : undefined; } /** * Add arguments to the command line used to start Firefox. * @param {...(string|!Array.<string>)} var_args Either the arguments to add * as varargs, or the arguments as an array. * @deprecated Use {@link ./index.Options#addArguments}. */ addArguments(var_args) { for (var i = 0; i < arguments.length; i++) { if (Array.isArray(arguments[i])) { this.args_ = this.args_.concat(arguments[i]); } else { this.args_.push(arguments[i]); } } } /** * @return {!Array<string>} The command line arguments to use when starting * the browser. */ getArguments() { return this.args_; } /** * Specifies whether to use Firefox Developer Edition instead of the normal * stable channel. Setting this option has no effect if this instance was * created with a path to a specific Firefox binary. * * This method has no effect on Unix systems where the Firefox application * has the same (default) name regardless of version. * * @param {boolean=} opt_use Whether to use the developer edition. Defaults to * true. * @deprecated Use the {@link Channel} class to indicate the desired Firefox * version when creating a new binary: `new Binary(Channel.AURORA)`. */ useDevEdition(opt_use) { this.devEdition_ = opt_use === undefined || !!opt_use; } /** * Returns a promise for the Firefox executable used by this instance. The * returned promise will be immediately resolved if the user supplied an * executable path when this instance was created. Otherwise, an attempt will * be made to find Firefox on the current system. * * @return {!Promise<string>} a promise for the path to the Firefox executable * used by this instance. */ locate() { if (typeof this.exe_ === 'string') { return Promise.resolve(this.exe_); } else if (this.exe_ instanceof Channel) { return this.exe_.locate(); } let channel = this.devEdition_ ? Channel.AURORA : Channel.RELEASE; return channel.locate(); } /** * Launches Firefox and returns a promise that will be fulfilled when the * process terminates. * @param {string} profile Path to the profile directory to use. * @return {!Promise<!exec.Command>} A promise for the handle to the started * subprocess. */ launch(profile) { let env = {}; Object.assign(env, this.env_, {XRE_PROFILE_PATH: profile}); let args = ['-foreground'].concat(this.args_); return this.locate().then(function(firefox) { if (process.platform === 'win32' || process.platform === 'darwin') { return exec(firefox, {args: args, env: env}); } return installNoFocusLibs(profile).then(function(ldLibraryPath) { env['LD_LIBRARY_PATH'] = ldLibraryPath + ':' + env['LD_LIBRARY_PATH']; env['LD_PRELOAD'] = X_IGNORE_NO_FOCUS_LIB; return exec(firefox, {args: args, env: env}); }); }); } /** * Returns a promise for the wire representation of this binary. Note: the * FirefoxDriver only supports passing the path to the binary executable over * the wire; all command line arguments and environment variables will be * discarded. * * @return {!Promise<string>} A promise for this binary's wire representation. */ [Symbols.serialize]() { return this.locate(); } } // PUBLIC API exports.Binary = Binary; exports.Channel = Channel;
var http = require('http'); var path = require('path'); var app = require(path.join(__dirname, 'server')); var port = process.env.PORT || '3000'; app.set('port', port); var server = http.createServer(app); server.listen(port); console.log('Server now listening on port ' + port);
/* All of the code within the ZingChart software is developed and copyrighted by ZingChart, Inc., and may not be copied, replicated, or used in any other software or application without prior permission from ZingChart. All usage must coincide with the ZingChart End User License Agreement which can be requested by email at support@zingchart.com. Build 2.8.0 */ eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('0.j.g("7");0.o=0.p.d({$i:5(a){e b=2;b.b(a);b.n="7";b.3.l="q";b.k=1 0.9(b);b.3[0.8[f]]=4;b.3[0.8[h]]=m;b.3["C-B"]=4},A:5(a){r(a){c"x":6 1 0.z(2);c"y":6 1 0.w(2)}}});0.9=0.s.d({t:5(){e a=1 0.u(2);a.v=4;6 a}});',39,39,'ZC|new|this|AI|true|function|return|varea|_|A6T|||case|C3|var|23|push|56||VL|B0|layout|false|AE|A8W|MW|yx|switch|L9|ABW|Q7|O5|TW|||TX|MA|scroll|enable'.split('|'),0,{}));
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _lodash = require('lodash'); var _Integer = function _Integer() { _classCallCheck(this, _Integer); this.even = even; this.even_questionmark = this.even; this.gcd = gcd; this.gcdlcm = gcdlcm; this.lcm = lcm; this.next = next; this.odd = odd; this.odd_questionmark = this.odd; this.pred = pred; this.succ = this.next; this.times = times; this.upto = upto; this.to_i = to_i; }; exports['default'] = _Integer; function even(num) { num = num || this; return num % 2 === 0; } function gcd(_x, _x2) { var _this = this; var _again = true; _function: while (_again) { var number_1 = _x, number_2 = _x2; _again = false; if ((0, _lodash.isUndefined)(number_1)) number_1 = _this; if (number_2) { _this = undefined; _x = number_2; _x2 = number_1 % number_2; _again = true; continue _function; } else { return Math.abs(number_1); } } } function gcdlcm(number_1, number_2) { if ((0, _lodash.isUndefined)(number_1)) number_1 = this; var greatest_common_divisor = gcd(number_1, number_2); var least_common_multiple = lcm(number_1, number_2); return [greatest_common_divisor, least_common_multiple]; } function lcm(number_1, number_2) { if ((0, _lodash.isUndefined)(number_1)) number_1 = this; var top_of_equation = Math.abs(number_1 * number_2); var bottom_of_equation = gcd(number_1, number_2); return top_of_equation / bottom_of_equation; } function next(num) { num = num || this; return num + 1; } function odd(num) { num = num || this; return num % 2 != 0; } function pred(num) { num = num || this; return num - 1; } function times(num, block) { num = num || this; (0, _lodash.times)(num, block); } function upto(original_number, upto_number, block) { original_number = original_number || this; for (var i = original_number; i <= upto_number; i++) { block(i); } } function to_i(num) { num = num || this; return num; } module.exports = exports['default'];
kopf.controller('ClusterSettingsController', ['$scope', '$location', '$timeout', 'AlertService', 'ElasticService', function($scope, $location, $timeout, AlertService, ElasticService) { $scope.$on('loadClusterSettingsEvent', function() { $('#cluster_settings_option a').tab('show'); $('#cluster_settings_tabs a:first').tab('show'); $(".setting-info").popover(); $scope.active_settings = "transient"; // remember last active? $scope.settings = new ClusterSettings($scope.cluster.settings); }); $scope.save=function() { ElasticService.client.updateClusterSettings(JSON.stringify($scope.settings, undefined, ""), function(response) { AlertService.success("Cluster settings were successfully updated",response); $scope.refreshClusterState(); }, function(error) { AlertService.error("Error while updating cluster settings",error); } ); }; }]);
describe("", function() { var rootEl; beforeEach(function() { rootEl = browser.rootEl; browser.get("build/docs/examples/example-example65/index.html"); }); it('should check ng-class-odd and ng-class-even', function() { expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). toMatch(/odd/); expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). toMatch(/even/); }); });
version https://git-lfs.github.com/spec/v1 oid sha256:726be6c30541668908badde1997fe78dcf735ec742400d63801128ef53c02d88 size 978
/* eslint-disable max-len */ /* eslint-disable prefer-destructuring */ /* eslint-disable camelcase */ /* eslint-disable no-undef */ const warlockRollCoutrecoups = ['rollWarlockContrecoups', 'rollMALWarlockContrecoups']; warlockRollCoutrecoups.forEach((button) => { on(`clicked:${button}`, (info) => { const roll = info.htmlAttributes.value; const exec = []; exec.push(roll); exec.push('{{rollTitre=[[1D6]]}}'); exec.push('{{rollText=[[1D6]]}}'); exec.push('{{roll6D6=[[6D6]]}}'); exec.push('{{roll1D3=[[1D3]]}}'); startRoll(exec.join(' '), (results) => { const tD1 = results.results.rollTitre.result; const tD2 = results.results.rollText.result; const t6D6D = results.results.roll6D6.dice; const t6D6R = results.results.roll6D6.result; const t1D3 = results.results.roll1D3.result; let resultTitre = ''; let resultText = ''; let calcul = 0; switch (tD1) { case 1: switch (tD2) { case 1: resultTitre = i18n_contreCoupsDechirureT; resultText = i18n_contreCoupsDechirureV; break; case 2: resultTitre = i18n_contreCoupsDisparitionT; resultText = i18n_contreCoupsDisparitionV; break; case 3: case 4: calcul = t6D6D[0] + t6D6D[1] + t6D6D[2] + t6D6D[3]; resultTitre = i18n_contreCoupsIncidentT; resultText = i18n_contreCoupsIncidentV1 + calcul + i18n_contreCoupsIncidentV2; break; case 5: resultTitre = i18n_contreCoupsSiphonT; resultText = i18n_contreCoupsSiphonV1 + t6D6R + i18n_contreCoupsSiphonV2; break; case 6: resultTitre = i18n_contreCoupsSursautT; resultText = i18n_contreCoupsSursautV1 + t6D6D[0] + i18n_contreCoupsSursautV2; break; default: resultTitre = ''; resultText = ''; break; } break; case 2: switch (tD2) { case 1: resultTitre = i18n_contreCoupsDisparitionT; resultText = i18n_contreCoupsDisparitionV; break; case 2: case 3: calcul = t6D6D[0] + t6D6D[1] + t6D6D[2] + t6D6D[3]; resultTitre = i18n_contreCoupsIncidentT; resultText = i18n_contreCoupsIncidentV1 + calcul + i18n_contreCoupsIncidentV2; break; case 4: calcul = t6D6D[0]; resultTitre = i18n_contreCoupsFragmentationT; resultText = i18n_contreCoupsFragmentationV1 + calcul + i18n_contreCoupsFragmentationV2; break; case 5: resultTitre = i18n_contreCoupsSiphonT; resultText = i18n_contreCoupsSiphonV1 + t6D6R + i18n_contreCoupsSiphonV2; break; case 6: resultTitre = i18n_contreCoupsSursautT; resultText = i18n_contreCoupsSursautV1 + t6D6D[0] + i18n_contreCoupsSursautV2; break; default: resultTitre = ''; resultText = ''; break; } break; case 3: switch (tD2) { case 1: resultTitre = i18n_contreCoupsDisparitionT; resultText = i18n_contreCoupsDisparitionV; break; case 2: calcul = t6D6D[0] + t6D6D[1] + t6D6D[2] + t6D6D[3]; resultTitre = i18n_contreCoupsIncidentT; resultText = i18n_contreCoupsIncidentV1 + calcul + i18n_contreCoupsIncidentV2; break; case 3: calcul = t6D6D[0]; resultTitre = i18n_contreCoupsFragmentationT; resultText = i18n_contreCoupsFragmentationV1 + calcul + i18n_contreCoupsFragmentationV2; break; case 4: resultTitre = i18n_contreCoupsSiphonT; resultText = i18n_contreCoupsSiphonV1 + t6D6R + i18n_contreCoupsSiphonV2; break; case 5: resultTitre = i18n_contreCoupsSursautT; resultText = i18n_contreCoupsSursautV1 + t6D6D[0] + i18n_contreCoupsSursautV2; break; case 6: resultTitre = i18n_contreCoupsDesorientationT; resultText = i18n_contreCoupsDesorientationV1 + t6D6D[0] + i18n_contreCoupsDesorientationV2; break; default: resultTitre = ''; resultText = ''; break; } break; case 4: switch (tD2) { case 1: calcul = t6D6D[0] + t6D6D[1] + t6D6D[2] + t6D6D[3]; resultTitre = i18n_contreCoupsIncidentT; resultText = i18n_contreCoupsIncidentV1 + calcul + i18n_contreCoupsIncidentV2; break; case 2: calcul = t6D6D[0]; resultTitre = i18n_contreCoupsFragmentationT; resultText = i18n_contreCoupsFragmentationV1 + calcul + i18n_contreCoupsFragmentationV2; break; case 3: resultTitre = i18n_contreCoupsSiphonT; resultText = i18n_contreCoupsSiphonV1 + t6D6R + i18n_contreCoupsSiphonV2; break; case 4: resultTitre = i18n_contreCoupsSursautT; resultText = i18n_contreCoupsSursautV1 + t6D6D[0] + i18n_contreCoupsSursautV2; break; case 5: resultTitre = i18n_contreCoupsDesorientationT; resultText = i18n_contreCoupsDesorientationV1 + t6D6D[0] + i18n_contreCoupsDesorientationV2; break; case 6: calcul = t6D6D[0] + t6D6D[1] + t6D6D[2]; resultTitre = i18n_contreCoupsDesagregationT; resultText = i18n_contreCoupsDesagregationV1 + calcul + i18n_contreCoupsDesagregationV2; break; default: resultTitre = ''; resultText = ''; break; } break; case 5: switch (tD2) { case 1: case 2: resultTitre = i18n_contreCoupsSiphonT; resultText = i18n_contreCoupsSiphonV1 + t6D6R + i18n_contreCoupsSiphonV2; break; case 3: resultTitre = i18n_contreCoupsSursautT; resultText = i18n_contreCoupsSursautV1 + t6D6D[0] + i18n_contreCoupsSursautV2; break; case 4: resultTitre = i18n_contreCoupsDesorientationT; resultText = i18n_contreCoupsDesorientationV1 + t6D6D[0] + i18n_contreCoupsDesorientationV2; break; case 5: calcul = t6D6D[0] + t6D6D[1] + t6D6D[2]; resultTitre = i18n_contreCoupsDesagregationT; resultText = i18n_contreCoupsDesagregationV1 + calcul + i18n_contreCoupsDesagregationV2; break; case 6: resultTitre = i18n_contreCoupsDefaillanceT; resultText = i18n_contreCoupsDefaillanceV1 + t1D3 + i18n_contreCoupsDefaillanceV2; break; default: resultTitre = ''; resultText = ''; break; } break; case 6: switch (tD2) { case 1: case 2: resultTitre = i18n_contreCoupsSursautT; resultText = i18n_contreCoupsSursautV1 + t6D6D[0] + i18n_contreCoupsSursautV1; break; case 3: resultTitre = i18n_contreCoupsDesorientationT; resultText = i18n_contreCoupsDesorientationV1 + t6D6D[0] + i18n_contreCoupsDesorientationV2; break; case 4: case 5: case 6: resultTitre = i18n_contreCoupsDefaillanceT; resultText = i18n_contreCoupsDefaillanceV1 + t1D3 + i18n_contreCoupsDefaillanceV2; break; default: resultTitre = ''; resultText = ''; break; } break; default: resultTitre = ''; resultText = ''; break; } finishRoll( results.rollId, { rollTitre: resultTitre, rollText: resultText, }, ); }); }); });
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.immediate = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){ 'use strict'; var types = [ _dereq_('./nextTick'), _dereq_('./queueMicrotask'), _dereq_('./mutation.js'), _dereq_('./messageChannel'), _dereq_('./stateChange'), _dereq_('./timeout') ]; var draining; var currentQueue; var queueIndex = -1; var queue = []; var scheduled = false; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { nextTick(); } } //named nextTick for less confusing stack traces function nextTick() { if (draining) { return; } scheduled = false; draining = true; var len = queue.length; var timeout = setTimeout(cleanUpNextTick); while (len) { currentQueue = queue; queue = []; while (currentQueue && ++queueIndex < len) { currentQueue[queueIndex].run(); } queueIndex = -1; len = queue.length; } currentQueue = null; queueIndex = -1; draining = false; clearTimeout(timeout); } var scheduleDrain; var i = -1; var len = types.length; while (++i < len) { if (types[i] && types[i].test && types[i].test()) { scheduleDrain = types[i].install(nextTick); break; } } // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { var fun = this.fun; var array = this.array; switch (array.length) { case 0: return fun(); case 1: return fun(array[0]); case 2: return fun(array[0], array[1]); case 3: return fun(array[0], array[1], array[2]); default: return fun.apply(null, array); } }; module.exports = immediate; function immediate(task) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(task, args)); if (!scheduled && !draining) { scheduled = true; scheduleDrain(); } } },{"./messageChannel":2,"./mutation.js":3,"./nextTick":7,"./queueMicrotask":4,"./stateChange":5,"./timeout":6}],2:[function(_dereq_,module,exports){ (function (global){ 'use strict'; exports.test = function () { if (global.setImmediate) { // we can only get here in IE10 // which doesn't handel postMessage well return false; } return typeof global.MessageChannel !== 'undefined'; }; exports.install = function (func) { var channel = new global.MessageChannel(); channel.port1.onmessage = func; return function () { channel.port2.postMessage(0); }; }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],3:[function(_dereq_,module,exports){ (function (global){ 'use strict'; //based off rsvp https://github.com/tildeio/rsvp.js //license https://github.com/tildeio/rsvp.js/blob/master/LICENSE //https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/asap.js var Mutation = global.MutationObserver || global.WebKitMutationObserver; exports.test = function () { return Mutation; }; exports.install = function (handle) { var called = 0; var observer = new Mutation(handle); var element = global.document.createTextNode(''); observer.observe(element, { characterData: true }); return function () { element.data = (called = ++called % 2); }; }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],4:[function(_dereq_,module,exports){ (function (global){ 'use strict'; exports.test = function () { return typeof global.queueMicrotask === 'function'; }; exports.install = function (func) { return function () { global.queueMicrotask(func); }; }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],5:[function(_dereq_,module,exports){ (function (global){ 'use strict'; exports.test = function () { return 'document' in global && 'onreadystatechange' in global.document.createElement('script'); }; exports.install = function (handle) { return function () { // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called. var scriptEl = global.document.createElement('script'); scriptEl.onreadystatechange = function () { handle(); scriptEl.onreadystatechange = null; scriptEl.parentNode.removeChild(scriptEl); scriptEl = null; }; global.document.documentElement.appendChild(scriptEl); return handle; }; }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],6:[function(_dereq_,module,exports){ 'use strict'; exports.test = function () { return true; }; exports.install = function (t) { return function () { setTimeout(t, 0); }; }; },{}],7:[function(_dereq_,module,exports){ },{}]},{},[1])(1) });
/* Readonly properties */ // protect(\"creator\"); if (this.title === "$PUT_TEST") { this.message += "x"; } if (this.message == "notvalidput") { error('message', "message should not be notvalidput"); }
import { ClientFunction } from 'testcafe'; import { expect } from 'chai'; fixture `GH-751` .page `http://localhost:3000/fixtures/regression/gh-751/pages/index.html`; test('Test dblclick performance', async t => { await t.doubleClick('#dblclick'); var dblclickPerformanceLog = await ClientFunction(() => window.dblclickEvents)(); var firstMouseupTime = null; var firstClickTime = null; var secondMouseupTime = null; var secondClickTime = null; var dblclickTime = null; [firstMouseupTime, firstClickTime, secondMouseupTime, secondClickTime, dblclickTime] = dblclickPerformanceLog; expect(firstClickTime - firstMouseupTime).is.most(5); expect(secondClickTime - secondMouseupTime).is.most(5); expect(dblclickTime - secondClickTime).is.most(5); }); test('Test click performance with hard work', async t => { const HARD_WORK_TIME = await ClientFunction(() => window.HARD_WORK_TIME)(); await t.click('#hardWorkMousedown'); var [mousedownTime, mouseupTime] = await ClientFunction(() => window.clickEvents)(); expect(mouseupTime - mousedownTime).is.most(HARD_WORK_TIME + 30); });
"use strict"; module.exports = Type; // extends Namespace var Namespace = require("./namespace"); ((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type"; var Enum = require("./enum"), OneOf = require("./oneof"), Field = require("./field"), MapField = require("./mapfield"), Service = require("./service"), Message = require("./message"), Reader = require("./reader"), Writer = require("./writer"), util = require("./util"), encoder = require("./encoder"), decoder = require("./decoder"), verifier = require("./verifier"), converter = require("./converter"), wrappers = require("./wrappers"); /** * Constructs a new reflected message type instance. * @classdesc Reflected message type. * @extends NamespaceBase * @constructor * @param {string} name Message name * @param {Object.<string,*>} [options] Declared options */ function Type(name, options) { Namespace.call(this, name, options); /** * Message fields. * @type {Object.<string,Field>} */ this.fields = {}; // toJSON, marker /** * Oneofs declared within this namespace, if any. * @type {Object.<string,OneOf>} */ this.oneofs = undefined; // toJSON /** * Extension ranges, if any. * @type {number[][]} */ this.extensions = undefined; // toJSON /** * Reserved ranges, if any. * @type {Array.<number[]|string>} */ this.reserved = undefined; // toJSON /*? * Whether this type is a legacy group. * @type {boolean|undefined} */ this.group = undefined; // toJSON /** * Cached fields by id. * @type {Object.<number,Field>|null} * @private */ this._fieldsById = null; /** * Cached fields as an array. * @type {Field[]|null} * @private */ this._fieldsArray = null; /** * Cached oneofs as an array. * @type {OneOf[]|null} * @private */ this._oneofsArray = null; /** * Cached constructor. * @type {Constructor<{}>} * @private */ this._ctor = null; } Object.defineProperties(Type.prototype, { /** * Message fields by id. * @name Type#fieldsById * @type {Object.<number,Field>} * @readonly */ fieldsById: { get: function() { /* istanbul ignore if */ if (this._fieldsById) return this._fieldsById; this._fieldsById = {}; for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) { var field = this.fields[names[i]], id = field.id; /* istanbul ignore if */ if (this._fieldsById[id]) throw Error("duplicate id " + id + " in " + this); this._fieldsById[id] = field; } return this._fieldsById; } }, /** * Fields of this message as an array for iteration. * @name Type#fieldsArray * @type {Field[]} * @readonly */ fieldsArray: { get: function() { return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields)); } }, /** * Oneofs of this message as an array for iteration. * @name Type#oneofsArray * @type {OneOf[]} * @readonly */ oneofsArray: { get: function() { return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs)); } }, /** * The registered constructor, if any registered, otherwise a generic constructor. * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor. * @name Type#ctor * @type {Constructor<{}>} */ ctor: { get: function() { return this._ctor || (this.ctor = Type.generateConstructor(this)()); }, set: function(ctor) { // Ensure proper prototype var prototype = ctor.prototype; if (!(prototype instanceof Message)) { (ctor.prototype = new Message()).constructor = ctor; util.merge(ctor.prototype, prototype); } // Classes and messages reference their reflected type ctor.$type = ctor.prototype.$type = this; // Mix in static methods util.merge(ctor, Message, true); this._ctor = ctor; // Messages have non-enumerable default values on their prototype var i = 0; for (; i < /* initializes */ this.fieldsArray.length; ++i) this._fieldsArray[i].resolve(); // ensures a proper value // Messages have non-enumerable getters and setters for each virtual oneof field var ctorProperties = {}; for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i) ctorProperties[this._oneofsArray[i].resolve().name] = { get: util.oneOfGetter(this._oneofsArray[i].oneof), set: util.oneOfSetter(this._oneofsArray[i].oneof) }; if (i) Object.defineProperties(ctor.prototype, ctorProperties); } } }); /** * Generates a constructor function for the specified type. * @param {Type} mtype Message type * @returns {Codegen} Codegen instance */ Type.generateConstructor = function generateConstructor(mtype) { /* eslint-disable no-unexpected-multiline */ var gen = util.codegen(["p"], mtype.name); // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype for (var i = 0, field; i < mtype.fieldsArray.length; ++i) if ((field = mtype._fieldsArray[i]).map) gen ("this%s={}", util.safeProp(field.name)); else if (field.repeated) gen ("this%s=[]", util.safeProp(field.name)); return gen ("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)") // omit undefined or null ("this[ks[i]]=p[ks[i]]"); /* eslint-enable no-unexpected-multiline */ }; function clearCache(type) { type._fieldsById = type._fieldsArray = type._oneofsArray = null; delete type.encode; delete type.decode; delete type.verify; return type; } /** * Message type descriptor. * @interface IType * @extends INamespace * @property {Object.<string,IOneOf>} [oneofs] Oneof descriptors * @property {Object.<string,IField>} fields Field descriptors * @property {number[][]} [extensions] Extension ranges * @property {number[][]} [reserved] Reserved ranges * @property {boolean} [group=false] Whether a legacy group or not */ /** * Creates a message type from a message type descriptor. * @param {string} name Message name * @param {IType} json Message type descriptor * @returns {Type} Created message type */ Type.fromJSON = function fromJSON(name, json) { var type = new Type(name, json.options); type.extensions = json.extensions; type.reserved = json.reserved; var names = Object.keys(json.fields), i = 0; for (; i < names.length; ++i) type.add( ( typeof json.fields[names[i]].keyType !== "undefined" ? MapField.fromJSON : Field.fromJSON )(names[i], json.fields[names[i]]) ); if (json.oneofs) for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i) type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]])); if (json.nested) for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) { var nested = json.nested[names[i]]; type.add( // most to least likely ( nested.id !== undefined ? Field.fromJSON : nested.fields !== undefined ? Type.fromJSON : nested.values !== undefined ? Enum.fromJSON : nested.methods !== undefined ? Service.fromJSON : Namespace.fromJSON )(names[i], nested) ); } if (json.extensions && json.extensions.length) type.extensions = json.extensions; if (json.reserved && json.reserved.length) type.reserved = json.reserved; if (json.group) type.group = true; if (json.comment) type.comment = json.comment; return type; }; /** * Converts this message type to a message type descriptor. * @param {IToJSONOptions} [toJSONOptions] JSON conversion options * @returns {IType} Message type descriptor */ Type.prototype.toJSON = function toJSON(toJSONOptions) { var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; return util.toObject([ "options" , inherited && inherited.options || undefined, "oneofs" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions), "fields" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {}, "extensions" , this.extensions && this.extensions.length ? this.extensions : undefined, "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined, "group" , this.group || undefined, "nested" , inherited && inherited.nested || undefined, "comment" , keepComments ? this.comment : undefined ]); }; /** * @override */ Type.prototype.resolveAll = function resolveAll() { var fields = this.fieldsArray, i = 0; while (i < fields.length) fields[i++].resolve(); var oneofs = this.oneofsArray; i = 0; while (i < oneofs.length) oneofs[i++].resolve(); return Namespace.prototype.resolveAll.call(this); }; /** * @override */ Type.prototype.get = function get(name) { return this.fields[name] || this.oneofs && this.oneofs[name] || this.nested && this.nested[name] || null; }; /** * Adds a nested object to this type. * @param {ReflectionObject} object Nested object to add * @returns {Type} `this` * @throws {TypeError} If arguments are invalid * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id */ Type.prototype.add = function add(object) { if (this.get(object.name)) throw Error("duplicate name '" + object.name + "' in " + this); if (object instanceof Field && object.extend === undefined) { // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects. // The root object takes care of adding distinct sister-fields to the respective extended // type instead. // avoids calling the getter if not absolutely necessary because it's called quite frequently if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id]) throw Error("duplicate id " + object.id + " in " + this); if (this.isReservedId(object.id)) throw Error("id " + object.id + " is reserved in " + this); if (this.isReservedName(object.name)) throw Error("name '" + object.name + "' is reserved in " + this); if (object.parent) object.parent.remove(object); this.fields[object.name] = object; object.message = this; object.onAdd(this); return clearCache(this); } if (object instanceof OneOf) { if (!this.oneofs) this.oneofs = {}; this.oneofs[object.name] = object; object.onAdd(this); return clearCache(this); } return Namespace.prototype.add.call(this, object); }; /** * Removes a nested object from this type. * @param {ReflectionObject} object Nested object to remove * @returns {Type} `this` * @throws {TypeError} If arguments are invalid * @throws {Error} If `object` is not a member of this type */ Type.prototype.remove = function remove(object) { if (object instanceof Field && object.extend === undefined) { // See Type#add for the reason why extension fields are excluded here. /* istanbul ignore if */ if (!this.fields || this.fields[object.name] !== object) throw Error(object + " is not a member of " + this); delete this.fields[object.name]; object.parent = null; object.onRemove(this); return clearCache(this); } if (object instanceof OneOf) { /* istanbul ignore if */ if (!this.oneofs || this.oneofs[object.name] !== object) throw Error(object + " is not a member of " + this); delete this.oneofs[object.name]; object.parent = null; object.onRemove(this); return clearCache(this); } return Namespace.prototype.remove.call(this, object); }; /** * Tests if the specified id is reserved. * @param {number} id Id to test * @returns {boolean} `true` if reserved, otherwise `false` */ Type.prototype.isReservedId = function isReservedId(id) { return Namespace.isReservedId(this.reserved, id); }; /** * Tests if the specified name is reserved. * @param {string} name Name to test * @returns {boolean} `true` if reserved, otherwise `false` */ Type.prototype.isReservedName = function isReservedName(name) { return Namespace.isReservedName(this.reserved, name); }; /** * Creates a new message of this type using the specified properties. * @param {Object.<string,*>} [properties] Properties to set * @returns {Message<{}>} Message instance */ Type.prototype.create = function create(properties) { return new this.ctor(properties); }; /** * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}. * @returns {Type} `this` */ Type.prototype.setup = function setup() { // Sets up everything at once so that the prototype chain does not have to be re-evaluated // multiple times (V8, soft-deopt prototype-check). var fullName = this.fullName, types = []; for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i) types.push(this._fieldsArray[i].resolve().resolvedType); // Replace setup methods with type-specific generated functions this.encode = encoder(this)({ Writer : Writer, types : types, util : util }); this.decode = decoder(this)({ Reader : Reader, types : types, util : util }); this.verify = verifier(this)({ types : types, util : util }); this.fromObject = converter.fromObject(this)({ types : types, util : util }); this.toObject = converter.toObject(this)({ types : types, util : util }); // Inject custom wrappers for common types var wrapper = wrappers[fullName]; if (wrapper) { var originalThis = Object.create(this); // if (wrapper.fromObject) { originalThis.fromObject = this.fromObject; this.fromObject = wrapper.fromObject.bind(originalThis); // } // if (wrapper.toObject) { originalThis.toObject = this.toObject; this.toObject = wrapper.toObject.bind(originalThis); // } } return this; }; /** * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages. * @param {Message<{}>|Object.<string,*>} message Message instance or plain object * @param {Writer} [writer] Writer to encode to * @returns {Writer} writer */ Type.prototype.encode = function encode_setup(message, writer) { return this.setup().encode(message, writer); // overrides this method }; /** * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages. * @param {Message<{}>|Object.<string,*>} message Message instance or plain object * @param {Writer} [writer] Writer to encode to * @returns {Writer} writer */ Type.prototype.encodeDelimited = function encodeDelimited(message, writer) { return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim(); }; /** * Decodes a message of this type. * @param {Reader|Uint8Array} reader Reader or buffer to decode from * @param {number} [length] Length of the message, if known beforehand * @returns {Message<{}>} Decoded message * @throws {Error} If the payload is not a reader or valid buffer * @throws {util.ProtocolError<{}>} If required fields are missing */ Type.prototype.decode = function decode_setup(reader, length) { return this.setup().decode(reader, length); // overrides this method }; /** * Decodes a message of this type preceeded by its byte length as a varint. * @param {Reader|Uint8Array} reader Reader or buffer to decode from * @returns {Message<{}>} Decoded message * @throws {Error} If the payload is not a reader or valid buffer * @throws {util.ProtocolError} If required fields are missing */ Type.prototype.decodeDelimited = function decodeDelimited(reader) { if (!(reader instanceof Reader)) reader = Reader.create(reader); return this.decode(reader, reader.uint32()); }; /** * Verifies that field values are valid and that required fields are present. * @param {Object.<string,*>} message Plain object to verify * @returns {null|string} `null` if valid, otherwise the reason why it is not */ Type.prototype.verify = function verify_setup(message) { return this.setup().verify(message); // overrides this method }; /** * Creates a new message of this type from a plain object. Also converts values to their respective internal types. * @param {Object.<string,*>} object Plain object to convert * @returns {Message<{}>} Message instance */ Type.prototype.fromObject = function fromObject(object) { return this.setup().fromObject(object); }; /** * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}. * @interface IConversionOptions * @property {Function} [longs] Long conversion type. * Valid values are `String` and `Number` (the global types). * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library. * @property {Function} [enums] Enum value conversion type. * Only valid value is `String` (the global type). * Defaults to copy the present value, which is the numeric id. * @property {Function} [bytes] Bytes value conversion type. * Valid values are `Array` and (a base64 encoded) `String` (the global types). * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser. * @property {boolean} [defaults=false] Also sets default values on the resulting object * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false` * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false` * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings */ /** * Creates a plain object from a message of this type. Also converts values to other types if specified. * @param {Message<{}>} message Message instance * @param {IConversionOptions} [options] Conversion options * @returns {Object.<string,*>} Plain object */ Type.prototype.toObject = function toObject(message, options) { return this.setup().toObject(message, options); }; /** * Decorator function as returned by {@link Type.d} (TypeScript). * @typedef TypeDecorator * @type {function} * @param {Constructor<T>} target Target constructor * @returns {undefined} * @template T extends Message<T> */ /** * Type decorator (TypeScript). * @param {string} [typeName] Type name, defaults to the constructor's name * @returns {TypeDecorator<T>} Decorator function * @template T extends Message<T> */ Type.d = function decorateType(typeName) { return function typeDecorator(target) { util.decorateType(target, typeName); }; };
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import _extends from "@babel/runtime/helpers/esm/extends"; import { formatMuiErrorMessage as _formatMuiErrorMessage } from "@material-ui/utils"; const _excluded = ["aria-describedby", "autoComplete", "autoFocus", "className", "color", "components", "componentsProps", "defaultValue", "disabled", "endAdornment", "error", "fullWidth", "id", "inputComponent", "inputProps", "inputRef", "margin", "maxRows", "minRows", "multiline", "name", "onBlur", "onChange", "onClick", "onFocus", "onKeyDown", "onKeyUp", "placeholder", "readOnly", "renderSuffix", "rows", "size", "startAdornment", "type", "value"]; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { refType, elementTypeAcceptingRef } from '@material-ui/utils'; import { unstable_composeClasses as composeClasses, isHostComponent } from '@material-ui/unstyled'; import formControlState from '../FormControl/formControlState'; import FormControlContext from '../FormControl/FormControlContext'; import useFormControl from '../FormControl/useFormControl'; import styled from '../styles/styled'; import useThemeProps from '../styles/useThemeProps'; import useTheme from '../styles/useTheme'; import capitalize from '../utils/capitalize'; import useForkRef from '../utils/useForkRef'; import useEnhancedEffect from '../utils/useEnhancedEffect'; import TextareaAutosize from '../TextareaAutosize'; import GlobalStyles from '../GlobalStyles'; import { isFilled } from './utils'; import inputBaseClasses, { getInputBaseUtilityClass } from './inputBaseClasses'; import { jsx as _jsx } from "react/jsx-runtime"; import { jsxs as _jsxs } from "react/jsx-runtime"; export const rootOverridesResolver = (props, styles) => { const { styleProps } = props; return [styles.root, styleProps.formControl && styles.formControl, styleProps.startAdornment && styles.adornedStart, styleProps.endAdornment && styles.adornedEnd, styleProps.error && styles.error, styleProps.size === 'small' && styles.sizeSmall, styleProps.multiline && styles.multiline, styleProps.color && styles[`color${capitalize(styleProps.color)}`], styleProps.fullWidth && styles.fullWidth, styleProps.hiddenLabel && styles.hiddenLabel]; }; export const inputOverridesResolver = (props, styles) => { const { styleProps } = props; return [styles.input, styleProps.size === 'small' && styles.inputSizeSmall, styleProps.multiline && styles.inputMultiline, styleProps.type === 'search' && styles.inputTypeSearch, styleProps.startAdornment && styles.inputAdornedStart, styleProps.endAdornment && styles.inputAdornedEnd, styleProps.hiddenLabel && styles.inputHiddenLabel]; }; const useUtilityClasses = styleProps => { const { classes, color, disabled, error, endAdornment, focused, formControl, fullWidth, hiddenLabel, multiline, size, startAdornment, type } = styleProps; const slots = { root: ['root', `color${capitalize(color)}`, disabled && 'disabled', error && 'error', fullWidth && 'fullWidth', focused && 'focused', formControl && 'formControl', size === 'small' && 'sizeSmall', multiline && 'multiline', startAdornment && 'adornedStart', endAdornment && 'adornedEnd', hiddenLabel && 'hiddenLabel'], input: ['input', disabled && 'disabled', type === 'search' && 'inputTypeSearch', multiline && 'inputMultiline', size === 'small' && 'inputSizeSmall', hiddenLabel && 'inputHiddenLabel', startAdornment && 'inputAdornedStart', endAdornment && 'inputAdornedEnd'] }; return composeClasses(slots, getInputBaseUtilityClass, classes); }; export const InputBaseRoot = styled('div', { name: 'MuiInputBase', slot: 'Root', overridesResolver: rootOverridesResolver })(({ theme, styleProps }) => _extends({}, theme.typography.body1, { color: theme.palette.text.primary, lineHeight: '1.4375em', // 23px boxSizing: 'border-box', // Prevent padding issue with fullWidth. position: 'relative', cursor: 'text', display: 'inline-flex', alignItems: 'center', [`&.${inputBaseClasses.disabled}`]: { color: theme.palette.text.disabled, cursor: 'default' } }, styleProps.multiline && _extends({ padding: '4px 0 5px' }, styleProps.size === 'small' && { paddingTop: 1 }), styleProps.fullWidth && { width: '100%' })); export const InputBaseComponent = styled('input', { name: 'MuiInputBase', slot: 'Input', overridesResolver: inputOverridesResolver })(({ theme, styleProps }) => { const light = theme.palette.mode === 'light'; const placeholder = { color: 'currentColor', opacity: light ? 0.42 : 0.5, transition: theme.transitions.create('opacity', { duration: theme.transitions.duration.shorter }) }; const placeholderHidden = { opacity: '0 !important' }; const placeholderVisible = { opacity: light ? 0.42 : 0.5 }; return _extends({ font: 'inherit', letterSpacing: 'inherit', color: 'currentColor', padding: '4px 0 5px', border: 0, boxSizing: 'content-box', background: 'none', height: '1.4375em', // Reset 23pxthe native input line-height margin: 0, // Reset for Safari WebkitTapHighlightColor: 'transparent', display: 'block', // Make the flex item shrink with Firefox minWidth: 0, width: '100%', // Fix IE11 width issue animationName: 'mui-auto-fill-cancel', animationDuration: '10ms', '&::-webkit-input-placeholder': placeholder, '&::-moz-placeholder': placeholder, // Firefox 19+ '&:-ms-input-placeholder': placeholder, // IE11 '&::-ms-input-placeholder': placeholder, // Edge '&:focus': { outline: 0 }, // Reset Firefox invalid required input style '&:invalid': { boxShadow: 'none' }, '&::-webkit-search-decoration': { // Remove the padding when type=search. WebkitAppearance: 'none' }, // Show and hide the placeholder logic [`label[data-shrink=false] + .${inputBaseClasses.formControl} &`]: { '&::-webkit-input-placeholder': placeholderHidden, '&::-moz-placeholder': placeholderHidden, // Firefox 19+ '&:-ms-input-placeholder': placeholderHidden, // IE11 '&::-ms-input-placeholder': placeholderHidden, // Edge '&:focus::-webkit-input-placeholder': placeholderVisible, '&:focus::-moz-placeholder': placeholderVisible, // Firefox 19+ '&:focus:-ms-input-placeholder': placeholderVisible, // IE11 '&:focus::-ms-input-placeholder': placeholderVisible // Edge }, [`&.${inputBaseClasses.disabled}`]: { opacity: 1, // Reset iOS opacity WebkitTextFillColor: theme.palette.text.disabled // Fix opacity Safari bug }, '&:-webkit-autofill': { animationDuration: '5000s', animationName: 'mui-auto-fill' } }, styleProps.size === 'small' && { paddingTop: 1 }, styleProps.multiline && { height: 'auto', resize: 'none', padding: 0, paddingTop: 0 }, styleProps.type === 'search' && { // Improve type search style. MozAppearance: 'textfield', WebkitAppearance: 'textfield' }); }); /** * `InputBase` contains as few styles as possible. * It aims to be a simple building block for creating an input. * It contains a load of style reset and some state logic. */ const InputBase = /*#__PURE__*/React.forwardRef(function InputBase(inProps, ref) { const props = useThemeProps({ props: inProps, name: 'MuiInputBase' }); const { 'aria-describedby': ariaDescribedby, autoComplete, autoFocus, className, components = {}, componentsProps = {}, defaultValue, disabled, endAdornment, fullWidth = false, id, inputComponent = 'input', inputProps: inputPropsProp = {}, inputRef: inputRefProp, maxRows, minRows, multiline = false, name, onBlur, onChange, onClick, onFocus, onKeyDown, onKeyUp, placeholder, readOnly, renderSuffix, rows, startAdornment, type = 'text', value: valueProp } = props, other = _objectWithoutPropertiesLoose(props, _excluded); const theme = useTheme(); const value = inputPropsProp.value != null ? inputPropsProp.value : valueProp; const { current: isControlled } = React.useRef(value != null); const inputRef = React.useRef(); const handleInputRefWarning = React.useCallback(instance => { if (process.env.NODE_ENV !== 'production') { if (instance && instance.nodeName !== 'INPUT' && !instance.focus) { console.error(['Material-UI: You have provided a `inputComponent` to the input component', 'that does not correctly handle the `ref` prop.', 'Make sure the `ref` prop is called with a HTMLInputElement.'].join('\n')); } } }, []); const handleInputPropsRefProp = useForkRef(inputPropsProp.ref, handleInputRefWarning); const handleInputRefProp = useForkRef(inputRefProp, handleInputPropsRefProp); const handleInputRef = useForkRef(inputRef, handleInputRefProp); const [focused, setFocused] = React.useState(false); const muiFormControl = useFormControl(); if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line react-hooks/rules-of-hooks React.useEffect(() => { if (muiFormControl) { return muiFormControl.registerEffect(); } return undefined; }, [muiFormControl]); } const fcs = formControlState({ props, muiFormControl, states: ['color', 'disabled', 'error', 'hiddenLabel', 'size', 'required', 'filled'] }); fcs.focused = muiFormControl ? muiFormControl.focused : focused; // The blur won't fire when the disabled state is set on a focused input. // We need to book keep the focused state manually. React.useEffect(() => { if (!muiFormControl && disabled && focused) { setFocused(false); if (onBlur) { onBlur(); } } }, [muiFormControl, disabled, focused, onBlur]); const onFilled = muiFormControl && muiFormControl.onFilled; const onEmpty = muiFormControl && muiFormControl.onEmpty; const checkDirty = React.useCallback(obj => { if (isFilled(obj)) { if (onFilled) { onFilled(); } } else if (onEmpty) { onEmpty(); } }, [onFilled, onEmpty]); useEnhancedEffect(() => { if (isControlled) { checkDirty({ value }); } }, [value, checkDirty, isControlled]); const handleFocus = event => { // Fix a bug with IE11 where the focus/blur events are triggered // while the component is disabled. if (fcs.disabled) { event.stopPropagation(); return; } if (onFocus) { onFocus(event); } if (inputPropsProp.onFocus) { inputPropsProp.onFocus(event); } if (muiFormControl && muiFormControl.onFocus) { muiFormControl.onFocus(event); } else { setFocused(true); } }; const handleBlur = event => { if (onBlur) { onBlur(event); } if (inputPropsProp.onBlur) { inputPropsProp.onBlur(event); } if (muiFormControl && muiFormControl.onBlur) { muiFormControl.onBlur(event); } else { setFocused(false); } }; const handleChange = (event, ...args) => { if (!isControlled) { const element = event.target || inputRef.current; if (element == null) { throw new Error(process.env.NODE_ENV !== "production" ? `Material-UI: Expected valid input target. Did you use a custom \`inputComponent\` and forget to forward refs? See https://material-ui.com/r/input-component-ref-interface for more info.` : _formatMuiErrorMessage(1)); } checkDirty({ value: element.value }); } if (inputPropsProp.onChange) { inputPropsProp.onChange(event, ...args); } // Perform in the willUpdate if (onChange) { onChange(event, ...args); } }; // Check the input state on mount, in case it was filled by the user // or auto filled by the browser before the hydration (for SSR). React.useEffect(() => { checkDirty(inputRef.current); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const handleClick = event => { if (inputRef.current && event.currentTarget === event.target) { inputRef.current.focus(); } if (onClick) { onClick(event); } }; let InputComponent = inputComponent; let inputProps = inputPropsProp; if (multiline && InputComponent === 'input') { if (rows) { if (process.env.NODE_ENV !== 'production') { if (minRows || maxRows) { console.warn('Material-UI: You can not use the `minRows` or `maxRows` props when the input `rows` prop is set.'); } } inputProps = _extends({ type: undefined }, inputProps); InputComponent = 'textarea'; } else { inputProps = _extends({ type: undefined, maxRows, minRows }, inputProps); InputComponent = TextareaAutosize; } } const handleAutoFill = event => { // Provide a fake value as Chrome might not let you access it for security reasons. checkDirty(event.animationName === 'mui-auto-fill-cancel' ? inputRef.current : { value: 'x' }); }; React.useEffect(() => { if (muiFormControl) { muiFormControl.setAdornedStart(Boolean(startAdornment)); } }, [muiFormControl, startAdornment]); const styleProps = _extends({}, props, { color: fcs.color || 'primary', disabled: fcs.disabled, endAdornment, error: fcs.error, focused: fcs.focused, formControl: muiFormControl, fullWidth, hiddenLabel: fcs.hiddenLabel, multiline, size: fcs.size, startAdornment, type }); const classes = useUtilityClasses(styleProps); const Root = components.Root || InputBaseRoot; const rootProps = componentsProps.root || {}; const Input = components.Input || InputBaseComponent; inputProps = _extends({}, inputProps, componentsProps.input); return /*#__PURE__*/_jsxs(React.Fragment, { children: [/*#__PURE__*/_jsx(GlobalStyles, { styles: { '@keyframes mui-auto-fill': {}, '@keyframes mui-auto-fill-cancel': {} } }), /*#__PURE__*/_jsxs(Root, _extends({}, rootProps, !isHostComponent(Root) && { styleProps: _extends({}, styleProps, rootProps.styleProps), theme }, { ref: ref, onClick: handleClick }, other, { className: clsx(classes.root, rootProps.className, className), children: [startAdornment, /*#__PURE__*/_jsx(FormControlContext.Provider, { value: null, children: /*#__PURE__*/_jsx(Input, _extends({ styleProps: styleProps, "aria-invalid": fcs.error, "aria-describedby": ariaDescribedby, autoComplete: autoComplete, autoFocus: autoFocus, defaultValue: defaultValue, disabled: fcs.disabled, id: id, onAnimationStart: handleAutoFill, name: name, placeholder: placeholder, readOnly: readOnly, required: fcs.required, rows: rows, value: value, onKeyDown: onKeyDown, onKeyUp: onKeyUp, type: type }, inputProps, !isHostComponent(Input) && { as: InputComponent, styleProps: _extends({}, styleProps, inputProps.styleProps), theme }, { ref: handleInputRef, className: clsx(classes.input, inputProps.className, inputPropsProp.className), onBlur: handleBlur, onChange: handleChange, onFocus: handleFocus })) }), endAdornment, renderSuffix ? renderSuffix(_extends({}, fcs, { startAdornment })) : null] }))] }); }); process.env.NODE_ENV !== "production" ? InputBase.propTypes /* remove-proptypes */ = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * @ignore */ 'aria-describedby': PropTypes.string, /** * This prop helps users to fill forms faster, especially on mobile devices. * The name can be confusing, as it's more like an autofill. * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill). */ autoComplete: PropTypes.string, /** * If `true`, the `input` element is focused during the first mount. */ autoFocus: PropTypes.bool, /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * The color of the component. It supports those theme colors that make sense for this component. * The prop defaults to the value (`'primary'`) inherited from the parent FormControl component. */ color: PropTypes /* @typescript-to-proptypes-ignore */ .oneOfType([PropTypes.oneOf(['primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]), /** * The components used for each slot inside the InputBase. * Either a string to use a HTML element or a component. * @default {} */ components: PropTypes.shape({ Input: PropTypes.elementType, Root: PropTypes.elementType }), /** * The props used for each slot inside the Input. * @default {} */ componentsProps: PropTypes.object, /** * The default value. Use when the component is not controlled. */ defaultValue: PropTypes.any, /** * If `true`, the component is disabled. * The prop defaults to the value (`false`) inherited from the parent FormControl component. */ disabled: PropTypes.bool, /** * End `InputAdornment` for this component. */ endAdornment: PropTypes.node, /** * If `true`, the `input` will indicate an error. * The prop defaults to the value (`false`) inherited from the parent FormControl component. */ error: PropTypes.bool, /** * If `true`, the `input` will take up the full width of its container. * @default false */ fullWidth: PropTypes.bool, /** * The id of the `input` element. */ id: PropTypes.string, /** * The component used for the `input` element. * Either a string to use a HTML element or a component. * @default 'input' */ inputComponent: elementTypeAcceptingRef, /** * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element. * @default {} */ inputProps: PropTypes.object, /** * Pass a ref to the `input` element. */ inputRef: refType, /** * If `dense`, will adjust vertical spacing. This is normally obtained via context from * FormControl. * The prop defaults to the value (`'none'`) inherited from the parent FormControl component. */ margin: PropTypes.oneOf(['dense', 'none']), /** * Maximum number of rows to display when multiline option is set to true. */ maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * Minimum number of rows to display when multiline option is set to true. */ minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * If `true`, a `textarea` element is rendered. * @default false */ multiline: PropTypes.bool, /** * Name attribute of the `input` element. */ name: PropTypes.string, /** * Callback fired when the `input` is blurred. * * Notice that the first argument (event) might be undefined. */ onBlur: PropTypes.func, /** * Callback fired when the value is changed. * * @param {React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>} event The event source of the callback. * You can pull out the new value by accessing `event.target.value` (string). */ onChange: PropTypes.func, /** * @ignore */ onClick: PropTypes.func, /** * @ignore */ onFocus: PropTypes.func, /** * @ignore */ onKeyDown: PropTypes.func, /** * @ignore */ onKeyUp: PropTypes.func, /** * The short hint displayed in the `input` before the user enters a value. */ placeholder: PropTypes.string, /** * It prevents the user from changing the value of the field * (not from interacting with the field). */ readOnly: PropTypes.bool, /** * @ignore */ renderSuffix: PropTypes.func, /** * If `true`, the `input` element is required. * The prop defaults to the value (`false`) inherited from the parent FormControl component. */ required: PropTypes.bool, /** * Number of rows to display when multiline option is set to true. */ rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** * The size of the component. */ size: PropTypes /* @typescript-to-proptypes-ignore */ .oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.string]), /** * Start `InputAdornment` for this component. */ startAdornment: PropTypes.node, /** * The system prop that allows defining system overrides as well as additional CSS styles. */ sx: PropTypes.object, /** * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types). * @default 'text' */ type: PropTypes.string, /** * The value of the `input` element, required for a controlled component. */ value: PropTypes.any } : void 0; export default InputBase;
var crypto = require('crypto'); var keystone = require('../'); var scmp = require('scmp'); var utils = require('keystone-utils'); /** * Creates a hash of str with Keystone's cookie secret. * Only hashes the first half of the string. */ function hash(str) { // force type str = '' + str; // get the first half str = str.substr(0, Math.round(str.length / 2)); // hash using sha256 return crypto .createHmac('sha256', keystone.get('cookie secret')) .update(str) .digest('base64') .replace(/\=+$/, ''); } /** * Signs in a user using user obejct * * @param {Object} user - user object * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} onSuccess callback, is passed the User instance */ function signinWithUser(user, req, res, onSuccess) { if (arguments.length < 4) { throw new Error('keystone.session.signinWithUser requires user, req and res objects, and an onSuccess callback.'); } if ('object' !== typeof user) { throw new Error('keystone.session.signinWithUser requires user to be an object.'); } if ('object' !== typeof req) { throw new Error('keystone.session.signinWithUser requires req to be an object.'); } if ('object' !== typeof res) { throw new Error('keystone.session.signinWithUser requires res to be an object.'); } if ('function' !== typeof onSuccess) { throw new Error('keystone.session.signinWithUser requires onSuccess to be a function.'); } req.session.regenerate(function() { req.user = user; req.session.userId = user.id; // if the user has a password set, store a persistence cookie to resume sessions if (keystone.get('cookie signin') && user.password) { var userToken = user.id + ':' + hash(user.password); res.cookie('keystone.uid', userToken, { signed: true, httpOnly: true }); } onSuccess(user); }); } exports.signinWithUser = signinWithUser; var postHookedSigninWithUser = function(user, req, res, onSuccess, onFail) { keystone.callHook(user, 'post:signin', function(err){ if(err){ return onFail(err); } exports.signinWithUser(user, req, res, onSuccess, onFail); }); }; /** * Signs in a user user matching the lookup filters * * @param {Object} lookup - must contain email and password * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} onSuccess callback, is passed the User instance * @param {function()} onFail callback */ var doSignin = function(lookup, req, res, onSuccess, onFail) { if (!lookup) { return onFail(new Error('session.signin requires a User ID or Object as the first argument')); } var User = keystone.list(keystone.get('user model')); if ('string' === typeof lookup.email && 'string' === typeof lookup.password) { // create regex for email lookup with special characters escaped var emailRegExp = new RegExp('^' + utils.escapeRegExp(lookup.email) + '$', 'i'); // match email address and password User.model.findOne({ email: emailRegExp }).exec(function(err, user) { if (user) { user._.password.compare(lookup.password, function(err, isMatch) { if (!err && isMatch) { postHookedSigninWithUser(user, req, res, onSuccess, onFail); } else { onFail(err); } }); } else { onFail(err); } }); } else { lookup = '' + lookup; // match the userId, with optional password check var userId = (lookup.indexOf(':') > 0) ? lookup.substr(0, lookup.indexOf(':')) : lookup, passwordCheck = (lookup.indexOf(':') > 0) ? lookup.substr(lookup.indexOf(':') + 1) : false; User.model.findById(userId).exec(function(err, user) { if (user && (!passwordCheck || scmp(passwordCheck, hash(user.password)))) { postHookedSigninWithUser(user, req, res, onSuccess, onFail); } else { onFail(err); } }); } }; exports.signin = function(lookup, req, res, onSuccess, onFail) { keystone.callHook({}, 'pre:signin', function(err){ if(err){ return onFail(err); } doSignin(lookup, req, res, onSuccess, onFail); }); }; /** * Signs the current user out and resets the session * * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} next callback */ exports.signout = function(req, res, next) { keystone.callHook(req.user, 'pre:signout', function(err) { if (err) { console.log("An error occurred in signout 'pre' middleware", err); } res.clearCookie('keystone.uid'); req.user = null; req.session.regenerate(function(err) { if (err) { return next(err); } keystone.callHook({}, 'post:signout', function(err) { if (err) { console.log("An error occurred in signout 'post' middleware", err); } next(); }); }); }); }; /** * Middleware to ensure session persistence across server restarts * * Looks for a userId cookie, and if present, and there is no user signed in, * automatically signs the user in. * * @param {Object} req - express request object * @param {Object} res - express response object * @param {function()} next callback */ exports.persist = function(req, res, next) { var User = keystone.list(keystone.get('user model')); if (!req.session) { console.error('\nKeystoneJS Runtime Error:\n\napp must have session middleware installed. Try adding "express-session" to your express instance.\n'); process.exit(1); } if (keystone.get('cookie signin') && !req.session.userId && req.signedCookies['keystone.uid'] && req.signedCookies['keystone.uid'].indexOf(':') > 0) { exports.signin(req.signedCookies['keystone.uid'], req, res, function() { next(); }, function(err) { next(err); }); } else if (req.session.userId) { User.model.findById(req.session.userId).exec(function(err, user) { if (err) return next(err); req.user = user; next(); }); } else { next(); } }; /** * Middleware to enable access to Keystone * * Bounces the user to the signin screen if they are not signed in or do not have permission. * * req.user is the user returned by the database. It's type is Keystone.List. * * req.user.canAccessKeystone denotes whether the user has access to the admin panel. * If you're having issues double check your user model. Setting `canAccessKeystone` to true in * the database will not be reflected here if it is virtual. * See http://mongoosejs.com/docs/guide.html#virtuals * * @param {Object} req - express request object * @param req.user - The user object Keystone.List * @param req.user.canAccessKeystone {Boolean|Function} * @param {Object} res - express response object * @param {function()} next callback */ exports.keystoneAuth = function(req, res, next) { if (!req.user || !req.user.canAccessKeystone) { var from = new RegExp('^\/keystone\/?$', 'i').test(req.url) ? '' : '?from=' + req.url; return res.redirect(keystone.get('signin url') + from); } next(); };
/** * @class Ext.panel.Panel * @extends Ext.panel.AbstractPanel * <p>Panel is a container that has specific functionality and structural components that make * it the perfect building block for application-oriented user interfaces.</p> * <p>Panels are, by virtue of their inheritance from {@link Ext.container.Container}, capable * of being configured with a {@link Ext.container.Container#layout layout}, and containing child Components.</p> * <p>When either specifying child {@link Ext.Component#items items} of a Panel, or dynamically {@link Ext.container.Container#add adding} Components * to a Panel, remember to consider how you wish the Panel to arrange those child elements, and whether * those child elements need to be sized using one of Ext&#39;s built-in <code><b>{@link Ext.container.Container#layout layout}</b></code> schemes. By * default, Panels use the {@link Ext.layout.container.Auto Auto} scheme. This simply renders * child components, appending them one after the other inside the Container, and <b>does not apply any sizing</b> * at all.</p> * {@img Ext.panel.Panel/panel.png Panel components} * <p>A Panel may also contain {@link #bbar bottom} and {@link #tbar top} toolbars, along with separate * {@link #header}, {@link #footer} and {@link #body} sections (see {@link #frame} for additional * information).</p> * <p>Panel also provides built-in {@link #collapsible collapsible, expandable} and {@link #closable} behavior. * Panels can be easily dropped into any {@link Ext.container.Container Container} or layout, and the * layout and rendering pipeline is {@link Ext.container.Container#add completely managed by the framework}.</p> * <p><b>Note:</b> By default, the <code>{@link #closable close}</code> header tool <i>destroys</i> the Panel resulting in removal of the Panel * and the destruction of any descendant Components. This makes the Panel object, and all its descendants <b>unusable</b>. To enable the close * tool to simply <i>hide</i> a Panel for later re-use, configure the Panel with <b><code>{@link #closeAction closeAction: 'hide'}</code></b>.</p> * <p>Usually, Panels are used as constituents within an application, in which case, they would be used as child items of Containers, * and would themselves use Ext.Components as child {@link #items}. However to illustrate simply rendering a Panel into the document, * here&#39;s how to do it:<pre><code> Ext.create('Ext.panel.Panel', { title: 'Hello', width: 200, html: '&lt;p&gt;World!&lt;/p&gt;', renderTo: document.body }); </code></pre></p> * <p>A more realistic scenario is a Panel created to house input fields which will not be rendered, but used as a constituent part of a Container:<pre><code> var filterPanel = Ext.create('Ext.panel.Panel', { bodyPadding: 5, // Don&#39;t want content to crunch against the borders title: 'Filters', items: [{ xtype: 'datefield', fieldLabel: 'Start date' }, { xtype: 'datefield', fieldLabel: 'End date' }] }); </code></pre></p> * <p>Note that the Panel above is not configured to render into the document, nor is it configured with a size or position. In a real world scenario, * the Container into which the Panel is added will use a {@link #layout} to render, size and position its child Components.</p> * <p>Panels will often use specific {@link #layout}s to provide an application with shape and structure by containing and arranging child * Components: <pre><code> var resultsPanel = Ext.create('Ext.panel.Panel', { title: 'Results', width: 600, height: 400, renderTo: document.body, layout: { type: 'vbox', // Arrange child items vertically align: 'stretch', // Each takes up full width padding: 5 }, items: [{ // Results grid specified as a config object with an xtype of 'grid' xtype: 'grid', columns: [{header: 'Column One'}], // One header just for show. There&#39;s no data, store: Ext.create('Ext.data.ArrayStore', {}), // A dummy empty data store flex: 1 // Use 1/3 of Container&#39;s height (hint to Box layout) }, { xtype: 'splitter' // A splitter between the two child items }, { // Details Panel specified as a config object (no xtype defaults to 'panel'). title: 'Details', bodyPadding: 5, items: [{ fieldLabel: 'Data item', xtype: 'textfield' }], // An array of form fields flex: 2 // Use 2/3 of Container&#39;s height (hint to Box layout) }] }); </code></pre> * The example illustrates one possible method of displaying search results. The Panel contains a grid with the resulting data arranged * in rows. Each selected row may be displayed in detail in the Panel below. The {@link Ext.layout.container.VBox vbox} layout is used * to arrange the two vertically. It is configured to stretch child items horizontally to full width. Child items may either be configured * with a numeric height, or with a <code>flex</code> value to distribute available space proportionately.</p> * <p>This Panel itself may be a child item of, for exaple, a {@link Ext.tab.Panel} which will size its child items to fit within its * content area.</p> * <p>Using these techniques, as long as the <b>layout</b> is chosen and configured correctly, an application may have any level of * nested containment, all dynamically sized according to configuration, the user&#39;s preference and available browser size.</p> * @constructor * @param {Object} config The config object * @xtype panel */ Ext.define('Ext.panel.Panel', { extend: 'Ext.panel.AbstractPanel', requires: [ 'Ext.panel.Header', 'Ext.fx.Anim', 'Ext.util.KeyMap', 'Ext.panel.DD', 'Ext.XTemplate', 'Ext.layout.component.Dock' ], alias: 'widget.panel', alternateClassName: 'Ext.Panel', /** * @cfg {String} collapsedCls * A CSS class to add to the panel&#39;s element after it has been collapsed (defaults to * <code>'collapsed'</code>). */ collapsedCls: 'collapsed', /** * @cfg {Boolean} animCollapse * <code>true</code> to animate the transition when the panel is collapsed, <code>false</code> to skip the * animation (defaults to <code>true</code> if the {@link Ext.fx.Anim} class is available, otherwise <code>false</code>). * May also be specified as the animation duration in milliseconds. */ animCollapse: Ext.enableFx, /** * @cfg {Number} minButtonWidth * Minimum width of all footer toolbar buttons in pixels (defaults to <tt>75</tt>). If set, this will * be used as the default value for the <tt>{@link Ext.button.Button#minWidth}</tt> config of * each Button added to the <b>footer toolbar</b> via the {@link #fbar} or {@link #buttons} configurations. * It will be ignored for buttons that have a minWidth configured some other way, e.g. in their own config * object or via the {@link Ext.container.Container#config-defaults defaults} of their parent container. */ minButtonWidth: 75, /** * @cfg {Boolean} collapsed * <code>true</code> to render the panel collapsed, <code>false</code> to render it expanded (defaults to * <code>false</code>). */ collapsed: false, /** * @cfg {Boolean} collapseFirst * <code>true</code> to make sure the collapse/expand toggle button always renders first (to the left of) * any other tools in the panel&#39;s title bar, <code>false</code> to render it last (defaults to <code>true</code>). */ collapseFirst: true, /** * @cfg {Boolean} hideCollapseTool * <code>true</code> to hide the expand/collapse toggle button when <code>{@link #collapsible} == true</code>, * <code>false</code> to display it (defaults to <code>false</code>). */ hideCollapseTool: false, /** * @cfg {Boolean} titleCollapse * <code>true</code> to allow expanding and collapsing the panel (when <code>{@link #collapsible} = true</code>) * by clicking anywhere in the header bar, <code>false</code>) to allow it only by clicking to tool button * (defaults to <code>false</code>)). */ titleCollapse: false, /** * @cfg {String} collapseMode * <p><b>Important: this config is only effective for {@link #collapsible} Panels which are direct child items of a {@link Ext.layout.container.Border border layout}.</b></p> * <p>When <i>not</i> a direct child item of a {@link Ext.layout.container.Border border layout}, then the Panel&#39;s header remains visible, and the body is collapsed to zero dimensions. * If the Panel has no header, then a new header (orientated correctly depending on the {@link #collapseDirection}) will be inserted to show a the title and a re-expand tool.</p> * <p>When a child item of a {@link Ext.layout.container.Border border layout}, this config has two options: * <div class="mdetail-params"><ul> * <li><b><code>undefined/omitted</code></b><div class="sub-desc">When collapsed, a placeholder {@link Ext.panel.Header Header} is injected into the layout to represent the Panel * and to provide a UI with a Tool to allow the user to re-expand the Panel.</div></li> * <li><b><code>header</code></b> : <div class="sub-desc">The Panel collapses to leave its header visible as when not inside a {@link Ext.layout.container.Border border layout}.</div></li> * </ul></div></p> */ /** * @cfg {Mixed} placeholder * <p><b>Important: This config is only effective for {@link #collapsible} Panels which are direct child items of a {@link Ext.layout.container.Border border layout} * when not using the <code>'header'</code> {@link #collapseMode}.</b></p> * <p><b>Optional.</b> A Component (or config object for a Component) to show in place of this Panel when this Panel is collapsed by a * {@link Ext.layout.container.Border border layout}. Defaults to a generated {@link Ext.panel.Header Header} * containing a {@link Ext.panel.Tool Tool} to re-expand the Panel.</p> */ /** * @cfg {Boolean} floatable * <p><b>Important: This config is only effective for {@link #collapsible} Panels which are direct child items of a {@link Ext.layout.container.Border border layout}.</b></p> * <tt>true</tt> to allow clicking a collapsed Panel&#39;s {@link #placeholder} to display the Panel floated * above the layout, <tt>false</tt> to force the user to fully expand a collapsed region by * clicking the expand button to see it again (defaults to <tt>true</tt>). */ floatable: true, /** * @cfg {Mixed} overlapHeader * True to overlap the header in a panel over the framing of the panel itself. This is needed when frame:true (and is done automatically for you). Otherwise it is undefined. * If you manually add rounded corners to a panel header which does not have frame:true, this will need to be set to true. */ /** * @cfg {Boolean} collapsible * <p>True to make the panel collapsible and have an expand/collapse toggle Tool added into * the header tool button area. False to keep the panel sized either statically, or by an owning layout manager, with no toggle Tool (defaults to false).</p> * See {@link #collapseMode} and {@link #collapseDirection} */ collapsible: false, /** * @cfg {Boolean} collapseDirection * <p>The direction to collapse the Panel when the toggle button is clicked.</p> * <p>Defaults to the {@link #headerPosition}</p> * <p><b>Important: This config is <u>ignored</u> for {@link #collapsible} Panels which are direct child items of a {@link Ext.layout.container.Border border layout}.</b></p> * <p>Specify as <code>'top'</code>, <code>'bottom'</code>, <code>'left'</code> or <code>'right'</code>.</p> */ /** * @cfg {Boolean} closable * <p>True to display the 'close' tool button and allow the user to close the window, false to * hide the button and disallow closing the window (defaults to <code>false</code>).</p> * <p>By default, when close is requested by clicking the close button in the header, the {@link #close} * method will be called. This will <i>{@link Ext.Component#destroy destroy}</i> the Panel and its content * meaning that it may not be reused.</p> * <p>To make closing a Panel <i>hide</i> the Panel so that it may be reused, set * {@link #closeAction} to 'hide'.</p> */ closable: false, /** * @cfg {String} closeAction * <p>The action to take when the close header tool is clicked: * <div class="mdetail-params"><ul> * <li><b><code>'{@link #destroy}'</code></b> : <b>Default</b><div class="sub-desc"> * {@link #destroy remove} the window from the DOM and {@link Ext.Component#destroy destroy} * it and all descendant Components. The window will <b>not</b> be available to be * redisplayed via the {@link #show} method. * </div></li> * <li><b><code>'{@link #hide}'</code></b> : <div class="sub-desc"> * {@link #hide} the window by setting visibility to hidden and applying negative offsets. * The window will be available to be redisplayed via the {@link #show} method. * </div></li> * </ul></div> * <p><b>Note:</b> This behavior has changed! setting *does* affect the {@link #close} method * which will invoke the approriate closeAction. */ closeAction: 'destroy', /** * @cfg {Object/Array} dockedItems * A component or series of components to be added as docked items to this panel. * The docked items can be docked to either the top, right, left or bottom of a panel. * This is typically used for things like toolbars or tab bars: * <pre><code> var panel = new Ext.panel.Panel({ dockedItems: [{ xtype: 'toolbar', dock: 'top', items: [{ text: 'Docked to the top' }] }] });</pre></code> */ /** * @cfg {Boolean} preventHeader Prevent a Header from being created and shown. Defaults to false. */ preventHeader: false, /** * @cfg {String} headerPosition Specify as <code>'top'</code>, <code>'bottom'</code>, <code>'left'</code> or <code>'right'</code>. Defaults to <code>'top'</code>. */ headerPosition: 'top', /** * @cfg {Boolean} frame * True to apply a frame to the panel. */ frame: false, /** * @cfg {Boolean} frameHeader * True to apply a frame to the panel panels header (if 'frame' is true). */ frameHeader: true, /** * @cfg {Array} tools * An array of {@link Ext.panel.Tool} configs/instances to be added to the header tool area. The tools are stored as child * components of the header container. They can be accessed using {@link #down} and {#query}, as well as the other * component methods. The toggle tool is automatically created if {@link #collapsible} is set to true. * <p>Note that, apart from the toggle tool which is provided when a panel is collapsible, these * tools only provide the visual button. Any required functionality must be provided by adding * handlers that implement the necessary behavior.</p> * <p>Example usage:</p> * <pre><code> tools:[{ type:'refresh', qtip: 'Refresh form Data', // hidden:true, handler: function(event, toolEl, panel){ // refresh logic } }, { type:'help', qtip: 'Get Help', handler: function(event, toolEl, panel){ // show help here } }] </code></pre> */ initComponent: function() { var me = this, cls; me.addEvents( /** * @event titlechange * Fires after the Panel title has been set or changed. * @param {Ext.panel.Panel} p the Panel which has been resized. * @param {String} newTitle The new title. * @param {String} oldTitle The previous panel title. */ 'titlechange', /** * @event iconchange * Fires after the Panel iconCls has been set or changed. * @param {Ext.panel.Panel} p the Panel which has been resized. * @param {String} newIconCls The new iconCls. * @param {String} oldIconCls The previous panel iconCls. */ 'iconchange' ); if (me.unstyled) { me.setUI('plain'); } if (me.frame) { me.setUI('default-framed'); } me.callParent(); me.collapseDirection = me.collapseDirection || me.headerPosition || Ext.Component.DIRECTION_TOP; // Backwards compatibility me.bridgeToolbars(); }, setBorder: function(border) { // var me = this, // method = (border === false || border === 0) ? 'addClsWithUI' : 'removeClsWithUI'; // // me.callParent(arguments); // // if (me.collapsed) { // me[method](me.collapsedCls + '-noborder'); // } // // if (me.header) { // me.header.setBorder(border); // if (me.collapsed) { // me.header[method](me.collapsedCls + '-noborder'); // } // } this.callParent(arguments); }, beforeDestroy: function() { Ext.destroy( this.ghostPanel, this.dd ); this.callParent(); }, initAria: function() { this.callParent(); this.initHeaderAria(); }, initHeaderAria: function() { var me = this, el = me.el, header = me.header; if (el && header) { el.dom.setAttribute('aria-labelledby', header.titleCmp.id); } }, getHeader: function() { return this.header; }, /** * Set a title for the panel&#39;s header. See {@link Ext.panel.Header#title}. * @param {String} newTitle */ setTitle: function(newTitle) { var me = this, oldTitle = this.title; me.title = newTitle; if (me.header) { me.header.setTitle(newTitle); } else { me.updateHeader(); } if (me.reExpander) { me.reExpander.setTitle(newTitle); } me.fireEvent('titlechange', me, newTitle, oldTitle); }, /** * Set the iconCls for the panel&#39;s header. See {@link Ext.panel.Header#iconCls}. * @param {String} newIconCls */ setIconCls: function(newIconCls) { var me = this, oldIconCls = me.iconCls; me.iconCls = newIconCls; var header = me.header; if (header) { header.setIconCls(newIconCls); } me.fireEvent('iconchange', me, newIconCls, oldIconCls); }, bridgeToolbars: function() { var me = this, fbar, fbarDefaults, minButtonWidth = me.minButtonWidth; function initToolbar (toolbar, pos) { if (Ext.isArray(toolbar)) { toolbar = { xtype: 'toolbar', items: toolbar }; } else if (!toolbar.xtype) { toolbar.xtype = 'toolbar'; } toolbar.dock = pos; if (pos == 'left' || pos == 'right') { toolbar.vertical = true; } return toolbar; } // Backwards compatibility /** * @cfg {Object/Array} tbar Convenience method. Short for 'Top Bar'. tbar: [ { xtype: 'button', text: 'Button 1' } ] is equivalent to dockedItems: [{ xtype: 'toolbar', dock: 'top', items: [ { xtype: 'button', text: 'Button 1' } ] }] * @markdown */ if (me.tbar) { me.addDocked(initToolbar(me.tbar, 'top')); me.tbar = null; } /** * @cfg {Object/Array} bbar Convenience method. Short for 'Bottom Bar'. bbar: [ { xtype: 'button', text: 'Button 1' } ] is equivalent to dockedItems: [{ xtype: 'toolbar', dock: 'bottom', items: [ { xtype: 'button', text: 'Button 1' } ] }] * @markdown */ if (me.bbar) { me.addDocked(initToolbar(me.bbar, 'bottom')); me.bbar = null; } /** * @cfg {Object/Array} buttons Convenience method used for adding buttons docked to the bottom right of the panel. This is a synonym for the {@link #fbar} config. buttons: [ { text: 'Button 1' } ] is equivalent to dockedItems: [{ xtype: 'toolbar', dock: 'bottom', defaults: {minWidth: {@link #minButtonWidth}}, items: [ { xtype: 'component', flex: 1 }, { xtype: 'button', text: 'Button 1' } ] }] The {@link #minButtonWidth} is used as the default {@link Ext.button.Button#minWidth minWidth} for each of the buttons in the buttons toolbar. * @markdown */ if (me.buttons) { me.fbar = me.buttons; me.buttons = null; } /** * @cfg {Object/Array} fbar Convenience method used for adding items to the bottom right of the panel. Short for Footer Bar. fbar: [ { type: 'button', text: 'Button 1' } ] is equivalent to dockedItems: [{ xtype: 'toolbar', dock: 'bottom', defaults: {minWidth: {@link #minButtonWidth}}, items: [ { xtype: 'component', flex: 1 }, { xtype: 'button', text: 'Button 1' } ] }] The {@link #minButtonWidth} is used as the default {@link Ext.button.Button#minWidth minWidth} for each of the buttons in the fbar. * @markdown */ if (me.fbar) { fbar = initToolbar(me.fbar, 'bottom'); fbar.ui = 'footer'; // Apply the minButtonWidth config to buttons in the toolbar if (minButtonWidth) { fbarDefaults = fbar.defaults; fbar.defaults = function(config) { var defaults = fbarDefaults || {}; if ((!config.xtype || config.xtype === 'button' || (config.isComponent && config.isXType('button'))) && !('minWidth' in defaults)) { defaults = Ext.apply({minWidth: minButtonWidth}, defaults); } return defaults; }; } fbar = me.addDocked(fbar)[0]; fbar.insert(0, { flex: 1, xtype: 'component', focusable: false }); me.fbar = null; } /** * @cfg {Object/Array} lbar * * Convenience method. Short for 'Left Bar' (left-docked, vertical toolbar). * * lbar: [ * { xtype: 'button', text: 'Button 1' } * ] * * is equivalent to * * dockedItems: [{ * xtype: 'toolbar', * dock: 'left', * items: [ * { xtype: 'button', text: 'Button 1' } * ] * }] * * @markdown */ if (me.lbar) { me.addDocked(initToolbar(me.lbar, 'left')); me.lbar = null; } /** * @cfg {Object/Array} rbar * * Convenience method. Short for 'Right Bar' (right-docked, vertical toolbar). * * rbar: [ * { xtype: 'button', text: 'Button 1' } * ] * * is equivalent to * * dockedItems: [{ * xtype: 'toolbar', * dock: 'right', * items: [ * { xtype: 'button', text: 'Button 1' } * ] * }] * * @markdown */ if (me.rbar) { me.addDocked(initToolbar(me.rbar, 'right')); me.rbar = null; } }, /** * @private * Tools are a Panel-specific capabilty. * Panel uses initTools. Subclasses may contribute tools by implementing addTools. */ initTools: function() { var me = this; me.tools = me.tools || []; // Add a collapse tool unless configured to not show a collapse tool // or to not even show a header. if (me.collapsible && !(me.hideCollapseTool || me.header === false)) { me.collapseDirection = me.collapseDirection || me.headerPosition || 'top'; me.collapseTool = me.expandTool = me.createComponent({ xtype: 'tool', type: 'collapse-' + me.collapseDirection, expandType: me.getOppositeDirection(me.collapseDirection), handler: me.toggleCollapse, scope: me }); // Prepend collapse tool is configured to do so. if (me.collapseFirst) { me.tools.unshift(me.collapseTool); } } // Add subclass-specific tools. me.addTools(); // Make Panel closable. if (me.closable) { me.addClsWithUI('closable'); me.addTool({ type: 'close', handler: Ext.Function.bind(me.close, this, []) }); } // Append collapse tool if needed. if (me.collapseTool && !me.collapseFirst) { me.tools.push(me.collapseTool); } }, /** * @private * Template method to be implemented in subclasses to add their tools after the collapsible tool. */ addTools: Ext.emptyFn, /** * <p>Closes the Panel. By default, this method, removes it from the DOM, {@link Ext.Component#destroy destroy}s * the Panel object and all its descendant Components. The {@link #beforeclose beforeclose} * event is fired before the close happens and will cancel the close action if it returns false.<p> * <p><b>Note:</b> This method is not affected by the {@link #closeAction} setting which * only affects the action triggered when clicking the {@link #closable 'close' tool in the header}. * To hide the Panel without destroying it, call {@link #hide}.</p> */ close: function() { if (this.fireEvent('beforeclose', this) !== false) { this.doClose(); } }, // private doClose: function() { this.fireEvent('close', this); this[this.closeAction](); }, onRender: function(ct, position) { var me = this, topContainer; // Add class-specific header tools. // Panel adds collapsible and closable. me.initTools(); // Dock the header/title me.updateHeader(); // If initially collapsed, collapsed flag must indicate true current state at this point. // Do collapse after the first time the Panel's structure has been laid out. if (me.collapsed) { me.collapsed = false; topContainer = me.findLayoutController(); if (!me.hidden && topContainer) { topContainer.on({ afterlayout: function() { me.collapse(null, false, true); }, single: true }); } else { me.afterComponentLayout = function() { delete me.afterComponentLayout; Ext.getClass(me).prototype.afterComponentLayout.apply(me, arguments); me.collapse(null, false, true); }; } } // Call to super after adding the header, to prevent an unnecessary re-layout me.callParent(arguments); }, /** * Create, hide, or show the header component as appropriate based on the current config. * @private * @param {Boolean} force True to force the the header to be created */ updateHeader: function(force) { var me = this, header = me.header, title = me.title, tools = me.tools; if (!me.preventHeader && (force || title || (tools && tools.length))) { if (!header) { header = me.header = Ext.create('Ext.panel.Header', { title : title, orientation : (me.headerPosition == 'left' || me.headerPosition == 'right') ? 'vertical' : 'horizontal', dock : me.headerPosition || 'top', textCls : me.headerTextCls, iconCls : me.iconCls, baseCls : me.baseCls + '-header', tools : tools, ui : me.ui, indicateDrag: me.draggable, border : me.border, frame : me.frame && me.frameHeader, ignoreParentFrame : me.frame || me.overlapHeader, ignoreBorderManagement: me.frame || me.ignoreHeaderBorderManagement, listeners : me.collapsible && me.titleCollapse ? { click: me.toggleCollapse, scope: me } : null }); me.addDocked(header, 0); // Reference the Header's tool array. // Header injects named references. me.tools = header.tools; } header.show(); me.initHeaderAria(); } else if (header) { header.hide(); } }, // inherit docs setUI: function(ui) { var me = this; me.callParent(arguments); if (me.header) { me.header.setUI(ui); } }, // private getContentTarget: function() { return this.body; }, getTargetEl: function() { return this.body || this.frameBody || this.el; }, addTool: function(tool) { this.tools.push(tool); var header = this.header; if (header) { header.addTool(tool); } this.updateHeader(); }, getOppositeDirection: function(d) { var c = Ext.Component; switch (d) { case c.DIRECTION_TOP: return c.DIRECTION_BOTTOM; case c.DIRECTION_RIGHT: return c.DIRECTION_LEFT; case c.DIRECTION_BOTTOM: return c.DIRECTION_TOP; case c.DIRECTION_LEFT: return c.DIRECTION_RIGHT; } }, /** * Collapses the panel body so that the body becomes hidden. Docked Components parallel to the * border towards which the collapse takes place will remain visible. Fires the {@link #beforecollapse} event which will * cancel the collapse action if it returns false. * @param {Number} direction. The direction to collapse towards. Must be one of<ul> * <li>Ext.Component.DIRECTION_TOP</li> * <li>Ext.Component.DIRECTION_RIGHT</li> * <li>Ext.Component.DIRECTION_BOTTOM</li> * <li>Ext.Component.DIRECTION_LEFT</li></ul> * @param {Boolean} animate True to animate the transition, else false (defaults to the value of the * {@link #animCollapse} panel config) * @return {Ext.panel.Panel} this */ collapse: function(direction, animate, /* private - passed if called at render time */ internal) { var me = this, c = Ext.Component, height = me.getHeight(), width = me.getWidth(), frameInfo, newSize = 0, dockedItems = me.dockedItems.items, dockedItemCount = dockedItems.length, i = 0, comp, pos, anim = { from: { height: height, width: width }, to: { height: height, width: width }, listeners: { afteranimate: me.afterCollapse, scope: me }, duration: Ext.Number.from(animate, Ext.fx.Anim.prototype.duration) }, reExpander, reExpanderOrientation, reExpanderDock, getDimension, setDimension, collapseDimension; if (!direction) { direction = me.collapseDirection; } // If internal (Called because of initial collapsed state), then no animation, and no events. if (internal) { animate = false; } else if (me.collapsed || me.fireEvent('beforecollapse', me, direction, animate) === false) { return false; } reExpanderDock = direction; me.expandDirection = me.getOppositeDirection(direction); // Track docked items which we hide during collapsed state me.hiddenDocked = []; switch (direction) { case c.DIRECTION_TOP: case c.DIRECTION_BOTTOM: me.expandedSize = me.getHeight(); reExpanderOrientation = 'horizontal'; collapseDimension = 'height'; getDimension = 'getHeight'; setDimension = 'setHeight'; // Collect the height of the visible header. // Hide all docked items except the header. // Hide *ALL* docked items if we're going to end up hiding the whole Panel anyway for (; i < dockedItemCount; i++) { comp = dockedItems[i]; if (comp.isVisible()) { if (comp.isHeader && (!comp.dock || comp.dock == 'top' || comp.dock == 'bottom')) { reExpander = comp; } else { me.hiddenDocked.push(comp); } } } if (direction == Ext.Component.DIRECTION_BOTTOM) { pos = me.getPosition()[1] - Ext.fly(me.el.dom.offsetParent).getRegion().top; anim.from.top = pos; } break; case c.DIRECTION_LEFT: case c.DIRECTION_RIGHT: me.expandedSize = me.getWidth(); reExpanderOrientation = 'vertical'; collapseDimension = 'width'; getDimension = 'getWidth'; setDimension = 'setWidth'; // Collect the height of the visible header. // Hide all docked items except the header. // Hide *ALL* docked items if we're going to end up hiding the whole Panel anyway for (; i < dockedItemCount; i++) { comp = dockedItems[i]; if (comp.isVisible()) { if (comp.isHeader && (comp.dock == 'left' || comp.dock == 'right')) { reExpander = comp; } else { me.hiddenDocked.push(comp); } } } if (direction == Ext.Component.DIRECTION_RIGHT) { pos = me.getPosition()[0] - Ext.fly(me.el.dom.offsetParent).getRegion().left; anim.from.left = pos; } break; default: throw('Panel collapse must be passed a valid Component collapse direction'); } // No scrollbars when we shrink this Panel // And no laying out of any children... we're effectively *hiding* the body me.setAutoScroll(false); me.suspendLayout = true; me.body.setVisibilityMode(Ext.core.Element.DISPLAY); // Disable toggle tool during animated collapse if (animate && me.collapseTool) { me.collapseTool.disable(); } // Add the collapsed class now, so that collapsed CSS rules are applied before measurements are taken. me.addClsWithUI(me.collapsedCls); // if (me.border === false) { // me.addClsWithUI(me.collapsedCls + '-noborder'); // } // We found a header: Measure it to find the collapse-to size. if (reExpander) { //we must add the collapsed cls to the header and then remove to get the proper height reExpander.addClsWithUI(me.collapsedCls); reExpander.addClsWithUI(me.collapsedCls + '-' + reExpander.dock); if (me.border && (!me.frame || (me.frame && Ext.supports.CSS3BorderRadius))) { reExpander.addClsWithUI(me.collapsedCls + '-border-' + reExpander.dock); } frameInfo = reExpander.getFrameInfo(); //get the size newSize = reExpander[getDimension]() + (frameInfo ? frameInfo[direction] : 0); //and remove reExpander.removeClsWithUI(me.collapsedCls); reExpander.removeClsWithUI(me.collapsedCls + '-' + reExpander.dock); if (me.border && (!me.frame || (me.frame && Ext.supports.CSS3BorderRadius))) { reExpander.removeClsWithUI(me.collapsedCls + '-border-' + reExpander.dock); } } // No header: Render and insert a temporary one, and then measure it. else { reExpander = { hideMode: 'offsets', temporary: true, title: me.title, orientation: reExpanderOrientation, dock: reExpanderDock, textCls: me.headerTextCls, iconCls: me.iconCls, baseCls: me.baseCls + '-header', ui: me.ui, frame: me.frame && me.frameHeader, ignoreParentFrame: me.frame || me.overlapHeader, indicateDrag: me.draggable, cls: me.baseCls + '-collapsed-placeholder ' + ' ' + Ext.baseCSSPrefix + 'docked ' + me.baseCls + '-' + me.ui + '-collapsed', renderTo: me.el }; if (!me.hideCollapseTool) { reExpander[(reExpander.orientation == 'horizontal') ? 'tools' : 'items'] = [{ xtype: 'tool', type: 'expand-' + me.expandDirection, handler: me.toggleCollapse, scope: me }]; } // Capture the size of the re-expander. // For vertical headers in IE6 and IE7, this will be sized by a CSS rule in _panel.scss reExpander = me.reExpander = Ext.create('Ext.panel.Header', reExpander); newSize = reExpander[getDimension]() + ((reExpander.frame) ? reExpander.frameSize[direction] : 0); reExpander.hide(); // Insert the new docked item me.insertDocked(0, reExpander); } me.reExpander = reExpander; me.reExpander.addClsWithUI(me.collapsedCls); me.reExpander.addClsWithUI(me.collapsedCls + '-' + reExpander.dock); if (me.border && (!me.frame || (me.frame && Ext.supports.CSS3BorderRadius))) { me.reExpander.addClsWithUI(me.collapsedCls + '-border-' + me.reExpander.dock); } // If collapsing right or down, we'll be also animating the left or top. if (direction == Ext.Component.DIRECTION_RIGHT) { anim.to.left = pos + (width - newSize); } else if (direction == Ext.Component.DIRECTION_BOTTOM) { anim.to.top = pos + (height - newSize); } // Animate to the new size anim.to[collapseDimension] = newSize; // Remove any flex config before we attempt to collapse. me.savedFlex = me.flex; me.savedMinWidth = me.minWidth; me.savedMinHeight = me.minHeight; me.minWidth = 0; me.minHeight = 0; delete me.flex; if (animate) { me.animate(anim); } else { // EXTJSIV-1937 (would like to use setCalculateSize) // save width/height here, expand puts them back me.uncollapsedSize = { width: me.width, height: me.height }; me.setSize(anim.to.width, anim.to.height); if (Ext.isDefined(anim.to.left) || Ext.isDefined(anim.to.top)) { me.setPosition(anim.to.left, anim.to.top); } me.afterCollapse(false, internal); } return me; }, afterCollapse: function(animated, internal) { var me = this, i = 0, l = me.hiddenDocked.length; me.minWidth = me.savedMinWidth; me.minHeight = me.savedMinHeight; me.body.hide(); for (; i < l; i++) { me.hiddenDocked[i].hide(); } if (me.reExpander) { me.reExpander.updateFrame(); me.reExpander.show(); } me.collapsed = true; if (!internal) { me.doComponentLayout(); } if (me.resizer) { me.resizer.disable(); } // If me Panel was configured with a collapse tool in its header, flip it's type if (me.collapseTool) { me.collapseTool.setType('expand-' + me.expandDirection); } if (!internal) { me.fireEvent('collapse', me); } // Re-enable the toggle tool after an animated collapse if (animated && me.collapseTool) { me.collapseTool.enable(); } }, /** * Expands the panel body so that it becomes visible. Fires the {@link #beforeexpand} event which will * cancel the expand action if it returns false. * @param {Boolean} animate True to animate the transition, else false (defaults to the value of the * {@link #animCollapse} panel config) * @return {Ext.panel.Panel} this */ expand: function(animate) { if (!this.collapsed || this.fireEvent('beforeexpand', this, animate) === false) { return false; } // EXTJSIV-1937 (would like to use setCalculateSize) if (this.uncollapsedSize) { Ext.Object.each(this.uncollapsedSize, function (name, value) { if (Ext.isDefined(value)) { this[name] = value; } else { delete this[name]; } }, this); delete this.uncollapsedSize; } var me = this, i = 0, l = me.hiddenDocked.length, direction = me.expandDirection, height = me.getHeight(), width = me.getWidth(), pos, anim, satisfyJSLint; // Disable toggle tool during animated expand if (animate && me.collapseTool) { me.collapseTool.disable(); } // Show any docked items that we hid on collapse // And hide the injected reExpander Header for (; i < l; i++) { me.hiddenDocked[i].hidden = false; me.hiddenDocked[i].el.show(); } if (me.reExpander) { if (me.reExpander.temporary) { me.reExpander.hide(); } else { me.reExpander.removeClsWithUI(me.collapsedCls); me.reExpander.removeClsWithUI(me.collapsedCls + '-' + me.reExpander.dock); if (me.border && (!me.frame || (me.frame && Ext.supports.CSS3BorderRadius))) { me.reExpander.removeClsWithUI(me.collapsedCls + '-border-' + me.reExpander.dock); } me.reExpander.updateFrame(); } } // If me Panel was configured with a collapse tool in its header, flip it's type if (me.collapseTool) { me.collapseTool.setType('collapse-' + me.collapseDirection); } // Unset the flag before the potential call to calculateChildBox to calculate our newly flexed size me.collapsed = false; // Collapsed means body element was hidden me.body.show(); // Remove any collapsed styling before any animation begins me.removeClsWithUI(me.collapsedCls); // if (me.border === false) { // me.removeClsWithUI(me.collapsedCls + '-noborder'); // } anim = { to: { }, from: { height: height, width: width }, listeners: { afteranimate: me.afterExpand, scope: me } }; if ((direction == Ext.Component.DIRECTION_TOP) || (direction == Ext.Component.DIRECTION_BOTTOM)) { // If autoHeight, measure the height now we have shown the body element. if (me.autoHeight) { me.setCalculatedSize(me.width, null); anim.to.height = me.getHeight(); // Must size back down to collapsed for the animation. me.setCalculatedSize(me.width, anim.from.height); } // If we were flexed, then we can't just restore to the saved size. // We must restore to the currently correct, flexed size, so we much ask the Box layout what that is. else if (me.savedFlex) { me.flex = me.savedFlex; anim.to.height = me.ownerCt.layout.calculateChildBox(me).height; delete me.flex; } // Else, restore to saved height else { anim.to.height = me.expandedSize; } // top needs animating upwards if (direction == Ext.Component.DIRECTION_TOP) { pos = me.getPosition()[1] - Ext.fly(me.el.dom.offsetParent).getRegion().top; anim.from.top = pos; anim.to.top = pos - (anim.to.height - height); } } else if ((direction == Ext.Component.DIRECTION_LEFT) || (direction == Ext.Component.DIRECTION_RIGHT)) { // If autoWidth, measure the width now we have shown the body element. if (me.autoWidth) { me.setCalculatedSize(null, me.height); anim.to.width = me.getWidth(); // Must size back down to collapsed for the animation. me.setCalculatedSize(anim.from.width, me.height); } // If we were flexed, then we can't just restore to the saved size. // We must restore to the currently correct, flexed size, so we much ask the Box layout what that is. else if (me.savedFlex) { me.flex = me.savedFlex; anim.to.width = me.ownerCt.layout.calculateChildBox(me).width; delete me.flex; } // Else, restore to saved width else { anim.to.width = me.expandedSize; } // left needs animating leftwards if (direction == Ext.Component.DIRECTION_LEFT) { pos = me.getPosition()[0] - Ext.fly(me.el.dom.offsetParent).getRegion().left; anim.from.left = pos; anim.to.left = pos - (anim.to.width - width); } } if (animate) { me.animate(anim); } else { me.setSize(anim.to.width, anim.to.height); if (anim.to.x) { me.setLeft(anim.to.x); } if (anim.to.y) { me.setTop(anim.to.y); } me.afterExpand(false); } return me; }, afterExpand: function(animated) { var me = this; me.setAutoScroll(me.initialConfig.autoScroll); // Restored to a calculated flex. Delete the set width and height properties so that flex works from now on. if (me.savedFlex) { me.flex = me.savedFlex; delete me.savedFlex; delete me.width; delete me.height; } // Reinstate layout out after Panel has re-expanded delete me.suspendLayout; if (animated && me.ownerCt) { me.ownerCt.doLayout(); } if (me.resizer) { me.resizer.enable(); } me.fireEvent('expand', me); // Re-enable the toggle tool after an animated expand if (animated && me.collapseTool) { me.collapseTool.enable(); } }, /** * Shortcut for performing an {@link #expand} or {@link #collapse} based on the current state of the panel. * @return {Ext.panel.Panel} this */ toggleCollapse: function() { if (this.collapsed) { this.expand(this.animCollapse); } else { this.collapse(this.collapseDirection, this.animCollapse); } return this; }, // private getKeyMap : function(){ if(!this.keyMap){ this.keyMap = Ext.create('Ext.util.KeyMap', this.el, this.keys); } return this.keyMap; }, // private initDraggable : function(){ /** * <p>If this Panel is configured {@link #draggable}, this property will contain * an instance of {@link Ext.dd.DragSource} which handles dragging the Panel.</p> * The developer must provide implementations of the abstract methods of {@link Ext.dd.DragSource} * in order to supply behaviour for each stage of the drag/drop process. See {@link #draggable}. * @type Ext.dd.DragSource. * @property dd */ this.dd = Ext.create('Ext.panel.DD', this, Ext.isBoolean(this.draggable) ? null : this.draggable); }, // private - helper function for ghost ghostTools : function() { var tools = [], origTools = this.initialConfig.tools; if (origTools) { Ext.each(origTools, function(tool) { // Some tools can be full components, and copying them into the ghost // actually removes them from the owning panel. You could also potentially // end up with duplicate DOM ids as well. To avoid any issues we just make // a simple bare-minimum clone of each tool for ghosting purposes. tools.push({ type: tool.type }); }); } else { tools = [{ type: 'placeholder' }]; } return tools; }, // private - used for dragging ghost: function(cls) { var me = this, ghostPanel = me.ghostPanel, box = me.getBox(); if (!ghostPanel) { ghostPanel = Ext.create('Ext.panel.Panel', { renderTo: document.body, floating: { shadow: false }, frame: Ext.supports.CSS3BorderRadius ? me.frame : false, title: me.title, overlapHeader: me.overlapHeader, headerPosition: me.headerPosition, width: me.getWidth(), height: me.getHeight(), iconCls: me.iconCls, baseCls: me.baseCls, tools: me.ghostTools(), cls: me.baseCls + '-ghost ' + (cls ||'') }); me.ghostPanel = ghostPanel; } ghostPanel.floatParent = me.floatParent; if (me.floating) { ghostPanel.setZIndex(Ext.Number.from(me.el.getStyle('zIndex'), 0)); } else { ghostPanel.toFront(); } ghostPanel.el.show(); ghostPanel.setPosition(box.x, box.y); ghostPanel.setSize(box.width, box.height); me.el.hide(); if (me.floatingItems) { me.floatingItems.hide(); } return ghostPanel; }, // private unghost: function(show, matchPosition) { var me = this; if (!me.ghostPanel) { return; } if (show !== false) { me.el.show(); if (matchPosition !== false) { me.setPosition(me.ghostPanel.getPosition()); } if (me.floatingItems) { me.floatingItems.show(); } Ext.defer(me.focus, 10, me); } me.ghostPanel.el.hide(); }, initResizable: function(resizable) { if (this.collapsed) { resizable.disabled = true; } this.callParent([resizable]); } });
/* * Duktape ArrayBuffer/view virtual properties don't work in * Object.defineProperty(). */ /*@include util-buffer.js@*/ /*--- { "custom": true } ---*/ /*=== object 8 [object Uint8Array] 0 TypeError 0 object 8 [object Uint8Array] ===*/ function test() { var buf = new ArrayBuffer(8); var u8 = new Uint8Array(buf); print(typeof u8, u8.length, String(u8)); print(u8[4]); try { Object.defineProperty(u8, '4', { value: 68 }); } catch (e) { // Duktape: TypeError: property is virtual // Node.js: TypeError: Cannot redefine a property of an object with external array elements print(e.name); //print(e.stack || e); } print(u8[4]); print(typeof u8, u8.length, String(u8)); } try { test(); } catch (e) { print(e.stack || e); }
/*! * ui-grid - v4.6.2 - 2018-07-09 * Copyright (c) 2018 ; License: MIT */ (function() { 'use strict'; /** * @ngdoc overview * @name ui.grid.pagination * * @description * * # ui.grid.pagination * * <div class="alert alert-warning" role="alert"><strong>Alpha</strong> This feature is in development. There will almost certainly be breaking api changes, or there are major outstanding bugs.</div> * * This module provides pagination support to ui-grid */ var module = angular.module('ui.grid.pagination', ['ng', 'ui.grid']); /** * @ngdoc service * @name ui.grid.pagination.service:uiGridPaginationService * * @description Service for the pagination feature */ module.service('uiGridPaginationService', ['gridUtil', function (gridUtil) { var service = { /** * @ngdoc method * @name initializeGrid * @methodOf ui.grid.pagination.service:uiGridPaginationService * @description Attaches the service to a certain grid * @param {Grid} grid The grid we want to work with */ initializeGrid: function (grid) { service.defaultGridOptions(grid.options); /** * @ngdoc object * @name ui.grid.pagination.api:PublicAPI * * @description Public API for the pagination feature */ var publicApi = { events: { pagination: { /** * @ngdoc event * @name paginationChanged * @eventOf ui.grid.pagination.api:PublicAPI * @description This event fires when the pageSize or currentPage changes * @param {int} currentPage requested page number * @param {int} pageSize requested page size */ paginationChanged: function (currentPage, pageSize) { } } }, methods: { pagination: { /** * @ngdoc method * @name getPage * @methodOf ui.grid.pagination.api:PublicAPI * @description Returns the number of the current page */ getPage: function () { return grid.options.enablePagination ? grid.options.paginationCurrentPage : null; }, /** * @ngdoc method * @name getFirstRowIndex * @methodOf ui.grid.pagination.api:PublicAPI * @description Returns the index of the first row of the current page. */ getFirstRowIndex: function () { if (grid.options.useCustomPagination) { return grid.options.paginationPageSizes.reduce(function(result, size, index) { return index < grid.options.paginationCurrentPage - 1 ? result + size : result; }, 0); } return ((grid.options.paginationCurrentPage - 1) * grid.options.paginationPageSize); }, /** * @ngdoc method * @name getLastRowIndex * @methodOf ui.grid.pagination.api:PublicAPI * @description Returns the index of the last row of the current page. */ getLastRowIndex: function () { if (grid.options.useCustomPagination) { return publicApi.methods.pagination.getFirstRowIndex() + grid.options.paginationPageSizes[grid.options.paginationCurrentPage - 1] - 1; } return Math.min(grid.options.paginationCurrentPage * grid.options.paginationPageSize, grid.options.totalItems) - 1; }, /** * @ngdoc method * @name getTotalPages * @methodOf ui.grid.pagination.api:PublicAPI * @description Returns the total number of pages */ getTotalPages: function () { if (!grid.options.enablePagination) { return null; } if (grid.options.useCustomPagination) { return grid.options.paginationPageSizes.length; } return (grid.options.totalItems === 0) ? 1 : Math.ceil(grid.options.totalItems / grid.options.paginationPageSize); }, /** * @ngdoc method * @name nextPage * @methodOf ui.grid.pagination.api:PublicAPI * @description Moves to the next page, if possible */ nextPage: function () { if (!grid.options.enablePagination) { return; } if (grid.options.totalItems > 0) { grid.options.paginationCurrentPage = Math.min( grid.options.paginationCurrentPage + 1, publicApi.methods.pagination.getTotalPages() ); } else { grid.options.paginationCurrentPage++; } }, /** * @ngdoc method * @name previousPage * @methodOf ui.grid.pagination.api:PublicAPI * @description Moves to the previous page, if we're not on the first page */ previousPage: function () { if (!grid.options.enablePagination) { return; } grid.options.paginationCurrentPage = Math.max(grid.options.paginationCurrentPage - 1, 1); }, /** * @ngdoc method * @name seek * @methodOf ui.grid.pagination.api:PublicAPI * @description Moves to the requested page * @param {int} page The number of the page that should be displayed */ seek: function (page) { if (!grid.options.enablePagination) { return; } if (!angular.isNumber(page) || page < 1) { throw 'Invalid page number: ' + page; } grid.options.paginationCurrentPage = Math.min(page, publicApi.methods.pagination.getTotalPages()); } } } }; grid.api.registerEventsFromObject(publicApi.events); grid.api.registerMethodsFromObject(publicApi.methods); var processPagination = function( renderableRows ) { if (grid.options.useExternalPagination || !grid.options.enablePagination) { return renderableRows; } // client side pagination var pageSize = parseInt(grid.options.paginationPageSize, 10); var currentPage = parseInt(grid.options.paginationCurrentPage, 10); var visibleRows = renderableRows.filter(function (row) { return row.visible; }); grid.options.totalItems = visibleRows.length; var firstRow = publicApi.methods.pagination.getFirstRowIndex(); var lastRow = publicApi.methods.pagination.getLastRowIndex(); if (firstRow > visibleRows.length) { currentPage = grid.options.paginationCurrentPage = 1; firstRow = (currentPage - 1) * pageSize; } return visibleRows.slice(firstRow, lastRow + 1); }; grid.registerRowsProcessor(processPagination, 900 ); }, defaultGridOptions: function (gridOptions) { /** * @ngdoc object * @name ui.grid.pagination.api:GridOptions * * @description GridOptions for the pagination feature, these are available to be * set using the ui-grid {@link ui.grid.class:GridOptions gridOptions} */ /** * @ngdoc property * @name enablePagination * @propertyOf ui.grid.pagination.api:GridOptions * @description Enables pagination. Defaults to true. */ gridOptions.enablePagination = gridOptions.enablePagination !== false; /** * @ngdoc property * @name enablePaginationControls * @propertyOf ui.grid.pagination.api:GridOptions * @description Enables the paginator at the bottom of the grid. Turn this off if you want to implement your * own controls outside the grid. */ gridOptions.enablePaginationControls = gridOptions.enablePaginationControls !== false; /** * @ngdoc property * @name useExternalPagination * @propertyOf ui.grid.pagination.api:GridOptions * @description Disables client side pagination. When true, handle the paginationChanged event and set data * and totalItems. Defaults to `false` */ gridOptions.useExternalPagination = gridOptions.useExternalPagination === true; /** * @ngdoc property * @name useCustomPagination * @propertyOf ui.grid.pagination.api:GridOptions * @description Disables client-side pagination. When true, handle the `paginationChanged` event and set `data`, * `firstRowIndex`, `lastRowIndex`, and `totalItems`. Defaults to `false`. */ gridOptions.useCustomPagination = gridOptions.useCustomPagination === true; /** * @ngdoc property * @name totalItems * @propertyOf ui.grid.pagination.api:GridOptions * @description Total number of items, set automatically when using client side pagination, but needs set by user * for server side pagination */ if (gridUtil.isNullOrUndefined(gridOptions.totalItems)) { gridOptions.totalItems = 0; } /** * @ngdoc property * @name paginationPageSizes * @propertyOf ui.grid.pagination.api:GridOptions * @description Array of page sizes, defaults to `[250, 500, 1000]` */ if (gridUtil.isNullOrUndefined(gridOptions.paginationPageSizes)) { gridOptions.paginationPageSizes = [250, 500, 1000]; } /** * @ngdoc property * @name paginationPageSize * @propertyOf ui.grid.pagination.api:GridOptions * @description Page size, defaults to the first item in paginationPageSizes, or 0 if paginationPageSizes is empty */ if (gridUtil.isNullOrUndefined(gridOptions.paginationPageSize)) { if (gridOptions.paginationPageSizes.length > 0) { gridOptions.paginationPageSize = gridOptions.paginationPageSizes[0]; } else { gridOptions.paginationPageSize = 0; } } /** * @ngdoc property * @name paginationCurrentPage * @propertyOf ui.grid.pagination.api:GridOptions * @description Current page number, defaults to 1 */ if (gridUtil.isNullOrUndefined(gridOptions.paginationCurrentPage)) { gridOptions.paginationCurrentPage = 1; } /** * @ngdoc property * @name paginationTemplate * @propertyOf ui.grid.pagination.api:GridOptions * @description A custom template for the pager, defaults to `ui-grid/pagination` */ if (gridUtil.isNullOrUndefined(gridOptions.paginationTemplate)) { gridOptions.paginationTemplate = 'ui-grid/pagination'; } }, /** * @ngdoc method * @methodOf ui.grid.pagination.service:uiGridPaginationService * @name uiGridPaginationService * @description Raises paginationChanged and calls refresh for client side pagination * @param {Grid} grid the grid for which the pagination changed * @param {int} currentPage requested page number * @param {int} pageSize requested page size */ onPaginationChanged: function (grid, currentPage, pageSize) { grid.api.pagination.raise.paginationChanged(currentPage, pageSize); if (!grid.options.useExternalPagination) { grid.queueGridRefresh(); // client side pagination } } }; return service; } ]); /** * @ngdoc directive * @name ui.grid.pagination.directive:uiGridPagination * @element div * @restrict A * * @description Adds pagination features to grid * @example <example module="app"> <file name="app.js"> var app = angular.module('app', ['ui.grid', 'ui.grid.pagination']); app.controller('MainCtrl', ['$scope', function ($scope) { $scope.data = [ { name: 'Alex', car: 'Toyota' }, { name: 'Sam', car: 'Lexus' }, { name: 'Joe', car: 'Dodge' }, { name: 'Bob', car: 'Buick' }, { name: 'Cindy', car: 'Ford' }, { name: 'Brian', car: 'Audi' }, { name: 'Malcom', car: 'Mercedes Benz' }, { name: 'Dave', car: 'Ford' }, { name: 'Stacey', car: 'Audi' }, { name: 'Amy', car: 'Acura' }, { name: 'Scott', car: 'Toyota' }, { name: 'Ryan', car: 'BMW' }, ]; $scope.gridOptions = { data: 'data', paginationPageSizes: [5, 10, 25], paginationPageSize: 5, columnDefs: [ {name: 'name'}, {name: 'car'} ] } }]); </file> <file name="index.html"> <div ng-controller="MainCtrl"> <div ui-grid="gridOptions" ui-grid-pagination></div> </div> </file> </example> */ module.directive('uiGridPagination', ['gridUtil', 'uiGridPaginationService', function (gridUtil, uiGridPaginationService) { return { priority: -200, scope: false, require: 'uiGrid', link: { pre: function ($scope, $elm, $attr, uiGridCtrl) { uiGridPaginationService.initializeGrid(uiGridCtrl.grid); gridUtil.getTemplate(uiGridCtrl.grid.options.paginationTemplate) .then(function (contents) { var template = angular.element(contents); $elm.append(template); uiGridCtrl.innerCompile(template); }); } } }; } ]); /** * @ngdoc directive * @name ui.grid.pagination.directive:uiGridPager * @element div * * @description Panel for handling pagination */ module.directive('uiGridPager', ['uiGridPaginationService', 'uiGridConstants', 'gridUtil', 'i18nService', 'i18nConstants', function (uiGridPaginationService, uiGridConstants, gridUtil, i18nService, i18nConstants) { return { priority: -200, scope: true, require: '^uiGrid', link: function ($scope, $elm, $attr, uiGridCtrl) { var defaultFocusElementSelector = '.ui-grid-pager-control-input'; $scope.aria = i18nService.getSafeText('pagination.aria'); // Returns an object with all of the aria labels var updateLabels = function() { $scope.paginationApi = uiGridCtrl.grid.api.pagination; $scope.sizesLabel = i18nService.getSafeText('pagination.sizes'); $scope.totalItemsLabel = i18nService.getSafeText('pagination.totalItems'); $scope.paginationOf = i18nService.getSafeText('pagination.of'); $scope.paginationThrough = i18nService.getSafeText('pagination.through'); }; updateLabels(); $scope.$on(i18nConstants.UPDATE_EVENT, updateLabels); var options = uiGridCtrl.grid.options; uiGridCtrl.grid.renderContainers.body.registerViewportAdjuster(function (adjustment) { if (options.enablePaginationControls) { adjustment.height = adjustment.height - gridUtil.elementHeight($elm, "padding"); } return adjustment; }); var dataChangeDereg = uiGridCtrl.grid.registerDataChangeCallback(function (grid) { if (!grid.options.useExternalPagination) { grid.options.totalItems = grid.rows.length; } }, [uiGridConstants.dataChange.ROW]); $scope.$on('$destroy', dataChangeDereg); var deregP = $scope.$watch('grid.options.paginationCurrentPage + grid.options.paginationPageSize', function (newValues, oldValues) { if (newValues === oldValues || oldValues === undefined) { return; } if (!angular.isNumber(options.paginationCurrentPage) || options.paginationCurrentPage < 1) { options.paginationCurrentPage = 1; return; } if (options.totalItems > 0 && options.paginationCurrentPage > $scope.paginationApi.getTotalPages()) { options.paginationCurrentPage = $scope.paginationApi.getTotalPages(); return; } uiGridPaginationService.onPaginationChanged($scope.grid, options.paginationCurrentPage, options.paginationPageSize); }); $scope.$on('$destroy', function() { deregP(); }); $scope.cantPageForward = function () { if ($scope.paginationApi.getTotalPages()) { return $scope.cantPageToLast(); } else { return options.data.length < 1; } }; $scope.cantPageToLast = function () { var totalPages = $scope.paginationApi.getTotalPages(); return !totalPages || options.paginationCurrentPage >= totalPages; }; $scope.cantPageBackward = function () { return options.paginationCurrentPage <= 1; }; var focusToInputIf = function(condition) { if (condition) { gridUtil.focus.bySelector($elm, defaultFocusElementSelector); } }; // Takes care of setting focus to the middle element when focus is lost $scope.pageFirstPageClick = function () { $scope.paginationApi.seek(1); focusToInputIf($scope.cantPageBackward()); }; $scope.pagePreviousPageClick = function () { $scope.paginationApi.previousPage(); focusToInputIf($scope.cantPageBackward()); }; $scope.pageNextPageClick = function () { $scope.paginationApi.nextPage(); focusToInputIf($scope.cantPageForward()); }; $scope.pageLastPageClick = function () { $scope.paginationApi.seek($scope.paginationApi.getTotalPages()); focusToInputIf($scope.cantPageToLast()); }; } }; } ]); })();
define("dojox/gfx/canvasWithEvents", ["dojo/_base/lang", "dojo/_base/declare", "dojo/has", "dojo/on", "dojo/aspect", "dojo/touch", "dojo/_base/Color", "dojo/dom", "dojo/dom-geometry", "dojo/_base/window", "./_base","./canvas", "./shape", "./matrix"], function(lang, declare, has, on, aspect, touch, Color, dom, domGeom, win, g, canvas, shapeLib, m){ function makeFakeEvent(event){ // summary: // Generates a "fake", fully mutable event object by copying the properties from an original host Event // object to a new standard JavaScript object. var fakeEvent = {}; for(var k in event){ if(typeof event[k] === "function"){ // Methods (like preventDefault) must be invoked on the original event object, or they will not work fakeEvent[k] = lang.hitch(event, k); } else{ fakeEvent[k] = event[k]; } } return fakeEvent; } // Browsers that implement the current (January 2013) WebIDL spec allow Event object properties to be mutated // using Object.defineProperty; some older WebKits (Safari 6-) and at least IE10- do not follow the spec. Direct // mutation is, of course, much faster when it can be done. has.add("dom-mutableEvents", function(){ var event = document.createEvent("UIEvents"); try { if(Object.defineProperty){ Object.defineProperty(event, "type", { value: "foo" }); }else{ event.type = "foo"; } return event.type === "foo"; }catch(e){ return false; } }); has.add("MSPointer", navigator.msPointerEnabled); has.add("pointer-events", navigator.pointerEnabled); var canvasWithEvents = g.canvasWithEvents = { // summary: // This the graphics rendering bridge for W3C Canvas compliant browsers which extends // the basic canvas drawing renderer bridge to add additional support for graphics events // on Shapes. // Since Canvas is an immediate mode graphics api, with no object graph or // eventing capabilities, use of the canvas module alone will only add in drawing support. // This additional module, canvasWithEvents extends this module with additional support // for handling events on Canvas. By default, the support for events is now included // however, if only drawing capabilities are needed, canvas event module can be disabled // using the dojoConfig option, canvasEvents:true|false. }; canvasWithEvents.Shape = declare("dojox.gfx.canvasWithEvents.Shape", canvas.Shape, { _testInputs: function(/* Object */ ctx, /* Array */ pos){ if(this.clip || (!this.canvasFill && this.strokeStyle)){ // pixel-based until a getStrokedPath-like api is available on the path this._hitTestPixel(ctx, pos); }else{ this._renderShape(ctx); var length = pos.length, t = this.getTransform(); for(var i = 0; i < length; ++i){ var input = pos[i]; // already hit if(input.target){continue;} var x = input.x, y = input.y, p = t ? m.multiplyPoint(m.invert(t), x, y) : { x: x, y: y }; input.target = this._hitTestGeometry(ctx, p.x, p.y); } } }, _hitTestPixel: function(/* Object */ ctx, /* Array */ pos){ for(var i = 0; i < pos.length; ++i){ var input = pos[i]; if(input.target){continue;} var x = input.x, y = input.y; ctx.clearRect(0,0,1,1); ctx.save(); ctx.translate(-x, -y); this._render(ctx, true); input.target = ctx.getImageData(0, 0, 1, 1).data[0] ? this : null; ctx.restore(); } }, _hitTestGeometry: function(ctx, x, y){ return ctx.isPointInPath(x, y) ? this : null; }, _renderFill: function(/* Object */ ctx, /* Boolean */ apply){ // summary: // render fill for the shape // ctx: // a canvas context object // apply: // whether ctx.fill() shall be called if(ctx.pickingMode){ if("canvasFill" in this && apply){ ctx.fill(); } return; } this.inherited(arguments); }, _renderStroke: function(/* Object */ ctx){ // summary: // render stroke for the shape // ctx: // a canvas context object // apply: // whether ctx.stroke() shall be called if(this.strokeStyle && ctx.pickingMode){ var c = this.strokeStyle.color; try{ this.strokeStyle.color = new Color(ctx.strokeStyle); this.inherited(arguments); }finally{ this.strokeStyle.color = c; } }else{ this.inherited(arguments); } }, // events getEventSource: function(){ return this.surface.rawNode; }, on: function(type, listener){ // summary: // Connects an event to this shape. var expectedTarget = this.rawNode; // note that event listeners' targets are automatically fixed up in the canvas's addEventListener method return on(this.getEventSource(), type, function(event){ if(dom.isDescendant(event.target, expectedTarget)){ listener.apply(expectedTarget, arguments); } }); }, connect: function(name, object, method){ // summary: // Deprecated. Connects a handler to an event on this shape. Use `on` instead. if(name.substring(0, 2) == "on"){ name = name.substring(2); } return this.on(name, method ? lang.hitch(object, method) : lang.hitch(null, object)); }, disconnect: function(handle){ // summary: // Deprecated. Disconnects an event handler. Use `handle.remove` instead. handle.remove(); } }); canvasWithEvents.Group = declare("dojox.gfx.canvasWithEvents.Group", [canvasWithEvents.Shape, canvas.Group], { _testInputs: function(/*Object*/ ctx, /*Array*/ pos){ var children = this.children, t = this.getTransform(), i, j, input; if(children.length === 0){ return; } var posbk = []; for(i = 0; i < pos.length; ++i){ input = pos[i]; // backup position before transform applied posbk[i] = { x: input.x, y: input.y }; if(input.target){continue;} var x = input.x, y = input.y; var p = t ? m.multiplyPoint(m.invert(t), x, y) : { x: x, y: y }; input.x = p.x; input.y = p.y; } for(i = children.length - 1; i >= 0; --i){ children[i]._testInputs(ctx, pos); // does it need more hit tests ? var allFound = true; for(j = 0; j < pos.length; ++j){ if(pos[j].target == null){ allFound = false; break; } } if(allFound){ break; } } if(this.clip){ // filter positive hittests against the group clipping area for(i = 0; i < pos.length; ++i){ input = pos[i]; input.x = posbk[i].x; input.y = posbk[i].y; if(input.target){ ctx.clearRect(0,0,1,1); ctx.save(); ctx.translate(-input.x, -input.y); this._render(ctx, true); if(!ctx.getImageData(0, 0, 1, 1).data[0]){ input.target = null; } ctx.restore(); } } }else{ for(i = 0; i < pos.length; ++i){ pos[i].x = posbk[i].x; pos[i].y = posbk[i].y; } } } }); canvasWithEvents.Image = declare("dojox.gfx.canvasWithEvents.Image", [canvasWithEvents.Shape, canvas.Image], { _renderShape: function(/* Object */ ctx){ // summary: // render image // ctx: // a canvas context object var s = this.shape; if(ctx.pickingMode){ ctx.fillRect(s.x, s.y, s.width, s.height); }else{ this.inherited(arguments); } }, _hitTestGeometry: function(ctx, x, y){ // TODO: improve hit testing to take into account transparency var s = this.shape; return x >= s.x && x <= s.x + s.width && y >= s.y && y <= s.y + s.height ? this : null; } }); canvasWithEvents.Text = declare("dojox.gfx.canvasWithEvents.Text", [canvasWithEvents.Shape, canvas.Text], { _testInputs: function(ctx, pos){ return this._hitTestPixel(ctx, pos); } }); canvasWithEvents.Rect = declare("dojox.gfx.canvasWithEvents.Rect", [canvasWithEvents.Shape, canvas.Rect], {}); canvasWithEvents.Circle = declare("dojox.gfx.canvasWithEvents.Circle", [canvasWithEvents.Shape, canvas.Circle], {}); canvasWithEvents.Ellipse = declare("dojox.gfx.canvasWithEvents.Ellipse", [canvasWithEvents.Shape, canvas.Ellipse],{}); canvasWithEvents.Line = declare("dojox.gfx.canvasWithEvents.Line", [canvasWithEvents.Shape, canvas.Line],{}); canvasWithEvents.Polyline = declare("dojox.gfx.canvasWithEvents.Polyline", [canvasWithEvents.Shape, canvas.Polyline],{}); canvasWithEvents.Path = declare("dojox.gfx.canvasWithEvents.Path", [canvasWithEvents.Shape, canvas.Path],{}); canvasWithEvents.TextPath = declare("dojox.gfx.canvasWithEvents.TextPath", [canvasWithEvents.Shape, canvas.TextPath],{}); // When events are dispatched using on.emit, certain properties of these events (like target) get overwritten by // the DOM. The only real way to deal with this at the moment, short of never using any standard event properties, // is to store this data out-of-band and fix up the event object passed to the listener by wrapping the listener. // The out-of-band data is stored here. var fixedEventData = null; canvasWithEvents.Surface = declare("dojox.gfx.canvasWithEvents.Surface", canvas.Surface, { constructor: function(){ this._elementUnderPointer = null; }, fixTarget: function(listener){ // summary: // Corrects the `target` properties of the event object passed to the actual listener. // listener: Function // An event listener function. var surface = this; return function(event){ var k; if(fixedEventData){ if(has("dom-mutableEvents")){ Object.defineProperties(event, fixedEventData); }else{ event = makeFakeEvent(event); for(k in fixedEventData){ event[k] = fixedEventData[k].value; } } }else{ // non-synthetic events need to have target correction too, but since there is no out-of-band // data we need to figure out the target ourselves var canvas = surface.getEventSource(), target = canvas._dojoElementFromPoint( // touch events may not be fixed at this point, so clientX/Y may not be set on the // event object (event.changedTouches ? event.changedTouches[0] : event).pageX, (event.changedTouches ? event.changedTouches[0] : event).pageY ); if(has("dom-mutableEvents")){ Object.defineProperties(event, { target: { value: target, configurable: true, enumerable: true }, gfxTarget: { value: target.shape, configurable: true, enumerable: true } }); }else{ event = makeFakeEvent(event); event.target = target; event.gfxTarget = target.shape; } } // fixTouchListener in dojo/on undoes target changes by copying everything from changedTouches even // if the value already exists on the event; of course, this canvas implementation currently only // supports one pointer at a time. if we wanted to make sure all the touches arrays' targets were // updated correctly as well, we could support multi-touch and this workaround would not be needed if(has("touch")){ // some standard properties like clientX/Y are not provided on the main touch event object, // so copy them over if we need to if(event.changedTouches && event.changedTouches[0]){ var changedTouch = event.changedTouches[0]; for(k in changedTouch){ if(!event[k]){ if(has("dom-mutableEvents")){ Object.defineProperty(event, k, { value: changedTouch[k], configurable: true, enumerable: true }); }else{ event[k] = changedTouch[k]; } } } } event.corrected = event; } return listener.call(this, event); }; }, _checkPointer: function(event){ // summary: // Emits enter/leave/over/out events in response to the pointer entering/leaving the inner elements // within the canvas. function emit(types, target, relatedTarget){ // summary: // Emits multiple synthetic events defined in `types` with the given target `target`. var oldBubbles = event.bubbles; for(var i = 0, type; (type = types[i]); ++i){ // targets get reset when the event is dispatched so we need to give information to fixTarget to // restore the target on the dispatched event through a back channel fixedEventData = { target: { value: target, configurable: true, enumerable: true}, gfxTarget: { value: target.shape, configurable: true, enumerable: true }, relatedTarget: { value: relatedTarget, configurable: true, enumerable: true } }; // bubbles can be set directly, though. Object.defineProperty(event, "bubbles", { value: type.bubbles, configurable: true, enumerable: true }); on.emit(canvas, type.type, event); fixedEventData = null; } Object.defineProperty(event, "bubbles", { value: oldBubbles, configurable: true, enumerable: true }); } // Types must be arrays because hash map order is not guaranteed but we must fire in order to match normal // event behaviour var TYPES = { out: [ { type: "mouseout", bubbles: true }, { type: "MSPointerOut", bubbles: true }, { type: "pointerout", bubbles: true }, { type: "mouseleave", bubbles: false }, { type: "dojotouchout", bubbles: true} ], over: [ { type: "mouseover", bubbles: true }, { type: "MSPointerOver", bubbles: true }, { type: "pointerover", bubbles: true }, { type: "mouseenter", bubbles: false }, { type: "dojotouchover", bubbles: true} ] }, elementUnderPointer = event.target, oldElementUnderPointer = this._elementUnderPointer, canvas = this.getEventSource(); if(oldElementUnderPointer !== elementUnderPointer){ if(oldElementUnderPointer && oldElementUnderPointer !== canvas){ emit(TYPES.out, oldElementUnderPointer, elementUnderPointer); } this._elementUnderPointer = elementUnderPointer; if(elementUnderPointer && elementUnderPointer !== canvas){ emit(TYPES.over, elementUnderPointer, oldElementUnderPointer); } } }, getEventSource: function(){ return this.rawNode; }, on: function(type, listener){ // summary: // Connects an event to this surface. return on(this.getEventSource(), type, listener); }, connect: function(/*String*/ name, /*Object*/ object, /*Function|String*/ method){ // summary: // Deprecated. Connects a handler to an event on this surface. Use `on` instead. // name: String // The event name // object: Object // The object that method will receive as "this". // method: Function // A function reference, or name of a function in context. if(name.substring(0, 2) == "on"){ name = name.substring(2); } return this.on(name, method ? lang.hitch(object, method) : object); }, disconnect: function(handle){ // summary: // Deprecated. Disconnects a handler. Use `handle.remove` instead. handle.remove(); }, _initMirrorCanvas: function(){ // summary: // Initialises a mirror canvas used for event hit detection. this._initMirrorCanvas = function(){}; var canvas = this.getEventSource(), mirror = this.mirrorCanvas = canvas.ownerDocument.createElement("canvas"); mirror.width = 1; mirror.height = 1; mirror.style.position = "absolute"; mirror.style.left = mirror.style.top = "-99999px"; canvas.parentNode.appendChild(mirror); var moveEvt = "mousemove"; if(has("pointer-events")){ moveEvt = "pointermove"; }else if(has("MSPointer")){ moveEvt = "MSPointerMove"; }else if(has("touch")){ moveEvt = "touchmove"; } on(canvas, moveEvt, lang.hitch(this, "_checkPointer")); }, destroy: function(){ if(this.mirrorCanvas){ this.mirrorCanvas.parentNode.removeChild(this.mirrorCanvas); this.mirrorCanvas = null; } this.inherited(arguments); } }); canvasWithEvents.createSurface = function(parentNode, width, height){ // summary: // creates a surface (Canvas) // parentNode: Node // a parent node // width: String // width of surface, e.g., "100px" // height: String // height of surface, e.g., "100px" if(!width && !height){ var pos = domGeom.position(parentNode); width = width || pos.w; height = height || pos.h; } if(typeof width === "number"){ width = width + "px"; } if(typeof height === "number"){ height = height + "px"; } var surface = new canvasWithEvents.Surface(), parent = dom.byId(parentNode), canvas = parent.ownerDocument.createElement("canvas"); canvas.width = g.normalizedLength(width); // in pixels canvas.height = g.normalizedLength(height); // in pixels parent.appendChild(canvas); surface.rawNode = canvas; surface._parent = parent; surface.surface = surface; g._base._fixMsTouchAction(surface); // any event handler added to the canvas needs to have its target fixed. var oldAddEventListener = canvas.addEventListener, oldRemoveEventListener = canvas.removeEventListener, listeners = []; var addEventListenerImpl = function(type, listener, useCapture){ surface._initMirrorCanvas(); var actualListener = surface.fixTarget(listener); listeners.push({ original: listener, actual: actualListener }); oldAddEventListener.call(this, type, actualListener, useCapture); }; var removeEventListenerImpl = function(type, listener, useCapture){ for(var i = 0, record; (record = listeners[i]); ++i){ if(record.original === listener){ oldRemoveEventListener.call(this, type, record.actual, useCapture); listeners.splice(i, 1); break; } } }; try{ Object.defineProperties(canvas, { addEventListener: { value: addEventListenerImpl, enumerable: true, configurable: true }, removeEventListener: { value: removeEventListenerImpl } }); }catch(e){ // Object.defineProperties fails on iOS 4-5. "Not supported on DOM objects"). canvas.addEventListener = addEventListenerImpl; canvas.removeEventListener = removeEventListenerImpl; } canvas._dojoElementFromPoint = function(x, y){ // summary: // Returns the shape under the given (x, y) coordinate. // evt: // mouse event if(!surface.mirrorCanvas){ return this; } var surfacePosition = domGeom.position(this, true); // use canvas-relative positioning x -= surfacePosition.x; y -= surfacePosition.y; var mirror = surface.mirrorCanvas, ctx = mirror.getContext("2d"), children = surface.children; ctx.clearRect(0, 0, mirror.width, mirror.height); ctx.save(); ctx.strokeStyle = "rgba(127,127,127,1.0)"; ctx.fillStyle = "rgba(127,127,127,1.0)"; ctx.pickingMode = true; // TODO: Make inputs non-array var inputs = [ { x: x, y: y } ]; // process the inputs to find the target. for(var i = children.length - 1; i >= 0; i--){ children[i]._testInputs(ctx, inputs); if(inputs[0].target){ break; } } ctx.restore(); return inputs[0] && inputs[0].target ? inputs[0].target.rawNode : this; }; return surface; // dojox/gfx.Surface }; var Creator = { createObject: function(){ // summary: // Creates a synthetic, partially-interoperable Element object used to uniquely identify the given // shape within the canvas pseudo-DOM. var shape = this.inherited(arguments), listeners = {}; shape.rawNode = { shape: shape, ownerDocument: shape.surface.rawNode.ownerDocument, parentNode: shape.parent ? shape.parent.rawNode : null, addEventListener: function(type, listener){ var listenersOfType = listeners[type] = (listeners[type] || []); for(var i = 0, record; (record = listenersOfType[i]); ++i){ if(record.listener === listener){ return; } } listenersOfType.push({ listener: listener, handle: aspect.after(this, "on" + type, shape.surface.fixTarget(listener), true) }); }, removeEventListener: function(type, listener){ var listenersOfType = listeners[type]; if(!listenersOfType){ return; } for(var i = 0, record; (record = listenersOfType[i]); ++i){ if(record.listener === listener){ record.handle.remove(); listenersOfType.splice(i, 1); return; } } } }; return shape; } }; canvasWithEvents.Group.extend(Creator); canvasWithEvents.Surface.extend(Creator); return canvasWithEvents; });
var searchData= [ ['reason',['Reason',['../struct_jmcpp_1_1_force_logout_event.html#a2bad86d7b0d12010890195ee6f1ed4bc',1,'Jmcpp::ForceLogoutEvent']]] ];
import { Meteor } from 'meteor/meteor'; export const rolesStreamer = new Meteor.Streamer('roles');
/** * Module dependencies. */ var EventEmitter = require('events').EventEmitter , debug = require('debug')('runner') , Test = require('./test') , utils = require('./utils') , noop = function(){}; /** * Expose `Runner`. */ module.exports = Runner; /** * Initialize a `Runner` for the given `suite`. * * Events: * * - `start` execution started * - `end` execution complete * - `suite` (suite) test suite execution started * - `suite end` (suite) all tests (and sub-suites) have finished * - `test` (test) test execution started * - `test end` (test) test completed * - `hook` (hook) hook execution started * - `hook end` (hook) hook complete * - `pass` (test) test passed * - `fail` (test, err) test failed * * @api public */ function Runner(suite) { var self = this; this._globals = []; this.suite = suite; this.total = suite.total(); this.failures = 0; this.on('test end', function(test){ self.checkGlobals(test); }); this.on('hook end', function(hook){ self.checkGlobals(hook); }); this.grep(/.*/); this.globals(utils.keys(global).concat(['errno'])); } /** * Inherit from `EventEmitter.prototype`. */ Runner.prototype.__proto__ = EventEmitter.prototype; /** * Run tests with full titles matching `re`. * * @param {RegExp} re * @return {Runner} for chaining * @api public */ Runner.prototype.grep = function(re){ debug('grep %s', re); this._grep = re; return this; }; /** * Allow the given `arr` of globals. * * @param {Array} arr * @return {Runner} for chaining * @api public */ Runner.prototype.globals = function(arr){ if (0 == arguments.length) return this._globals; debug('globals %j', arr); utils.forEach(arr, function(arr){ this._globals.push(arr); }, this); return this; }; /** * Check for global variable leaks. * * @api private */ Runner.prototype.checkGlobals = function(test){ if (this.ignoreLeaks) return; var leaks = utils.filter(utils.keys(global), function(key){ return !~utils.indexOf(this._globals, key) && (!global.navigator || 'onerror' !== key); }, this); this._globals = this._globals.concat(leaks); if (leaks.length > 1) { this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); } else if (leaks.length) { this.fail(test, new Error('global leak detected: ' + leaks[0])); } }; /** * Fail the given `test`. * * @param {Test} test * @param {Error} err * @api private */ Runner.prototype.fail = function(test, err){ ++this.failures; test.failed = true; this.emit('fail', test, err); }; /** * Fail the given `hook` with `err`. * * Hook failures (currently) hard-end due * to that fact that a failing hook will * surely cause subsequent tests to fail, * causing jumbled reporting. * * @param {Hook} hook * @param {Error} err * @api private */ Runner.prototype.failHook = function(hook, err){ this.fail(hook, err); this.emit('end'); }; /** * Run hook `name` callbacks and then invoke `fn()`. * * @param {String} name * @param {Function} function * @api private */ Runner.prototype.hook = function(name, fn){ var suite = this.suite , hooks = suite['_' + name] , ms = suite._timeout , self = this , timer; function next(i) { var hook = hooks[i]; if (!hook) return fn(); self.currentRunnable = hook; hook.context = self.test; self.emit('hook', hook); hook.on('error', function(err){ self.failHook(hook, err); }); hook.run(function(err){ hook.removeAllListeners('error'); if (err) return self.failHook(hook, err); self.emit('hook end', hook); next(++i); }); } process.nextTick(function(){ next(0); }); }; /** * Run hook `name` for the given array of `suites` * in order, and callback `fn(err)`. * * @param {String} name * @param {Array} suites * @param {Function} fn * @api private */ Runner.prototype.hooks = function(name, suites, fn){ var self = this , orig = this.suite; function next(suite) { self.suite = suite; if (!suite) { self.suite = orig; return fn(); } self.hook(name, function(err){ if (err) { self.suite = orig; return fn(err); } next(suites.pop()); }); } next(suites.pop()); }; /** * Run hooks from the top level down. * * @param {String} name * @param {Function} fn * @api private */ Runner.prototype.hookUp = function(name, fn){ var suites = [this.suite].concat(this.parents()).reverse(); this.hooks(name, suites, fn); }; /** * Run hooks from the bottom up. * * @param {String} name * @param {Function} fn * @api private */ Runner.prototype.hookDown = function(name, fn){ var suites = [this.suite].concat(this.parents()); this.hooks(name, suites, fn); }; /** * Return an array of parent Suites from * closest to furthest. * * @return {Array} * @api private */ Runner.prototype.parents = function(){ var suite = this.suite , suites = []; while (suite = suite.parent) suites.push(suite); return suites; }; /** * Run the current test and callback `fn(err)`. * * @param {Function} fn * @api private */ Runner.prototype.runTest = function(fn){ var test = this.test , self = this; try { test.on('error', function(err){ self.fail(test, err); }); test.run(fn); } catch (err) { fn(err); } }; /** * Run tests in the given `suite` and invoke * the callback `fn()` when complete. * * @param {Suite} suite * @param {Function} fn * @api private */ Runner.prototype.runTests = function(suite, fn){ var self = this , tests = suite.tests , test; function next(err) { // if we bail after first err if (self.failures && suite._bail) return fn(); // next test test = tests.shift(); // all done if (!test) return fn(); // grep if (!self._grep.test(test.fullTitle())) return next(); // pending if (test.pending) { self.emit('pending', test); self.emit('test end', test); return next(); } // execute test and hook(s) self.emit('test', self.test = test); self.hookDown('beforeEach', function(){ self.currentRunnable = self.test; self.runTest(function(err){ test = self.test; if (err) { self.fail(test, err); self.emit('test end', test); return self.hookUp('afterEach', next); } test.passed = true; self.emit('pass', test); self.emit('test end', test); self.hookUp('afterEach', next); }); }); } this.next = next; next(); }; /** * Run the given `suite` and invoke the * callback `fn()` when complete. * * @param {Suite} suite * @param {Function} fn * @api private */ Runner.prototype.runSuite = function(suite, fn){ var self = this , i = 0; debug('run suite %s', suite.fullTitle()); this.emit('suite', this.suite = suite); function next() { var curr = suite.suites[i++]; if (!curr) return done(); self.runSuite(curr, next); } function done() { self.suite = suite; self.hook('afterAll', function(){ self.emit('suite end', suite); fn(); }); } this.hook('beforeAll', function(){ self.runTests(suite, next); }); }; /** * Handle uncaught exceptions. * * @param {Error} err * @api private */ Runner.prototype.uncaught = function(err){ debug('uncaught exception'); var runnable = this.currentRunnable; if (runnable.failed) return; runnable.clearTimeout(); err.uncaught = true; this.fail(runnable, err); // recover from test if ('test' == runnable.type) { this.emit('test end', runnable); this.hookUp('afterEach', this.next); return; } // bail on hooks this.emit('end'); }; /** * Run the root suite and invoke `fn(failures)` * on completion. * * @param {Function} fn * @return {Runner} for chaining * @api public */ Runner.prototype.run = function(fn){ var self = this , fn = fn || function(){}; debug('start'); // callback this.on('end', function(){ debug('end'); process.removeListener('uncaughtException', this.uncaught); fn(self.failures); }); // run suites this.emit('start'); this.runSuite(this.suite, function(){ debug('finished running'); self.emit('end'); }); // uncaught exception process.on('uncaughtException', function(err){ self.uncaught(err); }); return this; };
'use strict'; module.exports = { get: function (html_file) { var return_html = ""; if( html_file ) { var filePath = "./" + html_file + ".html", xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", filePath, false); xmlhttp.send(); return_html = xmlhttp.responseText; } return return_html; } };