code
stringlengths
2
1.05M
function BxTimelineView(oOptions) { this._sActionsUri = oOptions.sActionUri; this._sActionsUrl = oOptions.sActionUrl; this._sObjName = oOptions.sObjName == undefined ? 'oTimelineView' : oOptions.sObjName; this._iOwnerId = oOptions.iOwnerId == undefined ? 0 : oOptions.iOwnerId; this._sAnimationEffect = oOptions.sAnimationEffect == undefined ? 'slide' : oOptions.sAnimationEffect; this._iAnimationSpeed = oOptions.iAnimationSpeed == undefined ? 'slow' : oOptions.iAnimationSpeed; this._aHtmlIds = oOptions.aHtmlIds == undefined ? {} : oOptions.aHtmlIds; this._oRequestParams = oOptions.oRequestParams == undefined ? {} : oOptions.oRequestParams; var $this = this; $(document).ready(function() { $this.initMasonry(); $('.bx-tl-item').resize(function() { $this.reloadMasonry(); }); $('img.bx-tl-item-image').load(function() { $this.reloadMasonry(); }); }); } BxTimelineView.prototype = new BxTimelineMain(); BxTimelineView.prototype.changePage = function(oElement, iStart, iPerPage) { this._oRequestParams.start = iStart; this._oRequestParams.per_page = iPerPage; this._getPosts(oElement, 'page'); }; BxTimelineView.prototype.changeFilter = function(oLink) { var sId = $(oLink).attr('id'); this._oRequestParams.start = 0; this._oRequestParams.filter = sId.substr(sId.lastIndexOf('-') + 1, sId.length); this._getPosts(oLink, 'filter'); }; BxTimelineView.prototype.changeTimeline = function(oLink, iYear) { this._oRequestParams.start = 0; this._oRequestParams.timeline = iYear; this._getPosts(oLink, 'timeline'); }; BxTimelineView.prototype.deletePost = function(oLink, iId) { var $this = this; var oView = $(this.sIdView); var oData = this._getDefaultData(); oData['id'] = iId; this.loadingInBlock(oLink, true); $.post( this._sActionsUrl + 'delete/', oData, function(oData) { $this.loadingInBlock(oLink, false); if(oData && oData.msg != undefined) alert(oData.msg); if(oData && oData.code == 0) $(oLink).parents('.bx-popup-applied:first:visible').dolPopupHide(); $($this.sIdItem + oData.id).bx_anim('hide', $this._sAnimationEffect, $this._iAnimationSpeed, function() { $(this).remove(); if(oView.find('.bx-tl-item').length != 0) { $this.reloadMasonry(); return; } $this.destroyMasonry(); oView.find('.bx-tl-load-more').hide(); oView.find('.bx-tl-empty').show(); }); }, 'json' ); }; BxTimelineView.prototype.showMoreContent = function(oLink) { $(oLink).parent('span').next('span').show().prev('span').remove(); this.reloadMasonry(); }; BxTimelineView.prototype.showPhoto = function(oLink, sUrl) { $('#' + this._aHtmlIds['photo_popup']).dolPopupImage(sUrl, $(oLink).parent()); }; BxTimelineView.prototype.commentItem = function(oLink, sSystem, iId) { var $this = this; var oData = this._getDefaultData(); oData['system'] = sSystem; oData['id'] = iId; var oComments = $(oLink).parents('.' + this.sClassItem + ':first').find('.' + this.sClassItemComments); if(oComments.children().length > 0) { oComments.bx_anim('toggle', this._sAnimationEffect, this._iAnimationSpeed); return; } if(oLink) this.loadingInItem(oLink, true); jQuery.get ( this._sActionsUrl + 'get_comments', oData, function(oData) { if(oLink) $this.loadingInItem(oLink, false); if(!oData.content) return; oComments.html($(oData.content).hide()).children(':hidden').bxTime().bx_anim('show', $this._sAnimationEffect, $this._iAnimationSpeed); }, 'json' ); }; BxTimelineView.prototype._getPosts = function(oElement, sAction) { var $this = this; var oView = $(this.sIdView); switch(sAction) { case 'page': this.loadingInButton(oElement, true); break; default: this.loadingInBlock(oElement, true); break; } jQuery.get( this._sActionsUrl + 'get_posts/', this._getDefaultData(), function(oData) { if(oData && oData.items != undefined) { var sItems = $.trim(oData.items); switch(sAction) { case 'page': $this.loadingInButton(oElement, false); $this.appendMasonry($(sItems).bxTime()); break; default: $this.loadingInBlock(oElement, false); oView.find('.' + $this.sClassItems).bx_anim('hide', $this._sAnimationEffect, $this._iAnimationSpeed, function() { $(this).html(sItems).show().bxTime(); if($this.isMasonryEmpty()) { $this.destroyMasonry(); return; } if($this.isMasonry()) $this.reloadMasonry(); else $this.initMasonry(); }); break; } } if(oData && oData.load_more != undefined) oView.find('.' + $this.sSP + '-load-more-holder').html($.trim(oData.load_more)); if(oData && oData.back != undefined) oView.find('.' + $this.sSP + '-back-holder').html($.trim(oData.back)); }, 'json' ); };
var TasteEntriesIndexView = Backbone.View.extend({ initialize: function () { this.initial_data = $('#data').data('response'); this.collection = new TasteEntriesCollection(this.initial_data); this.render(); this.taste_entries_index_list_view = new TasteEntriesIndexListView({ el: '#entries_list', collection: this.collection }); this.taste_entries_index_form_view = new TasteEntriesIndexFormView({ el: '#entry_form', collection: this.collection }); }, render: function () { this.$el.html(''); this.$el.html(render('taste_entries/index', {})); } });
var AWS = require('./core'); var SequentialExecutor = require('./sequential_executor'); /** * The namespace used to register global event listeners for request building * and sending. */ AWS.EventListeners = { /** * @!attribute VALIDATE_CREDENTIALS * A request listener that validates whether the request is being * sent with credentials. * Handles the {AWS.Request~validate 'validate' Request event} * @example Sending a request without validating credentials * var listener = AWS.EventListeners.Core.VALIDATE_CREDENTIALS; * request.removeListener('validate', listener); * @readonly * @return [Function] * @!attribute VALIDATE_REGION * A request listener that validates whether the region is set * for a request. * Handles the {AWS.Request~validate 'validate' Request event} * @example Sending a request without validating region configuration * var listener = AWS.EventListeners.Core.VALIDATE_REGION; * request.removeListener('validate', listener); * @readonly * @return [Function] * @!attribute VALIDATE_PARAMETERS * A request listener that validates input parameters in a request. * Handles the {AWS.Request~validate 'validate' Request event} * @example Sending a request without validating parameters * var listener = AWS.EventListeners.Core.VALIDATE_PARAMETERS; * request.removeListener('validate', listener); * @example Disable parameter validation globally * AWS.EventListeners.Core.removeListener('validate', * AWS.EventListeners.Core.VALIDATE_REGION); * @readonly * @return [Function] * @!attribute SEND * A request listener that initiates the HTTP connection for a * request being sent. Handles the {AWS.Request~send 'send' Request event} * @example Replacing the HTTP handler * var listener = AWS.EventListeners.Core.SEND; * request.removeListener('send', listener); * request.on('send', function(response) { * customHandler.send(response); * }); * @return [Function] * @readonly * @!attribute HTTP_DATA * A request listener that reads data from the HTTP connection in order * to build the response data. * Handles the {AWS.Request~httpData 'httpData' Request event}. * Remove this handler if you are overriding the 'httpData' event and * do not want extra data processing and buffering overhead. * @example Disabling default data processing * var listener = AWS.EventListeners.Core.HTTP_DATA; * request.removeListener('httpData', listener); * @return [Function] * @readonly */ Core: {} /* doc hack */ }; AWS.EventListeners = { Core: new SequentialExecutor().addNamedListeners(function(add, addAsync) { addAsync('VALIDATE_CREDENTIALS', 'validate', function VALIDATE_CREDENTIALS(req, done) { if (!req.service.api.signatureVersion) return done(); // none req.service.config.getCredentials(function(err) { if (err) { req.response.error = AWS.util.error(err, {code: 'CredentialsError', message: 'Missing credentials in config'}); } done(); }); }); add('VALIDATE_REGION', 'validate', function VALIDATE_REGION(req) { if (!req.service.config.region && !req.service.isGlobalEndpoint) { req.response.error = AWS.util.error(new Error(), {code: 'ConfigError', message: 'Missing region in config'}); } }); add('BUILD_IDEMPOTENCY_TOKENS', 'validate', function BUILD_IDEMPOTENCY_TOKENS(req) { var operation = req.service.api.operations[req.operation]; if (!operation) { return; } var idempotentMembers = operation.idempotentMembers; if (!idempotentMembers.length) { return; } // creates a copy of params so user's param object isn't mutated var params = AWS.util.copy(req.params); for (var i = 0, iLen = idempotentMembers.length; i < iLen; i++) { if (!params[idempotentMembers[i]]) { // add the member params[idempotentMembers[i]] = AWS.util.uuid.v4(); } } req.params = params; }); add('VALIDATE_PARAMETERS', 'validate', function VALIDATE_PARAMETERS(req) { var rules = req.service.api.operations[req.operation].input; var validation = req.service.config.paramValidation; new AWS.ParamValidator(validation).validate(rules, req.params); }); addAsync('COMPUTE_SHA256', 'afterBuild', function COMPUTE_SHA256(req, done) { req.haltHandlersOnError(); var operation = req.service.api.operations[req.operation]; var authtype = operation ? operation.authtype : ''; if (!req.service.api.signatureVersion && !authtype) return done(); // none if (req.service.getSignerClass(req) === AWS.Signers.V4) { var body = req.httpRequest.body || ''; if (authtype.indexOf('unsigned-body') >= 0) { req.httpRequest.headers['X-Amz-Content-Sha256'] = 'UNSIGNED-PAYLOAD'; return done(); } AWS.util.computeSha256(body, function(err, sha) { if (err) { done(err); } else { req.httpRequest.headers['X-Amz-Content-Sha256'] = sha; done(); } }); } else { done(); } }); add('SET_CONTENT_LENGTH', 'afterBuild', function SET_CONTENT_LENGTH(req) { if (req.httpRequest.headers['Content-Length'] === undefined) { var length = AWS.util.string.byteLength(req.httpRequest.body); req.httpRequest.headers['Content-Length'] = length; } }); add('SET_HTTP_HOST', 'afterBuild', function SET_HTTP_HOST(req) { req.httpRequest.headers['Host'] = req.httpRequest.endpoint.host; }); add('RESTART', 'restart', function RESTART() { var err = this.response.error; if (!err || !err.retryable) return; this.httpRequest = new AWS.HttpRequest( this.service.endpoint, this.service.region ); if (this.response.retryCount < this.service.config.maxRetries) { this.response.retryCount++; } else { this.response.error = null; } }); addAsync('SIGN', 'sign', function SIGN(req, done) { var service = req.service; var operation = req.service.api.operations[req.operation]; var authtype = operation ? operation.authtype : ''; if (!service.api.signatureVersion && !authtype) return done(); // none service.config.getCredentials(function (err, credentials) { if (err) { req.response.error = err; return done(); } try { var date = AWS.util.date.getDate(); var SignerClass = service.getSignerClass(req); var signer = new SignerClass(req.httpRequest, service.api.signingName || service.api.endpointPrefix, { signatureCache: service.config.signatureCache, operation: operation }); signer.setServiceClientId(service._clientId); // clear old authorization headers delete req.httpRequest.headers['Authorization']; delete req.httpRequest.headers['Date']; delete req.httpRequest.headers['X-Amz-Date']; // add new authorization signer.addAuthorization(credentials, date); req.signedAt = date; } catch (e) { req.response.error = e; } done(); }); }); add('VALIDATE_RESPONSE', 'validateResponse', function VALIDATE_RESPONSE(resp) { if (this.service.successfulResponse(resp, this)) { resp.data = {}; resp.error = null; } else { resp.data = null; resp.error = AWS.util.error(new Error(), {code: 'UnknownError', message: 'An unknown error occurred.'}); } }); addAsync('SEND', 'send', function SEND(resp, done) { resp.httpResponse._abortCallback = done; resp.error = null; resp.data = null; function callback(httpResp) { resp.httpResponse.stream = httpResp; httpResp.on('headers', function onHeaders(statusCode, headers, statusMessage) { resp.request.emit( 'httpHeaders', [statusCode, headers, resp, statusMessage] ); if (!resp.httpResponse.streaming) { if (AWS.HttpClient.streamsApiVersion === 2) { // streams2 API check httpResp.on('readable', function onReadable() { var data = httpResp.read(); if (data !== null) { resp.request.emit('httpData', [data, resp]); } }); } else { // legacy streams API httpResp.on('data', function onData(data) { resp.request.emit('httpData', [data, resp]); }); } } }); httpResp.on('end', function onEnd() { resp.request.emit('httpDone'); done(); }); } function progress(httpResp) { httpResp.on('sendProgress', function onSendProgress(value) { resp.request.emit('httpUploadProgress', [value, resp]); }); httpResp.on('receiveProgress', function onReceiveProgress(value) { resp.request.emit('httpDownloadProgress', [value, resp]); }); } function error(err) { resp.error = AWS.util.error(err, { code: 'NetworkingError', region: resp.request.httpRequest.region, hostname: resp.request.httpRequest.endpoint.hostname, retryable: true }); resp.request.emit('httpError', [resp.error, resp], function() { done(); }); } function executeSend() { var http = AWS.HttpClient.getInstance(); var httpOptions = resp.request.service.config.httpOptions || {}; try { var stream = http.handleRequest(resp.request.httpRequest, httpOptions, callback, error); progress(stream); } catch (err) { error(err); } } var timeDiff = (AWS.util.date.getDate() - this.signedAt) / 1000; if (timeDiff >= 60 * 10) { // if we signed 10min ago, re-sign this.emit('sign', [this], function(err) { if (err) done(err); else executeSend(); }); } else { executeSend(); } }); add('HTTP_HEADERS', 'httpHeaders', function HTTP_HEADERS(statusCode, headers, resp, statusMessage) { resp.httpResponse.statusCode = statusCode; resp.httpResponse.statusMessage = statusMessage; resp.httpResponse.headers = headers; resp.httpResponse.body = new AWS.util.Buffer(''); resp.httpResponse.buffers = []; resp.httpResponse.numBytes = 0; var dateHeader = headers.date || headers.Date; if (dateHeader) { var serverTime = Date.parse(dateHeader); if (resp.request.service.config.correctClockSkew && AWS.util.isClockSkewed(serverTime)) { AWS.util.applyClockOffset(serverTime); } } }); add('HTTP_DATA', 'httpData', function HTTP_DATA(chunk, resp) { if (chunk) { if (AWS.util.isNode()) { resp.httpResponse.numBytes += chunk.length; var total = resp.httpResponse.headers['content-length']; var progress = { loaded: resp.httpResponse.numBytes, total: total }; resp.request.emit('httpDownloadProgress', [progress, resp]); } resp.httpResponse.buffers.push(new AWS.util.Buffer(chunk)); } }); add('HTTP_DONE', 'httpDone', function HTTP_DONE(resp) { // convert buffers array into single buffer if (resp.httpResponse.buffers && resp.httpResponse.buffers.length > 0) { var body = AWS.util.buffer.concat(resp.httpResponse.buffers); resp.httpResponse.body = body; } delete resp.httpResponse.numBytes; delete resp.httpResponse.buffers; }); add('FINALIZE_ERROR', 'retry', function FINALIZE_ERROR(resp) { if (resp.httpResponse.statusCode) { resp.error.statusCode = resp.httpResponse.statusCode; if (resp.error.retryable === undefined) { resp.error.retryable = this.service.retryableError(resp.error, this); } } }); add('INVALIDATE_CREDENTIALS', 'retry', function INVALIDATE_CREDENTIALS(resp) { if (!resp.error) return; switch (resp.error.code) { case 'RequestExpired': // EC2 only case 'ExpiredTokenException': case 'ExpiredToken': resp.error.retryable = true; resp.request.service.config.credentials.expired = true; } }); add('EXPIRED_SIGNATURE', 'retry', function EXPIRED_SIGNATURE(resp) { var err = resp.error; if (!err) return; if (typeof err.code === 'string' && typeof err.message === 'string') { if (err.code.match(/Signature/) && err.message.match(/expired/)) { resp.error.retryable = true; } } }); add('CLOCK_SKEWED', 'retry', function CLOCK_SKEWED(resp) { if (!resp.error) return; if (this.service.clockSkewError(resp.error) && this.service.config.correctClockSkew && AWS.config.isClockSkewed) { resp.error.retryable = true; } }); add('REDIRECT', 'retry', function REDIRECT(resp) { if (resp.error && resp.error.statusCode >= 300 && resp.error.statusCode < 400 && resp.httpResponse.headers['location']) { this.httpRequest.endpoint = new AWS.Endpoint(resp.httpResponse.headers['location']); this.httpRequest.headers['Host'] = this.httpRequest.endpoint.host; resp.error.redirect = true; resp.error.retryable = true; } }); add('RETRY_CHECK', 'retry', function RETRY_CHECK(resp) { if (resp.error) { if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) { resp.error.retryDelay = 0; } else if (resp.retryCount < resp.maxRetries) { resp.error.retryDelay = this.service.retryDelays(resp.retryCount) || 0; } } }); addAsync('RESET_RETRY_STATE', 'afterRetry', function RESET_RETRY_STATE(resp, done) { var delay, willRetry = false; if (resp.error) { delay = resp.error.retryDelay || 0; if (resp.error.retryable && resp.retryCount < resp.maxRetries) { resp.retryCount++; willRetry = true; } else if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) { resp.redirectCount++; willRetry = true; } } if (willRetry) { resp.error = null; setTimeout(done, delay); } else { done(); } }); }), CorePost: new SequentialExecutor().addNamedListeners(function(add) { add('EXTRACT_REQUEST_ID', 'extractData', AWS.util.extractRequestId); add('EXTRACT_REQUEST_ID', 'extractError', AWS.util.extractRequestId); add('ENOTFOUND_ERROR', 'httpError', function ENOTFOUND_ERROR(err) { if (err.code === 'NetworkingError' && err.errno === 'ENOTFOUND') { var message = 'Inaccessible host: `' + err.hostname + '\'. This service may not be available in the `' + err.region + '\' region.'; this.response.error = AWS.util.error(new Error(message), { code: 'UnknownEndpoint', region: err.region, hostname: err.hostname, retryable: true, originalError: err }); } }); }), Logger: new SequentialExecutor().addNamedListeners(function(add) { add('LOG_REQUEST', 'complete', function LOG_REQUEST(resp) { var req = resp.request; var logger = req.service.config.logger; if (!logger) return; function buildMessage() { var time = AWS.util.date.getDate().getTime(); var delta = (time - req.startTime.getTime()) / 1000; var ansi = logger.isTTY ? true : false; var status = resp.httpResponse.statusCode; var params = require('util').inspect(req.params, true, null); var message = ''; if (ansi) message += '\x1B[33m'; message += '[AWS ' + req.service.serviceIdentifier + ' ' + status; message += ' ' + delta.toString() + 's ' + resp.retryCount + ' retries]'; if (ansi) message += '\x1B[0;1m'; message += ' ' + AWS.util.string.lowerFirst(req.operation); message += '(' + params + ')'; if (ansi) message += '\x1B[0m'; return message; } var line = buildMessage(); if (typeof logger.log === 'function') { logger.log(line); } else if (typeof logger.write === 'function') { logger.write(line + '\n'); } }); }), Json: new SequentialExecutor().addNamedListeners(function(add) { var svc = require('./protocol/json'); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }), Rest: new SequentialExecutor().addNamedListeners(function(add) { var svc = require('./protocol/rest'); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }), RestJson: new SequentialExecutor().addNamedListeners(function(add) { var svc = require('./protocol/rest_json'); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }), RestXml: new SequentialExecutor().addNamedListeners(function(add) { var svc = require('./protocol/rest_xml'); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }), Query: new SequentialExecutor().addNamedListeners(function(add) { var svc = require('./protocol/query'); add('BUILD', 'build', svc.buildRequest); add('EXTRACT_DATA', 'extractData', svc.extractData); add('EXTRACT_ERROR', 'extractError', svc.extractError); }) };
var searchData= [ ['changedetailsapi',['ChangeDetailsAPI',['../classbackend_1_1api_1_1users_1_1_change_details_a_p_i.html',1,'backend::api::users']]], ['chatmessageapi',['ChatMessageApi',['../classbackend_1_1api_1_1messages_1_1_chat_message_api.html',1,'backend::api::messages']]], ['chatuserapi',['ChatUserApi',['../classbackend_1_1api_1_1messages_1_1_chat_user_api.html',1,'backend::api::messages']]], ['chatuserretrieveapi',['ChatUserRetrieveApi',['../classbackend_1_1api_1_1messages_1_1_chat_user_retrieve_api.html',1,'backend::api::messages']]] ];
/* * The trigger API * * - Documentation: ../docs/input-trigger.md */ +function ($) { "use strict"; var TriggerOn = function (element, options) { var $el = this.$el = $(element); this.options = options || {}; if (this.options.triggerCondition === false) throw new Error('Trigger condition is not specified.') if (this.options.trigger === false) throw new Error('Trigger selector is not specified.') if (this.options.triggerAction === false) throw new Error('Trigger action is not specified.') this.triggerCondition = this.options.triggerCondition if (this.options.triggerCondition.indexOf('value') == 0) { var match = this.options.triggerCondition.match(/[^[\]]+(?=])/g) this.triggerCondition = 'value' this.triggerConditionValue = (match) ? match : [""] } this.triggerParent = this.options.triggerClosestParent !== undefined ? $el.closest(this.options.triggerClosestParent) : undefined if ( this.triggerCondition == 'checked' || this.triggerCondition == 'unchecked' || this.triggerCondition == 'value' ) { $(document).on('change', this.options.trigger, $.proxy(this.onConditionChanged, this)) } var self = this $el.on('oc.triggerOn.update', function(e){ e.stopPropagation() self.onConditionChanged() }) self.onConditionChanged() } TriggerOn.prototype.onConditionChanged = function() { if (this.triggerCondition == 'checked') { this.updateTarget(!!$(this.options.trigger + ':checked', this.triggerParent).length) } else if (this.triggerCondition == 'unchecked') { this.updateTarget(!$(this.options.trigger + ':checked', this.triggerParent).length) } else if (this.triggerCondition == 'value') { var trigger, triggerValue = '' trigger = $(this.options.trigger, this.triggerParent) .not('input[type=checkbox], input[type=radio], input[type=button], input[type=submit]') if (!trigger.length) { trigger = $(this.options.trigger, this.triggerParent) .not(':not(input[type=checkbox]:checked, input[type=radio]:checked)') } if (!!trigger.length) { triggerValue = trigger.val() } this.updateTarget($.inArray(triggerValue, this.triggerConditionValue) != -1) } } TriggerOn.prototype.updateTarget = function(status) { var self = this, actions = this.options.triggerAction.split('|') $.each(actions, function(index, action) { self.updateTargetAction(action, status) }) $(window).trigger('resize') this.$el.trigger('oc.triggerOn.afterUpdate', status) } TriggerOn.prototype.updateTargetAction = function(action, status) { if (action == 'show') { this.$el .toggleClass('hide', !status) .trigger('hide.oc.triggerapi', [!status]) } else if (action == 'hide') { this.$el .toggleClass('hide', status) .trigger('hide.oc.triggerapi', [status]) } else if (action == 'enable') { this.$el .prop('disabled', !status) .toggleClass('control-disabled', !status) .trigger('disable.oc.triggerapi', [!status]) } else if (action == 'disable') { this.$el .prop('disabled', status) .toggleClass('control-disabled', status) .trigger('disable.oc.triggerapi', [status]) } else if (action == 'empty' && status) { this.$el .not('input[type=checkbox], input[type=radio], input[type=button], input[type=submit]') .val('') this.$el .not(':not(input[type=checkbox], input[type=radio])') .prop('checked', false) this.$el .trigger('empty.oc.triggerapi') .trigger('change') } if (action == 'show' || action == 'hide') { this.fixButtonClasses() } } TriggerOn.prototype.fixButtonClasses = function() { var group = this.$el.closest('.btn-group') if (group.length > 0 && this.$el.is(':last-child')) this.$el.prev().toggleClass('last', this.$el.hasClass('hide')) } TriggerOn.DEFAULTS = { triggerAction: false, triggerCondition: false, triggerClosestParent: undefined, trigger: false } // TRIGGERON PLUGIN DEFINITION // ============================ var old = $.fn.triggerOn $.fn.triggerOn = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('oc.triggerOn') var options = $.extend({}, TriggerOn.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('oc.triggerOn', (data = new TriggerOn(this, options))) }) } $.fn.triggerOn.Constructor = TriggerOn // TRIGGERON NO CONFLICT // ================= $.fn.triggerOn.noConflict = function () { $.fn.triggerOn = old return this } // TRIGGERON DATA-API // =============== $(document).render(function(){ $('[data-trigger]').triggerOn() }) }(window.jQuery);
Astro.createValidator({ name: 'gte', validate: function(fieldValue, fieldName, compareValue) { if (_.isFunction(compareValue)) { compareValue = compareValue.call(this); } return fieldValue >= compareValue; }, events: { validationerror: function(e) { var fieldName = e.data.field; var compareValue = e.data.options; if (_.isFunction(compareValue)) { compareValue = compareValue.call(this); } e.data.message = 'The "' + fieldName + '" field\'s value has to be greater than or equal "' + compareValue + '"'; } } });
define(function(require) { // Include parent class var utility = require('../Helper/utility.js') var Human = require('./Human.js') var Teacher = Human.extend({ init: function(firstName, lastName, age, specialty) { Human.init.apply(this, arguments); this.specialty = specialty; return this; }, introduce: function() { return Human.introduce.apply(this) + ", Specialty: " + this.specialty; } }); return Teacher; })
/** ! * Google Drive File Picker Example * By Daniel Lo Nigro (http://dan.cx/) */ (function () { /** * Initialise a Google Driver file picker */ var FilePicker = window.FilePicker = function (options) { // Config this.apiKey = options.apiKey this.clientId = options.clientId // Elements this.buttonEl = options.buttonEl // Events this.onSelect = options.onSelect this.buttonEl.on('click', this.open.bind(this)) // Disable the button until the API loads, as it won't work properly until then. this.buttonEl.prop('disabled', true) // Load the drive API window.gapi.client.setApiKey(this.apiKey) window.gapi.client.load('drive', 'v2', this._driveApiLoaded.bind(this)) window.google.load('picker', '1', { callback: this._pickerApiLoaded.bind(this) }) } FilePicker.prototype = { /** * Open the file picker. */ open: function () { // Check if the user has already authenticated var token = window.gapi.auth.getToken() if (token) { this._showPicker() } else { // The user has not yet authenticated with Google // We need to do the authentication before displaying the Drive picker. this._doAuth(false, function () { this._showPicker() }.bind(this)) } }, /** * Show the file picker once authentication has been done. * @private */ _showPicker: function () { var accessToken = window.gapi.auth.getToken().access_token var view = new window.google.picker.DocsView() view.setMimeTypes('text/markdown,text/html') view.setIncludeFolders(true) view.setOwnedByMe(true) this.picker = new window.google.picker.PickerBuilder() .enableFeature(window.google.picker.Feature.NAV_HIDDEN) .addView(view) .setAppId(this.clientId) .setOAuthToken(accessToken) .setCallback(this._pickerCallback.bind(this)) .build() .setVisible(true) }, /** * Called when a file has been selected in the Google Drive file picker. * @private */ _pickerCallback: function (data) { if (data[window.google.picker.Response.ACTION] === window.google.picker.Action.PICKED) { var file = data[window.google.picker.Response.DOCUMENTS][0] var id = file[window.google.picker.Document.ID] var request = window.gapi.client.drive.files.get({ fileId: id }) request.execute(this._fileGetCallback.bind(this)) } }, /** * Called when file details have been retrieved from Google Drive. * @private */ _fileGetCallback: function (file) { if (this.onSelect) { this.onSelect(file) } }, /** * Called when the Google Drive file picker API has finished loading. * @private */ _pickerApiLoaded: function () { this.buttonEl.prop('disabled', false) }, /** * Called when the Google Drive API has finished loading. * @private */ _driveApiLoaded: function () { this._doAuth(true) }, /** * Authenticate with Google Drive via the Google JavaScript API. * @private */ _doAuth: function (immediate, callback) { window.gapi.auth.authorize({ client_id: this.clientId, scope: 'https://www.googleapis.com/auth/drive.readonly', immediate: immediate }, callback || function () {}) } } }())
version https://git-lfs.github.com/spec/v1 oid sha256:866863ba9feea81e907968a3bc09f6876511c89dbf5be91d1ed9358a2b6ad4a3 size 563
import { createReturnPromise } from '../helpers' function getUserFactory() { function getUser({ firebase, path }) { return createReturnPromise(firebase.getUser(), path) } return getUser } export default getUserFactory
Joshfire.define(['joshfire/class', 'joshfire/tree.ui', 'joshfire/uielements/list', 'joshfire/uielements/panel', 'joshfire/uielements/panel.manager', 'joshfire/uielements/button', 'src/ui-components'], function(Class, UITree, List, Panel, PanelManager, Button, UI) { return Class(UITree, { buildTree: function() { var app = this.app; return [ { id: 'sidebarleft', type: Panel, children: [ { id: 'menu', type: List, dataPath: '/datasourcelist/', itemInnerTemplate: '<div class="picto item-<%= item.config.col %>"></div><div class="name"><%= item.name %></div>', onData: function() {} // trigger data, WTF? } ] }, { id: 'sidebarright', type: Panel, children: [ { id: 'header', type: Panel, htmlClass: 'header', children: [ { id: 'prev', type: Button, label: 'Prev', autoShow: false }, { id: 'title', // the title or the logo type: Panel, innerTemplate: UI.tplHeader } ] }, { id: 'content', type: PanelManager, uiMaster: '/sidebarleft/menu', children: [ { id: 'itemList', type: List, loadingTemplate: '<div class="loading"></div>', itemTemplate: "<li id='<%=itemHtmlId%>' " + "data-josh-ui-path='<%= path %>' data-josh-grid-id='<%= item.id %>'" + "class='josh-List joshover item-<%= (item['@type'] || item.itemType).replace('/', '') %> mainitemlist " + // grid view "<% if ((item['@type'] || item.itemType) === 'ImageObject') { %>" + "grid" + "<% } else if ((item['@type'] || item.itemType) === 'VideoObject') { %>" + // two rows "rows" + "<% } else { %>" + // list view "list" + "<% } %>" + "' >" + "<%= itemInner %>" + "</li>", itemInnerTemplate: '<% if ((item["@type"] || item.itemType) === "VideoObject") { %>' + '<div class="title"><%= item.name %></div>' + UI.getItemDescriptionTemplate(130) + UI.tplItemPreview + '<span class="list-arrow"></span>' + '<% } else if ((item["@type"] || item.itemType) === "ImageObject") { %>' + UI.tplItemThumbnail + '<% } else if ((item["@type"] || item.itemType) === "Article/Status") { %>' + UI.tplTweetItem + '<% } else if ((item["@type"] || item.itemType) === "Event") { %>' + UI.tplEventItem + '<% } else { %>' + '<%= item.name %><span class="list-arrow"></span>' + '<% } %>' }, { id: 'detail', type: Panel, htmlClass: 'detailView', uiDataMaster: '/sidebarright/content/itemList', loadingTemplate: '<div class="loading"></div>', autoShow: false, children: [ { // Article (default) id: 'article', type: Panel, uiDataMaster: '/sidebarright/content/itemList', forceDataPathRefresh: true, loadingTemplate: '<div class="loading"></div>', innerTemplate: '<div class="title"><h1><%= data.name %></h1>' + UI.tplDataAuthor + '<% if (data.articleBody) { print(data.articleBody); } %>', onData: function(ui) { var thisEl = app.ui.element('/sidebarright/content/detail/article').htmlEl; var type = ui.data['@type'] || ui.data.itemType; if (type === 'VideoObject' || type === 'ImageObject' || type === 'Event' || type === 'Article/Status' ) { $(thisEl).hide(); } else { $(thisEl).show(); } } }, { // Twitter id: 'twitter', type: Panel, uiDataMaster: '/sidebarright/content/itemList', forceDataPathRefresh: true, loadingTemplate: '<div class="loading"></div>', innerTemplate: UI.tplTweetPage, onData: function(ui) { var thisEl = app.ui.element('/sidebarright/content/detail/twitter').htmlEl; if ((ui.data['@type'] || ui.data.itemType) === 'Article/Status') { $(thisEl).show(); } else { $(thisEl).hide(); } } }, { // Flickr id: 'image', type: Panel, uiDataMaster: '/sidebarright/content/itemList', forceDataPathRefresh: true, loadingTemplate: '<div class="loading"></div>', innerTemplate: '<img src="<%= data.contentURL %>" />', onData: function(ui) { var thisEl = app.ui.element('/sidebarright/content/detail/image').htmlEl; if ((ui.data['@type'] || ui.data.itemType) === 'ImageObject') { $(thisEl).show(); } else { $(thisEl).hide(); } } }, { // Event id: 'event', type: Panel, uiDataMaster: '/sidebarright/content/itemList', forceDataPathRefresh: true, loadingTemplate: '<div class="loading"></div>', innerTemplate: UI.tplEventPage, onData: function(ui) { var thisEl = app.ui.element('/sidebarright/content/detail/event').htmlEl; if ((ui.data['@type'] || ui.data.itemType) === 'Event') { $(thisEl).show(); } else { $(thisEl).hide(); } } }, { // Video id: 'video', type: Panel, uiDataMaster: '/sidebarright/content/itemList', forceDataPathRefresh: true, loadingTemplate: '<div class="loading"></div>', onData: function(ui) { var thisEl = app.ui.element('/sidebarright/content/detail/video').htmlEl, player = app.ui.element('/sidebarright/content/detail/video/player.youtube'); if (((ui.data['@type'] || ui.data.itemType) === 'VideoObject') && ui.data.publisher && (ui.data.publisher.name === 'Youtube')) { player.playWithStaticUrl({ url: ui.data.url.replace('http://www.youtube.com/watch?v=', ''), width: '480px' }); $(thisEl).show(); } else { $(thisEl).hide(); } }, children: [ { id: 'title', type: Panel, uiDataMaster: '/sidebarright/content/itemList', innerTemplate: '<div class="title"><h1><%= data.name %></h1>' + UI.tplDataAuthor + '</div>' }, { id: 'player.youtube', type: 'video.youtube', autoShow: true, controls: true, noAutoPlay: false } ] } ] }, { id: 'about', type: Panel, loadingTemplate: '<div class="loading"></div>', autoShow: false, innerTemplate: UI.tplAboutPage } ] } ] } ]; } }); });
'use strict'; module.exports = function (context) { return { CallExpression: function (node) { if (node.callee.name === 'alert') { context.report(node, 'testing custom rules.'); } } }; };
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- function echo(msg) { WScript.Echo(msg); } function guarded_call(func) { try { func(); } catch(e) { echo("Exception: " + e.name + " : " + e.message); } } function dump_args() { var args = ""; for (var i = 0; i < arguments.length; i++) { if (i > 0) { args += ", "; } args += arguments[i]; } echo("Called with this: " + typeof this + "[" + this + "], args: [" + args + "]"); } // 1. If IsCallable(func) is false, throw TypeError var noncallable = { apply: Function.prototype.apply }; echo("--- f is not callable ---"); guarded_call(function() { noncallable.apply(); }); guarded_call(function() { noncallable.apply({}, [1, 2, 3]); }); // 2. If argArray is null or undefined, call func with an empty list of arguments var o = {}; echo("\n--- f.apply(x) ---"); guarded_call(function() { dump_args.apply(o); }); echo("\n--- f.apply(x, null), f.apply(x, undefined) ---"); guarded_call(function() { dump_args.apply(o, null); }); guarded_call(function() { dump_args.apply(o, undefined); }); // 3. Type(argArray) is invalid echo("\n--- f.apply(x, 123), f.apply(x, 'string'), f.apply(x, true) ---"); guarded_call(function() { dump_args.apply(o, 123); }); guarded_call(function() { dump_args.apply(o, 'string'); }); guarded_call(function() { dump_args.apply(o, true); }); // 5, 7 argArray.length is invalid echo("\n--- f.apply(x, obj), obj.length is null/undefined/NaN/string/OutOfRange ---"); guarded_call(function() { dump_args.apply(o, {length: null}); }); guarded_call(function() { dump_args.apply(o, {length: undefined}); }); guarded_call(function() { dump_args.apply(o, {length: NaN}); }); guarded_call(function() { dump_args.apply(o, {length: 'string'}); }); guarded_call(function() { dump_args.apply(o, {length: 4294967295 + 1}); //UINT32_MAX + 1 }); guarded_call(function() { dump_args.apply(o, {length: -1}); }); echo("\n--- f.apply(x, arr), arr.length is huge ---"); var huge_array_length = []; huge_array_length.length = 2147483647; //INT32_MAX guarded_call(function() { dump_args.apply(o, huge_array_length); }); echo("\n--- f.apply(x, obj), obj.length is huge ---"); guarded_call(function() { dump_args.apply(o, {length: 4294967295}); //UINT32_MAX }); // Normal usage -- argArray tests echo("\n--- f.apply(x, arr) ---"); dump_args.apply(o, []); dump_args.apply(o, [1]); dump_args.apply(o, [2, 3, NaN, null, undefined, false, "hello", o]); echo("\n--- f.apply(x, arr) arr.length increased ---"); var arr = [1, 2]; arr.length = 5; dump_args.apply(o, arr); echo("\n--- f.apply(x, arguments) ---"); function apply_arguments() { dump_args.apply(o, arguments); } apply_arguments(); apply_arguments(1); apply_arguments(2, 3, NaN, null, undefined, false, "hello", o); echo("\n--- f.apply(x, obj) ---"); guarded_call(function() { dump_args.apply(o, { length: 0 }); }); guarded_call(function() { dump_args.apply(o, { length: 1, "0": 1 }); }); guarded_call(function() { dump_args.apply(o, { length: 8, "0": 2, "1": 3, "2": NaN, "3": null, "4": undefined, "5": false, "6": "hello", "7": o }); }); // Normal usage -- thisArg tests function f1() { this.x1 = "hello"; } echo("\n--- f.apply(), f.apply(null), f.apply(undefined), global x1 should be changed ---"); f1.apply(); echo("global x1 : " + x1); x1 = 0; f1.apply(null); echo("global x1 : " + x1); x1 = 0; f1.apply(undefined); echo("global x1 : " + x1); echo("\n--- f.apply(x), global x1 should NOT be changed ---"); var o = {}; x1 = 0; f1.apply(o); echo("global x1 : " + x1); echo("o.x1 : " + o.x1); // apply on non-objects -- test thisArg function apply_non_object(func, doEcho) { var echo_if = function(msg) { if (doEcho) { echo(msg); } }; guarded_call(function() { echo_if(func.apply()); }); guarded_call(function() { echo_if(func.apply(null)); }); guarded_call(function() { echo_if(func.apply(undefined)); }); guarded_call(function() { echo_if(func.apply(123)); }); guarded_call(function() { echo_if(func.apply(true)); }); guarded_call(function() { echo_if(func.apply("string")); }); } echo("\n--- f.apply(v), v is missing/null/undefined/123/true/'string' ---"); apply_non_object(dump_args); // // ES5: String.prototype.charCodeAt calls CheckObjectCoercible(thisArg). It should throw // when thisArg is missing/null/undefined. // echo("\n--- f.apply(v), v is missing/null/undefined/123/true/'string', f: string.charCodeAt ---"); apply_non_object(String.prototype.charCodeAt, true); echo("\n--- f.apply(v), v is missing/null/undefined/123/true/'string', f: string.charAt ---"); apply_non_object(String.prototype.charAt, true); // // Similarly, test thisArg behavior in Function.prototype.call // // call on non-objects -- test thisArg function call_non_object(func, doEcho) { var echo_if = function(msg) { if (doEcho) { echo(msg); } }; guarded_call(function() { echo_if(func.call()); }); guarded_call(function() { echo_if(func.call(null)); }); guarded_call(function() { echo_if(func.call(undefined)); }); guarded_call(function() { echo_if(func.call(123)); }); guarded_call(function() { echo_if(func.call(true)); }); guarded_call(function() { echo_if(func.call("string")); }); } echo("\n--- f.call(v), v is missing/null/undefined/123/true/'string' ---"); call_non_object(dump_args); echo("\n--- f.call(v), v is missing/null/undefined/123/true/'string', f: string.charCodeAt ---"); call_non_object(String.prototype.charCodeAt, true); echo("\n--- f.call(v), v is missing/null/undefined/123/true/'string', f: string.charAt ---"); call_non_object(String.prototype.charAt, true);
/** * Rooms * Pokemon Showdown - http://pokemonshowdown.com/ * * Every chat room and battle is a room, and what they do is done in * rooms.js. There's also a global room which every user is in, and * handles miscellaneous things like welcoming the user. * * @license MIT license */ const TIMEOUT_EMPTY_DEALLOCATE = 10 * 60 * 1000; const TIMEOUT_INACTIVE_DEALLOCATE = 40 * 60 * 1000; const REPORT_USER_STATS_INTERVAL = 1000 * 60 * 10; var fs = require('fs'); /* global Rooms: true */ var Rooms = module.exports = getRoom; var rooms = Rooms.rooms = Object.create(null); var Room = (function () { function Room(roomid, title) { this.id = roomid; this.title = (title || roomid); this.users = Object.create(null); this.log = []; this.bannedUsers = Object.create(null); this.bannedIps = Object.create(null); } Room.prototype.title = ""; Room.prototype.type = 'chat'; Room.prototype.lastUpdate = 0; Room.prototype.log = null; Room.prototype.users = null; Room.prototype.userCount = 0; Room.prototype.send = function (message, errorArgument) { if (errorArgument) throw new Error("Use Room#sendUser"); if (this.id !== 'lobby') message = '>' + this.id + '\n' + message; Sockets.channelBroadcast(this.id, message); }; Room.prototype.sendAuth = function (message) { for (var i in this.users) { var user = this.users[i]; if (user.connected && user.can('receiveauthmessages', null, this)) { user.sendTo(this, message); } } }; Room.prototype.sendUser = function (user, message) { user.sendTo(this, message); }; Room.prototype.add = function (message) { if (typeof message !== 'string') throw new Error("Deprecated message type"); this.logEntry(message); if (this.logTimes && message.substr(0, 3) === '|c|') { message = '|c:|' + (~~(Date.now() / 1000)) + '|' + message.substr(3); } this.log.push(message); }; Room.prototype.logEntry = function () {}; Room.prototype.addRaw = function (message) { this.add('|raw|' + message); }; Room.prototype.getLogSlice = function (amount) { var log = this.log.slice(amount); log.unshift('|:|' + (~~(Date.now() / 1000))); return log; }; Room.prototype.chat = function (user, message, connection) { // Battle actions are actually just text commands that are handled in // parseCommand(), which in turn often calls Simulator.prototype.sendFor(). // Sometimes the call to sendFor is done indirectly, by calling // room.decision(), where room.constructor === BattleRoom. message = CommandParser.parse(message, this, user, connection); if (message) { this.add('|c|' + user.getIdentity(this.id) + '|' + message); } this.update(); }; return Room; })(); var GlobalRoom = (function () { function GlobalRoom(roomid) { this.id = roomid; // init battle rooms this.battleCount = 0; this.searchers = []; // Never do any other file IO synchronously // but this is okay to prevent race conditions as we start up PS this.lastBattle = 0; try { this.lastBattle = parseInt(fs.readFileSync('logs/lastbattle.txt')) || 0; } catch (e) {} // file doesn't exist [yet] this.chatRoomData = []; try { this.chatRoomData = JSON.parse(fs.readFileSync('config/chatrooms.json')); if (!Array.isArray(this.chatRoomData)) this.chatRoomData = []; } catch (e) {} // file doesn't exist [yet] if (!this.chatRoomData.length) { this.chatRoomData = [{ title: 'Lobby', isOfficial: true, autojoin: true }, { title: 'Staff', isPrivate: true, staffRoom: true, staffAutojoin: true }]; } this.chatRooms = []; this.autojoin = []; // rooms that users autojoin upon connecting this.staffAutojoin = []; // rooms that staff autojoin upon connecting for (var i = 0; i < this.chatRoomData.length; i++) { if (!this.chatRoomData[i] || !this.chatRoomData[i].title) { console.log('ERROR: Room number ' + i + ' has no data.'); continue; } var id = toId(this.chatRoomData[i].title); console.log("NEW CHATROOM: " + id); var room = Rooms.createChatRoom(id, this.chatRoomData[i].title, this.chatRoomData[i]); this.chatRooms.push(room); if (room.autojoin) this.autojoin.push(id); if (room.staffAutojoin) this.staffAutojoin.push(id); } // this function is complex in order to avoid several race conditions var self = this; this.writeNumRooms = (function () { var writing = false; var lastBattle; // last lastBattle to be written to file var finishWriting = function () { writing = false; if (lastBattle < self.lastBattle) { self.writeNumRooms(); } }; return function () { if (writing) return; // batch writing lastbattle.txt for every 10 battles if (lastBattle >= self.lastBattle) return; lastBattle = self.lastBattle + 10; writing = true; fs.writeFile('logs/lastbattle.txt.0', '' + lastBattle, function () { // rename is atomic on POSIX, but will throw an error on Windows fs.rename('logs/lastbattle.txt.0', 'logs/lastbattle.txt', function (err) { if (err) { // This should only happen on Windows. fs.writeFile('logs/lastbattle.txt', '' + lastBattle, finishWriting); return; } finishWriting(); }); }); }; })(); this.writeChatRoomData = (function () { var writing = false; var writePending = false; // whether or not a new write is pending var finishWriting = function () { writing = false; if (writePending) { writePending = false; self.writeChatRoomData(); } }; return function () { if (writing) { writePending = true; return; } writing = true; var data = JSON.stringify(self.chatRoomData).replace(/\{"title"\:/g, '\n{"title":').replace(/\]$/, '\n]'); fs.writeFile('config/chatrooms.json.0', data, function () { // rename is atomic on POSIX, but will throw an error on Windows fs.rename('config/chatrooms.json.0', 'config/chatrooms.json', function (err) { if (err) { // This should only happen on Windows. fs.writeFile('config/chatrooms.json', data, finishWriting); return; } finishWriting(); }); }); }; })(); // init users this.users = {}; this.userCount = 0; // cache of `Object.size(this.users)` this.maxUsers = 0; this.maxUsersDate = 0; this.reportUserStatsInterval = setInterval( this.reportUserStats.bind(this), REPORT_USER_STATS_INTERVAL ); } GlobalRoom.prototype.type = 'global'; GlobalRoom.prototype.formatListText = '|formats'; GlobalRoom.prototype.reportUserStats = function () { if (this.maxUsersDate) { LoginServer.request('updateuserstats', { date: this.maxUsersDate, users: this.maxUsers }, function () {}); this.maxUsersDate = 0; } LoginServer.request('updateuserstats', { date: Date.now(), users: this.userCount }, function () {}); }; GlobalRoom.prototype.getFormatListText = function () { var formatListText = '|formats'; var curSection = ''; for (var i in Tools.data.Formats) { var format = Tools.data.Formats[i]; if (!format.challengeShow && !format.searchShow) continue; var section = format.section; if (section === undefined) section = format.mod; if (!section) section = ''; if (section !== curSection) { curSection = section; formatListText += '|,' + (format.column || 1) + '|' + section; } formatListText += '|' + format.name; if (!format.challengeShow) formatListText += ',,'; else if (!format.searchShow) formatListText += ','; if (format.team) formatListText += ',#'; } return formatListText; }; GlobalRoom.prototype.getRoomList = function (filter) { var roomList = {}; var total = 0; for (var i in Rooms.rooms) { var room = Rooms.rooms[i]; if (!room || !room.active || room.isPrivate) continue; if (filter && filter !== room.format && filter !== true) continue; var roomData = {}; if (room.active && room.battle) { if (room.battle.players[0]) roomData.p1 = room.battle.players[0].getIdentity(); if (room.battle.players[1]) roomData.p2 = room.battle.players[1].getIdentity(); } if (!roomData.p1 || !roomData.p2) continue; roomList[room.id] = roomData; total++; if (total >= 100) break; } return roomList; }; GlobalRoom.prototype.getRooms = function () { var roomsData = {official:[], chat:[], userCount: this.userCount, battleCount: this.battleCount}; for (var i = 0; i < this.chatRooms.length; i++) { var room = this.chatRooms[i]; if (!room) continue; if (room.isPrivate) continue; (room.isOfficial ? roomsData.official : roomsData.chat).push({ title: room.title, desc: room.desc, userCount: room.userCount }); } return roomsData; }; GlobalRoom.prototype.cancelSearch = function (user) { var success = false; user.cancelChallengeTo(); for (var i = 0; i < this.searchers.length; i++) { var search = this.searchers[i]; var searchUser = Users.get(search.userid); if (!searchUser.connected) { this.searchers.splice(i, 1); i--; continue; } if (searchUser === user) { this.searchers.splice(i, 1); i--; if (!success) { searchUser.send('|updatesearch|' + JSON.stringify({searching: false})); success = true; } continue; } } return success; }; GlobalRoom.prototype.searchBattle = function (user, formatid) { if (!user.connected) return; formatid = toId(formatid); user.prepBattle(formatid, 'search', null, this.finishSearchBattle.bind(this, user, formatid)); }; GlobalRoom.prototype.finishSearchBattle = function (user, formatid, result) { if (!result) return; // tell the user they've started searching var newSearchData = { format: formatid }; user.send('|updatesearch|' + JSON.stringify({searching: newSearchData})); // get the user's rating before actually starting to search var newSearch = { userid: user.userid, formatid: formatid, team: user.team, rating: 1000, time: new Date().getTime() }; var self = this; user.doWithMMR(formatid, function (mmr, error) { if (error) { user.popup("Connection to ladder server failed with error: " + error + "; please try again later"); return; } newSearch.rating = mmr; self.addSearch(newSearch, user); }); }; GlobalRoom.prototype.matchmakingOK = function (search1, search2, user1, user2) { // users must be different if (user1 === user2) return false; // users must have different IPs if (user1.latestIp === user2.latestIp) return false; // users must not have been matched immediately previously if (user1.lastMatch === user2.userid || user2.lastMatch === user1.userid) return false; // search must be within range var searchRange = 100, formatid = search1.formatid, elapsed = Math.abs(search1.time - search2.time); if (formatid === 'ou' || formatid === 'oucurrent' || formatid === 'randombattle') searchRange = 50; searchRange += elapsed / 300; // +1 every .3 seconds if (searchRange > 300) searchRange = 300; if (Math.abs(search1.rating - search2.rating) > searchRange) return false; user1.lastMatch = user2.userid; user2.lastMatch = user1.userid; return true; }; GlobalRoom.prototype.addSearch = function (newSearch, user) { if (!user.connected) return; for (var i = 0; i < this.searchers.length; i++) { var search = this.searchers[i]; var searchUser = Users.get(search.userid); if (!searchUser || !searchUser.connected) { this.searchers.splice(i, 1); i--; continue; } if (newSearch.formatid === search.formatid && searchUser === user) return; // only one search per format if (newSearch.formatid === search.formatid && this.matchmakingOK(search, newSearch, searchUser, user)) { this.cancelSearch(user, true); this.cancelSearch(searchUser, true); user.send('|updatesearch|' + JSON.stringify({searching: false})); this.startBattle(searchUser, user, search.formatid, true, search.team, newSearch.team); return; } } this.searchers.push(newSearch); }; GlobalRoom.prototype.send = function (message, user) { if (user) { user.sendTo(this, message); } else { Sockets.channelBroadcast(this.id, message); } }; GlobalRoom.prototype.sendAuth = function (message) { for (var i in this.users) { var user = this.users[i]; if (user.connected && user.can('receiveauthmessages', null, this)) { user.sendTo(this, message); } } }; GlobalRoom.prototype.add = function (message) { if (rooms.lobby) rooms.lobby.add(message); }; GlobalRoom.prototype.addRaw = function (message) { if (rooms.lobby) rooms.lobby.addRaw(message); }; GlobalRoom.prototype.addChatRoom = function (title) { var id = toId(title); if (rooms[id]) return false; var chatRoomData = { title: title }; var room = Rooms.createChatRoom(id, title, chatRoomData); this.chatRoomData.push(chatRoomData); this.chatRooms.push(room); this.writeChatRoomData(); return true; }; GlobalRoom.prototype.deregisterChatRoom = function (id) { id = toId(id); var room = rooms[id]; if (!room) return false; // room doesn't exist if (!room.chatRoomData) return false; // room isn't registered // deregister from global chatRoomData // looping from the end is a pretty trivial optimization, but the // assumption is that more recently added rooms are more likely to // be deleted for (var i = this.chatRoomData.length - 1; i >= 0; i--) { if (id === toId(this.chatRoomData[i].title)) { this.chatRoomData.splice(i, 1); this.writeChatRoomData(); break; } } delete room.chatRoomData; return true; }; GlobalRoom.prototype.delistChatRoom = function (id) { id = toId(id); if (!rooms[id]) return false; // room doesn't exist for (var i = this.chatRooms.length - 1; i >= 0; i--) { if (id === this.chatRooms[i].id) { this.chatRooms.splice(i, 1); break; } } }; GlobalRoom.prototype.removeChatRoom = function (id) { id = toId(id); var room = rooms[id]; if (!room) return false; // room doesn't exist room.destroy(); return true; }; GlobalRoom.prototype.autojoinRooms = function (user, connection) { // we only autojoin regular rooms if the client requests it with /autojoin // note that this restriction doesn't apply to staffAutojoin for (var i = 0; i < this.autojoin.length; i++) { user.joinRoom(this.autojoin[i], connection); } }; GlobalRoom.prototype.checkAutojoin = function (user, connection) { if (user.isStaff) { for (var i = 0; i < this.staffAutojoin.length; i++) { user.joinRoom(this.staffAutojoin[i], connection); } } }; GlobalRoom.prototype.onJoinConnection = function (user, connection) { var initdata = '|updateuser|' + user.name + '|' + (user.named ? '1' : '0') + '|' + user.avatar + '\n'; connection.send(initdata + this.formatListText); if (this.chatRooms.length > 2) connection.send('|queryresponse|rooms|null'); // should display room list }; GlobalRoom.prototype.onJoin = function (user, connection, merging) { if (!user) return false; // ??? if (this.users[user.userid]) return user; this.users[user.userid] = user; if (++this.userCount > this.maxUsers) { this.maxUsers = this.userCount; this.maxUsersDate = Date.now(); } if (!merging) { var initdata = '|updateuser|' + user.name + '|' + (user.named ? '1' : '0') + '|' + user.avatar + '\n'; connection.send(initdata + this.formatListText); if (this.chatRooms.length > 2) connection.send('|queryresponse|rooms|null'); // should display room list } return user; }; GlobalRoom.prototype.onRename = function (user, oldid, joining) { delete this.users[oldid]; this.users[user.userid] = user; return user; }; GlobalRoom.prototype.onUpdateIdentity = function () {}; GlobalRoom.prototype.onLeave = function (user) { if (!user) return; // ... delete this.users[user.userid]; --this.userCount; this.cancelSearch(user, true); }; GlobalRoom.prototype.startBattle = function (p1, p2, format, rated, p1team, p2team) { var newRoom; p1 = Users.get(p1); p2 = Users.get(p2); if (!p1 || !p2) { // most likely, a user was banned during the battle start procedure this.cancelSearch(p1, true); this.cancelSearch(p2, true); return; } if (p1 === p2) { this.cancelSearch(p1, true); this.cancelSearch(p2, true); p1.popup("You can't battle your own account. Please use something like Private Browsing to battle yourself."); return; } if (this.lockdown) { this.cancelSearch(p1, true); this.cancelSearch(p2, true); p1.popup("The server is shutting down. Battles cannot be started at this time."); p2.popup("The server is shutting down. Battles cannot be started at this time."); return; } //console.log('BATTLE START BETWEEN: ' + p1.userid + ' ' + p2.userid); var i = this.lastBattle + 1; var formaturlid = format.toLowerCase().replace(/[^a-z0-9]+/g, ''); while(rooms['battle-' + formaturlid + i]) { i++; } this.lastBattle = i; rooms.global.writeNumRooms(); newRoom = this.addRoom('battle-' + formaturlid + '-' + i, format, p1, p2, this.id, rated); p1.joinRoom(newRoom); p2.joinRoom(newRoom); newRoom.joinBattle(p1, p1team); newRoom.joinBattle(p2, p2team); this.cancelSearch(p1, true); this.cancelSearch(p2, true); if (Config.reportbattles && rooms.lobby) { rooms.lobby.add('|b|' + newRoom.id + '|' + p1.getIdentity() + '|' + p2.getIdentity()); } if (Config.logladderip && rated) { if (!this.ladderIpLog) { this.ladderIpLog = fs.createWriteStream('logs/ladderip/ladderip.txt', {flags: 'a'}); } this.ladderIpLog.write(p1.userid+': '+p1.latestIp+'\n'); this.ladderIpLog.write(p2.userid+': '+p2.latestIp+'\n'); } return newRoom; }; GlobalRoom.prototype.addRoom = function (room, format, p1, p2, parent, rated) { room = Rooms.createBattle(room, format, p1, p2, parent, rated); return room; }; GlobalRoom.prototype.removeRoom = function (room) {}; GlobalRoom.prototype.chat = function (user, message, connection) { if (rooms.lobby) return rooms.lobby.chat(user, message, connection); message = CommandParser.parse(message, this, user, connection); if (message) { connection.sendPopup("You can't send messages directly to the server."); } }; return GlobalRoom; })(); var BattleRoom = (function () { function BattleRoom(roomid, format, p1, p2, parentid, rated) { Room.call(this, roomid, "" + p1.name + " vs. " + p2.name); this.modchat = (Config.battlemodchat || false); format = '' + (format || ''); this.format = format; this.auth = {}; //console.log("NEW BATTLE"); var formatid = toId(format); if (rated && Tools.getFormat(formatid).rated !== false) { rated = { p1: p1.userid, p2: p2.userid, format: format }; } else { rated = false; } this.rated = rated; this.battle = Simulator.create(this.id, format, rated, this); this.parentid = parentid || ''; this.p1 = p1 || ''; this.p2 = p2 || ''; this.sideTicksLeft = [21, 21]; if (!rated) this.sideTicksLeft = [28, 28]; this.sideTurnTicks = [0, 0]; this.disconnectTickDiff = [0, 0]; if (Config.forcetimer) this.requestKickInactive(false); } BattleRoom.prototype = Object.create(Room.prototype); BattleRoom.prototype.type = 'battle'; BattleRoom.prototype.resetTimer = null; BattleRoom.prototype.resetUser = ''; BattleRoom.prototype.expireTimer = null; BattleRoom.prototype.active = false; BattleRoom.prototype.push = function (message) { if (typeof message === 'string') { this.log.push(message); } else { this.log = this.log.concat(message); } }; BattleRoom.prototype.win = function (winner) { if (this.rated) { var winnerid = toId(winner); var rated = this.rated; this.rated = false; var p1score = 0.5; if (winnerid === rated.p1) { p1score = 1; } else if (winnerid === rated.p2) { p1score = 0; } var p1 = rated.p1; if (Users.getExact(rated.p1)) p1 = Users.getExact(rated.p1).name; var p2 = rated.p2; if (Users.getExact(rated.p2)) p2 = Users.getExact(rated.p2).name; //update.updates.push('[DEBUG] uri: ' + Config.loginserver + 'action.php?act=ladderupdate&serverid=' + Config.serverid + '&p1=' + encodeURIComponent(p1) + '&p2=' + encodeURIComponent(p2) + '&score=' + p1score + '&format=' + toId(rated.format) + '&servertoken=[token]'); if (!rated.p1 || !rated.p2) { this.push('|raw|ERROR: Ladder not updated: a player does not exist'); } else { winner = Users.get(winnerid); if (winner && !winner.authenticated) { this.sendUser(winner, '|askreg|' + winner.userid); } var p1rating, p2rating; // update rankings this.push('|raw|Ladder updating...'); var self = this; LoginServer.request('ladderupdate', { p1: p1, p2: p2, score: p1score, format: toId(rated.format) }, function (data, statusCode, error) { if (!self.battle) { console.log('room expired before ladder update was received'); return; } if (!data) { self.addRaw('Ladder (probably) updated, but score could not be retrieved (' + error + ').'); // log the battle anyway if (!Tools.getFormat(self.format).noLog) { self.logBattle(p1score); } return; } else if (data.errorip) { self.addRaw("This server's request IP " + data.errorip + " is not a registered server."); return; } else { try { p1rating = data.p1rating; p2rating = data.p2rating; //self.add("Ladder updated."); var oldacre = Math.round(data.p1rating.oldacre); var acre = Math.round(data.p1rating.acre); var reasons = '' + (acre - oldacre) + ' for ' + (p1score > 0.99 ? 'winning' : (p1score < 0.01 ? 'losing' : 'tying')); if (reasons.substr(0, 1) !== '-') reasons = '+' + reasons; self.addRaw(Tools.escapeHTML(p1) + '\'s rating: ' + oldacre + ' &rarr; <strong>' + acre + '</strong><br />(' + reasons + ')'); oldacre = Math.round(data.p2rating.oldacre); acre = Math.round(data.p2rating.acre); reasons = '' + (acre - oldacre) + ' for ' + (p1score > 0.99 ? 'losing' : (p1score < 0.01 ? 'winning' : 'tying')); if (reasons.substr(0, 1) !== '-') reasons = '+' + reasons; self.addRaw(Tools.escapeHTML(p2) + '\'s rating: ' + oldacre + ' &rarr; <strong>' + acre + '</strong><br />(' + reasons + ')'); Users.get(p1).cacheMMR(rated.format, data.p1rating); Users.get(p2).cacheMMR(rated.format, data.p2rating); self.update(); } catch(e) { self.addRaw('There was an error calculating rating changes.'); self.update(); } if (!Tools.getFormat(self.format).noLog) { self.logBattle(p1score, p1rating, p2rating); } } }); } } rooms.global.battleCount += 0 - (this.active ? 1 : 0); this.active = false; this.update(); }; // logNum = 0 : spectator log // logNum = 1, 2 : player log // logNum = 3 : replay log BattleRoom.prototype.getLog = function (logNum) { var log = []; for (var i = 0; i < this.log.length; ++i) { var line = this.log[i]; if (line === '|split') { log.push(this.log[i + logNum + 1]); i += 4; } else { log.push(line); } } return log; }; BattleRoom.prototype.getLogForUser = function (user) { var logNum = this.battle.getSlot(user) + 1; if (logNum < 0) logNum = 0; return this.getLog(logNum); }; BattleRoom.prototype.update = function (excludeUser) { if (this.log.length <= this.lastUpdate) return; Sockets.subchannelBroadcast(this.id, '>' + this.id + '\n\n' + this.log.slice(this.lastUpdate).join('\n')); this.lastUpdate = this.log.length; // empty rooms time out after ten minutes var hasUsers = false; for (var i in this.users) { hasUsers = true; break; } if (!hasUsers) { if (!this.expireTimer) { this.expireTimer = setTimeout(this.tryExpire.bind(this), TIMEOUT_EMPTY_DEALLOCATE); } } else { if (this.expireTimer) clearTimeout(this.expireTimer); this.expireTimer = setTimeout(this.tryExpire.bind(this), TIMEOUT_INACTIVE_DEALLOCATE); } }; BattleRoom.prototype.logBattle = function (p1score, p1rating, p2rating) { var logData = this.battle.logData; logData.p1rating = p1rating; logData.p2rating = p2rating; logData.endType = this.battle.endType; if (!p1rating) logData.ladderError = true; logData.log = BattleRoom.prototype.getLog.call(logData, 3); // replay log (exact damage) var date = new Date(); var logfolder = date.format('{yyyy}-{MM}'); var logsubfolder = date.format('{yyyy}-{MM}-{dd}'); var curpath = 'logs/' + logfolder; var self = this; fs.mkdir(curpath, '0755', function () { var tier = self.format.toLowerCase().replace(/[^a-z0-9]+/g, ''); curpath += '/' + tier; fs.mkdir(curpath, '0755', function () { curpath += '/' + logsubfolder; fs.mkdir(curpath, '0755', function () { fs.writeFile(curpath + '/' + self.id + '.log.json', JSON.stringify(logData)); }); }); }); // asychronicity //console.log(JSON.stringify(logData)); }; BattleRoom.prototype.tryExpire = function () { this.expire(); }; BattleRoom.prototype.getInactiveSide = function () { if (this.battle.players[0] && !this.battle.players[1]) return 1; if (this.battle.players[1] && !this.battle.players[0]) return 0; return this.battle.inactiveSide; }; BattleRoom.prototype.forfeit = function (user, message, side) { if (!this.battle || this.battle.ended || !this.battle.started) return false; if (!message) message = ' forfeited.'; if (side === undefined) { if (user && user.userid === this.battle.playerids[0]) side = 0; if (user && user.userid === this.battle.playerids[1]) side = 1; } if (side === undefined) return false; var ids = ['p1', 'p2']; var otherids = ['p2', 'p1']; var name = 'Player ' + (side + 1); if (user) { name = user.name; } else if (this.rated) { name = this.rated[ids[side]]; } this.add('|-message|' + name + message); this.battle.endType = 'forfeit'; this.battle.send('win', otherids[side]); rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; this.update(); return true; }; BattleRoom.prototype.sendPlayer = function (num, message) { var player = this.battle.getPlayer(num); if (!player) return false; this.sendUser(player, message); }; BattleRoom.prototype.kickInactive = function () { clearTimeout(this.resetTimer); this.resetTimer = null; if (!this.battle || this.battle.ended || !this.battle.started) return false; var inactiveSide = this.getInactiveSide(); var ticksLeft = [0, 0]; if (inactiveSide !== 1) { // side 0 is inactive this.sideTurnTicks[0]--; this.sideTicksLeft[0]--; } if (inactiveSide !== 0) { // side 1 is inactive this.sideTurnTicks[1]--; this.sideTicksLeft[1]--; } ticksLeft[0] = Math.min(this.sideTurnTicks[0], this.sideTicksLeft[0]); ticksLeft[1] = Math.min(this.sideTurnTicks[1], this.sideTicksLeft[1]); if (ticksLeft[0] && ticksLeft[1]) { if (inactiveSide === 0 || inactiveSide === 1) { // one side is inactive var inactiveTicksLeft = ticksLeft[inactiveSide]; var inactiveUser = this.battle.getPlayer(inactiveSide); if (inactiveTicksLeft % 3 === 0 || inactiveTicksLeft <= 4) { this.send('|inactive|' + (inactiveUser ? inactiveUser.name : 'Player ' + (inactiveSide + 1)) + ' has ' + (inactiveTicksLeft * 10) + ' seconds left.'); } } else { // both sides are inactive var inactiveUser0 = this.battle.getPlayer(0); if (inactiveUser0 && (ticksLeft[0] % 3 === 0 || ticksLeft[0] <= 4)) { this.sendUser(inactiveUser0, '|inactive|' + inactiveUser0.name + ' has ' + (ticksLeft[0] * 10) + ' seconds left.'); } var inactiveUser1 = this.battle.getPlayer(1); if (inactiveUser1 && (ticksLeft[1] % 3 === 0 || ticksLeft[1] <= 4)) { this.sendUser(inactiveUser1, '|inactive|' + inactiveUser1.name + ' has ' + (ticksLeft[1] * 10) + ' seconds left.'); } } this.resetTimer = setTimeout(this.kickInactive.bind(this), 10 * 1000); return; } if (inactiveSide < 0) { if (ticksLeft[0]) inactiveSide = 1; else if (ticksLeft[1]) inactiveSide = 0; } this.forfeit(this.battle.getPlayer(inactiveSide), ' lost due to inactivity.', inactiveSide); this.resetUser = ''; }; BattleRoom.prototype.requestKickInactive = function (user, force) { if (this.resetTimer) { if (user) this.sendUser(user, '|inactive|The inactivity timer is already counting down.'); return false; } if (user) { if (!force && this.battle.getSlot(user) < 0) return false; this.resetUser = user.userid; this.send('|inactive|Battle timer is now ON: inactive players will automatically lose when time\'s up. (requested by ' + user.name + ')'); } else if (user === false) { this.resetUser = '~'; this.add('|inactive|Battle timer is ON: inactive players will automatically lose when time\'s up.'); } // a tick is 10 seconds var maxTicksLeft = 15; // 2 minutes 30 seconds if (!this.battle.p1 || !this.battle.p2) { // if a player has left, don't wait longer than 6 ticks (1 minute) maxTicksLeft = 6; } if (!this.rated) maxTicksLeft = 30; this.sideTurnTicks = [maxTicksLeft, maxTicksLeft]; var inactiveSide = this.getInactiveSide(); if (inactiveSide < 0) { // add 10 seconds to bank if they're below 160 seconds if (this.sideTicksLeft[0] < 16) this.sideTicksLeft[0]++; if (this.sideTicksLeft[1] < 16) this.sideTicksLeft[1]++; } this.sideTicksLeft[0]++; this.sideTicksLeft[1]++; if (inactiveSide !== 1) { // side 0 is inactive var ticksLeft0 = Math.min(this.sideTicksLeft[0] + 1, maxTicksLeft); this.sendPlayer(0, '|inactive|You have ' + (ticksLeft0 * 10) + ' seconds to make your decision.'); } if (inactiveSide !== 0) { // side 1 is inactive var ticksLeft1 = Math.min(this.sideTicksLeft[1] + 1, maxTicksLeft); this.sendPlayer(1, '|inactive|You have ' + (ticksLeft1 * 10) + ' seconds to make your decision.'); } this.resetTimer = setTimeout(this.kickInactive.bind(this), 10 * 1000); return true; }; BattleRoom.prototype.nextInactive = function () { if (this.resetTimer) { this.update(); clearTimeout(this.resetTimer); this.resetTimer = null; this.requestKickInactive(); } }; BattleRoom.prototype.stopKickInactive = function (user, force) { if (!force && user && user.userid !== this.resetUser) return false; if (this.resetTimer) { clearTimeout(this.resetTimer); this.resetTimer = null; this.send('|inactiveoff|Battle timer is now OFF.'); return true; } return false; }; BattleRoom.prototype.kickInactiveUpdate = function () { if (!this.rated) return false; if (this.resetTimer) { var inactiveSide = this.getInactiveSide(); var changed = false; if ((!this.battle.p1 || !this.battle.p2) && !this.disconnectTickDiff[0] && !this.disconnectTickDiff[1]) { if ((!this.battle.p1 && inactiveSide === 0) || (!this.battle.p2 && inactiveSide === 1)) { var inactiveUser = this.battle.getPlayer(inactiveSide); if (!this.battle.p1 && inactiveSide === 0 && this.sideTurnTicks[0] > 7) { this.disconnectTickDiff[0] = this.sideTurnTicks[0] - 7; this.sideTurnTicks[0] = 7; changed = true; } else if (!this.battle.p2 && inactiveSide === 1 && this.sideTurnTicks[1] > 7) { this.disconnectTickDiff[1] = this.sideTurnTicks[1] - 7; this.sideTurnTicks[1] = 7; changed = true; } if (changed) { this.send('|inactive|' + (inactiveUser ? inactiveUser.name : 'Player ' + (inactiveSide + 1)) + ' disconnected and has a minute to reconnect!'); return true; } } } else if (this.battle.p1 && this.battle.p2) { // Only one of the following conditions should happen, but do // them both since you never know... if (this.disconnectTickDiff[0]) { this.sideTurnTicks[0] = this.sideTurnTicks[0] + this.disconnectTickDiff[0]; this.disconnectTickDiff[0] = 0; changed = 0; } if (this.disconnectTickDiff[1]) { this.sideTurnTicks[1] = this.sideTurnTicks[1] + this.disconnectTickDiff[1]; this.disconnectTickDiff[1] = 0; changed = 1; } if (changed !== false) { var user = this.battle.getPlayer(changed); this.send('|inactive|' + (user ? user.name : 'Player ' + (changed + 1)) + ' reconnected and has ' + (this.sideTurnTicks[changed] * 10) + ' seconds left!'); return true; } } } return false; }; BattleRoom.prototype.decision = function (user, choice, data) { this.battle.sendFor(user, choice, data); if (this.active !== this.battle.active) { rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; } this.update(); }; // This function is only called when the room is not empty. // Joining an empty room calls this.join() below instead. BattleRoom.prototype.onJoinConnection = function (user, connection) { this.sendUser(connection, '|init|battle\n|title|' + this.title + '\n' + this.getLogForUser(user).join('\n')); // this handles joining a battle in which a user is a participant, // where the user has already identified before attempting to join // the battle this.battle.resendRequest(user); }; BattleRoom.prototype.onJoin = function (user, connection) { if (!user) return false; if (this.users[user.userid]) return user; if (user.named) { this.add('|join|' + user.name); this.update(); } this.users[user.userid] = user; this.userCount++; this.sendUser(connection, '|init|battle\n|title|' + this.title + '\n' + this.getLogForUser(user).join('\n')); return user; }; BattleRoom.prototype.onRename = function (user, oldid, joining) { if (joining) { this.add('|join|' + user.name); } var resend = joining || !this.battle.playerTable[oldid]; if (this.battle.playerTable[oldid]) { if (this.rated) { this.add('|message|' + user.name + ' forfeited by changing their name.'); this.battle.lose(oldid); this.battle.leave(oldid); resend = false; } else { this.battle.rename(); } } delete this.users[oldid]; this.users[user.userid] = user; this.update(); if (resend) { // this handles a named user renaming themselves into a user in the // battle (i.e. by using /nick) this.battle.resendRequest(user); } return user; }; BattleRoom.prototype.onUpdateIdentity = function () {}; BattleRoom.prototype.onLeave = function (user) { if (!user) return; // ... if (user.battles[this.id]) { this.battle.leave(user); rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; } else if (!user.named) { delete this.users[user.userid]; return; } delete this.users[user.userid]; this.userCount--; this.add('|leave|' + user.name); if (Object.isEmpty(this.users)) { rooms.global.battleCount += 0 - (this.active ? 1 : 0); this.active = false; } this.update(); this.kickInactiveUpdate(); }; BattleRoom.prototype.joinBattle = function (user, team) { var slot; if (this.rated) { if (this.rated.p1 === user.userid) { slot = 0; } else if (this.rated.p2 === user.userid) { slot = 1; } else { user.popup("This is a rated battle; your username must be " + this.rated.p1 + " or " + this.rated.p2 + " to join."); return false; } } if (this.battle.active) { user.popup("This battle already has two players."); return false; } this.auth[user.userid] = '\u2605'; this.battle.join(user, slot, team); rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; if (this.active) { this.title = "" + this.battle.p1 + " vs. " + this.battle.p2; this.send('|title|' + this.title); } this.update(); this.kickInactiveUpdate(); }; BattleRoom.prototype.leaveBattle = function (user) { if (!user) return false; // ... if (user.battles[this.id]) { this.battle.leave(user); } else { return false; } this.auth[user.userid] = '+'; rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; this.update(); this.kickInactiveUpdate(); return true; }; BattleRoom.prototype.expire = function () { this.send('|expire|'); this.destroy(); }; BattleRoom.prototype.destroy = function () { // deallocate ourself // remove references to ourself for (var i in this.users) { this.users[i].leaveRoom(this); delete this.users[i]; } this.users = null; rooms.global.removeRoom(this.id); // deallocate children and get rid of references to them if (this.battle) { this.battle.destroy(); } this.battle = null; if (this.resetTimer) { clearTimeout(this.resetTimer); } this.resetTimer = null; // get rid of some possibly-circular references delete rooms[this.id]; }; return BattleRoom; })(); var ChatRoom = (function () { function ChatRoom(roomid, title, options) { Room.call(this, roomid, title); if (options) { this.chatRoomData = options; Object.merge(this, options); } this.logTimes = true; this.logFile = null; this.logFilename = ''; this.destroyingLog = false; if (!this.modchat) this.modchat = (Config.chatmodchat || false); if (Config.logchat) { this.rollLogFile(true); this.logEntry = function (entry, date) { var timestamp = (new Date()).format('{HH}:{mm}:{ss} '); this.logFile.write(timestamp + entry + '\n'); }; this.logEntry('NEW CHATROOM: ' + this.id); if (Config.loguserstats) { setInterval(this.logUserStats.bind(this), Config.loguserstats); } } if (Config.reportjoinsperiod) { this.userList = this.getUserList(); this.reportJoinsQueue = []; } } ChatRoom.prototype = Object.create(Room.prototype); ChatRoom.prototype.type = 'chat'; ChatRoom.prototype.reportRecentJoins = function () { delete this.reportJoinsInterval; if (this.reportJoinsQueue.length === 0) { // nothing to report return; } if (Config.reportjoinsperiod) { this.userList = this.getUserList(); } this.send(this.reportJoinsQueue.join('\n')); this.reportJoinsQueue.length = 0; }; ChatRoom.prototype.rollLogFile = function (sync) { var mkdir = sync ? function (path, mode, callback) { try { fs.mkdirSync(path, mode); } catch (e) {} // directory already exists callback(); } : fs.mkdir; var date = new Date(); var basepath = 'logs/chat/' + this.id + '/'; var self = this; mkdir(basepath, '0755', function () { var path = date.format('{yyyy}-{MM}'); mkdir(basepath + path, '0755', function () { if (self.destroyingLog) return; path += '/' + date.format('{yyyy}-{MM}-{dd}') + '.txt'; if (path !== self.logFilename) { self.logFilename = path; if (self.logFile) self.logFile.destroySoon(); self.logFile = fs.createWriteStream(basepath + path, {flags: 'a'}); // Create a symlink to today's lobby log. // These operations need to be synchronous, but it's okay // because this code is only executed once every 24 hours. var link0 = basepath + 'today.txt.0'; try { fs.unlinkSync(link0); } catch (e) {} // file doesn't exist try { fs.symlinkSync(path, link0); // `basepath` intentionally not included try { fs.renameSync(link0, basepath + 'today.txt'); } catch (e) {} // OS doesn't support atomic rename } catch (e) {} // OS doesn't support symlinks } var timestamp = +date; date.advance('1 hour').reset('minutes').advance('1 second'); setTimeout(self.rollLogFile.bind(self), +date - timestamp); }); }); }; ChatRoom.prototype.destroyLog = function (initialCallback, finalCallback) { this.destroyingLog = true; initialCallback(); if (this.logFile) { this.logEntry = function () { }; this.logFile.on('close', finalCallback); this.logFile.destroySoon(); } else { finalCallback(); } }; ChatRoom.prototype.logUserStats = function () { var total = 0; var guests = 0; var groups = {}; Config.groupsranking.forEach(function (group) { groups[group] = 0; }); for (var i in this.users) { var user = this.users[i]; ++total; if (!user.named) { ++guests; } ++groups[user.group]; } var entry = '|userstats|total:' + total + '|guests:' + guests; for (var i in groups) { entry += '|' + i + ':' + groups[i]; } this.logEntry(entry); }; ChatRoom.prototype.getUserList = function () { var buffer = ''; var counter = 0; for (var i in this.users) { if (!this.users[i].named) { continue; } counter++; buffer += ',' + this.users[i].getIdentity(this.id); } var msg = '|users|' + counter + buffer; return msg; }; ChatRoom.prototype.reportJoin = function (entry) { if (Config.reportjoinsperiod) { if (!this.reportJoinsInterval) { this.reportJoinsInterval = setTimeout( this.reportRecentJoins.bind(this), Config.reportjoinsperiod ); } this.reportJoinsQueue.push(entry); } else { this.send(entry); } this.logEntry(entry); }; ChatRoom.prototype.update = function () { if (this.log.length <= this.lastUpdate) return; var entries = this.log.slice(this.lastUpdate); if (this.reportJoinsQueue && this.reportJoinsQueue.length) { clearTimeout(this.reportJoinsInterval); delete this.reportJoinsInterval; Array.prototype.unshift.apply(entries, this.reportJoinsQueue); this.reportJoinsQueue.length = 0; this.userList = this.getUserList(); } var update = entries.join('\n'); if (this.log.length > 100) { this.log.splice(0, this.log.length - 100); } this.lastUpdate = this.log.length; this.send(update); }; ChatRoom.prototype.getIntroMessage = function () { var html = this.introMessage || ''; if (this.modchat) { if (html) html += '<br /><br />'; html += '<div class="broadcast-red">'; html += 'Must be rank ' + this.modchat + ' or higher to talk right now.'; html += '</div>'; } if (html) return '\n|raw|<div class="infobox">' + html + '</div>'; return ''; }; ChatRoom.prototype.onJoinConnection = function (user, connection) { var userList = this.userList ? this.userList : this.getUserList(); this.sendUser(connection, '|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.getLogSlice(-25).join('\n') + this.getIntroMessage()); if (global.Tournaments && Tournaments.get(this.id)) { Tournaments.get(this.id).updateFor(user, connection); } }; ChatRoom.prototype.onJoin = function (user, connection, merging) { if (!user) return false; // ??? if (this.users[user.userid]) return user; if (user.named && Config.reportjoins) { this.add('|j|' + user.getIdentity(this.id)); this.update(); } else if (user.named) { var entry = '|J|' + user.getIdentity(this.id); this.reportJoin(entry); } this.users[user.userid] = user; this.userCount++; if (!merging) { var userList = this.userList ? this.userList : this.getUserList(); this.sendUser(connection, '|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.getLogSlice(-100).join('\n') + this.getIntroMessage()); } if (global.Tournaments && Tournaments.get(this.id)) { Tournaments.get(this.id).updateFor(user, connection); } return user; }; ChatRoom.prototype.onRename = function (user, oldid, joining) { delete this.users[oldid]; if (this.bannedUsers && (user.userid in this.bannedUsers || user.autoconfirmed in this.bannedUsers)) { this.bannedUsers[oldid] = true; for (var ip in user.ips) this.bannedIps[ip] = true; user.leaveRoom(this); var alts = user.getAlts(); for (var i = 0; i < alts.length; ++i) { this.bannedUsers[toId(alts[i])] = true; Users.getExact(alts[i]).leaveRoom(this); } return; } this.users[user.userid] = user; var entry; if (joining) { if (Config.reportjoins) { entry = '|j|' + user.getIdentity(this.id); } else { entry = '|J|' + user.getIdentity(this.id); } } else if (!user.named) { entry = '|L| ' + oldid; } else { entry = '|N|' + user.getIdentity(this.id) + '|' + oldid; } if (Config.reportjoins) { this.add(entry); } else { this.reportJoin(entry); } if (global.Tournaments && Tournaments.get(this.id)) { Tournaments.get(this.id).updateFor(user); } return user; }; /** * onRename, but without a userid change */ ChatRoom.prototype.onUpdateIdentity = function (user) { if (user && user.connected && user.named) { if (!this.users[user.userid]) return false; var entry = '|N|' + user.getIdentity(this.id) + '|' + user.userid; this.reportJoin(entry); } }; ChatRoom.prototype.onLeave = function (user) { if (!user) return; // ... delete this.users[user.userid]; this.userCount--; if (user.named && Config.reportjoins) { this.add('|l|' + user.getIdentity(this.id)); } else if (user.named) { var entry = '|L|' + user.getIdentity(this.id); this.reportJoin(entry); } }; ChatRoom.prototype.destroy = function () { // deallocate ourself // remove references to ourself for (var i in this.users) { this.users[i].leaveRoom(this); delete this.users[i]; } this.users = null; rooms.global.deregisterChatRoom(this.id); rooms.global.delistChatRoom(this.id); // get rid of some possibly-circular references delete rooms[this.id]; }; return ChatRoom; })(); // to make sure you don't get null returned, pass the second argument function getRoom(roomid, fallback) { if (roomid && roomid.id) return roomid; if (!roomid) roomid = 'default'; if (!rooms[roomid] && fallback) { return rooms.global; } return rooms[roomid]; } Rooms.get = getRoom; Rooms.createBattle = function (roomid, format, p1, p2, parent, rated) { if (roomid && roomid.id) return roomid; if (!p1 || !p2) return false; if (!roomid) roomid = 'default'; if (!rooms[roomid]) { // console.log("NEW BATTLE ROOM: " + roomid); ResourceMonitor.countBattle(p1.latestIp, p1.name); ResourceMonitor.countBattle(p2.latestIp, p2.name); rooms[roomid] = new BattleRoom(roomid, format, p1, p2, parent, rated); } return rooms[roomid]; }; Rooms.createChatRoom = function (roomid, title, data) { var room; if ((room = rooms[roomid])) return room; room = rooms[roomid] = new ChatRoom(roomid, title, data); return room; }; console.log("NEW GLOBAL: global"); rooms.global = new GlobalRoom('global'); Rooms.GlobalRoom = GlobalRoom; Rooms.BattleRoom = BattleRoom; Rooms.ChatRoom = ChatRoom; Rooms.global = rooms.global; Rooms.lobby = rooms.lobby;
/** * Copyright (c) 2008-2011 The Open Planning Project * * Published under the BSD license. * See https://github.com/opengeo/gxp/raw/master/license.txt for the full text * of the license. */ /** * @requires plugins/ZoomToExtent.js */ /** api: (define) * module = gxp.plugins * class = ZoomToSelectedFeatures */ /** api: (extends) * plugins/ZoomToExtent.js */ Ext.namespace("gxp.plugins"); /** api: constructor * .. class:: ZoomToSelectedFeatures(config) * * Plugin for zooming to the extent of selected features */ gxp.plugins.ZoomToSelectedFeatures = Ext.extend(gxp.plugins.ZoomToExtent, { /** api: ptype = gxp_zoomtoselectedfeatures */ ptype: "gxp_zoomtoselectedfeatures", /** api: config[menuText] * ``String`` * Text for zoom menu item (i18n). */ menuText: "Zoom to selected features", /** api: config[tooltip] * ``String`` * Text for zoom action tooltip (i18n). */ tooltip: "Zoom to selected features", /** api: config[featureManager] * ``String`` id of the :class:`gxp.plugins.FeatureManager` to look for * selected features */ /** api: config[closest] * ``Boolean`` Find the zoom level that most closely fits the specified * extent. Note that this may result in a zoom that does not exactly * contain the entire extent. Default is false. */ closest: false, /** private: property[iconCls] */ iconCls: "gxp-icon-zoom-to", /** private: method[extent] */ extent: function() { var layer = this.target.tools[this.featureManager].featureLayer; var bounds, geom, extent, features = layer.selectedFeatures; for (var i=features.length-1; i>=0; --i) { geom = features[i].geometry; if (geom) { extent = geom.getBounds(); if (bounds) { bounds.extend(extent); } else { bounds = extent.clone(); } } }; return bounds; }, /** api: method[addActions] */ addActions: function() { var actions = gxp.plugins.ZoomToSelectedFeatures.superclass.addActions.apply(this, arguments); actions[0].disable(); var layer = this.target.tools[this.featureManager].featureLayer; layer.events.on({ "featureselected": function() { actions[0].isDisabled() && actions[0].enable(); }, "featureunselected": function() { layer.selectedFeatures.length == 0 && actions[0].disable(); } }); return actions; } }); Ext.preg(gxp.plugins.ZoomToSelectedFeatures.prototype.ptype, gxp.plugins.ZoomToSelectedFeatures);
version https://git-lfs.github.com/spec/v1 oid sha256:7076c06d1c5b0c8a10633ae2837be365f999203218d8484d9c4dd3bcb53c7e95 size 49060
'use strict'; var React = require('react'); var PureRenderMixin = require('react-addons-pure-render-mixin'); var SvgIcon = require('../../svg-icon'); var SocialPages = React.createClass({ displayName: 'SocialPages', mixins: [PureRenderMixin], render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M3 5v6h5L7 7l4 1V3H5c-1.1 0-2 .9-2 2zm5 8H3v6c0 1.1.9 2 2 2h6v-5l-4 1 1-4zm9 4l-4-1v5h6c1.1 0 2-.9 2-2v-6h-5l1 4zm2-14h-6v5l4-1-1 4h5V5c0-1.1-.9-2-2-2z' }) ); } }); module.exports = SocialPages;
import $ from 'jquery'; import ParsleyUI from '../../src/parsley/ui'; import Parsley from '../../src/parsley'; describe('ParsleyUI', () => { before(() => { Parsley.setLocale('en'); }); it('should create proper errors container when needed', () => { $('body').append('<input type="text" id="element" data-parsley-required />'); var parsleyField = $('#element').psly(); expect($('ul#parsley-id-' + parsleyField.__id__).length).to.be(0); parsleyField.validate(); expect($('#element').attr('data-parsley-id')).to.be(parsleyField.__id__); expect($('ul#parsley-id-' + parsleyField.__id__).length).to.be(1); expect($('ul#parsley-id-' + parsleyField.__id__).hasClass('parsley-errors-list')).to.be(true); }); it('should handle errors-container option', () => { $('body').append( '<form id="element">' + '<input id="field1" type="text" required data-parsley-errors-container="#container" />' + '<div id="container"></div>' + '<div id="container2"></div>' + '</form>'); $('#element').psly().validate(); expect($('#container .parsley-errors-list').length).to.be(1); $('#element').psly().destroy(); $('#field1').removeAttr('data-parsley-errors-container'); $('#element').psly({ errorsContainer: function (ins) { expect(ins).to.be($('#field1').psly()); expect(this).to.be($('#field1').psly()); return $('#container2'); } }).validate(); expect($('#container2 .parsley-errors-list').length).to.be(1); }); it('should handle wrong errors-container option', () => { $('body').append('<input type="text" id="element" data-parsley-errors-container="#donotexist" required/>'); var parsley = $('#element').psly(); expectWarning(() => { parsley.validate(); }); }); it('should not add success class on a field without constraints', () => { $('body').append('<input type="text" id="element" />'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('#element').hasClass('parsley-error')).to.be(false); expect($('#element').hasClass('parsley-success')).to.be(false); }); it('should not add success class on an empty optional field', () => { $('body').append('<input type="number" id="element" />'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('#element').hasClass('parsley-error')).to.be(false); expect($('#element').hasClass('parsley-success')).to.be(false); }); var checkType = (type, html, fillValue) => { it(`should add proper parsley class on success or failure (${type})`, () => { $('body').append(`<form id="element"><section>${html}</section></form>`); let form = $('#element').parsley(); let $inputHolder = $('#element section').children().first(); form.validate(); expect($inputHolder.attr('class')).to.be('parsley-error'); expect($('.parsley-errors-list').parent().prop("tagName")).to.be('SECTION'); // Fill and revalidate: fillValue($inputHolder); form.validate(); expect($inputHolder.attr('class')).to.be('parsley-success'); }); }; let callVal = $input => $input.val('foo'); checkType('text', '<input type="text" required/>', callVal); checkType('select', '<select multiple required><option value="foo">foo</option>', callVal); let callProp = $fieldset => $fieldset.find('input').prop('checked', true); checkType('radio', '<fieldset><input type="radio" name="foo" required /></fieldset>', callProp); checkType('checkbox', '<fieldset><input type="checkbox" name="foo" required /></fieldset>', callProp); it('should handle class-handler option', () => { $('body').append( '<form id="element">' + '<input id="field1" type="email" data-parsley-class-handler="#field2" required />' + '<div id="field2"></div>' + '<div id="field3"></div>' + '</form>'); $('#element').psly().validate(); expect($('#field2').hasClass('parsley-error')).to.be(true); $('#element').psly().destroy(); $('#field1').removeAttr('data-parsley-class-handler'); $('#element').psly({ classHandler: function (ins) { expect(ins).to.be($('#field1').parsley()); expect(this).to.be($('#field1').parsley()); return $('#field3'); } }).validate(); expect($('#field3').hasClass('parsley-error')).to.be(true); }); it('should show higher priority error message by default', () => { $('body').append('<input type="email" id="element" required />'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('#element').hasClass('parsley-error')).to.be(true); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-required')).to.be(true); $('#element').val('foo').psly().validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-type')).to.be(true); }); it('should show all errors message if priority enabled set to false', () => { $('body').append('<input type="email" id="element" required data-parsley-priority-enabled="false"/>'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(2); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').eq(0).hasClass('parsley-required')).to.be(true); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').eq(1).hasClass('parsley-type')).to.be(true); $('#element').val('foo').psly().validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-type')).to.be(true); }); it('should show custom error message by validator', () => { $('body').append('<input type="email" id="element" required data-parsley-required-message="foo" data-parsley-type-message="bar"/>'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').text()).to.be('foo'); $('#element').val('foo').psly().validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').text()).to.be('bar'); }); it('should show custom error message with variabilized parameters', () => { $('body').append('<input type="text" id="element" value="bar" data-parsley-minlength="7" data-parsley-minlength-message="foo %s bar"/>'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').text()).to.be('foo 7 bar'); }); it('should show custom error message for whole field', () => { $('body').append('<input type="email" id="element" required data-parsley-error-message="baz"/>'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').text()).to.be('baz'); $('#element').val('foo').psly().validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').text()).to.be('baz'); $('#element').val('[email protected]').psly().validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); }); it('should display no error message if diabled', () => { $('body').append('<input type="email" id="element" required data-parsley-errors-messages-disabled />'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); expect($('#element').hasClass('parsley-error')).to.be(true); }); it('should handle simple triggers (change, focus...)', () => { $('body').append('<input type="email" id="element" required data-parsley-trigger="change" />'); var parsleyField = $('#element').psly(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); $('#element').trigger($.Event('change')); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); }); it('should allow customization of triggers after first error', () => { $('body').append('<input type="email" id="element" required data-parsley-trigger-after-failure="focusout" />'); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); $('#element').val('[email protected]'); $('#element').trigger('input'); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); $('#element').trigger('focusout'); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); }); it('should auto bind error trigger on select field error (input=text)', () => { $('body').append('<input type="email" id="element" required />'); var parsleyField = $('#element').psly(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-required')).to.be(true); $('#element').val('foo').trigger('input'); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-type')).to.be(true); }); it('should auto bind error trigger on select field error (select)', () => { $('body').append('<select id="element" required>' + '<option value="">Choose</option>' + '<option value="foo">foo</option>' + '<option value="bar">bar</option>' + '</select>'); var parsleyField = $('#element').psly(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-required')).to.be(true); $('#element [option="foo"]').attr('selected', 'selected'); $('#element').trigger($.Event('change')); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-type')).to.be(false); }); it('should handle complex triggers (keyup, keypress...)', () => { $('body').append('<input type="email" id="element" required data-parsley-trigger="keyup" />'); var parsleyField = $('#element').psly(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); $('#element').val('foo').trigger($.Event('keyup')); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); $('#element').val('foob').trigger($.Event('keyup')); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); }); it('should handle trigger keyup threshold validation', () => { $('body').append('<input type="email" id="element" data-parsley-validation-threshold="7" required data-parsley-trigger="keyup" />'); var parsleyField = $('#element').psly(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); $('#element').val('[email protected]').trigger('keyup'); expect($('#element').hasClass('success')).to.be(false); $('#element').val('[email protected]').trigger('keyup'); expect($('#element').hasClass('parsley-success')).to.be(true); $('#element').val('@b.com').trigger('keyup'); expect($('#element').hasClass('parsley-success')).to.be(false); }); it('should handle UI disabling', () => { $('body').append('<input type="email" id="element" data-parsley-ui-enabled="false" required data-parsley-trigger="keyup" />'); var parsleyField = $('#element').psly(); expect($('ul#parsley-id-' + parsleyField.__id__).length).to.be(0); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__).length).to.be(0); }); it('should add novalidate on form elem', () => { $('body').append( '<form id="element" data-parsley-trigger="change">' + '<input id="field1" type="text" data-parsley-required="true" />' + '<div id="field2"></div>' + '<textarea id="field3" data-parsley-notblank="true"></textarea>' + '</form>'); var parsleyForm = $('#element').parsley(); expect($('#element').attr('novalidate')).not.to.be(undefined); }); it('should test the no-focus option', () => { $('body').append( '<form id="element" data-parsley-focus="first">' + '<input id="field1" type="text" data-parsley-required="true" data-parsley-no-focus />' + '<input id="field2" data-parsley-required />' + '</form>'); $('#element').parsley().validate(); expect($('#element').parsley()._focusedField.attr('id')).to.be('field2'); $('#field2').val('foo'); $('#element').psly().validate(); expect($('#element').parsley()._focusedField).to.be(null); $('#field1').removeAttr('data-parsley-no-focus'); $('#element').psly().validate(); expect($('#element').parsley()._focusedField.attr('id')).to.be('field1'); $('#element').attr('data-parsley-focus', 'last'); $('#element').psly().validate(); expect($('#element').parsley()._focusedField.attr('id')).to.be('field1'); $('#field2').val(''); $('#element').psly().validate(); expect($('#element').parsley()._focusedField.attr('id')).to.be('field2'); }); it('should test the manual add / update / remove error', () => { $('body').append('<input type="text" id="element" />'); var parsleyField = $('#element').parsley(); parsleyField.removeError('non-existent'); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); expect($('#element').hasClass('parsley-error')).to.be(false); expectWarning(() => { window.ParsleyUI.addError(parsleyField, 'foo', 'bar'); }); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1); expect($('#element').hasClass('parsley-error')).to.be(true); expect($('li.parsley-foo').length).to.be(1); expect($('li.parsley-foo').text()).to.be('bar'); expectWarning(() => { window.ParsleyUI.updateError(parsleyField, 'foo', 'baz'); }); expect($('li.parsley-foo').text()).to.be('baz'); expectWarning(() => { window.ParsleyUI.removeError(parsleyField, 'foo'); }); expect($('#element').hasClass('parsley-error')).to.be(false); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0); }); it('should have a getErrorsMessage() method', () => { $('body').append('<input type="email" id="element" value="foo" data-parsley-minlength="5" />'); var parsleyInstance = $('#element').parsley(); parsleyInstance.validate(); expectWarning(() => { window.ParsleyUI.getErrorsMessages(parsleyInstance); }); expect(window.ParsleyUI.getErrorsMessages(parsleyInstance).length).to.be(1); expect(window.ParsleyUI.getErrorsMessages(parsleyInstance)[0]).to.be('This value should be a valid email.'); $('#element').attr('data-parsley-priority-enabled', false); parsleyInstance.validate(); expect(window.ParsleyUI.getErrorsMessages(parsleyInstance).length).to.be(2); expect(window.ParsleyUI.getErrorsMessages(parsleyInstance)[0]).to.be('This value is too short. It should have 5 characters or more.'); }); it('should not have errors ul created for excluded fields', () => { $('body').append('<div id="hidden"><input type="hidden" id="element" value="foo" data-parsley-minlength="5" /></div>'); var parsleyInstance = $('#element').parsley(); expect($('#hidden ul').length).to.be(0); $('#hidden').remove(); }); it('should remove filled class from errors container when reseting', () => { $('body').append('<input type="email" id="element" value="foo" data-parsley-minlength="5" />'); var parsleyInstance = $('#element').parsley(); parsleyInstance.validate(); parsleyInstance.reset(); expect($('ul#parsley-id-' + parsleyInstance.__id__).hasClass('filled')).to.be(false); }); it('should re-bind error triggers after a reset (input=text)', () => { $('body').append('<input type="text" id="element" required />'); var parsleyInstance = $('#element').parsley(); parsleyInstance.validate(); parsleyInstance.reset(); parsleyInstance.validate(); expect($('ul#parsley-id-' + parsleyInstance.__id__ + ' li').length).to.be(1); $('#element').val('foo').trigger('input'); expect($('ul#parsley-id-' + parsleyInstance.__id__ + ' li').length).to.be(0); }); it('should re-bind error triggers after a reset (select)', () => { $('body').append('<select id="element" required>' + '<option value="">Choose</option>' + '<option value="foo">foo</option>' + '<option value="bar">bar</option>' + '</select>'); var parsleyInstance = $('#element').parsley(); parsleyInstance.validate(); parsleyInstance.reset(); parsleyInstance.validate(); expect($('ul#parsley-id-' + parsleyInstance.__id__ + ' li').length).to.be(1); $('#element option[value="foo"]').prop('selected', true); $('#element').trigger('input'); expect($('ul#parsley-id-' + parsleyInstance.__id__ + ' li').length).to.be(0); }); it('should re-bind custom triggers after a reset', () => { $('body').append('<input type="text" id="element" required data-parsley-trigger="focusout" />'); var parsleyInstance = $('#element').parsley(); parsleyInstance.validate(); parsleyInstance.reset(); $('#element').trigger('focusout'); expect($('ul#parsley-id-' + parsleyInstance.__id__ + ' li').length).to.be(1); }); it('should handle custom error message for validators with compound names', () => { $('body').append('<input type="text" value="1" id="element" data-parsley-custom-validator="2" data-parsley-custom-validator-message="custom-validator error"/>'); window.Parsley.addValidator('customValidator', (value, requirement) => { return requirement === value; }, 32); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').text()).to.be('custom-validator error'); window.Parsley.removeValidator('customValidator'); }); it('should handle custom error messages returned from custom validators', () => { $('body').append('<input type="text" value="1" id="element" data-parsley-custom-validator="2" data-parsley-custom-validator-message="custom-validator error"/>'); window.Parsley.addValidator('customValidator', (value, requirement) => { return $.Deferred().reject("Hey, this ain't good at all").promise(); }, 32); var parsleyField = $('#element').psly(); parsleyField.validate(); expect($(`ul#parsley-id-${parsleyField.__id__} li`).text()).to.be("Hey, this ain't good at all"); window.Parsley.removeValidator('customValidator'); }); it('should run before events are fired', () => { $('body').append('<input type="text" id="element" required/>'); var parsley = $('#element').parsley().on('field:validated', () => { expect($('.parsley-errors-list')).to.have.length(1); }); parsley.validate(); }); afterEach(() => { $('#element, .parsley-errors-list').remove(); }); });
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var is = require('@redux-saga/is'); var __chunk_1 = require('./chunk-5caa0f1a.js'); var __chunk_2 = require('./chunk-062c0282.js'); require('@babel/runtime/helpers/extends'); require('@redux-saga/symbols'); require('@redux-saga/delay-p'); var done = function done(value) { return { done: true, value: value }; }; var qEnd = {}; function safeName(patternOrChannel) { if (is.channel(patternOrChannel)) { return 'channel'; } if (is.stringableFunc(patternOrChannel)) { return String(patternOrChannel); } if (is.func(patternOrChannel)) { return patternOrChannel.name; } return String(patternOrChannel); } function fsmIterator(fsm, startState, name) { var stateUpdater, errorState, effect, nextState = startState; function next(arg, error) { if (nextState === qEnd) { return done(arg); } if (error && !errorState) { nextState = qEnd; throw error; } else { stateUpdater && stateUpdater(arg); var currentState = error ? fsm[errorState](error) : fsm[nextState](); nextState = currentState.nextState; effect = currentState.effect; stateUpdater = currentState.stateUpdater; errorState = currentState.errorState; return nextState === qEnd ? done(arg) : effect; } } return __chunk_1.makeIterator(next, function (error) { return next(null, error); }, name); } function takeEvery(patternOrChannel, worker) { for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } var yTake = { done: false, value: __chunk_2.take(patternOrChannel) }; var yFork = function yFork(ac) { return { done: false, value: __chunk_2.fork.apply(void 0, [worker].concat(args, [ac])) }; }; var action, setAction = function setAction(ac) { return action = ac; }; return fsmIterator({ q1: function q1() { return { nextState: 'q2', effect: yTake, stateUpdater: setAction }; }, q2: function q2() { return { nextState: 'q1', effect: yFork(action) }; } }, 'q1', "takeEvery(" + safeName(patternOrChannel) + ", " + worker.name + ")"); } function takeLatest(patternOrChannel, worker) { for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } var yTake = { done: false, value: __chunk_2.take(patternOrChannel) }; var yFork = function yFork(ac) { return { done: false, value: __chunk_2.fork.apply(void 0, [worker].concat(args, [ac])) }; }; var yCancel = function yCancel(task) { return { done: false, value: __chunk_2.cancel(task) }; }; var task, action; var setTask = function setTask(t) { return task = t; }; var setAction = function setAction(ac) { return action = ac; }; return fsmIterator({ q1: function q1() { return { nextState: 'q2', effect: yTake, stateUpdater: setAction }; }, q2: function q2() { return task ? { nextState: 'q3', effect: yCancel(task) } : { nextState: 'q1', effect: yFork(action), stateUpdater: setTask }; }, q3: function q3() { return { nextState: 'q1', effect: yFork(action), stateUpdater: setTask }; } }, 'q1', "takeLatest(" + safeName(patternOrChannel) + ", " + worker.name + ")"); } function takeLeading(patternOrChannel, worker) { for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } var yTake = { done: false, value: __chunk_2.take(patternOrChannel) }; var yCall = function yCall(ac) { return { done: false, value: __chunk_2.call.apply(void 0, [worker].concat(args, [ac])) }; }; var action; var setAction = function setAction(ac) { return action = ac; }; return fsmIterator({ q1: function q1() { return { nextState: 'q2', effect: yTake, stateUpdater: setAction }; }, q2: function q2() { return { nextState: 'q1', effect: yCall(action) }; } }, 'q1', "takeLeading(" + safeName(patternOrChannel) + ", " + worker.name + ")"); } function throttle(delayLength, pattern, worker) { for (var _len = arguments.length, args = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) { args[_key - 3] = arguments[_key]; } var action, channel; var yActionChannel = { done: false, value: __chunk_2.actionChannel(pattern, __chunk_2.sliding(1)) }; var yTake = function yTake() { return { done: false, value: __chunk_2.take(channel) }; }; var yFork = function yFork(ac) { return { done: false, value: __chunk_2.fork.apply(void 0, [worker].concat(args, [ac])) }; }; var yDelay = { done: false, value: __chunk_2.delay(delayLength) }; var setAction = function setAction(ac) { return action = ac; }; var setChannel = function setChannel(ch) { return channel = ch; }; return fsmIterator({ q1: function q1() { return { nextState: 'q2', effect: yActionChannel, stateUpdater: setChannel }; }, q2: function q2() { return { nextState: 'q3', effect: yTake(), stateUpdater: setAction }; }, q3: function q3() { return { nextState: 'q4', effect: yFork(action) }; }, q4: function q4() { return { nextState: 'q2', effect: yDelay }; } }, 'q1', "throttle(" + safeName(pattern) + ", " + worker.name + ")"); } function retry(maxTries, delayLength, fn) { var counter = maxTries; for (var _len = arguments.length, args = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) { args[_key - 3] = arguments[_key]; } var yCall = { done: false, value: __chunk_2.call.apply(void 0, [fn].concat(args)) }; var yDelay = { done: false, value: __chunk_2.delay(delayLength) }; return fsmIterator({ q1: function q1() { return { nextState: 'q2', effect: yCall, errorState: 'q10' }; }, q2: function q2() { return { nextState: qEnd }; }, q10: function q10(error) { counter -= 1; if (counter <= 0) { throw error; } return { nextState: 'q1', effect: yDelay }; } }, 'q1', "retry(" + fn.name + ")"); } function debounceHelper(delayLength, patternOrChannel, worker) { for (var _len = arguments.length, args = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) { args[_key - 3] = arguments[_key]; } var action, raceOutput; var yTake = { done: false, value: __chunk_2.take(patternOrChannel) }; var yRace = { done: false, value: __chunk_2.race({ action: __chunk_2.take(patternOrChannel), debounce: __chunk_2.delay(delayLength) }) }; var yFork = function yFork(ac) { return { done: false, value: __chunk_2.fork.apply(void 0, [worker].concat(args, [ac])) }; }; var yNoop = function yNoop(value) { return { done: false, value: value }; }; var setAction = function setAction(ac) { return action = ac; }; var setRaceOutput = function setRaceOutput(ro) { return raceOutput = ro; }; return fsmIterator({ q1: function q1() { return { nextState: 'q2', effect: yTake, stateUpdater: setAction }; }, q2: function q2() { return { nextState: 'q3', effect: yRace, stateUpdater: setRaceOutput }; }, q3: function q3() { return raceOutput.debounce ? { nextState: 'q1', effect: yFork(action) } : { nextState: 'q2', effect: yNoop(raceOutput.action), stateUpdater: setAction }; } }, 'q1', "debounce(" + safeName(patternOrChannel) + ", " + worker.name + ")"); } var validateTakeEffect = function validateTakeEffect(fn, patternOrChannel, worker) { __chunk_1.check(patternOrChannel, is.notUndef, fn.name + " requires a pattern or channel"); __chunk_1.check(worker, is.notUndef, fn.name + " requires a saga parameter"); }; function takeEvery$1(patternOrChannel, worker) { { validateTakeEffect(takeEvery$1, patternOrChannel, worker); } for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } return __chunk_2.fork.apply(void 0, [takeEvery, patternOrChannel, worker].concat(args)); } function takeLatest$1(patternOrChannel, worker) { { validateTakeEffect(takeLatest$1, patternOrChannel, worker); } for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } return __chunk_2.fork.apply(void 0, [takeLatest, patternOrChannel, worker].concat(args)); } function takeLeading$1(patternOrChannel, worker) { { validateTakeEffect(takeLeading$1, patternOrChannel, worker); } for (var _len3 = arguments.length, args = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) { args[_key3 - 2] = arguments[_key3]; } return __chunk_2.fork.apply(void 0, [takeLeading, patternOrChannel, worker].concat(args)); } function throttle$1(ms, pattern, worker) { { __chunk_1.check(pattern, is.notUndef, 'throttle requires a pattern'); __chunk_1.check(worker, is.notUndef, 'throttle requires a saga parameter'); } for (var _len4 = arguments.length, args = new Array(_len4 > 3 ? _len4 - 3 : 0), _key4 = 3; _key4 < _len4; _key4++) { args[_key4 - 3] = arguments[_key4]; } return __chunk_2.fork.apply(void 0, [throttle, ms, pattern, worker].concat(args)); } function retry$1(maxTries, delayLength, worker) { for (var _len5 = arguments.length, args = new Array(_len5 > 3 ? _len5 - 3 : 0), _key5 = 3; _key5 < _len5; _key5++) { args[_key5 - 3] = arguments[_key5]; } return __chunk_2.call.apply(void 0, [retry, maxTries, delayLength, worker].concat(args)); } function debounce(delayLength, pattern, worker) { for (var _len6 = arguments.length, args = new Array(_len6 > 3 ? _len6 - 3 : 0), _key6 = 3; _key6 < _len6; _key6++) { args[_key6 - 3] = arguments[_key6]; } return __chunk_2.fork.apply(void 0, [debounceHelper, delayLength, pattern, worker].concat(args)); } exports.effectTypes = __chunk_2.effectTypes; exports.take = __chunk_2.take; exports.takeMaybe = __chunk_2.takeMaybe; exports.put = __chunk_2.put; exports.putResolve = __chunk_2.putResolve; exports.all = __chunk_2.all; exports.race = __chunk_2.race; exports.call = __chunk_2.call; exports.apply = __chunk_2.apply; exports.cps = __chunk_2.cps; exports.fork = __chunk_2.fork; exports.spawn = __chunk_2.spawn; exports.join = __chunk_2.join; exports.cancel = __chunk_2.cancel; exports.select = __chunk_2.select; exports.actionChannel = __chunk_2.actionChannel; exports.cancelled = __chunk_2.cancelled; exports.flush = __chunk_2.flush; exports.getContext = __chunk_2.getContext; exports.setContext = __chunk_2.setContext; exports.delay = __chunk_2.delay; exports.debounce = debounce; exports.retry = retry$1; exports.takeEvery = takeEvery$1; exports.takeLatest = takeLatest$1; exports.takeLeading = takeLeading$1; exports.throttle = throttle$1;
YUI.add("yuidoc-meta", function(Y) { Y.YUIDoc = { meta: { "classes": [ "Amplitude", "AudioIn", "Env", "FFT", "Noise", "Oscillator", "Pulse", "SoundFile", "p5.Element", "p5.MediaElement", "p5.dom", "p5.sound" ], "modules": [ "p5.dom", "p5.sound" ], "allModules": [ { "displayName": "p5.dom", "name": "p5.dom", "description": "This is the p5.dom library." }, { "displayName": "p5.sound", "name": "p5.sound", "description": "p5.sound extends p5 with Web Audio functionality including audio input, playback, analysis and synthesis." } ] } }; });
/// <reference path="angular.d.ts" /> /// <reference path="angular-route.d.ts" /> /// <reference path="angular-sanitize.d.ts" /> /// <reference path="bootstrap.d.ts" /> /// <reference path="moment.d.ts" /> /// <reference path="moment-duration-format.d.ts" /> /// <reference path="d3.d.ts" /> /// <reference path="underscore.d.ts" /> var bosunApp = angular.module('bosunApp', [ 'ngRoute', 'bosunControllers', 'mgcrea.ngStrap', 'ngSanitize', 'ui.ace', ]); bosunApp.config(['$routeProvider', '$locationProvider', '$httpProvider', function ($routeProvider, $locationProvider, $httpProvider) { $locationProvider.html5Mode(true); $routeProvider. when('/', { title: 'Dashboard', templateUrl: 'partials/dashboard.html', controller: 'DashboardCtrl' }). when('/items', { title: 'Items', templateUrl: 'partials/items.html', controller: 'ItemsCtrl' }). when('/expr', { title: 'Expression', templateUrl: 'partials/expr.html', controller: 'ExprCtrl' }). when('/graph', { title: 'Graph', templateUrl: 'partials/graph.html', controller: 'GraphCtrl' }). when('/host', { title: 'Host View', templateUrl: 'partials/host.html', controller: 'HostCtrl', reloadOnSearch: false }). when('/silence', { title: 'Silence', templateUrl: 'partials/silence.html', controller: 'SilenceCtrl' }). when('/config', { title: 'Configuration', templateUrl: 'partials/config.html', controller: 'ConfigCtrl', reloadOnSearch: false }). when('/action', { title: 'Action', templateUrl: 'partials/action.html', controller: 'ActionCtrl' }). when('/history', { title: 'Alert History', templateUrl: 'partials/history.html', controller: 'HistoryCtrl' }). when('/put', { title: 'Data Entry', templateUrl: 'partials/put.html', controller: 'PutCtrl' }). when('/incident', { title: 'Incident', templateUrl: 'partials/incident.html', controller: 'IncidentCtrl' }). otherwise({ redirectTo: '/' }); $httpProvider.interceptors.push(function ($q) { return { 'request': function (config) { config.headers['X-Miniprofiler'] = 'true'; return config; } }; }); }]); bosunApp.run(['$location', '$rootScope', function ($location, $rootScope) { $rootScope.$on('$routeChangeSuccess', function (event, current, previous) { $rootScope.title = current.$$route.title; $rootScope.shortlink = false; }); }]); var bosunControllers = angular.module('bosunControllers', []); bosunControllers.controller('BosunCtrl', ['$scope', '$route', '$http', '$q', '$rootScope', function ($scope, $route, $http, $q, $rootScope) { $scope.$on('$routeChangeSuccess', function (event, current, previous) { $scope.stop(true); }); $scope.active = function (v) { if (!$route.current) { return null; } if ($route.current.loadedTemplateUrl == 'partials/' + v + '.html') { return { active: true }; } return null; }; $scope.json = function (v) { return JSON.stringify(v, null, ' '); }; $scope.btoa = function (v) { return encodeURIComponent(btoa(v)); }; $scope.encode = function (v) { return encodeURIComponent(v); }; $scope.req_from_m = function (m) { var r = new Request(); var q = new Query(); q.metric = m; r.queries.push(q); return r; }; $scope.panelClass = function (status, prefix) { if (prefix === void 0) { prefix = "panel-"; } switch (status) { case "critical": return prefix + "danger"; case "unknown": return prefix + "info"; case "warning": return prefix + "warning"; case "normal": return prefix + "success"; case "error": return prefix + "danger"; default: return prefix + "default"; } }; $scope.values = {}; $scope.setKey = function (key, value) { if (value === undefined) { delete $scope.values[key]; } else { $scope.values[key] = value; } }; $scope.getKey = function (key) { return $scope.values[key]; }; var scheduleFilter; $scope.refresh = function (filter) { var d = $q.defer(); scheduleFilter = filter; $scope.animate(); var p = $http.get('/api/alerts?filter=' + encodeURIComponent(filter || "")) .success(function (data) { $scope.schedule = data; $scope.timeanddate = data.TimeAndDate; d.resolve(); }) .error(function (err) { d.reject(err); }); p.finally($scope.stop); return d.promise; }; var sz = 30; var orig = 700; var light = '#4ba2d9'; var dark = '#1f5296'; var med = '#356eb6'; var mult = sz / orig; var bgrad = 25 * mult; var circles = [ [150, 150, dark], [550, 150, dark], [150, 550, light], [550, 550, light], ]; var svg = d3.select('#logo') .append('svg') .attr('height', sz) .attr('width', sz); svg.selectAll('rect.bg') .data([[0, light], [sz / 2, dark]]) .enter() .append('rect') .attr('class', 'bg') .attr('width', sz) .attr('height', sz / 2) .attr('rx', bgrad) .attr('ry', bgrad) .attr('fill', function (d) { return d[1]; }) .attr('y', function (d) { return d[0]; }); svg.selectAll('path.diamond') .data([150, 550]) .enter() .append('path') .attr('d', function (d) { var s = 'M ' + d * mult + ' ' + 150 * mult; var w = 200 * mult; s += ' l ' + w + ' ' + w; s += ' l ' + -w + ' ' + w; s += ' l ' + -w + ' ' + -w + ' Z'; return s; }) .attr('fill', med) .attr('stroke', 'white') .attr('stroke-width', 15 * mult); svg.selectAll('rect.white') .data([150, 350, 550]) .enter() .append('rect') .attr('class', 'white') .attr('width', .5) .attr('height', '100%') .attr('fill', 'white') .attr('x', function (d) { return d * mult; }); svg.selectAll('circle') .data(circles) .enter() .append('circle') .attr('cx', function (d) { return d[0] * mult; }) .attr('cy', function (d) { return d[1] * mult; }) .attr('r', 62.5 * mult) .attr('fill', function (d) { return d[2]; }) .attr('stroke', 'white') .attr('stroke-width', 25 * mult); var transitionDuration = 750; var animateCount = 0; $scope.animate = function () { animateCount++; if (animateCount == 1) { doAnimate(); } }; function doAnimate() { if (!animateCount) { return; } d3.shuffle(circles); svg.selectAll('circle') .data(circles, function (d, i) { return i; }) .transition() .duration(transitionDuration) .attr('cx', function (d) { return d[0] * mult; }) .attr('cy', function (d) { return d[1] * mult; }) .attr('fill', function (d) { return d[2]; }); setTimeout(doAnimate, transitionDuration); } $scope.stop = function (all) { if (all === void 0) { all = false; } if (all) { animateCount = 0; } else if (animateCount > 0) { animateCount--; } }; var short = $('#shortlink')[0]; $scope.shorten = function () { $http.get('/api/shorten').success(function (data) { if (data.id) { short.value = data.id; $rootScope.shortlink = true; setTimeout(function () { short.setSelectionRange(0, data.id.length); }); } }); }; }]); var tsdbDateFormat = 'YYYY/MM/DD-HH:mm:ss'; moment.defaultFormat = tsdbDateFormat; moment.locale('en', { relativeTime: { future: "in %s", past: "%s-ago", s: "%ds", m: "%dm", mm: "%dm", h: "%dh", hh: "%dh", d: "%dd", dd: "%dd", M: "%dn", MM: "%dn", y: "%dy", yy: "%dy" } }); function createCookie(name, value, days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } else { expires = ""; } document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/"; } function readCookie(name) { var nameEQ = escape(name) + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) === ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) === 0) return unescape(c.substring(nameEQ.length, c.length)); } return null; } function eraseCookie(name) { createCookie(name, "", -1); } function getUser() { return readCookie('action-user'); } function setUser(name) { createCookie('action-user', name, 1000); } // from: http://stackoverflow.com/a/15267754/864236 bosunApp.filter('reverse', function () { return function (items) { if (!angular.isArray(items)) { return []; } return items.slice().reverse(); }; }); bosunControllers.controller('ActionCtrl', ['$scope', '$http', '$location', '$route', function ($scope, $http, $location, $route) { var search = $location.search(); $scope.user = readCookie("action-user"); $scope.type = search.type; $scope.notify = true; $scope.msgValid = true; $scope.message = ""; $scope.validateMsg = function () { $scope.msgValid = (!$scope.notify) || ($scope.message != ""); }; if (search.key) { var keys = search.key; if (!angular.isArray(search.key)) { keys = [search.key]; } $location.search('key', null); $scope.setKey('action-keys', keys); } else { $scope.keys = $scope.getKey('action-keys'); } $scope.submit = function () { $scope.validateMsg(); if (!$scope.msgValid || ($scope.user == "")) { return; } var data = { Type: $scope.type, User: $scope.user, Message: $scope.message, Keys: $scope.keys, Notify: $scope.notify }; createCookie("action-user", $scope.user, 1000); $http.post('/api/action', data) .success(function (data) { $location.url('/'); }) .error(function (error) { alert(error); }); }; }]); bosunControllers.controller('ConfigCtrl', ['$scope', '$http', '$location', '$route', '$timeout', '$sce', function ($scope, $http, $location, $route, $timeout, $sce) { var search = $location.search(); $scope.fromDate = search.fromDate || ''; $scope.fromTime = search.fromTime || ''; $scope.toDate = search.toDate || ''; $scope.toTime = search.toTime || ''; $scope.intervals = +search.intervals || 5; $scope.duration = +search.duration || null; $scope.config_text = 'Loading config...'; $scope.selected_alert = search.alert || ''; $scope.email = search.email || ''; $scope.template_group = search.template_group || ''; $scope.items = parseItems(); $scope.tab = search.tab || 'results'; $scope.aceTheme = 'chrome'; $scope.aceMode = 'bosun'; var expr = search.expr; function buildAlertFromExpr() { if (!expr) return; var newAlertName = "test"; var idx = 1; //find a unique alert name while ($scope.items["alert"].indexOf(newAlertName) != -1 || $scope.items["template"].indexOf(newAlertName) != -1) { newAlertName = "test" + idx; idx++; } var text = '\n\ntemplate ' + newAlertName + ' {\n' + ' subject = {{.Last.Status}}: {{.Alert.Name}} on {{.Group.host}}\n' + ' body = `<p>Name: {{.Alert.Name}}\n' + ' <p>Tags:\n' + ' <table>\n' + ' {{range $k, $v := .Group}}\n' + ' <tr><td>{{$k}}</td><td>{{$v}}</td></tr>\n' + ' {{end}}\n' + ' </table>`\n' + '}\n\n'; var expression = atob(expr); var lines = expression.split("\n").map(function (l) { return l.trim(); }); lines[lines.length - 1] = "crit = " + lines[lines.length - 1]; expression = lines.join("\n "); text += 'alert ' + newAlertName + ' {\n' + ' template = ' + newAlertName + '\n' + ' ' + expression + '\n' + '}\n'; $scope.config_text += text; $scope.items = parseItems(); $timeout(function () { //can't scroll editor until after control is updated. Defer it. $scope.scrollTo("alert", newAlertName); }); } function parseItems() { var configText = $scope.config_text; var re = /^\s*(alert|template|notification|lookup|macro)\s+([\w\-\.\$]+)\s*\{/gm; var match; var items = {}; items["alert"] = []; items["template"] = []; items["lookup"] = []; items["notification"] = []; items["macro"] = []; while (match = re.exec(configText)) { var type = match[1]; var name = match[2]; var list = items[type]; if (!list) { list = []; items[type] = list; } list.push(name); } return items; } $http.get('/api/config?hash=' + (search.hash || '')) .success(function (data) { $scope.config_text = data; $scope.items = parseItems(); buildAlertFromExpr(); if (!$scope.selected_alert && $scope.items["alert"].length) { $scope.selected_alert = $scope.items["alert"][0]; } $timeout(function () { //can't scroll editor until after control is updated. Defer it. $scope.scrollTo("alert", $scope.selected_alert); }); }) .error(function (data) { $scope.validationResult = "Error fetching config: " + data; }); $scope.reparse = function () { $scope.items = parseItems(); }; var editor; $scope.aceLoaded = function (_editor) { editor = _editor; $scope.editor = editor; editor.getSession().setUseWrapMode(true); editor.on("blur", function () { $scope.$apply(function () { $scope.items = parseItems(); }); }); }; var syntax = true; $scope.aceToggleHighlight = function () { if (syntax) { editor.getSession().setMode(); syntax = false; return; } syntax = true; editor.getSession().setMode({ path: 'ace/mode/' + $scope.aceMode, v: Date.now() }); }; $scope.scrollTo = function (type, name) { var searchRegex = new RegExp("^\\s*" + type + "\\s+" + name, "g"); editor.find(searchRegex, { backwards: false, wrap: true, caseSensitive: false, wholeWord: false, regExp: true }); if (type == "alert") { $scope.selectAlert(name); } }; $scope.scrollToInterval = function (id) { document.getElementById('time-' + id).scrollIntoView(); $scope.show($scope.sets[id]); }; $scope.show = function (set) { set.show = 'loading...'; $scope.animate(); var url = '/api/rule?' + 'alert=' + encodeURIComponent($scope.selected_alert) + '&from=' + encodeURIComponent(set.Time); $http.post(url, $scope.config_text) .success(function (data) { procResults(data); set.Results = data.Sets[0].Results; }) .error(function (error) { $scope.error = error; }) .finally(function () { $scope.stop(); delete (set.show); }); }; $scope.setInterval = function () { var from = moment.utc($scope.fromDate + ' ' + $scope.fromTime); var to = moment.utc($scope.toDate + ' ' + $scope.toTime); if (!from.isValid() || !to.isValid()) { return; } var diff = from.diff(to); if (!diff) { return; } var intervals = +$scope.intervals; if (intervals < 2) { return; } diff /= 1000 * 60; var d = Math.abs(Math.round(diff / intervals)); if (d < 1) { d = 1; } $scope.duration = d; }; $scope.setDuration = function () { var from = moment.utc($scope.fromDate + ' ' + $scope.fromTime); var to = moment.utc($scope.toDate + ' ' + $scope.toTime); if (!from.isValid() || !to.isValid()) { return; } var diff = from.diff(to); if (!diff) { return; } var duration = +$scope.duration; if (duration < 1) { return; } $scope.intervals = Math.abs(Math.round(diff / duration / 1000 / 60)); }; $scope.selectAlert = function (alert) { $scope.selected_alert = alert; $location.search("alert", alert); // Attempt to find `template = foo` in order to set up quick jump between template and alert var searchRegex = new RegExp("^\\s*alert\\s+" + alert, "g"); var lines = $scope.config_text.split("\n"); $scope.quickJumpTarget = null; for (var i = 0; i < lines.length; i++) { if (searchRegex.test(lines[i])) { for (var j = i + 1; j < lines.length; j++) { // Close bracket at start of line means end of alert. if (/^\s*\}/m.test(lines[j])) { return; } var found = /^\s*template\s*=\s*([\w\-\.\$]+)/m.exec(lines[j]); if (found) { $scope.quickJumpTarget = "template " + found[1]; } } } } }; $scope.quickJump = function () { var parts = $scope.quickJumpTarget.split(" "); if (parts.length != 2) { return; } $scope.scrollTo(parts[0], parts[1]); if (parts[0] == "template" && $scope.selected_alert) { $scope.quickJumpTarget = "alert " + $scope.selected_alert; } }; $scope.setTemplateGroup = function (group) { var match = group.match(/{(.*)}/); if (match) { $scope.template_group = match[1]; } }; var line_re = /test:(\d+)/; $scope.validate = function () { $http.post('/api/config_test', $scope.config_text) .success(function (data) { if (data == "") { $scope.validationResult = "Valid"; $timeout(function () { $scope.validationResult = ""; }, 2000); } else { $scope.validationResult = data; var m = data.match(line_re); if (angular.isArray(m) && (m.length > 1)) { editor.gotoLine(m[1]); } } }) .error(function (error) { $scope.validationResult = 'Error validating: ' + error; }); }; $scope.test = function () { $scope.error = ''; $scope.running = true; $scope.warning = []; $location.search('fromDate', $scope.fromDate || null); $location.search('fromTime', $scope.fromTime || null); $location.search('toDate', $scope.toDate || null); $location.search('toTime', $scope.toTime || null); $location.search('intervals', String($scope.intervals) || null); $location.search('duration', String($scope.duration) || null); $location.search('email', $scope.email || null); $location.search('template_group', $scope.template_group || null); $scope.animate(); var from = moment.utc($scope.fromDate + ' ' + $scope.fromTime); var to = moment.utc($scope.toDate + ' ' + $scope.toTime); if (!from.isValid()) { from = to; } if (!to.isValid()) { to = from; } if (!from.isValid() && !to.isValid()) { from = to = moment.utc(); } var diff = from.diff(to); var intervals; if (diff == 0) { intervals = 1; } else if (Math.abs(diff) < 60 * 1000) { intervals = 2; } else { intervals = +$scope.intervals; } var url = '/api/rule?' + 'alert=' + encodeURIComponent($scope.selected_alert) + '&from=' + encodeURIComponent(from.format()) + '&to=' + encodeURIComponent(to.format()) + '&intervals=' + encodeURIComponent(intervals) + '&email=' + encodeURIComponent($scope.email) + '&template_group=' + encodeURIComponent($scope.template_group); $http.post(url, $scope.config_text) .success(function (data) { $scope.sets = data.Sets; $scope.alert_history = data.AlertHistory; if (data.Hash) { $location.search('hash', data.Hash); } procResults(data); }) .error(function (error) { $scope.error = error; }) .finally(function () { $scope.running = false; $scope.stop(); }); }; $scope.zws = function (v) { return v.replace(/([,{}()])/g, '$1\u200b'); }; $scope.loadTimelinePanel = function (entry, v) { if (v.doneLoading && !v.error) { return; } v.error = null; v.doneLoading = false; var ak = entry.key; var openBrack = ak.indexOf("{"); var closeBrack = ak.indexOf("}"); var alertName = ak.substr(0, openBrack); var template = ak.substring(openBrack + 1, closeBrack); var url = '/api/rule?' + 'alert=' + encodeURIComponent(alertName) + '&from=' + encodeURIComponent(moment.utc(v.Time).format()) + '&template_group=' + encodeURIComponent(template); $http.post(url, $scope.config_text) .success(function (data) { v.subject = data.Subject; v.body = $sce.trustAsHtml(data.Body); }) .error(function (error) { v.error = error; }) .finally(function () { v.doneLoading = true; }); }; function procResults(data) { $scope.subject = data.Subject; $scope.body = $sce.trustAsHtml(data.Body); $scope.data = JSON.stringify(data.Data, null, ' '); $scope.error = data.Errors; $scope.warning = data.Warnings; } $scope.downloadConfig = function () { var blob = new Blob([$scope.config_text], { type: "text/plain;charset=utf-8" }); saveAs(blob, "bosun.conf"); }; return $scope; }]); bosunControllers.controller('DashboardCtrl', ['$scope', '$http', '$location', function ($scope, $http, $location) { var search = $location.search(); $scope.loading = 'Loading'; $scope.error = ''; $scope.filter = search.filter; if (!$scope.filter) { $scope.filter = readCookie("filter"); } $location.search('filter', $scope.filter || null); reload(); function reload() { $scope.refresh($scope.filter).then(function () { $scope.loading = ''; $scope.error = ''; }, function (err) { $scope.loading = ''; $scope.error = 'Unable to fetch alerts: ' + err; }); } $scope.keydown = function ($event) { if ($event.keyCode == 13) { createCookie("filter", $scope.filter || "", 1000); $location.search('filter', $scope.filter || null); } }; }]); bosunApp.directive('tsResults', function () { return { templateUrl: '/partials/results.html', link: function (scope, elem, attrs) { scope.isSeries = function (v) { return typeof (v) === 'object'; }; } }; }); bosunApp.directive('tsComputations', function () { return { scope: { computations: '=tsComputations', time: '=', header: '=' }, templateUrl: '/partials/computations.html', link: function (scope, elem, attrs) { if (scope.time) { var m = moment.utc(scope.time); scope.timeParam = "&date=" + encodeURIComponent(m.format("YYYY-MM-DD")) + "&time=" + encodeURIComponent(m.format("HH:mm")); } scope.btoa = function (v) { return encodeURIComponent(btoa(v)); }; } }; }); function fmtDuration(v) { var diff = moment.duration(v, 'milliseconds'); var f; if (Math.abs(v) < 60000) { return diff.format('ss[s]'); } return diff.format('d[d]hh[h]mm[m]ss[s]'); } function fmtTime(v) { var m = moment(v).utc(); var now = moment().utc(); var msdiff = now.diff(m); var ago = ''; var inn = ''; if (msdiff >= 0) { ago = ' ago'; } else { inn = 'in '; } return m.format() + ' (' + inn + fmtDuration(msdiff) + ago + ')'; } function parseDuration(v) { var pattern = /(\d+)(d|y|n|h|m|s)-ago/; var m = pattern.exec(v); return moment.duration(parseInt(m[1]), m[2].replace('n', 'M')); } bosunApp.directive("tsTime", function () { return { link: function (scope, elem, attrs) { scope.$watch(attrs.tsTime, function (v) { var m = moment(v).utc(); var text = fmtTime(v); if (attrs.tsEndTime) { var diff = moment(scope.$eval(attrs.tsEndTime)).diff(m); var duration = fmtDuration(diff); text += " for " + duration; } if (attrs.noLink) { elem.text(text); } else { var el = document.createElement('a'); el.text = text; el.href = 'http://www.timeanddate.com/worldclock/converted.html?iso='; el.href += m.format('YYYYMMDDTHHmm'); el.href += '&p1=0'; angular.forEach(scope.timeanddate, function (v, k) { el.href += '&p' + (k + 2) + '=' + v; }); elem.html(el); } }); } }; }); bosunApp.directive("tsSince", function () { return { link: function (scope, elem, attrs) { scope.$watch(attrs.tsSince, function (v) { var m = moment(v).utc(); elem.text(m.fromNow()); }); } }; }); bosunApp.directive("tooltip", function () { return { link: function (scope, elem, attrs) { angular.element(elem[0]).tooltip({ placement: "bottom" }); } }; }); bosunApp.directive('tsTab', function () { return { link: function (scope, elem, attrs) { var ta = elem[0]; elem.keydown(function (evt) { if (evt.ctrlKey) { return; } // This is so shift-enter can be caught to run a rule when tsTab is called from // the rule page if (evt.keyCode == 13 && evt.shiftKey) { return; } switch (evt.keyCode) { case 9: evt.preventDefault(); var v = ta.value; var start = ta.selectionStart; ta.value = v.substr(0, start) + "\t" + v.substr(start); ta.selectionStart = ta.selectionEnd = start + 1; return; case 13: if (ta.selectionStart != ta.selectionEnd) { return; } evt.preventDefault(); var v = ta.value; var start = ta.selectionStart; var sub = v.substr(0, start); var last = sub.lastIndexOf("\n") + 1; for (var i = last; i < sub.length && /[ \t]/.test(sub[i]); i++) ; var ws = sub.substr(last, i - last); ta.value = v.substr(0, start) + "\n" + ws + v.substr(start); ta.selectionStart = ta.selectionEnd = start + 1 + ws.length; } }); } }; }); bosunApp.directive('tsresizable', function () { return { restrict: 'A', scope: { callback: '&onResize' }, link: function postLink(scope, elem, attrs) { elem.resizable(); elem.on('resizestop', function (evt, ui) { if (scope.callback) { scope.callback(); } }); } }; }); bosunApp.directive('tsTableSort', ['$timeout', function ($timeout) { return { link: function (scope, elem, attrs) { $timeout(function () { $(elem).tablesorter({ sortList: scope.$eval(attrs.tsTableSort) }); }); } }; }]); bosunApp.directive('tsTimeLine', function () { var tsdbFormat = d3.time.format.utc("%Y/%m/%d-%X"); function parseDate(s) { return moment.utc(s).toDate(); } var margin = { top: 10, right: 10, bottom: 30, left: 250 }; return { link: function (scope, elem, attrs) { scope.shown = {}; scope.collapse = function (i, entry, v) { scope.shown[i] = !scope.shown[i]; if (scope.loadTimelinePanel && entry && scope.shown[i]) { scope.loadTimelinePanel(entry, v); } }; scope.$watch('alert_history', update); function update(history) { if (!history) { return; } var entries = d3.entries(history); if (!entries.length) { return; } entries.sort(function (a, b) { return a.key.localeCompare(b.key); }); scope.entries = entries; var values = entries.map(function (v) { return v.value; }); var keys = entries.map(function (v) { return v.key; }); var barheight = 500 / values.length; barheight = Math.min(barheight, 45); barheight = Math.max(barheight, 15); var svgHeight = values.length * barheight + margin.top + margin.bottom; var height = svgHeight - margin.top - margin.bottom; var svgWidth = elem.width(); var width = svgWidth - margin.left - margin.right; var xScale = d3.time.scale.utc().range([0, width]); var xAxis = d3.svg.axis() .scale(xScale) .orient('bottom'); elem.empty(); var svg = d3.select(elem[0]) .append('svg') .attr('width', svgWidth) .attr('height', svgHeight) .append('g') .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); svg.append('g') .attr('class', 'x axis tl-axis') .attr('transform', 'translate(0,' + height + ')'); xScale.domain([ d3.min(values, function (d) { return d3.min(d.History, function (c) { return parseDate(c.Time); }); }), d3.max(values, function (d) { return d3.max(d.History, function (c) { return parseDate(c.EndTime); }); }), ]); var legend = d3.select(elem[0]) .append('div') .attr('class', 'tl-legend'); var time_legend = legend .append('div') .text(values[0].History[0].Time); var alert_legend = legend .append('div') .text(keys[0]); svg.select('.x.axis') .transition() .call(xAxis); var chart = svg.append('g'); angular.forEach(entries, function (entry, i) { chart.selectAll('.bars') .data(entry.value.History) .enter() .append('rect') .attr('class', function (d) { return 'tl-' + d.Status; }) .attr('x', function (d) { return xScale(parseDate(d.Time)); }) .attr('y', i * barheight) .attr('height', barheight) .attr('width', function (d) { return xScale(parseDate(d.EndTime)) - xScale(parseDate(d.Time)); }) .on('mousemove.x', mousemove_x) .on('mousemove.y', function (d) { alert_legend.text(entry.key); }) .on('click', function (d, j) { var id = 'panel' + i + '-' + j; scope.shown['group' + i] = true; scope.shown[id] = true; if (scope.loadTimelinePanel) { scope.loadTimelinePanel(entry, d); } scope.$apply(); setTimeout(function () { var e = $("#" + id); if (!e) { console.log('no', id, e); return; } $('html, body').scrollTop(e.offset().top); }); }); }); chart.selectAll('.labels') .data(keys) .enter() .append('text') .attr('text-anchor', 'end') .attr('x', 0) .attr('dx', '-.5em') .attr('dy', '.25em') .attr('y', function (d, i) { return (i + .5) * barheight; }) .text(function (d) { return d; }); chart.selectAll('.sep') .data(values) .enter() .append('rect') .attr('y', function (d, i) { return (i + 1) * barheight; }) .attr('height', 1) .attr('x', 0) .attr('width', width) .on('mousemove.x', mousemove_x); function mousemove_x() { var x = xScale.invert(d3.mouse(this)[0]); time_legend .text(tsdbFormat(x)); } } ; } }; }); var fmtUnits = ['', 'k', 'M', 'G', 'T', 'P', 'E']; function nfmt(s, mult, suffix, opts) { opts = opts || {}; var n = parseFloat(s); if (isNaN(n) && typeof s === 'string') { return s; } if (opts.round) n = Math.round(n); if (!n) return suffix ? '0 ' + suffix : '0'; if (isNaN(n) || !isFinite(n)) return '-'; var a = Math.abs(n); if (a >= 1) { var number = Math.floor(Math.log(a) / Math.log(mult)); a /= Math.pow(mult, Math.floor(number)); if (fmtUnits[number]) { suffix = fmtUnits[number] + suffix; } } var r = a.toFixed(5); if (a < 1e-5) { r = a.toString(); } var neg = n < 0 ? '-' : ''; return neg + (+r) + suffix; } bosunApp.filter('nfmt', function () { return function (s) { return nfmt(s, 1000, '', {}); }; }); bosunApp.filter('bytes', function () { return function (s) { return nfmt(s, 1024, 'B', { round: true }); }; }); bosunApp.filter('bits', function () { return function (s) { return nfmt(s, 1024, 'b', { round: true }); }; }); bosunApp.directive('elastic', [ '$timeout', function ($timeout) { return { restrict: 'A', link: function ($scope, element) { $scope.initialHeight = $scope.initialHeight || element[0].style.height; var resize = function () { element[0].style.height = $scope.initialHeight; element[0].style.height = "" + element[0].scrollHeight + "px"; }; element.on("input change", resize); $timeout(resize, 0); } }; } ]); bosunApp.directive('tsGraph', ['$window', 'nfmtFilter', function ($window, fmtfilter) { var margin = { top: 10, right: 10, bottom: 30, left: 80 }; return { scope: { data: '=', height: '=', generator: '=', brushStart: '=bstart', brushEnd: '=bend', enableBrush: '@', max: '=', min: '=', normalize: '=' }, link: function (scope, elem, attrs) { var valueIdx = 1; if (scope.normalize) { valueIdx = 2; } var svgHeight = +scope.height || 150; var height = svgHeight - margin.top - margin.bottom; var svgWidth; var width; var yScale = d3.scale.linear().range([height, 0]); var xScale = d3.time.scale.utc(); var xAxis = d3.svg.axis() .orient('bottom'); var yAxis = d3.svg.axis() .scale(yScale) .orient('left') .ticks(Math.min(10, height / 20)) .tickFormat(fmtfilter); var line; switch (scope.generator) { case 'area': line = d3.svg.area(); break; default: line = d3.svg.line(); } var brush = d3.svg.brush() .x(xScale) .on('brush', brushed); var top = d3.select(elem[0]) .append('svg') .attr('height', svgHeight) .attr('width', '100%'); var svg = top .append('g') .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); var defs = svg.append('defs') .append('clipPath') .attr('id', 'clip') .append('rect') .attr('height', height); var chart = svg.append('g') .attr('pointer-events', 'all') .attr('clip-path', 'url(#clip)'); svg.append('g') .attr('class', 'x axis') .attr('transform', 'translate(0,' + height + ')'); svg.append('g') .attr('class', 'y axis'); var paths = chart.append('g'); chart.append('g') .attr('class', 'x brush'); top.append('rect') .style('opacity', 0) .attr('x', 0) .attr('y', 0) .attr('height', height) .attr('width', margin.left) .style('cursor', 'pointer') .on('click', yaxisToggle); var legendTop = d3.select(elem[0]).append('div'); var xloc = legendTop.append('div'); xloc.style('float', 'left'); var brushText = legendTop.append('div'); brushText.style('float', 'right'); var legend = d3.select(elem[0]).append('div'); legend.style('clear', 'both'); var color = d3.scale.ordinal().range([ '#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#a65628', '#f781bf', '#999999', ]); var mousex = 0; var mousey = 0; var oldx = 0; var hover = svg.append('g') .attr('class', 'hover') .style('pointer-events', 'none') .style('display', 'none'); var hoverPoint = hover.append('svg:circle') .attr('r', 5); var hoverRect = hover.append('svg:rect') .attr('fill', 'white'); var hoverText = hover.append('svg:text') .style('font-size', '12px'); var focus = svg.append('g') .attr('class', 'focus') .style('pointer-events', 'none'); focus.append('line'); var yaxisZero = false; function yaxisToggle() { yaxisZero = !yaxisZero; draw(); } var drawLegend = _.throttle(function (normalizeIdx) { var names = legend.selectAll('.series') .data(scope.data, function (d) { return d.Name; }); names.enter() .append('div') .attr('class', 'series'); names.exit() .remove(); var xi = xScale.invert(mousex); xloc.text('Time: ' + fmtTime(xi)); var t = xi.getTime() / 1000; var minDist = width + height; var minName, minColor; var minX, minY; names .each(function (d) { var idx = bisect(d.Data, t); if (idx >= d.Data.length) { idx = d.Data.length - 1; } var e = d3.select(this); var pt = d.Data[idx]; if (pt) { e.attr('title', pt[normalizeIdx]); e.text(d.Name + ': ' + fmtfilter(pt[1])); var ptx = xScale(pt[0] * 1000); var pty = yScale(pt[normalizeIdx]); var ptd = Math.sqrt(Math.pow(ptx - mousex, 2) + Math.pow(pty - mousey, 2)); if (ptd < minDist) { minDist = ptd; minX = ptx; minY = pty; minName = d.Name + ': ' + pt[1]; minColor = color(d.Name); } } }) .style('color', function (d) { return color(d.Name); }); hover .attr('transform', 'translate(' + minX + ',' + minY + ')'); hoverPoint.style('fill', minColor); hoverText .text(minName) .style('fill', minColor); var isRight = minX > width / 2; var isBottom = minY > height / 2; hoverText .attr('x', isRight ? -5 : 5) .attr('y', isBottom ? -8 : 15) .attr('text-anchor', isRight ? 'end' : 'start'); var node = hoverText.node(); var bb = node.getBBox(); hoverRect .attr('x', bb.x - 1) .attr('y', bb.y - 1) .attr('height', bb.height + 2) .attr('width', bb.width + 2); var x = mousex; if (x > width) { x = 0; } focus.select('line') .attr('x1', x) .attr('x2', x) .attr('y1', 0) .attr('y2', height); if (extentStart) { var s = extentStart; if (extentEnd != extentStart) { s += ' - ' + extentEnd; s += ' (' + extentDiff + ')'; } brushText.text(s); } }, 50); scope.$watch('data', update); var w = angular.element($window); scope.$watch(function () { return w.width(); }, resize, true); w.bind('resize', function () { scope.$apply(); }); function resize() { svgWidth = elem.width(); if (svgWidth <= 0) { return; } width = svgWidth - margin.left - margin.right; xScale.range([0, width]); xAxis.scale(xScale); if (!mousex) { mousex = width + 1; } svg.attr('width', svgWidth); defs.attr('width', width); xAxis.ticks(width / 60); draw(); } var oldx = 0; var bisect = d3.bisector(function (d) { return d[0]; }).left; function update(v) { if (!angular.isArray(v) || v.length == 0) { return; } resize(); } function draw() { if (!scope.data) { return; } if (scope.normalize) { valueIdx = 2; } function mousemove() { var pt = d3.mouse(this); mousex = pt[0]; mousey = pt[1]; drawLegend(valueIdx); } scope.data.map(function (data, i) { var max = d3.max(data.Data, function (d) { return d[1]; }); data.Data.map(function (d, j) { d.push(d[1] / max * 100 || 0); }); }); line.y(function (d) { return yScale(d[valueIdx]); }); line.x(function (d) { return xScale(d[0] * 1000); }); var xdomain = [ d3.min(scope.data, function (d) { return d3.min(d.Data, function (c) { return c[0]; }); }) * 1000, d3.max(scope.data, function (d) { return d3.max(d.Data, function (c) { return c[0]; }); }) * 1000, ]; if (!oldx) { oldx = xdomain[1]; } xScale.domain(xdomain); var ymin = d3.min(scope.data, function (d) { return d3.min(d.Data, function (c) { return c[1]; }); }); var ymax = d3.max(scope.data, function (d) { return d3.max(d.Data, function (c) { return c[valueIdx]; }); }); var diff = (ymax - ymin) / 50; if (!diff) { diff = 1; } ymin -= diff; ymax += diff; if (yaxisZero) { if (ymin > 0) { ymin = 0; } else if (ymax < 0) { ymax = 0; } } var ydomain = [ymin, ymax]; if (angular.isNumber(scope.min)) { ydomain[0] = +scope.min; } if (angular.isNumber(scope.max)) { ydomain[valueIdx] = +scope.max; } yScale.domain(ydomain); if (scope.generator == 'area') { line.y0(yScale(0)); } svg.select('.x.axis') .transition() .call(xAxis); svg.select('.y.axis') .transition() .call(yAxis); svg.append('text') .attr("class", "ylabel") .attr("transform", "rotate(-90)") .attr("y", -margin.left) .attr("x", -(height / 2)) .attr("dy", "1em") .text(_.uniq(scope.data.map(function (v) { return v.Unit; })).join("; ")); var queries = paths.selectAll('.line') .data(scope.data, function (d) { return d.Name; }); switch (scope.generator) { case 'area': queries.enter() .append('path') .attr('stroke', function (d) { return color(d.Name); }) .attr('class', 'line') .style('fill', function (d) { return color(d.Name); }); break; default: queries.enter() .append('path') .attr('stroke', function (d) { return color(d.Name); }) .attr('class', 'line'); } queries.exit() .remove(); queries .attr('d', function (d) { return line(d.Data); }) .attr('transform', null) .transition() .ease('linear') .attr('transform', 'translate(' + (xScale(oldx) - xScale(xdomain[1])) + ')'); chart.select('.x.brush') .call(brush) .selectAll('rect') .attr('height', height) .on('mouseover', function () { hover.style('display', 'block'); }) .on('mouseout', function () { hover.style('display', 'none'); }) .on('mousemove', mousemove); chart.select('.x.brush .extent') .style('stroke', '#fff') .style('fill-opacity', '.125') .style('shape-rendering', 'crispEdges'); oldx = xdomain[1]; drawLegend(valueIdx); } ; var extentStart; var extentEnd; var extentDiff; function brushed() { var extent = brush.extent(); extentStart = datefmt(extent[0]); extentEnd = datefmt(extent[1]); extentDiff = fmtDuration(moment(extent[1]).diff(moment(extent[0]))); drawLegend(valueIdx); if (scope.enableBrush && extentEnd != extentStart) { scope.brushStart = extentStart; scope.brushEnd = extentEnd; scope.$apply(); } } var mfmt = 'YYYY/MM/DD-HH:mm:ss'; function datefmt(d) { return moment(d).utc().format(mfmt); } } }; }]); bosunControllers.controller('ExprCtrl', ['$scope', '$http', '$location', '$route', function ($scope, $http, $location, $route) { var search = $location.search(); var current; try { current = atob(search.expr); } catch (e) { current = ''; } if (!current) { $location.search('expr', btoa('avg(q("avg:rate:os.cpu{host=*bosun*}", "5m", "")) > 80')); return; } $scope.date = search.date || ''; $scope.time = search.time || ''; $scope.expr = current; $scope.running = current; $scope.tab = search.tab || 'results'; $scope.animate(); $http.post('/api/expr?' + 'date=' + encodeURIComponent($scope.date) + '&time=' + encodeURIComponent($scope.time), current) .success(function (data) { $scope.result = data.Results; $scope.queries = data.Queries; $scope.result_type = data.Type; if (data.Type == 'series') { $scope.svg_url = '/api/egraph/' + btoa(current) + '.svg?now=' + Math.floor(Date.now() / 1000); $scope.graph = toChart(data.Results); } $scope.running = ''; }) .error(function (error) { $scope.error = error; $scope.running = ''; }) .finally(function () { $scope.stop(); }); $scope.set = function () { $location.search('expr', btoa($scope.expr)); $location.search('date', $scope.date || null); $location.search('time', $scope.time || null); $route.reload(); }; function toChart(res) { var graph = []; angular.forEach(res, function (d, idx) { var data = []; angular.forEach(d.Value, function (val, ts) { data.push([+ts, val]); }); if (data.length == 0) { return; } var name = '{'; angular.forEach(d.Group, function (tagv, tagk) { if (name.length > 1) { name += ','; } name += tagk + '=' + tagv; }); name += '}'; var series = { Data: data, Name: name }; graph[idx] = series; }); return graph; } $scope.keydown = function ($event) { if ($event.shiftKey && $event.keyCode == 13) { $scope.set(); } }; }]); var TagSet = (function () { function TagSet() { } return TagSet; })(); var TagV = (function () { function TagV() { } return TagV; })(); var RateOptions = (function () { function RateOptions() { } return RateOptions; })(); var Query = (function () { function Query(q) { this.aggregator = q && q.aggregator || 'sum'; this.metric = q && q.metric || ''; this.rate = q && q.rate || false; this.rateOptions = q && q.rateOptions || new RateOptions; if (q && !q.derivative) { // back compute derivative from q if (!this.rate) { this.derivative = 'gauge'; } else if (this.rateOptions.counter) { this.derivative = 'counter'; } else { this.derivative = 'rate'; } } else { this.derivative = q && q.derivative || 'auto'; } this.ds = q && q.ds || ''; this.dstime = q && q.dstime || ''; this.tags = q && q.tags || new TagSet; this.setDs(); this.setDerivative(); } Query.prototype.setDs = function () { if (this.dstime && this.ds) { this.downsample = this.dstime + '-' + this.ds; } else { this.downsample = ''; } }; Query.prototype.setDerivative = function () { var max = this.rateOptions.counterMax; this.rate = false; this.rateOptions = new RateOptions(); switch (this.derivative) { case "rate": this.rate = true; break; case "counter": this.rate = true; this.rateOptions.counter = true; this.rateOptions.counterMax = max; this.rateOptions.resetValue = 1; break; case "gauge": this.rate = false; break; } }; return Query; })(); var Request = (function () { function Request() { this.start = '1h-ago'; this.queries = []; } Request.prototype.prune = function () { var _this = this; for (var i = 0; i < this.queries.length; i++) { angular.forEach(this.queries[i], function (v, k) { var qi = _this.queries[i]; switch (typeof v) { case "string": if (!v) { delete qi[k]; } break; case "boolean": if (!v) { delete qi[k]; } break; case "object": if (Object.keys(v).length == 0) { delete qi[k]; } break; } }); } }; return Request; })(); var graphRefresh; bosunControllers.controller('GraphCtrl', ['$scope', '$http', '$location', '$route', '$timeout', function ($scope, $http, $location, $route, $timeout) { $scope.aggregators = ["sum", "min", "max", "avg", "dev", "zimsum", "mimmin", "minmax"]; $scope.dsaggregators = ["", "sum", "min", "max", "avg", "dev", "zimsum", "mimmin", "minmax"]; $scope.rate_options = ["auto", "gauge", "counter", "rate"]; $scope.canAuto = {}; var search = $location.search(); var j = search.json; if (search.b64) { j = atob(search.b64); } var request = j ? JSON.parse(j) : new Request; $scope.index = parseInt($location.hash()) || 0; $scope.tagvs = []; $scope.sorted_tagks = []; $scope.query_p = []; angular.forEach(request.queries, function (q, i) { $scope.query_p[i] = new Query(q); }); $scope.start = request.start; $scope.end = request.end; $scope.autods = search.autods != 'false'; $scope.refresh = search.refresh == 'true'; $scope.normalize = search.normalize == 'true'; if (search.min) { $scope.min = +search.min; } if (search.max) { $scope.max = +search.max; } var duration_map = { "s": "s", "m": "m", "h": "h", "d": "d", "w": "w", "n": "M", "y": "y" }; var isRel = /^(\d+)(\w)-ago$/; function RelToAbs(m) { return moment().utc().subtract(parseFloat(m[1]), duration_map[m[2]]).format(); } function AbsToRel(s) { //Not strict parsing of the time format. For example, just "2014" will be valid var t = moment.utc(s, moment.defaultFormat).fromNow(); return t; } function SwapTime(s) { if (!s) { return moment().utc().format(); } var m = isRel.exec(s); if (m) { return RelToAbs(m); } return AbsToRel(s); } $scope.SwitchTimes = function () { $scope.start = SwapTime($scope.start); $scope.end = SwapTime($scope.end); }; $scope.AddTab = function () { $scope.index = $scope.query_p.length; $scope.query_p.push(new Query); }; $scope.setIndex = function (i) { $scope.index = i; }; $scope.GetTagKByMetric = function (index) { $scope.tagvs[index] = new TagV; var metric = $scope.query_p[index].metric; if (!metric) { $scope.canAuto[metric] = true; return; } $http.get('/api/tagk/' + metric) .success(function (data) { var q = $scope.query_p[index]; var tags = new TagSet; q.metric_tags = {}; for (var i = 0; i < data.length; i++) { var d = data[i]; q.metric_tags[d] = true; if (q.tags) { tags[d] = q.tags[d]; } if (!tags[d]) { tags[d] = ''; } GetTagVs(d, index); } angular.forEach(q.tags, function (val, key) { if (val) { tags[key] = val; } }); q.tags = tags; // Make sure host is always the first tag. $scope.sorted_tagks[index] = Object.keys(tags); $scope.sorted_tagks[index].sort(function (a, b) { if (a == 'host') { return -1; } else if (b == 'host') { return 1; } return a.localeCompare(b); }); }) .error(function (error) { $scope.error = 'Unable to fetch metrics: ' + error; }); $http.get('/api/metadata/get?metric=' + metric) .success(function (data) { var canAuto = false; angular.forEach(data, function (val) { if (val.Metric == metric && val.Name == 'rate') { canAuto = true; } }); $scope.canAuto[metric] = canAuto; }) .error(function (err) { $scope.error = err; }); }; if ($scope.query_p.length == 0) { $scope.AddTab(); } $http.get('/api/metric') .success(function (data) { $scope.metrics = data; }) .error(function (error) { $scope.error = 'Unable to fetch metrics: ' + error; }); function GetTagVs(k, index) { $http.get('/api/tagv/' + k + '/' + $scope.query_p[index].metric) .success(function (data) { data.sort(); $scope.tagvs[index][k] = data; }) .error(function (error) { $scope.error = 'Unable to fetch metrics: ' + error; }); } function getRequest() { request = new Request; request.start = $scope.start; request.end = $scope.end; angular.forEach($scope.query_p, function (p) { if (!p.metric) { return; } var q = new Query(p); var tags = q.tags; q.tags = new TagSet; angular.forEach(tags, function (v, k) { if (v && k) { q.tags[k] = v; } }); request.queries.push(q); }); return request; } $scope.Query = function () { var r = getRequest(); angular.forEach($scope.query_p, function (q, index) { var m = q.metric_tags; if (!m) { return; } angular.forEach(q.tags, function (key, tag) { if (m[tag]) { return; } delete r.queries[index].tags[tag]; }); }); r.prune(); $location.search('b64', btoa(JSON.stringify(r))); $location.search('autods', $scope.autods ? undefined : 'false'); $location.search('refresh', $scope.refresh ? 'true' : undefined); $location.search('normalize', $scope.normalize ? 'true' : undefined); var min = angular.isNumber($scope.min) ? $scope.min.toString() : null; var max = angular.isNumber($scope.max) ? $scope.max.toString() : null; $location.search('min', min); $location.search('max', max); $route.reload(); }; request = getRequest(); if (!request.queries.length) { return; } var autods = $scope.autods ? '&autods=' + $('#chart').width() : ''; function getMetricMeta(metric) { $http.get('/api/metadata/metrics?metric=' + encodeURIComponent(metric)) .success(function (data) { if (Object.keys(data).length == 1) { $scope.meta[metric] = data[metric]; } }) .error(function (error) { console.log("Error getting metadata for metric " + metric); }); } function get(noRunning) { $timeout.cancel(graphRefresh); if (!noRunning) { $scope.running = 'Running'; } var autorate = ''; $scope.meta = {}; for (var i = 0; i < request.queries.length; i++) { if (request.queries[i].derivative == 'auto') { autorate += '&autorate=' + i; } getMetricMeta(request.queries[i].metric); } var min = angular.isNumber($scope.min) ? '&min=' + encodeURIComponent($scope.min.toString()) : ''; var max = angular.isNumber($scope.max) ? '&max=' + encodeURIComponent($scope.max.toString()) : ''; $scope.animate(); $scope.queryTime = ''; if (request.end && !isRel.exec(request.end)) { var t = moment.utc(request.end, moment.defaultFormat); $scope.queryTime = '&date=' + t.format('YYYY-MM-DD'); $scope.queryTime += '&time=' + t.format('HH:mm'); } $http.get('/api/graph?' + 'b64=' + encodeURIComponent(btoa(JSON.stringify(request))) + autods + autorate + min + max) .success(function (data) { $scope.result = data.Series; if (!$scope.result) { $scope.warning = 'No Results'; } else { $scope.warning = ''; } $scope.queries = data.Queries; $scope.running = ''; $scope.error = ''; var u = $location.absUrl(); u = u.substr(0, u.indexOf('?')) + '?'; u += 'b64=' + search.b64 + autods + autorate + min + max; $scope.url = u; }) .error(function (error) { $scope.error = error; $scope.running = ''; }) .finally(function () { $scope.stop(); if ($scope.refresh) { graphRefresh = $timeout(function () { get(true); }, 5000); } ; }); } ; get(false); }]); bosunApp.directive('tsPopup', function () { return { restrict: 'E', scope: { url: '=' }, template: '<button class="btn btn-default" data-html="true" data-placement="bottom">embed</button>', link: function (scope, elem, attrs) { var button = $('button', elem); scope.$watch(attrs.url, function (url) { if (!url) { return; } var text = '<input type="text" onClick="this.select();" readonly="readonly" value="&lt;a href=&quot;' + url + '&quot;&gt;&lt;img src=&quot;' + url + '&.png=png&quot;&gt;&lt;/a&gt;">'; button.popover({ content: text }); }); } }; }); bosunApp.directive('tsAlertHistory', function () { return { templateUrl: '/partials/alerthistory.html' }; }); bosunControllers.controller('HistoryCtrl', ['$scope', '$http', '$location', '$route', function ($scope, $http, $location, $route) { var search = $location.search(); var keys = {}; if (angular.isArray(search.key)) { angular.forEach(search.key, function (v) { keys[v] = true; }); } else { keys[search.key] = true; } var params = Object.keys(keys).map(function (v) { return 'ak=' + encodeURIComponent(v); }).join('&'); $http.get('/api/status?' + params) .success(function (data) { var selected_alerts = {}; angular.forEach(data, function (v, ak) { if (!keys[ak]) { return; } v.History.map(function (h) { h.Time = moment.utc(h.Time); }); angular.forEach(v.History, function (h, i) { if (i + 1 < v.History.length) { h.EndTime = v.History[i + 1].Time; } else { h.EndTime = moment.utc(); } }); selected_alerts[ak] = { History: v.History.reverse() }; }); if (Object.keys(selected_alerts).length > 0) { $scope.alert_history = selected_alerts; } else { $scope.error = 'No Matching Alerts Found'; } }) .error(function (err) { $scope.error = err; }); }]); bosunControllers.controller('HostCtrl', ['$scope', '$http', '$location', '$route', function ($scope, $http, $location, $route) { var search = $location.search(); $scope.host = search.host; $scope.time = search.time; $scope.tab = search.tab || "stats"; $scope.idata = []; $scope.fsdata = []; $scope.metrics = []; var currentURL = $location.url(); $scope.mlink = function (m) { var r = new Request(); var q = new Query(); q.metric = m; q.tags = { 'host': $scope.host }; r.queries.push(q); return r; }; $scope.setTab = function (t) { $location.search('tab', t); $scope.tab = t; }; $http.get('/api/metric/host/' + $scope.host) .success(function (data) { $scope.metrics = data || []; }); var start = moment().utc().subtract(parseDuration($scope.time)); function parseDuration(v) { var pattern = /(\d+)(d|y|n|h|m|s)-ago/; var m = pattern.exec(v); return moment.duration(parseInt(m[1]), m[2].replace('n', 'M')); } $http.get('/api/metadata/get?tagk=host&tagv=' + encodeURIComponent($scope.host)) .success(function (data) { $scope.metadata = _.filter(data, function (i) { return moment.utc(i.Time) > start; }); }); var autods = '&autods=100'; var cpu_r = new Request(); cpu_r.start = $scope.time; cpu_r.queries = [ new Query({ metric: 'os.cpu', derivative: 'counter', tags: { host: $scope.host } }) ]; $http.get('/api/graph?' + 'json=' + encodeURIComponent(JSON.stringify(cpu_r)) + autods) .success(function (data) { if (!data.Series) { return; } data.Series[0].Name = 'Percent Used'; $scope.cpu = data.Series; }); var mem_r = new Request(); mem_r.start = $scope.time; mem_r.queries.push(new Query({ metric: "os.mem.total", tags: { host: $scope.host } })); mem_r.queries.push(new Query({ metric: "os.mem.used", tags: { host: $scope.host } })); $http.get('/api/graph?' + 'json=' + encodeURIComponent(JSON.stringify(mem_r)) + autods) .success(function (data) { if (!data.Series) { return; } data.Series[1].Name = "Used"; $scope.mem_total = Math.max.apply(null, data.Series[0].Data.map(function (d) { return d[1]; })); $scope.mem = [data.Series[1]]; }); $http.get('/api/tagv/iface/os.net.bytes?host=' + $scope.host) .success(function (data) { angular.forEach(data, function (i, idx) { $scope.idata[idx] = { Name: i }; }); function next(idx) { var idata = $scope.idata[idx]; if (!idata || currentURL != $location.url()) { return; } var net_bytes_r = new Request(); net_bytes_r.start = $scope.time; net_bytes_r.queries = [ new Query({ metric: "os.net.bytes", rate: true, rateOptions: { counter: true, resetValue: 1 }, tags: { host: $scope.host, iface: idata.Name, direction: "*" } }) ]; $http.get('/api/graph?' + 'json=' + encodeURIComponent(JSON.stringify(net_bytes_r)) + autods) .success(function (data) { if (!data.Series) { return; } angular.forEach(data.Series, function (d) { d.Data = d.Data.map(function (dp) { return [dp[0], dp[1] * 8]; }); if (d.Name.indexOf("direction=out") != -1) { d.Data = d.Data.map(function (dp) { return [dp[0], dp[1] * -1]; }); d.Name = "out"; } else { d.Name = "in"; } }); $scope.idata[idx].Data = data.Series; }) .finally(function () { next(idx + 1); }); } next(0); }); $http.get('/api/tagv/disk/os.disk.fs.space_total?host=' + $scope.host) .success(function (data) { angular.forEach(data, function (i, idx) { if (i == '/dev/shm') { return; } var fs_r = new Request(); fs_r.start = $scope.time; fs_r.queries.push(new Query({ metric: "os.disk.fs.space_total", tags: { host: $scope.host, disk: i } })); fs_r.queries.push(new Query({ metric: "os.disk.fs.space_used", tags: { host: $scope.host, disk: i } })); $scope.fsdata[idx] = { Name: i }; $http.get('/api/graph?' + 'json=' + encodeURIComponent(JSON.stringify(fs_r)) + autods) .success(function (data) { if (!data.Series) { return; } data.Series[1].Name = 'Used'; var total = Math.max.apply(null, data.Series[0].Data.map(function (d) { return d[1]; })); var c_val = data.Series[1].Data.slice(-1)[0][1]; var percent_used = c_val / total * 100; $scope.fsdata[idx].total = total; $scope.fsdata[idx].c_val = c_val; $scope.fsdata[idx].percent_used = percent_used; $scope.fsdata[idx].Data = [data.Series[1]]; }); }); }); }]); bosunControllers.controller('IncidentCtrl', ['$scope', '$http', '$location', '$route', function ($scope, $http, $location, $route) { var search = $location.search(); var id = search.id; if (!id) { $scope.error = "must supply incident id as query parameter"; return; } $http.get('/api/incidents/events?id=' + id) .success(function (data) { $scope.incident = data.Incident; $scope.events = data.Events; $scope.actions = data.Actions; }) .error(function (err) { $scope.error = err; }); }]); bosunControllers.controller('ItemsCtrl', ['$scope', '$http', function ($scope, $http) { $http.get('/api/metric') .success(function (data) { $scope.metrics = data; }) .error(function (error) { $scope.status = 'Unable to fetch metrics: ' + error; }); $http.get('/api/tagv/host?since=default') .success(function (data) { $scope.hosts = data; }) .error(function (error) { $scope.status = 'Unable to fetch hosts: ' + error; }); }]); var Tag = (function () { function Tag() { } return Tag; })(); var DP = (function () { function DP() { } return DP; })(); bosunControllers.controller('PutCtrl', ['$scope', '$http', '$route', function ($scope, $http, $route) { $scope.tags = [new Tag]; var dp = new DP; dp.k = moment().utc().format(); $scope.dps = [dp]; $http.get('/api/metric') .success(function (data) { $scope.metrics = data; }) .error(function (error) { $scope.error = 'Unable to fetch metrics: ' + error; }); $scope.Submit = function () { var data = []; var tags = {}; angular.forEach($scope.tags, function (v, k) { if (v.k || v.v) { tags[v.k] = v.v; } }); angular.forEach($scope.dps, function (v, k) { if (v.k && v.v) { var ts = parseInt(moment.utc(v.k, tsdbDateFormat).format('X')); data.push({ metric: $scope.metric, timestamp: ts, value: parseFloat(v.v), tags: tags }); } }); $scope.running = 'submitting data...'; $scope.success = ''; $scope.error = ''; $http.post('/api/put', data) .success(function () { $scope.running = ''; $scope.success = 'Data Submitted'; }) .error(function (error) { $scope.running = ''; $scope.error = error.error.message; }); }; $scope.AddTag = function () { var last = $scope.tags[$scope.tags.length - 1]; if (last.k && last.v) { $scope.tags.push(new Tag); } }; $scope.AddDP = function () { var last = $scope.dps[$scope.dps.length - 1]; if (last.k && last.v) { var dp = new DP; dp.k = moment.utc(last.k, tsdbDateFormat).add(15, 'seconds').format(); $scope.dps.push(dp); } }; $scope.GetTagKByMetric = function () { $http.get('/api/tagk/' + $scope.metric) .success(function (data) { if (!angular.isArray(data)) { return; } $scope.tags = [new Tag]; for (var i = 0; i < data.length; i++) { var t = new Tag; t.k = data[i]; $scope.tags.push(t); } }) .error(function (error) { $scope.error = 'Unable to fetch metrics: ' + error; }); }; }]); bosunControllers.controller('SilenceCtrl', ['$scope', '$http', '$location', '$route', function ($scope, $http, $location, $route) { var search = $location.search(); $scope.start = search.start; $scope.end = search.end; $scope.duration = search.duration; $scope.alert = search.alert; $scope.hosts = search.hosts; $scope.tags = search.tags; $scope.edit = search.edit; $scope.forget = search.forget; $scope.user = getUser(); $scope.message = search.message; if (!$scope.end && !$scope.duration) { $scope.duration = '1h'; } function filter(data, startBefore, startAfter, endAfter, endBefore, limit) { var ret = {}; var count = 0; _.each(data, function (v, name) { if (limit && count >= limit) { return; } var s = moment(v.Start).utc(); var e = moment(v.End).utc(); if (startBefore && s > startBefore) { return; } if (startAfter && s < startAfter) { return; } if (endAfter && e < endAfter) { return; } if (endBefore && e > endBefore) { return; } ret[name] = v; }); return ret; } function get() { $http.get('/api/silence/get') .success(function (data) { $scope.silences = []; var now = moment.utc(); $scope.silences.push({ name: 'Active', silences: filter(data, now, null, now, null, 0) }); $scope.silences.push({ name: 'Upcoming', silences: filter(data, null, now, null, null, 0) }); $scope.silences.push({ name: 'Past', silences: filter(data, null, null, null, now, 25) }); }) .error(function (error) { $scope.error = error; }); } get(); function getData() { var tags = ($scope.tags || '').split(','); if ($scope.hosts) { tags.push('host=' + $scope.hosts.split(/[ ,|]+/).join('|')); } tags = tags.filter(function (v) { return v != ""; }); var data = { start: $scope.start, end: $scope.end, duration: $scope.duration, alert: $scope.alert, tags: tags.join(','), edit: $scope.edit, forget: $scope.forget ? 'true' : null, user: $scope.user, message: $scope.message }; return data; } var any = search.start || search.end || search.duration || search.alert || search.hosts || search.tags || search.forget; var state = getData(); $scope.change = function () { $scope.disableConfirm = true; }; if (any) { $scope.error = null; $http.post('/api/silence/set', state) .success(function (data) { if (!data) { data = { '(none)': false }; } $scope.testSilences = data; }) .error(function (error) { $scope.error = error; }); } $scope.test = function () { setUser($scope.user); $location.search('start', $scope.start || null); $location.search('end', $scope.end || null); $location.search('duration', $scope.duration || null); $location.search('alert', $scope.alert || null); $location.search('hosts', $scope.hosts || null); $location.search('tags', $scope.tags || null); $location.search('forget', $scope.forget || null); $location.search('message', $scope.message || null); $route.reload(); }; $scope.confirm = function () { $scope.error = null; $scope.testSilences = null; state.confirm = 'true'; $http.post('/api/silence/set', state) .error(function (error) { $scope.error = error; }) .finally(get); }; $scope.clear = function (id) { if (!window.confirm('Clear this silence?')) { return; } $scope.error = null; $http.post('/api/silence/clear?id=' + id, {}) .error(function (error) { $scope.error = error; }) .finally(get); }; $scope.time = function (v) { var m = moment(v).utc(); return m.format(); }; }]); bosunApp.directive('tsAckGroup', ['$location', function ($location) { return { scope: { ack: '=', groups: '=tsAckGroup', schedule: '=', timeanddate: '=' }, templateUrl: '/partials/ackgroup.html', link: function (scope, elem, attrs) { scope.canAckSelected = scope.ack == 'Needs Acknowledgement'; scope.panelClass = scope.$parent.panelClass; scope.btoa = scope.$parent.btoa; scope.encode = scope.$parent.encode; scope.shown = {}; scope.collapse = function (i) { scope.shown[i] = !scope.shown[i]; }; scope.click = function ($event, idx) { scope.collapse(idx); if ($event.shiftKey && scope.schedule.checkIdx != undefined) { var checked = scope.groups[scope.schedule.checkIdx].checked; var start = Math.min(idx, scope.schedule.checkIdx); var end = Math.max(idx, scope.schedule.checkIdx); for (var i = start; i <= end; i++) { if (i == idx) { continue; } scope.groups[i].checked = checked; } } scope.schedule.checkIdx = idx; scope.update(); }; scope.select = function (checked) { for (var i = 0; i < scope.groups.length; i++) { scope.groups[i].checked = checked; } scope.update(); }; scope.update = function () { scope.canCloseSelected = true; scope.canForgetSelected = true; scope.anySelected = false; for (var i = 0; i < scope.groups.length; i++) { var g = scope.groups[i]; if (!g.checked) { continue; } scope.anySelected = true; if (g.Active && g.Status != 'unknown' && g.Status != 'error') { scope.canCloseSelected = false; } if (g.Status != 'unknown') { scope.canForgetSelected = false; } } }; scope.multiaction = function (type) { var keys = []; angular.forEach(scope.groups, function (group) { if (!group.checked) { return; } if (group.AlertKey) { keys.push(group.AlertKey); } angular.forEach(group.Children, function (child) { keys.push(child.AlertKey); }); }); scope.$parent.setKey("action-keys", keys); $location.path("action"); $location.search("type", type); }; scope.history = function () { var url = '/history?'; angular.forEach(scope.groups, function (group) { if (!group.checked) { return; } if (group.AlertKey) { url += '&key=' + encodeURIComponent(group.AlertKey); } angular.forEach(group.Children, function (child) { url += '&key=' + encodeURIComponent(child.AlertKey); }); }); return url; }; } }; }]); bosunApp.directive('tsState', ['$sce', '$http', function ($sce, $http) { return { templateUrl: '/partials/alertstate.html', link: function (scope, elem, attrs) { scope.name = scope.child.AlertKey; scope.state = scope.child.State; scope.action = function (type) { var key = encodeURIComponent(scope.name); return '/action?type=' + type + '&key=' + key; }; var loadedBody = false; scope.toggle = function () { scope.show = !scope.show; if (scope.show && !loadedBody) { scope.state.Body = "loading..."; loadedBody = true; $http.get('/api/status?ak=' + scope.child.AlertKey) .success(function (data) { var body = data[scope.child.AlertKey].Body; scope.state.Body = $sce.trustAsHtml(body); }) .error(function (err) { scope.state.Body = "Error loading template body: " + err; }); } }; scope.zws = function (v) { if (!v) { return ''; } return v.replace(/([,{}()])/g, '$1\u200b'); }; scope.state.Touched = moment(scope.state.Touched).utc(); angular.forEach(scope.state.History, function (v, k) { v.Time = moment(v.Time).utc(); }); scope.state.last = scope.state.History[scope.state.History.length - 1]; if (scope.state.Actions && scope.state.Actions.length > 0) { scope.state.LastAction = scope.state.Actions[0]; } scope.state.RuleUrl = '/config?' + 'alert=' + encodeURIComponent(scope.state.Alert) + '&fromDate=' + encodeURIComponent(scope.state.last.Time.format("YYYY-MM-DD")) + '&fromTime=' + encodeURIComponent(scope.state.last.Time.format("HH:mm")); var groups = []; angular.forEach(scope.state.Group, function (v, k) { groups.push(k + "=" + v); }); if (groups.length > 0) { scope.state.RuleUrl += '&template_group=' + encodeURIComponent(groups.join(',')); } scope.state.Body = $sce.trustAsHtml(scope.state.Body); } }; }]); bosunApp.directive('tsAck', function () { return { restrict: 'E', templateUrl: '/partials/ack.html' }; }); bosunApp.directive('tsClose', function () { return { restrict: 'E', templateUrl: '/partials/close.html' }; }); bosunApp.directive('tsForget', function () { return { restrict: 'E', templateUrl: '/partials/forget.html' }; });
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import Typography from '../Typography'; import withStyles from '../styles/withStyles'; import FormControlContext, { useFormControl } from '../FormControl/FormControlContext'; export var styles = { /* Styles applied to the root element. */ root: { display: 'flex', height: '0.01em', // Fix IE 11 flexbox alignment. To remove at some point. maxHeight: '2em', alignItems: 'center', whiteSpace: 'nowrap' }, /* Styles applied to the root element if `variant="filled"`. */ filled: { '&$positionStart:not($hiddenLabel)': { marginTop: 16 } }, /* Styles applied to the root element if `position="start"`. */ positionStart: { marginRight: 8 }, /* Styles applied to the root element if `position="end"`. */ positionEnd: { marginLeft: 8 }, /* Styles applied to the root element if `disablePointerEvents=true`. */ disablePointerEvents: { pointerEvents: 'none' }, /* Styles applied if the adornment is used inside <FormControl hiddenLabel />. */ hiddenLabel: {}, /* Styles applied if the adornment is used inside <FormControl margin="dense" />. */ marginDense: {} }; var InputAdornment = /*#__PURE__*/React.forwardRef(function InputAdornment(props, ref) { var children = props.children, classes = props.classes, className = props.className, _props$component = props.component, Component = _props$component === void 0 ? 'div' : _props$component, _props$disablePointer = props.disablePointerEvents, disablePointerEvents = _props$disablePointer === void 0 ? false : _props$disablePointer, _props$disableTypogra = props.disableTypography, disableTypography = _props$disableTypogra === void 0 ? false : _props$disableTypogra, position = props.position, variantProp = props.variant, other = _objectWithoutProperties(props, ["children", "classes", "className", "component", "disablePointerEvents", "disableTypography", "position", "variant"]); var muiFormControl = useFormControl() || {}; var variant = variantProp; if (variantProp && muiFormControl.variant) { if (process.env.NODE_ENV !== 'production') { if (variantProp === muiFormControl.variant) { console.error('Material-UI: The `InputAdornment` variant infers the variant prop ' + 'you do not have to provide one.'); } } } if (muiFormControl && !variant) { variant = muiFormControl.variant; } return /*#__PURE__*/React.createElement(FormControlContext.Provider, { value: null }, /*#__PURE__*/React.createElement(Component, _extends({ className: clsx(classes.root, className, disablePointerEvents && classes.disablePointerEvents, muiFormControl.hiddenLabel && classes.hiddenLabel, variant === 'filled' && classes.filled, { 'start': classes.positionStart, 'end': classes.positionEnd }[position], muiFormControl.margin === 'dense' && classes.marginDense), ref: ref }, other), typeof children === 'string' && !disableTypography ? /*#__PURE__*/React.createElement(Typography, { color: "textSecondary" }, children) : children)); }); process.env.NODE_ENV !== "production" ? InputAdornment.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The content of the component, normally an `IconButton` or string. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * The component used for the root node. * Either a string to use a HTML element or a component. */ component: PropTypes.elementType, /** * Disable pointer events on the root. * This allows for the content of the adornment to focus the input on click. * @default false */ disablePointerEvents: PropTypes.bool, /** * If children is a string then disable wrapping in a Typography component. * @default false */ disableTypography: PropTypes.bool, /** * The position this adornment should appear relative to the `Input`. */ position: PropTypes.oneOf(['end', 'start']), /** * The variant to use. * Note: If you are using the `TextField` component or the `FormControl` component * you do not have to set this manually. */ variant: PropTypes.oneOf(['filled', 'outlined', 'standard']) } : void 0; export default withStyles(styles, { name: 'MuiInputAdornment' })(InputAdornment);
/*jshint eqeqeq:false */ /*global jQuery, define */ (function( factory ) { "use strict"; if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./grid.base" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { "use strict"; //module begin $.extend($.jgrid,{ focusableElementsList : [ '>a[href]', '>button:not([disabled])', '>area[href]', '>input:not([disabled])', '>select:not([disabled])', '>textarea:not([disabled])', '>iframe', '>object', '>embed', '>*[tabindex]', '>*[contenteditable]' ] }); $.jgrid.extend({ ariaBodyGrid : function ( p ) { var o = $.extend({ onEnterCell : null }, p || {}); return this.each(function (){ var $t = this, getstyle = $.jgrid.getMethod("getStyleUI"), highlight = getstyle($t.p.styleUI+'.common','highlight', true); // basic functions function isValidCell(row, col) { return ( !isNaN(row) && !isNaN(col) && row >= 0 && col >= 0 && $t.rows.length && row < $t.rows.length && col < $t.p.colModel.length ); }; function getNextCell( dirX, dirY) { var row = $t.p.iRow + dirY; // set the default one when initialize grid var col = $t.p.iCol + dirX; // set the default ................. var rowCount = $t.rows.length; var isLeftRight = dirX !== 0; if (!rowCount) { return false; } var colCount = $t.p.colModel.length; if (isLeftRight) { if (col < 0 && row >= 2) { col = colCount - 1; row--; } if (col >= colCount) { col = 0; row++; } } if (!isLeftRight) { if (row < 1) { col--; row = rowCount - 1; if ($t.rows[row] && col >= 0 && !$t.rows[row].cells[col]) { // Sometimes the bottom row is not completely filled in. In this case, // jump to the next filled in cell. row--; } } else if (row >= rowCount || !$t.rows[row].cells[col]) { row = 1; col++; } } if (isValidCell(row, col)) { return { row: row, col: col }; } else if (isValidCell($t.p.iRow, $t.p.iCol)) { return { row: $t.p.iRow, col: $t.p.iCol }; } else { return false; } } function getNextVisibleCell(dirX, dirY) { var nextCell = getNextCell( dirX, dirY); if (!nextCell) { return false; } while ( $($t.rows[nextCell.row].cells[nextCell.col]).is(":hidden") ) { $t.p.iRow = nextCell.row; $t.p.iCol = nextCell.col; nextCell = getNextCell(dirX, dirY); if ($t.p.iRow === nextCell.row && $t.p.iCol === nextCell.col) { // There are no more cells to try if getNextCell returns the current cell return false; } } if( dirY !== 0 ) { $($t).jqGrid('setSelection', $t.rows[nextCell.row].id, false, null, false); } return nextCell; } function movePage ( dir ) { var curpage = $t.p.page, last =$t.p.lastpage; curpage = curpage + dir; if( curpage <= 0) { curpage = 1; } if( curpage > last ) { curpage = last; } if( $t.p.page === curpage ) { return; } $t.p.page = curpage; $t.grid.populate(); } var focusableElementsSelector = $.jgrid.focusableElementsList.join(); function hasFocusableChild( el) { return $(focusableElementsSelector, el)[0]; } $($t).removeAttr("tabindex"); $($t).on('jqGridAfterGridComplete.setAriaGrid', function( e ) { //var grid = e.target; $("tbody:first>tr:not(.jqgfirstrow)>td:not(:hidden, :has("+focusableElementsSelector+"))", $t).attr("tabindex", -1); $("tbody:first>tr:not(.jqgfirstrow)", $t).removeAttr("tabindex"); if($t.p.iRow !== undefined && $t.p.iCol !== undefined) { if($t.rows[$t.p.iRow]) { $($t.rows[$t.p.iRow].cells[$t.p.iCol]) .attr('tabindex', 0) .focus( function() { $(this).addClass(highlight);}) .blur( function () { $(this).removeClass(highlight);}); } } }); $t.p.iRow = 1; $t.p.iCol = $.jgrid.getFirstVisibleCol( $t ); var focusRow=0, focusCol=0; // set the dafualt one $($t).on('keydown', function(e) { if($t.p.navigationDisabled && $t.p.navigationDisabled === true) { return; } var key = e.which || e.keyCode, nextCell; switch(key) { case (38) : nextCell = getNextVisibleCell(0, -1); focusRow = nextCell.row; focusCol = nextCell.col; e.preventDefault(); break; case (40) : nextCell = getNextVisibleCell(0, 1); focusRow = nextCell.row; focusCol = nextCell.col; e.preventDefault(); break; case (37) : nextCell = getNextVisibleCell(-1, 0); focusRow = nextCell.row; focusCol = nextCell.col; e.preventDefault(); break; case (39) : nextCell = getNextVisibleCell(1, 0); focusRow = nextCell.row; focusCol = nextCell.col; e.preventDefault(); break; case 36 : // HOME if(e.ctrlKey) { focusRow = 1; } else { focusRow = $t.p.iRow; } focusCol = 0; e.preventDefault(); break; case 35 : //END if(e.ctrlKey) { focusRow = $t.rows.length - 1; } else { focusRow = $t.p.iRow; } focusCol = $t.p.colModel.length - 1; e.preventDefault(); break; case 33 : // PAGEUP movePage( -1 ); focusCol = $t.p.iCol; focusRow = $t.p.iRow; e.preventDefault(); break; case 34 : // PAGEDOWN movePage( 1 ); focusCol = $t.p.iCol; focusRow = $t.p.iRow; if(focusRow > $t.rows.length-1) { focusRow = $t.rows.length-1; $t.p.iRow = $t.rows.length-1; } e.preventDefault(); break; case 13 : //Enter if( $.isFunction( o.onEnterCell )) { o.onEnterCell.call( $t, $t.rows[$t.p.iRow].id ,$t.p.iRow, $t.p.iCol, e); e.preventDefault(); } return; default: return; } $($t).jqGrid("focusBodyCell", focusRow, focusCol, getstyle, highlight); }); $($t).on('jqGridBeforeSelectRow.ariaGridClick',function() { return false; }); $($t).on('jqGridCellSelect.ariaGridClick', function(el1, id, status,tdhtml, e) { var el = e.target; if($t.p.iRow > 0 && $t.p.iCol >=0) { $($t.rows[$t.p.iRow].cells[$t.p.iCol]).attr("tabindex", -1); } if($(el).is("td") || $(el).is("th")) { $t.p.iCol = el.cellIndex; } else { return; } var row = $(el).closest("tr.jqgrow"); $t.p.iRow = row[0].rowIndex; $(el).attr("tabindex", 0) .addClass(highlight) .focus() .blur(function(){$(this).removeClass(highlight);}); }); }); }, focusBodyCell : function(focusRow, focusCol, _s, _h) { return this.each(function (){ var $t = this, getstyle = !_s ? $.jgrid.getMethod("getStyleUI") : _s, highlight = !_h ? getstyle($t.p.styleUI+'.common','highlight', true) : _h, focusableElementsSelector = $.jgrid.focusableElementsList.join(), fe; function hasFocusableChild( el) { return $(focusableElementsSelector, el)[0]; } if(focusRow !== undefined && focusCol !== undefined) { if (!isNaN($t.p.iRow) && !isNaN($t.p.iCol) && $t.p.iCol >= 0) { fe = hasFocusableChild($t.rows[$t.p.iRow].cells[$t.p.iCol]); if( fe ) { $(fe).attr('tabindex', -1); } else { $($t.rows[$t.p.iRow].cells[$t.p.iCol]).attr('tabindex', -1); } } } else { focusRow = $t.p.iRow; focusCol = $t.p.iCol; } focusRow = parseInt(focusRow, 10); focusCol = parseInt(focusCol, 10); if(focusRow > 0 && focusCol >=0) { fe = hasFocusableChild($t.rows[focusRow].cells[focusCol]); if( fe ) { $(fe).attr('tabindex', 0) .addClass(highlight) .focus() .blur( function () { $(this).removeClass(highlight); }); } else { $($t.rows[focusRow].cells[focusCol]) .attr('tabindex', 0) .addClass(highlight) .focus() .blur(function () { $(this).removeClass(highlight); }); } $t.p.iRow = focusRow; $t.p.iCol = focusCol; } }); }, resetAriaBody : function() { return this.each(function(){ var $t = this; $($t).attr("tabindex","0") .off('keydown') .off('jqGridBeforeSelectRow.ariaGridClick') .off('jqGridCellSelect.ariaGridClick') .off('jqGridAfterGridComplete.setAriaGrid'); var focusableElementsSelector = $.jgrid.focusableElementsList.join(); $("tbody:first>tr:not(.jqgfirstrow)>td:not(:hidden, :has("+focusableElementsSelector+"))", $t).removeAttr("tabindex").off("focus"); $("tbody:first>tr:not(.jqgfirstrow)", $t).attr("tabindex", -1); }); }, ariaHeaderGrid : function() { return this.each(function (){ var $t = this, getstyle = $.jgrid.getMethod("getStyleUI"), highlight = getstyle($t.p.styleUI+'.common','highlight', true), htable = $(".ui-jqgrid-hbox>table:first", "#gbox_"+$t.p.id); $('tr.ui-jqgrid-labels', htable).on("keydown", function(e) { var currindex = $t.p.selHeadInd; var key = e.which || e.keyCode; var len = $t.grid.headers.length; switch (key) { case 37: // left if(currindex-1 >= 0) { currindex--; while( $($t.grid.headers[currindex].el).is(':hidden') && currindex-1 >= 0) { currindex--; if(currindex < 0) { break; } } if(currindex >= 0) { $($t.grid.headers[currindex].el).focus(); $($t.grid.headers[$t.p.selHeadInd].el).attr("tabindex", "-1"); $t.p.selHeadInd = currindex; e.preventDefault(); } } break; case 39: // right if(currindex+1 < len) { currindex++; while( $($t.grid.headers[currindex].el).is(':hidden') && currindex+1 <len) { currindex++; if( currindex > len-1) { break; } } if( currindex < len) { $($t.grid.headers[currindex].el).focus(); $($t.grid.headers[$t.p.selHeadInd].el).attr("tabindex", "-1"); $t.p.selHeadInd = currindex; e.preventDefault(); } } break; case 13: // enter $("div:first",$t.grid.headers[currindex].el).trigger('click'); e.preventDefault(); break; default: return; } }); $('tr.ui-jqgrid-labels>th:not(:hidden)', htable).attr("tabindex", -1).focus(function(){ $(this).addClass(highlight).attr("tabindex", "0"); }).blur(function(){ $(this).removeClass(highlight); }); $t.p.selHeadInd = $.jgrid.getFirstVisibleCol( $t ); $($t.grid.headers[$t.p.selHeadInd].el).attr("tabindex","0"); }); }, focusHeaderCell : function( index) { return this.each( function(){ var $t = this; if(index === undefined) { index = $t.p.selHeadInd; } if(index >= 0 && index < $t.p.colModel.length) { $($t.grid.headers[$t.p.selHeadInd].el).attr("tabindex", "-1"); $($t.grid.headers[index].el).focus(); $t.p.selHeadInd = index; } }); }, resetAriaHeader : function() { return this.each(function(){ var htable = $(".ui-jqgrid-hbox>table:first", "#gbox_" + this.p.id); $('tr.ui-jqgrid-labels', htable).off("keydown"); $('tr.ui-jqgrid-labels>th:not(:hidden)', htable).removeAttr("tabindex").off("focus blur"); }); }, ariaPagerGrid : function () { return this.each( function(){ var $t = this, getstyle = $.jgrid.getMethod("getStyleUI"), highlight = getstyle($t.p.styleUI+'.common','highlight', true), disabled = "."+getstyle($t.p.styleUI+'.common','disabled', true), cels = $(".ui-pg-button",$t.p.pager), len = cels.length; cels.attr("tabindex","-1").focus(function(){ $(this).addClass(highlight); }).blur(function(){ $(this).removeClass(highlight); }); $t.p.navIndex = 0; setTimeout( function() { // make another decision here var navIndex = cels.not(disabled).first().attr("tabindex", "0"); $t.p.navIndex = navIndex[0].cellIndex ? navIndex[0].cellIndex-1 : 0; }, 100); $("table.ui-pager-table tr:first", $t.p.pager).on("keydown", function(e) { var key = e.which || e.keyCode; var indexa = $t.p.navIndex;//currindex; switch (key) { case 37: // left if(indexa-1 >= 0) { indexa--; while( $(cels[indexa]).is(disabled) && indexa-1 >= 0) { indexa--; if(indexa < 0) { break; } } if(indexa >= 0) { $(cels[$t.p.navIndex]).attr("tabindex","-1"); $(cels[indexa]).attr("tabindex","0").focus(); $t.p.navIndex = indexa; } e.preventDefault(); } break; case 39: // right if(indexa+1 < len) { indexa++; while( $(cels[indexa]).is(disabled) && indexa+1 < len + 1) { indexa++; if( indexa > len-1) { break; } } if( indexa < len) { $(cels[$t.p.navIndex]).attr("tabindex","-1"); $(cels[indexa]).attr("tabindex","0").focus(); $t.p.navIndex = indexa; } e.preventDefault(); } break; case 13: // enter $(cels[indexa]).trigger('click'); e.preventDefault(); break; default: return; } }); }); }, focusPagerCell : function( index) { return this.each( function(){ var $t = this, cels = $(".ui-pg-button",$t.p.pager), len = cels.length; if(index === undefined) { index = $t.p.navIndex; } if(index >= 0 && index < len) { $(cels[$t.p.navIndex]).attr("tabindex","-1"); $(cels[index]).attr("tabindex","0").focus(); $t.p.navIndex = index; } }); }, resetAriaPager : function() { return this.each(function(){ $(".ui-pg-button",this.p.pager).removeAttr("tabindex").off("focus");; $("table.ui-pager-table tr:first", this.p.pager).off("keydown"); }); }, setAriaGrid : function ( p ) { var o = $.extend({ header : true, body : true, pager : true, onEnterCell : null }, p || {}); return this.each(function(){ if( o.header ) { $(this).jqGrid('ariaHeaderGrid'); } if( o.body ) { $(this).jqGrid('ariaBodyGrid', {onEnterCell : o.onEnterCell}); } if( o.pager ) { $(this).jqGrid('ariaPagerGrid'); } }); }, resetAriaGrid : function( p ) { var o = $.extend({ header : true, body : true, pager : true }, p || {}); return this.each(function(){ var $t = this; if( o.body ) { $($t).jqGrid('resetAriaBody'); } if( o.header ) { $($t).jqGrid('resetAriaHeader'); } if( o.pager ) { $($t).jqGrid('resetAriaPager'); } }); } // end aria grid }); //module end }));
import React, { PureComponent } from 'react'; import { Animated, View, StyleSheet } from 'react-native'; var babelPluginFlowReactPropTypes_proptype_Style = require('../../TypeDefinition').babelPluginFlowReactPropTypes_proptype_Style || require('prop-types').any; var babelPluginFlowReactPropTypes_proptype_NavigationScreenProp = require('../../TypeDefinition').babelPluginFlowReactPropTypes_proptype_NavigationScreenProp || require('prop-types').any; var babelPluginFlowReactPropTypes_proptype_NavigationState = require('../../TypeDefinition').babelPluginFlowReactPropTypes_proptype_NavigationState || require('prop-types').any; var babelPluginFlowReactPropTypes_proptype_NavigationAction = require('../../TypeDefinition').babelPluginFlowReactPropTypes_proptype_NavigationAction || require('prop-types').any; var babelPluginFlowReactPropTypes_proptype_TabScene = require('./TabView').babelPluginFlowReactPropTypes_proptype_TabScene || require('prop-types').any; export default class TabBarIcon extends PureComponent { render() { const { position, scene, navigation, activeTintColor, inactiveTintColor, style } = this.props; const { route, index } = scene; const { routes } = navigation.state; // Prepend '-1', so there are always at least 2 items in inputRange const inputRange = [-1, ...routes.map((x, i) => i)]; const activeOpacity = position.interpolate({ inputRange, outputRange: inputRange.map(i => i === index ? 1 : 0) }); const inactiveOpacity = position.interpolate({ inputRange, outputRange: inputRange.map(i => i === index ? 0 : 1) }); // We render the icon twice at the same position on top of each other: // active and inactive one, so we can fade between them. return <View style={style}> <Animated.View style={[styles.icon, { opacity: activeOpacity }]}> {this.props.renderIcon({ route, index, focused: true, tintColor: activeTintColor })} </Animated.View> <Animated.View style={[styles.icon, { opacity: inactiveOpacity }]}> {this.props.renderIcon({ route, index, focused: false, tintColor: inactiveTintColor })} </Animated.View> </View>; } } TabBarIcon.propTypes = { activeTintColor: require('prop-types').string.isRequired, inactiveTintColor: require('prop-types').string.isRequired, scene: babelPluginFlowReactPropTypes_proptype_TabScene, position: require('prop-types').any.isRequired, navigation: babelPluginFlowReactPropTypes_proptype_NavigationScreenProp, renderIcon: require('prop-types').func.isRequired, style: babelPluginFlowReactPropTypes_proptype_Style }; TabBarIcon.propTypes = { activeTintColor: require('prop-types').string.isRequired, inactiveTintColor: require('prop-types').string.isRequired, scene: babelPluginFlowReactPropTypes_proptype_TabScene, position: require('prop-types').any.isRequired, navigation: babelPluginFlowReactPropTypes_proptype_NavigationScreenProp, renderIcon: require('prop-types').func.isRequired, style: babelPluginFlowReactPropTypes_proptype_Style }; const styles = StyleSheet.create({ icon: { // We render the icon twice at the same position on top of each other: // active and inactive one, so we can fade between them: // Cover the whole iconContainer: position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, alignItems: 'center', justifyContent: 'center' } });
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); //>>group: exclude define([ "require", "./widgets/loader", "./events/navigate", "./navigation/path", "./navigation/history", "./navigation/navigator", "./navigation/method", "./transitions/handlers", "./transitions/visuals", "./animationComplete", "./navigation", "./degradeInputs", "./widgets/page.dialog", "./widgets/dialog", "./widgets/collapsible", "./widgets/collapsibleSet", "./fieldContain", "./grid", "./widgets/navbar", "./widgets/listview", "./widgets/listview.autodividers", "./widgets/listview.hidedividers", "./nojs", "./widgets/forms/checkboxradio", "./widgets/forms/button", "./widgets/forms/slider", "./widgets/forms/slider.tooltip", "./widgets/forms/flipswitch", "./widgets/forms/rangeslider", "./widgets/forms/textinput", "./widgets/forms/clearButton", "./widgets/forms/autogrow", "./widgets/forms/select.custom", "./widgets/forms/select", "./buttonMarkup", "./widgets/controlgroup", "./links", "./widgets/toolbar", "./widgets/fixedToolbar", "./widgets/fixedToolbar.workarounds", "./widgets/popup", "./widgets/popup.arrow", "./widgets/panel", "./widgets/table", "./widgets/table.columntoggle", "./widgets/table.reflow", "./widgets/filterable", "./widgets/filterable.backcompat", "./widgets/tabs", "./zoom", "./zoom/iosorientationfix" ], function( require ) { require( [ "./init" ], function() {} ); }); //>>excludeEnd("jqmBuildExclude");
module.exports = { name: 'basis.type', test: [ require('./type/string.js'), require('./type/number.js'), require('./type/int.js'), require('./type/enum.js'), require('./type/array.js'), require('./type/object.js'), require('./type/date.js'), { name: 'definition of new types', init: function(){ var basis = window.basis.createSandbox(); var type = basis.require('basis.type'); var catchWarnings = basis.require('./helpers/common.js').catchWarnings; }, test: [ { name: 'simple case', test: function(){ var any = function(value){ return value; }; type.defineType('Any', any); assert(type.getTypeByName('Any') === any); } }, { name: 'corner case', test: function(){ var toStringType = type.getTypeByName('toString'); var warned = catchWarnings(function(){ toStringType({}); }); assert(warned); assert(type.getTypeByNameIfDefined('toString') === undefined); type.defineType('toString', basis.fn.$self); var warnedAgain = catchWarnings(function(){ toStringType({}); }); assert(!warnedAgain); assert(type.getTypeByNameIfDefined('toString') === basis.fn.$self); } }, { name: 'deferred type definition', test: function(){ var DeferredType = type.getTypeByName('DeferredType'); var warnedBefore = catchWarnings(function(){ assert(DeferredType('234.55') === undefined); }); assert(warnedBefore); type.defineType('DeferredType', type.int); var warnedAfter = catchWarnings(function(){ assert(DeferredType('234.55') === 234); }); assert(warnedAfter === false); } }, { name: 'deffered type definition with specifying type host', test: function(){ var typeHost = {}; var HostedType = type.getTypeByName('HostedType', typeHost, 'someType'); var warnedBefore = catchWarnings(function(){ assert(HostedType('234.55') === undefined); }); assert(warnedBefore); type.defineType('HostedType', type.number); var warnedAfter = catchWarnings(function(){ assert(HostedType('234.55') === 234.55); }); assert(warnedAfter === false); assert(typeHost.someType === type.number); } }, { name: 'double define', test: function(){ var DoubleTypeA = type.defineType('DoubleType', type.string); var DoubleTypeB; var warned = catchWarnings(function(){ var DoubleTypeB = type.defineType('DoubleType', type.date); }); assert(warned); assert(type.getTypeByName('DoubleType') === type.date); } }, { name: 'type definition with non string value', test: function(){ var warned = catchWarnings(function(){ var Three = type.defineType(3, type.object); }); assert(warned); } }, { name: 'validation', test: function(){ var StringType = type.getTypeByName('StringType'); var NumberType = type.getTypeByName('NumberType'); type.defineType('StringType', type.string); var warned = catchWarnings(function(){ type.validate(); }); assert(warned); type.defineType('NumberType', type.number); var warnedAgain = catchWarnings(function(){ type.validate(); }); assert(!warnedAgain); } } ] } ] };
/* Slovenia +*/ /*global jQuery */ (function ($) { $.ig = $.ig || {}; $.ig.regional = $.ig.regional || {}; if ($.datepicker && $.datepicker.regional) { $.datepicker.regional['sl'] = { closeText: 'Zapri', prevText: '&#x3C;Prejšnji', nextText: 'Naslednji&#x3E;', currentText: 'Trenutni', monthNames: ['Januar','Februar','Marec','April','Maj','Junij', 'Julij','Avgust','September','Oktober','November','December'], monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun', 'Jul','Avg','Sep','Okt','Nov','Dec'], dayNames: ['Nedelja','Ponedeljek','Torek','Sreda','Četrtek','Petek','Sobota'], dayNamesShort: ['Ned','Pon','Tor','Sre','Čet','Pet','Sob'], dayNamesMin: ['Ne','Po','To','Sr','Če','Pe','So'], weekHeader: 'Teden', dateFormat: 'dd.mm.yy', firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: '' }; } $.ig.regional.sl = { monthNames: ['Januar', 'Februar', 'Marec', 'April', 'Maj', 'Junij', 'Julij', 'Avgust', 'September', 'Oktober', 'November', 'December'], monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'Maj', 'Jun', 'Jul', 'Avg', 'Sep', 'Okt', 'Nov', 'Dec'], dayNames: ['Nedelja', 'Ponedeljek', 'Torek', 'Sreda', 'Četrtek', 'Petek', 'Sobota'], dayNamesShort: ['Ned', 'Pon', 'Tor', 'Sre', 'Čet', 'Pet', 'Sob'], datePattern: 'd.M.yyyy', dateLongPattern: 'd. MMMM yyyy', dateTimePattern: 'd.M.yyyy HH:mm', timePattern: 'HH:mm', timeLongPattern: 'HH:mm:ss', // numericNegativePattern: '-n$', numericDecimalSeparator: ',', numericGroupSeparator: '.', numericMaxDecimals: 2, currencyPositivePattern: 'n $', currencyNegativePattern: '-n $', currencySymbol: '€', currencyDecimalSeparator: ',', currencyGroupSeparator: '.', percentDecimalSeparator: ',', percentGroupSeparator: '.' }; if ($.ig.setRegionalDefault) { $.ig.setRegionalDefault('sl'); } })(jQuery);
const models = require('../../models'); const {i18n} = require('../../lib/common'); const errors = require('@tryghost/errors'); const urlUtils = require('../../../shared/url-utils'); const ALLOWED_INCLUDES = ['tags', 'authors', 'authors.roles']; const UNSAFE_ATTRS = ['status', 'authors', 'visibility']; module.exports = { docName: 'pages', browse: { options: [ 'include', 'filter', 'fields', 'formats', 'limit', 'order', 'page', 'debug', 'absolute_urls' ], validation: { options: { include: { values: ALLOWED_INCLUDES }, formats: { values: models.Post.allowedFormats } } }, permissions: { docName: 'posts', unsafeAttrs: UNSAFE_ATTRS }, query(frame) { return models.Post.findPage(frame.options); } }, read: { options: [ 'include', 'fields', 'formats', 'debug', 'absolute_urls', // NOTE: only for internal context 'forUpdate', 'transacting' ], data: [ 'id', 'slug', 'uuid' ], validation: { options: { include: { values: ALLOWED_INCLUDES }, formats: { values: models.Post.allowedFormats } } }, permissions: { docName: 'posts', unsafeAttrs: UNSAFE_ATTRS }, query(frame) { return models.Post.findOne(frame.data, frame.options) .then((model) => { if (!model) { throw new errors.NotFoundError({ message: i18n.t('errors.api.pages.pageNotFound') }); } return model; }); } }, add: { statusCode: 201, headers: {}, options: [ 'include', 'source' ], validation: { options: { include: { values: ALLOWED_INCLUDES }, source: { values: ['html'] } } }, permissions: { docName: 'posts', unsafeAttrs: UNSAFE_ATTRS }, query(frame) { return models.Post.add(frame.data.pages[0], frame.options) .then((model) => { if (model.get('status') !== 'published') { this.headers.cacheInvalidate = false; } else { this.headers.cacheInvalidate = true; } return model; }); } }, edit: { headers: {}, options: [ 'include', 'id', 'source', // NOTE: only for internal context 'forUpdate', 'transacting' ], validation: { options: { include: { values: ALLOWED_INCLUDES }, id: { required: true }, source: { values: ['html'] } } }, permissions: { docName: 'posts', unsafeAttrs: UNSAFE_ATTRS }, query(frame) { return models.Post.edit(frame.data.pages[0], frame.options) .then((model) => { if ( model.get('status') === 'published' && model.wasChanged() || model.get('status') === 'draft' && model.previous('status') === 'published' ) { this.headers.cacheInvalidate = true; } else if ( model.get('status') === 'draft' && model.previous('status') !== 'published' || model.get('status') === 'scheduled' && model.wasChanged() ) { this.headers.cacheInvalidate = { value: urlUtils.urlFor({ relativeUrl: urlUtils.urlJoin('/p', model.get('uuid'), '/') }) }; } else { this.headers.cacheInvalidate = false; } return model; }); } }, destroy: { statusCode: 204, headers: { cacheInvalidate: true }, options: [ 'include', 'id' ], validation: { options: { include: { values: ALLOWED_INCLUDES }, id: { required: true } } }, permissions: { docName: 'posts', unsafeAttrs: UNSAFE_ATTRS }, query(frame) { frame.options.require = true; return models.Post.destroy(frame.options) .then(() => null) .catch(models.Post.NotFoundError, () => { return Promise.reject(new errors.NotFoundError({ message: i18n.t('errors.api.pages.pageNotFound') })); }); } } };
'use strict'; module.exports = { env: 'test' };
function trading_init(){ if (!this.trading){ //if (this.trading === undefined || this.trading === null){ this.trading = apiNewOwnedDC(this); this.trading.label = 'Trading'; this.trading_create_escrow_bag(); this.trading.currants = 0; } var escrow = this.trading_get_escrow_bag(); if (!escrow){ this.trading_create_escrow_bag(); } else if (escrow.capacity != 6 && escrow.countContents() == 0){ escrow.apiDelete(); this.trading_create_escrow_bag(); } } function trading_create_escrow_bag(){ // Create a new private storage bag for holding items in escrow var it = apiNewItemStack('bag_escrow', 1); it.label = 'Private Trading Storage'; this.apiAddHiddenStack(it); this.trading.storage_tsid = it.tsid; } function trading_reset(){ this.trading_cancel_auto(); if (this.trading){ var escrow = this.trading_get_escrow_bag(); if (escrow){ var contents = escrow.getContents(); for (var i in contents){ if (contents[i]) contents[i].apiDelete(); } } } } function trading_delete(){ this.trading_cancel_auto(); if (this.trading){ var escrow = this.trading_get_escrow_bag(); if (escrow){ var contents = escrow.getContents(); for (var i in contents){ if (contents[i]) contents[i].apiDelete(); } escrow.apiDelete(); delete this.trading.storage_tsid; } this.trading.apiDelete(); delete this.trading; } } function trading_get_escrow_bag(){ return this.hiddenItems[this.trading.storage_tsid]; } function trading_has_escrow_items(){ var escrow = this.trading_get_escrow_bag(); return escrow.countContents() > 0 ? true : false; } // // Attempt to start a trade with player 'target_tsid' // function trading_request_start(target_tsid){ //log.info(this.tsid+' starting trade with '+target_tsid); this.trading_init(); // // Are we currently trading? // if (this['!is_trading']){ return { ok: 0, error: 'You are already trading with someone else. Finish that up first.' }; } // // Is there stuff in our escrow bag? // if (this.trading_has_escrow_items()){ return { ok: 0, error: 'You have unsettled items from a previous trade. Make some room in your pack for them before attempting another trade.' }; } // // Valid player? // if (target_tsid == this.tsid){ return { ok: 0, error: 'No trading with yourself.' }; } var target = getPlayer(target_tsid); if (!target){ return { ok: 0, error: 'Not a valid target player.' }; } if (this.buddies_is_ignored_by(target) || this.buddies_is_ignoring(target)){ return { ok: 0, error: 'You are blocking or blocked by that player.' }; } if (!apiIsPlayerOnline(target_tsid)){ return { ok: 0, error: 'That player is not online.' }; } if (target.getProp('location').tsid != this.location.tsid){ return { ok: 0, error: "Oh come on, they're not even in the same location as you!" }; } // // Are they currently trading? // if (target['!is_trading']){ target.sendOnlineActivity(this.label+' wanted to trade with you, but you are busy.'); return { ok: 0, error: 'That player is already trading with someone else. Please wait until they are done.' }; } // // Is there stuff in their escrow bag? // if (target.trading_has_escrow_items()){ target.sendOnlineActivity(this.label+' wanted to trade with you, but you have an unsettled previous trade.'); return { ok: 0, error: 'That player is not available for trading right now.' }; } // // PROCEED // target.trading_init(); this['!is_trading'] = target.tsid; target['!is_trading'] = this.tsid; target.apiSendMsgAsIs({ type: 'trade_start', tsid: this.tsid }); // // Overlays // var anncx = { type: 'pc_overlay', duration: 0, pc_tsid: this.tsid, delta_x: 0, delta_y: -110, bubble: true, width: 70, height: 70, swf_url: overlay_key_to_url('trading'), uid: this.tsid+'_trading' }; this.location.apiSendAnnouncementX(anncx, this); anncx['pc_tsid'] = target.tsid; anncx['uid'] = target.tsid+'_trading'; target.location.apiSendAnnouncementX(anncx, target); return { ok: 1 }; } // // Cancel an in-progress trade with 'target_tsid' // function trading_cancel(target_tsid){ //log.info(this.tsid+' canceling trade with '+target_tsid); // // Sanity check // if (!this['!is_trading'] || this['!is_trading'] != target_tsid){ return { ok: 0, error: 'You are not trading with that player.' }; } var target = getPlayer(target_tsid); // // Roll back the trade on us and the target // this.trading_rollback(); if (target['!is_trading'] == this.tsid){ target.trading_rollback(); } // // Overlays // this.location.apiSendMsgAsIsX({ type: 'overlay_cancel', uid: this.tsid+'_trading' }, this); if (apiIsPlayerOnline(target_tsid) && target['!is_trading'] == this.tsid){ target.location.apiSendMsgAsIsX({ type: 'overlay_cancel', uid: target.tsid+'_trading' }, target); } // // Tell the other player // if (apiIsPlayerOnline(target_tsid) && target['!is_trading'] == this.tsid){ target.apiSendMsgAsIs({ type: 'trade_cancel', tsid: this.tsid }); target.prompts_add({ txt : this.label+" canceled their trade with you.", icon_buttons : false, timeout : 10, choices : [ { value : 'ok', label : 'Oh well' } ] }); } delete this['!is_trading']; if (target['!is_trading'] == this.tsid){ delete target['!is_trading']; } return { ok: 1 }; } function trading_rollback(){ //log.info(this.tsid+' rolling back trade'); // // Refund all the in-progress items // var escrow = this.trading_get_escrow_bag(); if (escrow){ var returned = []; var overflow = false; var contents = escrow.getContents(); for (var i in contents){ if (contents[i]){ var restore = escrow.removeItemStackSlot(i); var count = restore.count; var remaining = this.addItemStack(restore); if (remaining) overflow = true; if (remaining != count){ returned.push(pluralize(count-remaining, restore.name_single, restore.name_plural)); } } } if (overflow){ //log.info('trading_rollback overflow detected'); this.prompts_add({ txt : "Your magic rock is holding items from a previous trade for you. Make room in your pack to hold them.", icon_buttons : false, timeout : 30, choices : [ { value : 'ok', label : 'Very well' } ] }); this.trading_reorder_escrow(); } if (returned.length){ this.prompts_add({ txt : "Your "+pretty_list(returned, ' and ')+" "+(returned.length == 1 ? 'has' : 'have')+" been returned to you.", icon_buttons : false, timeout : 5, choices : [ { value : 'ok', label : 'OK' } ] }); } } // // Refund currants // if (this.trading.currants){ this.stats_add_currants(this.trading.currants); this.trading.currants = 0; } delete this['!trade_accepted']; } // // Cancel any in-progress trade // function trading_cancel_auto(){ //log.info(this.tsid+' canceling all trades'); if (this['!is_trading']) this.trading_cancel(this['!is_trading']); } // // Add an item to the trade // function trading_add_item(target_tsid, itemstack_tsid, amount){ //log.info(this.tsid+' adding item '+itemstack_tsid+' to trade with '+target_tsid); // // Sanity check // if (!this['!is_trading'] || this['!is_trading'] != target_tsid){ return { ok: 0, error: 'You are not trading with that player.' }; } var target = getPlayer(target_tsid); if (!apiIsPlayerOnline(target_tsid)){ return { ok: 0, error: 'That player is not online.' }; } // // Get the item, put it in escrow // delete this['!trade_accepted']; delete target['!trade_accepted']; var ret = this.trading_add_item_do(itemstack_tsid, amount); if (!ret['ok']){ return ret; } // // Tell the other player // if (ret.item_class){ var rsp = { type: 'trade_add_item', tsid: this.tsid, itemstack_class: ret.item_class, amount: ret.count, slot: ret.slot, label: ret.label, config: ret.config }; if (ret.tool_state) rsp.tool_state = ret.tool_state; target.apiSendMsgAsIs(rsp); } return { ok: 1 }; } function trading_add_item_do(itemstack_tsid, amount, destination_slot){ //log.info('trading_add_item_do '+itemstack_tsid+' ('+amount+')'); var item = this.removeItemStackTsid(itemstack_tsid, amount); if (!item){ return { ok: 0, error: "That item is not in your possession." }; } var target = getPlayer(this['!is_trading']); if (!item.has_parent('furniture_base') && target.isBagFull(item)){ target.sendOnlineActivity(this.label+' tried to offer some '+item.label+' for trade, but you cannot hold it.'); this.items_put_back(item); return { ok: 0, error: "The other player cannot hold that item." }; } var item_class = item.class_tsid; var have_count = this.countItemClass(item_class); if (item.has_parent('furniture_base')){ have_count = this.furniture_get_bag().countItemClass(item_class); } // If this is a stack we split off from somewhere, we need to add it to the count if (!item.container) have_count += item.count; //log.info('trading_add_item_do have_count: '+have_count+', amount: '+amount); if (have_count < amount){ this.items_put_back(item); return { ok: 0, error: "You don't have enough of that item." }; } // // Some things are untradeable -- check them here // if (item.is_bag && item.countContents() > 0){ this.items_put_back(item); return { ok: 0, error: "You may not trade non-empty bags." }; } if (item.isSoulbound()){ this.items_put_back(item); return { ok: 0, error: "That item is locked to you, and can't be traded." }; } var escrow = this.trading_get_escrow_bag(); var slots = {}; var contents = escrow.getContents(); for (var i in contents){ if (contents[i]){ slots[i] = contents[i].count; } } var item_count = item.count; var remaining = escrow.addItemStack(item, destination_slot); if (remaining == item_count){ var restore = escrow.removeItemStackClass(item.class_tsid, remaining); this.items_put_back(item); this.addItemStack(restore); return { ok: 0, error: "Oops! We couldn't place that item in escrow." }; } if (item_count < amount){ var still_need = amount - item_count; do { var stack = this.removeItemStackClass(item_class, still_need); if (!stack){ return { ok: 0, error: "Oops! We couldn't place that item in escrow." }; } still_need -= stack.count; remaining = escrow.addItemStack(stack); if (remaining){ var restore = escrow.removeItemStackClass(item.class_tsid, remaining); this.items_put_back(stack); this.addItemStack(restore); return { ok: 0, error: "Oops! We couldn't place that item in escrow." }; } } while (still_need > 0); } // // Send changes // contents = escrow.getContents(); for (var i in contents){ if (contents[i]){ if (slots[i] && contents[i].count != slots[i]){ var rsp = { type: 'trade_change_item', tsid: this.tsid, itemstack_class: contents[i].class_id, amount: contents[i].count, slot: i, label: contents[i].label }; if (contents[i].is_tool) rsp.tool_state = contents[i].get_tool_state(); target.apiSendMsgAsIs(rsp); } } } if (item.apiIsDeleted()){ //log.info('Stack was merged'); return { ok: 1 }; } var rsp = { ok: 1, item_class: item_class, slot: intval(item.slot), count: item.count, label: item.label }; if (item.is_tool) rsp.tool_state = item.get_tool_state(); // Config? if (item.make_config){ rsp.config = item.make_config(); } return rsp; } // // Remove an item from the trade // function trading_remove_item(target_tsid, itemstack_tsid, amount){ //log.info(this.tsid+' removing item '+itemstack_tsid+' from trade with '+target_tsid); // // Sanity check // if (!this['!is_trading'] || this['!is_trading'] != target_tsid){ return { ok: 0, error: 'You are not trading with that player.' }; } var target = getPlayer(target_tsid); if (!apiIsPlayerOnline(target_tsid)){ return { ok: 0, error: 'That player is not online.' }; } // // Get the item from escrow // delete this['!trade_accepted']; delete target['!trade_accepted']; var ret = this.trading_remove_item_do(itemstack_tsid, amount); if (!ret['ok']){ return ret; } // // Tell the other player // target.apiSendMsgAsIs({ type: 'trade_remove_item', tsid: this.tsid, itemstack_class: ret.item_class, amount: amount, slot: ret.slot, label: ret.label }); return { ok: 1 }; } function trading_remove_item_do(itemstack_tsid, amount){ var escrow = this.trading_get_escrow_bag(); if (escrow.items[itemstack_tsid]){ var slot = escrow.items[itemstack_tsid].slot; var item = escrow.removeItemStackTsid(itemstack_tsid, amount); //log.info('trading_remove_item_do slot is '+slot); } else{ return { ok: 0, error: "That item is not in your escrow storage." }; } if (item.count != amount){ this.items_put_back(item); return { ok: 0, error: "You don't have enough of that item in escrow." }; } var item_class = item.class_tsid; var item_label = item.label; var remaining = this.addItemStack(item); if (remaining){ var restore = this.removeItemStackClass(item.class_tsid, remaining); this.items_put_back(item); escrow.addItemStack(restore); return { ok: 0, error: "Oops! We couldn't place that item in your pack." }; } // // Do we need to move everything around? // this.trading_reorder_escrow(); return { ok: 1, item_class: item_class, slot: intval(slot), label: item_label }; } // // Move items around in the escrow bag in order to keep things in sequential slots // function trading_reorder_escrow(){ var escrow = this.trading_get_escrow_bag(); if (escrow.countContents()){ var escrow_contents = escrow.getContents(); for (var slot in escrow_contents){ if (!escrow_contents[slot]){ for (var i=intval(slot); i<escrow.capacity; i++){ if (escrow_contents[i+1]){ escrow.addItemStack(escrow.removeItemStackSlot(i+1), i); } } break; } } } } // // Change the amount of an item to trage // function trading_change_item(target_tsid, itemstack_tsid, amount){ //log.info(this.tsid+' changing item '+itemstack_tsid+' to trade with '+target_tsid+' ('+amount+')'); // // Sanity check // if (!this['!is_trading'] || this['!is_trading'] != target_tsid){ return { ok: 0, error: 'You are not trading with that player.' }; } var target = getPlayer(target_tsid); if (!apiIsPlayerOnline(target_tsid)){ return { ok: 0, error: 'That player is not online.' }; } // // Adjust counts // delete this['!trade_accepted']; delete target['!trade_accepted']; var escrow = this.trading_get_escrow_bag(); var contents = escrow.getAllContents(); var item = contents[itemstack_tsid]; if (!item){ return { ok: 0, error: "That item is not in your escrow storage." }; } //log.info('trading_change_item '+item.count+' != '+amount); if (item.count != amount){ if (item.count < amount){ // We need an item from the pack to move var pack_item = this.findFirst(item.class_id); if (!pack_item){ return { ok: 0, error: "You don't have any more of that item." }; } //log.info('pack_item: '+pack_item.tsid); //log.info('Adding '+(amount-item.count)); var ret = this.trading_add_item_do(pack_item.tsid, amount-item.count, item.slot); amount = ret.count; } else{ //log.info('Removing '+(item.count-amount)); var ret = this.trading_remove_item_do(itemstack_tsid, item.count-amount); } if (!ret['ok']){ return ret; } // // Tell the other player // if (ret.item_class){ //log.info('trade_change_item ---------------------- slot '+ret.slot+' = '+amount); target.apiSendMsgAsIs({ type: 'trade_change_item', tsid: this.tsid, itemstack_class: ret.item_class, amount: amount, slot: ret.slot, label: ret.label, config: ret.config }); } } return { ok: 1 }; } // // Update the currants on the trade // function trading_update_currants(target_tsid, amount){ //log.info(this.tsid+' updating currants to '+amount+' on trade with '+target_tsid); // // Sanity check // if (!this['!is_trading'] || this['!is_trading'] != target_tsid){ return { ok: 0, error: 'You are not trading with that player.' }; } var target = getPlayer(target_tsid); if (!apiIsPlayerOnline(target_tsid)){ return { ok: 0, error: 'That player is not online.' }; } // // Put the currants in escrow // delete this['!trade_accepted']; delete target['!trade_accepted']; var amount_diff = amount - this.trading.currants; //log.info('Currants diff of '+amount+' - '+this.trading.currants+' is '+amount_diff); //log.info('Player currently has: '+this.stats.currants.value); if (amount_diff != 0){ if (amount_diff < 0){ //log.info('Restoring '+Math.abs(amount_diff)); this.stats_add_currants(Math.abs(amount_diff)); } else{ if (!this.stats_try_remove_currants(amount_diff, {type: 'trading', target: target_tsid})){ return { ok: 0, error: "You don't have enough currants for that." }; } } this.trading.currants = amount; // // Tell the other player // target.apiSendMsgAsIs({ type: 'trade_currants', tsid: this.tsid, amount: this.trading.currants }); } return { ok: 1 }; } // // Accept the trade // function trading_accept(target_tsid){ //log.info(this.tsid+' accepting trade with '+target_tsid); // // Sanity check // if (!this['!is_trading'] || this['!is_trading'] != target_tsid){ return { ok: 0, error: 'You are not trading with that player.' }; } var target = getPlayer(target_tsid); if (!apiIsPlayerOnline(target_tsid)){ return { ok: 0, error: 'That player is not online.' }; } this['!trade_accepted'] = true; // // Tell the other player // target.apiSendMsgAsIs({ type: 'trade_accept', tsid: this.tsid }); // // If both sides have accepted, then do it // if (target['!trade_accepted']){ var ret = this.trading_complete(target_tsid); if (!ret['ok']){ return ret; } } return { ok: 1 }; } // // Unlock the trade // function trading_unlock(target_tsid){ //log.info(this.tsid+' unlocking trade with '+target_tsid); // // Sanity check // if (!this['!is_trading'] || this['!is_trading'] != target_tsid){ return { ok: 0, error: 'You are not trading with that player.' }; } var target = getPlayer(target_tsid); if (!apiIsPlayerOnline(target_tsid)){ return { ok: 0, error: 'That player is not online.' }; } delete this['!trade_accepted']; // // Tell the other player // target.apiSendMsgAsIs({ type: 'trade_unlock', tsid: this.tsid }); return { ok: 1 }; } // // Complete the trade // function trading_complete(target_tsid){ //log.info(this.tsid+' completing trade with '+target_tsid); // // Sanity check // if (!this['!is_trading'] || this['!is_trading'] != target_tsid){ return { ok: 0, error: 'You are not trading with that player.' }; } var target = getPlayer(target_tsid); if (!apiIsPlayerOnline(target_tsid)){ return { ok: 0, error: 'That player is not online.' }; } // // Have both sides accepted? // if (!this['!trade_accepted']){ return { ok: 0, error: 'You have not accepted this trade.' }; } if (!target['!trade_accepted']){ return { ok: 0, error: 'That player has not accepted this trade.' }; } // // Perform the transfer // this.trading_transfer(target_tsid); target.trading_transfer(this.tsid); // // Overlays // this.location.apiSendMsgAsIsX({ type: 'overlay_cancel', uid: this.tsid+'_trading' }, this); target.location.apiSendMsgAsIsX({ type: 'overlay_cancel', uid: target.tsid+'_trading' }, target); // // Tell both players that we are done // this.apiSendMsgAsIs({ type: 'trade_complete', tsid: target_tsid }); target.apiSendMsgAsIs({ type: 'trade_complete', tsid: this.tsid }); // // Cleanup and exit // delete this['!is_trading']; delete target['!is_trading']; delete this['!trade_accepted']; delete target['!trade_accepted']; return { ok: 1 }; } // // Transfer items/currants from escrow to target_tsid. // If something goes wrong, oh well! // function trading_transfer(target_tsid){ var target = getPlayer(target_tsid); // // Items! // var traded_something = false; var escrow = this.trading_get_escrow_bag(); if (escrow){ var contents = escrow.getContents(); var overflow = false; for (var i in contents){ if (contents[i]){ var item = escrow.removeItemStackSlot(i); // Item callback if (item.onTrade) item.onTrade(this, target); var remaining = target.addItemStack(item); if (remaining){ var target_escrow = target.trading_get_escrow_bag(); target_escrow.addItemStack(item); overflow = true; } traded_something = true; } } if (overflow){ target.prompts_add({ txt : "Some of the items you received in your trade with "+this.label+" did not fit in your pack. Your magic rock will hold them for you until you make room, and you cannot start another trade until you do so.", icon_buttons : false, timeout : 30, choices : [ { value : 'ok', label : 'Very well' } ] }); } } // // Currants! // if (this.trading.currants){ target.stats_add_currants(this.trading.currants, {'trade':this.tsid}); this.trading.currants = 0; traded_something = true; } if (traded_something){ // // Achievements // this.achievements_increment('players_traded', target_tsid); target.achievements_increment('players_traded', this.tsid); } }
/**************************************************************************** Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org 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. ****************************************************************************/ /** * The tween class for Armature. * @class * @extends ccs.ProcessBase * * @property {ccs.ArmatureAnimation} animation - The animation */ ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{ _tweenData:null, _to:null, _from:null, _between:null, _movementBoneData:null, _bone:null, _frameTweenEasing:0, _betweenDuration:0, _totalDuration:0, _toIndex:0, _fromIndex:0, _animation:null, _passLastFrame:false, /** * Construction of ccs.Tween. */ ctor:function () { ccs.ProcessBase.prototype.ctor.call(this); this._frameTweenEasing = ccs.TweenType.linear; }, /** * initializes a ccs.Tween with a CCBone * @param {ccs.Bone} bone * @return {Boolean} */ init:function (bone) { this._from = new ccs.FrameData(); this._between = new ccs.FrameData(); this._bone = bone; this._tweenData = this._bone.getTweenData(); this._tweenData.displayIndex = -1; this._animation = this._bone.getArmature() != null ? this._bone.getArmature().getAnimation() : null; return true; }, /** * Plays the tween. * @param {ccs.MovementBoneData} movementBoneData * @param {Number} durationTo * @param {Number} durationTween * @param {Boolean} loop * @param {ccs.TweenType} tweenEasing */ play:function (movementBoneData, durationTo, durationTween, loop, tweenEasing) { ccs.ProcessBase.prototype.play.call(this, durationTo, durationTween, loop, tweenEasing); this._loopType = (loop)?ccs.ANIMATION_TYPE_TO_LOOP_FRONT:ccs.ANIMATION_TYPE_NO_LOOP; this._totalDuration = 0; this._betweenDuration = 0; this._fromIndex = this._toIndex = 0; var difMovement = movementBoneData != this._movementBoneData; this.setMovementBoneData(movementBoneData); this._rawDuration = this._movementBoneData.duration; var nextKeyFrame = this._movementBoneData.getFrameData(0); this._tweenData.displayIndex = nextKeyFrame.displayIndex; if (this._bone.getArmature().getArmatureData().dataVersion >= ccs.CONST_VERSION_COMBINED) { ccs.TransformHelp.nodeSub(this._tweenData, this._bone.getBoneData()); this._tweenData.scaleX += 1; this._tweenData.scaleY += 1; } if (this._rawDuration == 0) { this._loopType = ccs.ANIMATION_TYPE_SINGLE_FRAME; if (durationTo == 0) this.setBetween(nextKeyFrame, nextKeyFrame); else this.setBetween(this._tweenData, nextKeyFrame); this._frameTweenEasing = ccs.TweenType.linear; } else if (this._movementBoneData.frameList.length > 1) { this._durationTween = durationTween * this._movementBoneData.scale; if (loop && this._movementBoneData.delay != 0) this.setBetween(this._tweenData, this.tweenNodeTo(this.updateFrameData(1 - this._movementBoneData.delay), this._between)); else { if (!difMovement || durationTo == 0) this.setBetween(nextKeyFrame, nextKeyFrame); else this.setBetween(this._tweenData, nextKeyFrame); } } this.tweenNodeTo(0); }, /** * Goes to specified frame and plays frame. * @param {Number} frameIndex */ gotoAndPlay: function (frameIndex) { ccs.ProcessBase.prototype.gotoFrame.call(this, frameIndex); this._totalDuration = 0; this._betweenDuration = 0; this._fromIndex = this._toIndex = 0; this._isPlaying = true; this._isComplete = this._isPause = false; this._currentPercent = this._curFrameIndex / (this._rawDuration-1); this._currentFrame = this._nextFrameIndex * this._currentPercent; }, /** * Goes to specified frame and pauses frame. * @param {Number} frameIndex */ gotoAndPause: function (frameIndex) { this.gotoAndPlay(frameIndex); this.pause(); }, /** * update will call this handler, you can handle your logic here */ updateHandler:function () { var locCurrentPercent = this._currentPercent || 1; var locLoopType = this._loopType; if (locCurrentPercent >= 1) { switch (locLoopType) { case ccs.ANIMATION_TYPE_SINGLE_FRAME: locCurrentPercent = 1; this._isComplete = true; this._isPlaying = false; break; case ccs.ANIMATION_TYPE_NO_LOOP: locLoopType = ccs.ANIMATION_TYPE_MAX; if (this._durationTween <= 0) locCurrentPercent = 1; else locCurrentPercent = (locCurrentPercent - 1) * this._nextFrameIndex / this._durationTween; if (locCurrentPercent >= 1) { locCurrentPercent = 1; this._isComplete = true; this._isPlaying = false; break; } else { this._nextFrameIndex = this._durationTween; this._currentFrame = locCurrentPercent * this._nextFrameIndex; this._totalDuration = 0; this._betweenDuration = 0; this._fromIndex = this._toIndex = 0; break; } case ccs.ANIMATION_TYPE_TO_LOOP_FRONT: locLoopType = ccs.ANIMATION_TYPE_LOOP_FRONT; this._nextFrameIndex = this._durationTween > 0 ? this._durationTween : 1; if (this._movementBoneData.delay != 0) { this._currentFrame = (1 - this._movementBoneData.delay) * this._nextFrameIndex; locCurrentPercent = this._currentFrame / this._nextFrameIndex; } else { locCurrentPercent = 0; this._currentFrame = 0; } this._totalDuration = 0; this._betweenDuration = 0; this._fromIndex = this._toIndex = 0; break; case ccs.ANIMATION_TYPE_MAX: locCurrentPercent = 1; this._isComplete = true; this._isPlaying = false; break; default: this._currentFrame = ccs.fmodf(this._currentFrame, this._nextFrameIndex); break; } } if (locCurrentPercent < 1 && locLoopType < ccs.ANIMATION_TYPE_TO_LOOP_BACK) locCurrentPercent = Math.sin(locCurrentPercent * cc.PI / 2); this._currentPercent = locCurrentPercent; this._loopType = locLoopType; if (locLoopType > ccs.ANIMATION_TYPE_TO_LOOP_BACK) locCurrentPercent = this.updateFrameData(locCurrentPercent); if (this._frameTweenEasing != ccs.TweenType.tweenEasingMax) this.tweenNodeTo(locCurrentPercent); }, /** * Calculate the between value of _from and _to, and give it to between frame data * @param {ccs.FrameData} from * @param {ccs.FrameData} to * @param {Boolean} [limit=true] */ setBetween:function (from, to, limit) { //TODO set tweenColorTo to protected in v3.1 if(limit === undefined) limit = true; do { if (from.displayIndex < 0 && to.displayIndex >= 0) { this._from.copy(to); this._between.subtract(to, to, limit); break; } if (to.displayIndex < 0 && from.displayIndex >= 0) { this._from.copy(from); this._between.subtract(to, to, limit); break; } this._from.copy(from); this._between.subtract(from, to, limit); } while (0); if (!from.isTween){ this._tweenData.copy(from); this._tweenData.isTween = true; } this.arriveKeyFrame(from); }, /** * Update display index and process the key frame event when arrived a key frame * @param {ccs.FrameData} keyFrameData */ arriveKeyFrame:function (keyFrameData) { //TODO set tweenColorTo to protected in v3.1 if (keyFrameData) { var locBone = this._bone; var displayManager = locBone.getDisplayManager(); //! Change bone's display var displayIndex = keyFrameData.displayIndex; if (!displayManager.getForceChangeDisplay()) displayManager.changeDisplayWithIndex(displayIndex, false); //! Update bone zorder, bone's zorder is determined by frame zorder and bone zorder this._tweenData.zOrder = keyFrameData.zOrder; locBone.updateZOrder(); //! Update blend type this._bone.setBlendFunc(keyFrameData.blendFunc); var childAramture = locBone.getChildArmature(); if (childAramture) { if (keyFrameData.movement != "") childAramture.getAnimation().play(keyFrameData.movement); } } }, /** * According to the percent to calculate current CCFrameData with tween effect * @param {Number} percent * @param {ccs.FrameData} [node] * @return {ccs.FrameData} */ tweenNodeTo:function (percent, node) { //TODO set tweenColorTo to protected in v3.1 if (!node) node = this._tweenData; var locFrom = this._from; var locBetween = this._between; if (!locFrom.isTween) percent = 0; node.x = locFrom.x + percent * locBetween.x; node.y = locFrom.y + percent * locBetween.y; node.scaleX = locFrom.scaleX + percent * locBetween.scaleX; node.scaleY = locFrom.scaleY + percent * locBetween.scaleY; node.skewX = locFrom.skewX + percent * locBetween.skewX; node.skewY = locFrom.skewY + percent * locBetween.skewY; this._bone.setTransformDirty(true); if (node && locBetween.isUseColorInfo) this.tweenColorTo(percent, node); return node; }, /** * According to the percent to calculate current color with tween effect * @param {Number} percent * @param {ccs.FrameData} node */ tweenColorTo:function(percent,node){ //TODO set tweenColorTo to protected in v3.1 var locFrom = this._from; var locBetween = this._between; node.a = locFrom.a + percent * locBetween.a; node.r = locFrom.r + percent * locBetween.r; node.g = locFrom.g + percent * locBetween.g; node.b = locFrom.b + percent * locBetween.b; this._bone.updateColor(); }, /** * Calculate which frame arrived, and if current frame have event, then call the event listener * @param {Number} currentPercent * @return {Number} */ updateFrameData:function (currentPercent) { //TODO set tweenColorTo to protected in v3.1 if (currentPercent > 1 && this._movementBoneData.delay != 0) currentPercent = ccs.fmodf(currentPercent,1); var playedTime = (this._rawDuration-1) * currentPercent; var from, to; var locTotalDuration = this._totalDuration,locBetweenDuration = this._betweenDuration, locToIndex = this._toIndex; // if play to current frame's front or back, then find current frame again if (playedTime < locTotalDuration || playedTime >= locTotalDuration + locBetweenDuration) { /* * get frame length, if this._toIndex >= _length, then set this._toIndex to 0, start anew. * this._toIndex is next index will play */ var frames = this._movementBoneData.frameList; var length = frames.length; if (playedTime < frames[0].frameID){ from = to = frames[0]; this.setBetween(from, to); return this._currentPercent; } if (playedTime >= frames[length - 1].frameID) { // If _passLastFrame is true and playedTime >= frames[length - 1]->frameID, then do not need to go on. if (this._passLastFrame) { from = to = frames[length - 1]; this.setBetween(from, to); return this._currentPercent; } this._passLastFrame = true; } else this._passLastFrame = false; do { this._fromIndex = locToIndex; from = frames[this._fromIndex]; locTotalDuration = from.frameID; locToIndex = this._fromIndex + 1; if (locToIndex >= length) locToIndex = 0; to = frames[locToIndex]; //! Guaranteed to trigger frame event if(from.strEvent && !this._animation.isIgnoreFrameEvent()) this._animation.frameEvent(this._bone, from.strEvent,from.frameID, playedTime); if (playedTime == from.frameID|| (this._passLastFrame && this._fromIndex == length-1)) break; } while (playedTime < from.frameID || playedTime >= to.frameID); locBetweenDuration = to.frameID - from.frameID; this._frameTweenEasing = from.tweenEasing; this.setBetween(from, to, false); this._totalDuration = locTotalDuration; this._betweenDuration = locBetweenDuration; this._toIndex = locToIndex; } currentPercent = locBetweenDuration == 0 ? 0 : (playedTime - this._totalDuration) / this._betweenDuration; /* * if frame tween easing equal to TWEEN_EASING_MAX, then it will not do tween. */ var tweenType = (this._frameTweenEasing != ccs.TweenType.linear) ? this._frameTweenEasing : this._tweenEasing; if (tweenType != ccs.TweenType.tweenEasingMax && tweenType != ccs.TweenType.linear && !this._passLastFrame) { currentPercent = ccs.TweenFunction.tweenTo(currentPercent, tweenType, this._from.easingParams); } return currentPercent; }, /** * Sets Armature animation to ccs.Tween. * @param {ccs.ArmatureAnimation} animation */ setAnimation:function (animation) { this._animation = animation; }, /** * Returns Armature animation of ccs.Tween. * @return {ccs.ArmatureAnimation} */ getAnimation:function () { return this._animation; }, /** * Sets movement bone data to ccs.Tween. * @param data */ setMovementBoneData: function(data){ this._movementBoneData = data; } }); var _p = ccs.Tween.prototype; // Extended properties /** @expose */ _p.animation; cc.defineGetterSetter(_p, "animation", _p.getAnimation, _p.setAnimation); _p = null; /** * Allocates and initializes a ArmatureAnimation. * @param {ccs.Bone} bone * @return {ccs.Tween} * @example * // example * var animation = ccs.ArmatureAnimation.create(); */ ccs.Tween.create = function (bone) { //TODO it will be deprecated in v3.1 var tween = new ccs.Tween(); if (tween && tween.init(bone)) return tween; return null; };
var path = require('path'); var async = require('async'); module.exports = function(content) { var cb = this.async(); var json = JSON.parse(content); async.mapSeries( json.imports, function(url, callback) { this.loadModule(url, function(err, source, map, module) { if (err) { return callback(err); } callback(null, this.exec(source, url)); }.bind(this)) }.bind(this), function(err, results) { if (err) { return cb(err); } // Combine all the results into one object and return it cb(null, 'module.exports = ' + JSON.stringify(results.reduce(function(prev, result) { return Object.assign({}, prev, result); }, json))); } ); }
var THREEx = THREEx || {} ////////////////////////////////////////////////////////////////////////////////// // Constructor // ////////////////////////////////////////////////////////////////////////////////// /** * create a dynamic texture with a underlying canvas * * @param {Number} width width of the canvas * @param {Number} height height of the canvas */ THREEx.DynamicTexture = function(width, height){ var canvas = document.createElement( 'canvas' ) canvas.width = width canvas.height = height this.canvas = canvas var context = canvas.getContext( '2d' ) this.context = context var texture = new THREE.Texture(canvas) this.texture = texture } ////////////////////////////////////////////////////////////////////////////////// // methods // ////////////////////////////////////////////////////////////////////////////////// /** * clear the canvas * * @param {String*} fillStyle the fillStyle to clear with, if not provided, fallback on .clearRect * @return {THREEx.DynamicTexture} the object itself, for chained texture */ THREEx.DynamicTexture.prototype.clear = function(fillStyle){ // depends on fillStyle if( fillStyle !== undefined ){ this.context.fillStyle = fillStyle this.context.fillRect(0,0,this.canvas.width, this.canvas.height) }else{ this.context.clearRect(0,0,this.canvas.width, this.canvas.height) } // make the texture as .needsUpdate this.texture.needsUpdate = true; // for chained API return this; } /** * draw text * * @param {String} text the text to display * @param {Number|undefined} x if provided, it is the x where to draw, if not, the text is centered * @param {Number} y the y where to draw the text * @param {String*} fillStyle the fillStyle to clear with, if not provided, fallback on .clearRect * @param {String*} contextFont the font to use * @return {THREEx.DynamicTexture} the object itself, for chained texture */ THREEx.DynamicTexture.prototype.drawText = function(text, x, y, fillStyle, contextFont){ // set font if needed if( contextFont !== undefined ) this.context.font = contextFont; // if x isnt provided if( x === undefined || x === null ){ var textSize = this.context.measureText(text); x = (this.canvas.width - textSize.width) / 2; } // actually draw the text this.context.fillStyle = fillStyle; this.context.fillText(text, x, y); // make the texture as .needsUpdate this.texture.needsUpdate = true; // for chained API return this; }; THREEx.DynamicTexture.prototype.drawTextCooked = function(text, options){ var context = this.context var canvas = this.canvas options = options || {} var params = { margin : options.margin !== undefined ? options.margin : 0.1, lineHeight : options.lineHeight !== undefined ? options.lineHeight : 0.1, align : options.align !== undefined ? options.align : 'left', fillStyle : options.fillStyle !== undefined ? options.fillStyle : 'black', } context.save() context.fillStyle = params.fillStyle; var y = (params.lineHeight + params.margin)*canvas.height while(text.length > 0 ){ // compute the text for specifically this line var maxText = computeMaxTextLength(text) // update the remaining text text = text.substr(maxText.length) // compute x based on params.align var textSize = context.measureText(maxText); if( params.align === 'left' ){ var x = params.margin*canvas.width }else if( params.align === 'right' ){ var x = (1-params.margin)*canvas.width - textSize.width }else if( params.align === 'center' ){ var x = (canvas.width - textSize.width) / 2; }else console.assert( false ) // actually draw the text at the proper position this.context.fillText(maxText, x, y); // goto the next line y += params.lineHeight*canvas.height } context.restore() // make the texture as .needsUpdate this.texture.needsUpdate = true; // for chained API return this; function computeMaxTextLength(text){ var maxText = '' var maxWidth = (1-params.margin*2)*canvas.width while( maxText.length !== text.length ){ var textSize = context.measureText(maxText); if( textSize.width > maxWidth ) break; maxText += text.substr(maxText.length, 1) } return maxText } } /** * execute the drawImage on the internal context * the arguments are the same the official context2d.drawImage */ THREEx.DynamicTexture.prototype.drawImage = function(/* same params as context2d.drawImage */){ // call the drawImage this.context.drawImage.apply(this.context, arguments) // make the texture as .needsUpdate this.texture.needsUpdate = true; // for chained API return this; }
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var React = require('react'); var React__default = _interopDefault(React); var mobx = require('mobx'); var reactNative = require('react-native'); function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } // These functions can be stubbed out in specific environments function unwrapExports (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x.default : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var reactIs_production_min = createCommonjsModule(function (module, exports) { Object.defineProperty(exports,"__esModule",{value:!0}); var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.forward_ref"):60112,n=b?Symbol.for("react.placeholder"):60113; function q(a){if("object"===typeof a&&null!==a){var p=a.$$typeof;switch(p){case c:switch(a=a.type,a){case l:case e:case g:case f:return a;default:switch(a=a&&a.$$typeof,a){case k:case m:case h:return a;default:return p}}case d:return p}}}exports.typeOf=q;exports.AsyncMode=l;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=m;exports.Fragment=e;exports.Profiler=g;exports.Portal=d;exports.StrictMode=f; exports.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===e||a===l||a===g||a===f||a===n||"object"===typeof a&&null!==a&&("function"===typeof a.then||a.$$typeof===h||a.$$typeof===k||a.$$typeof===m)};exports.isAsyncMode=function(a){return q(a)===l};exports.isContextConsumer=function(a){return q(a)===k};exports.isContextProvider=function(a){return q(a)===h};exports.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===c}; exports.isForwardRef=function(a){return q(a)===m};exports.isFragment=function(a){return q(a)===e};exports.isProfiler=function(a){return q(a)===g};exports.isPortal=function(a){return q(a)===d};exports.isStrictMode=function(a){return q(a)===f}; }); unwrapExports(reactIs_production_min); var reactIs_production_min_1 = reactIs_production_min.typeOf; var reactIs_production_min_2 = reactIs_production_min.AsyncMode; var reactIs_production_min_3 = reactIs_production_min.ContextConsumer; var reactIs_production_min_4 = reactIs_production_min.ContextProvider; var reactIs_production_min_5 = reactIs_production_min.Element; var reactIs_production_min_6 = reactIs_production_min.ForwardRef; var reactIs_production_min_7 = reactIs_production_min.Fragment; var reactIs_production_min_8 = reactIs_production_min.Profiler; var reactIs_production_min_9 = reactIs_production_min.Portal; var reactIs_production_min_10 = reactIs_production_min.StrictMode; var reactIs_production_min_11 = reactIs_production_min.isValidElementType; var reactIs_production_min_12 = reactIs_production_min.isAsyncMode; var reactIs_production_min_13 = reactIs_production_min.isContextConsumer; var reactIs_production_min_14 = reactIs_production_min.isContextProvider; var reactIs_production_min_15 = reactIs_production_min.isElement; var reactIs_production_min_16 = reactIs_production_min.isForwardRef; var reactIs_production_min_17 = reactIs_production_min.isFragment; var reactIs_production_min_18 = reactIs_production_min.isProfiler; var reactIs_production_min_19 = reactIs_production_min.isPortal; var reactIs_production_min_20 = reactIs_production_min.isStrictMode; var reactIs = createCommonjsModule(function (module) { { module.exports = reactIs_production_min; } }); var _ReactIs$ForwardRef; function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } /** * Copyright 2015, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ var REACT_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, getDerivedStateFromProps: true, mixins: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var TYPE_STATICS = _defineProperty$1({}, reactIs.ForwardRef, (_ReactIs$ForwardRef = {}, _defineProperty$1(_ReactIs$ForwardRef, '$$typeof', true), _defineProperty$1(_ReactIs$ForwardRef, 'render', true), _ReactIs$ForwardRef)); var defineProperty = Object.defineProperty; var getOwnPropertyNames = Object.getOwnPropertyNames; var getOwnPropertySymbols = Object.getOwnPropertySymbols; var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; var getPrototypeOf = Object.getPrototypeOf; var objectPrototype = Object.prototype; function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components if (objectPrototype) { var inheritedComponent = getPrototypeOf(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); } } var keys = getOwnPropertyNames(sourceComponent); if (getOwnPropertySymbols) { keys = keys.concat(getOwnPropertySymbols(sourceComponent)); } var targetStatics = TYPE_STATICS[targetComponent['$$typeof']] || REACT_STATICS; var sourceStatics = TYPE_STATICS[sourceComponent['$$typeof']] || REACT_STATICS; for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) { var descriptor = getOwnPropertyDescriptor(sourceComponent, key); try { // Avoid failures from read-only properties defineProperty(targetComponent, key, descriptor); } catch (e) {} } } return targetComponent; } return targetComponent; } var hoistNonReactStatics_cjs = hoistNonReactStatics; var EventEmitter = /*#__PURE__*/ function () { function EventEmitter() { _classCallCheck(this, EventEmitter); this.listeners = []; } _createClass(EventEmitter, [{ key: "on", value: function on(cb) { var _this = this; this.listeners.push(cb); return function () { var index = _this.listeners.indexOf(cb); if (index !== -1) _this.listeners.splice(index, 1); }; } }, { key: "emit", value: function emit(data) { this.listeners.forEach(function (fn) { return fn(data); }); } }]); return EventEmitter; }(); function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName, location, propFullName) { for (var _len = arguments.length, rest = new Array(_len > 6 ? _len - 6 : 0), _key = 6; _key < _len; _key++) { rest[_key - 6] = arguments[_key]; } return mobx.untracked(function () { componentName = componentName || "<<anonymous>>"; propFullName = propFullName || propName; if (props[propName] == null) { if (isRequired) { var actual = props[propName] === null ? "null" : "undefined"; return new Error("The " + location + " `" + propFullName + "` is marked as required " + "in `" + componentName + "`, but its value is `" + actual + "`."); } return null; } else { return validate.apply(void 0, [props, propName, componentName, location, propFullName].concat(rest)); } }); } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } // Copied from React.PropTypes function isSymbol(propType, propValue) { // Native Symbol. if (propType === "symbol") { return true; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue["@@toStringTag"] === "Symbol") { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === "function" && propValue instanceof Symbol) { return true; } return false; } // Copied from React.PropTypes function getPropType(propValue) { var propType = _typeof(propValue); if (Array.isArray(propValue)) { return "array"; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return "object"; } if (isSymbol(propType, propValue)) { return "symbol"; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // Copied from React.PropTypes function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === "object") { if (propValue instanceof Date) { return "date"; } else if (propValue instanceof RegExp) { return "regexp"; } } return propType; } function createObservableTypeCheckerCreator(allowNativeType, mobxType) { return createChainableTypeChecker(function (props, propName, componentName, location, propFullName) { return mobx.untracked(function () { if (allowNativeType) { if (getPropType(props[propName]) === mobxType.toLowerCase()) return null; } var mobxChecker; switch (mobxType) { case "Array": mobxChecker = mobx.isObservableArray; break; case "Object": mobxChecker = mobx.isObservableObject; break; case "Map": mobxChecker = mobx.isObservableMap; break; default: throw new Error("Unexpected mobxType: ".concat(mobxType)); } var propValue = props[propName]; if (!mobxChecker(propValue)) { var preciseType = getPreciseType(propValue); var nativeTypeExpectationMessage = allowNativeType ? " or javascript `" + mobxType.toLowerCase() + "`" : ""; return new Error("Invalid prop `" + propFullName + "` of type `" + preciseType + "` supplied to" + " `" + componentName + "`, expected `mobx.Observable" + mobxType + "`" + nativeTypeExpectationMessage + "."); } return null; }); }); } function createObservableArrayOfTypeChecker(allowNativeType, typeChecker) { return createChainableTypeChecker(function (props, propName, componentName, location, propFullName) { for (var _len2 = arguments.length, rest = new Array(_len2 > 5 ? _len2 - 5 : 0), _key2 = 5; _key2 < _len2; _key2++) { rest[_key2 - 5] = arguments[_key2]; } return mobx.untracked(function () { if (typeof typeChecker !== "function") { return new Error("Property `" + propFullName + "` of component `" + componentName + "` has " + "invalid PropType notation."); } var error = createObservableTypeCheckerCreator(allowNativeType, "Array")(props, propName, componentName); if (error instanceof Error) return error; var propValue = props[propName]; for (var i = 0; i < propValue.length; i++) { error = typeChecker.apply(void 0, [propValue, i, componentName, location, propFullName + "[" + i + "]"].concat(rest)); if (error instanceof Error) return error; } return null; }); }); } var observableArray = createObservableTypeCheckerCreator(false, "Array"); var observableArrayOf = createObservableArrayOfTypeChecker.bind(null, false); var observableMap = createObservableTypeCheckerCreator(false, "Map"); var observableObject = createObservableTypeCheckerCreator(false, "Object"); var arrayOrObservableArray = createObservableTypeCheckerCreator(true, "Array"); var arrayOrObservableArrayOf = createObservableArrayOfTypeChecker.bind(null, true); var objectOrObservableObject = createObservableTypeCheckerCreator(true, "Object"); var propTypes = /*#__PURE__*/Object.freeze({ observableArray: observableArray, observableArrayOf: observableArrayOf, observableMap: observableMap, observableObject: observableObject, arrayOrObservableArray: arrayOrObservableArray, arrayOrObservableArrayOf: arrayOrObservableArrayOf, objectOrObservableObject: objectOrObservableObject }); function isStateless(component) { // `function() {}` has prototype, but `() => {}` doesn't // `() => {}` via Babel has prototype too. return !(component.prototype && component.prototype.render); } var symbolId = 0; function newSymbol(name) { if (typeof Symbol === "function") { return Symbol(name); } var symbol = "__$mobx-react ".concat(name, " (").concat(symbolId, ")"); symbolId++; return symbol; } var mobxMixins = newSymbol("patchMixins"); var mobxPatchedDefinition = newSymbol("patchedDefinition"); function getMixins(target, methodName) { var mixins = target[mobxMixins] = target[mobxMixins] || {}; var methodMixins = mixins[methodName] = mixins[methodName] || {}; methodMixins.locks = methodMixins.locks || 0; methodMixins.methods = methodMixins.methods || []; return methodMixins; } function wrapper(realMethod, mixins) { var _this = this; for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } // locks are used to ensure that mixins are invoked only once per invocation, even on recursive calls mixins.locks++; try { var retVal; if (realMethod !== undefined && realMethod !== null) { retVal = realMethod.apply(this, args); } return retVal; } finally { mixins.locks--; if (mixins.locks === 0) { mixins.methods.forEach(function (mx) { mx.apply(_this, args); }); } } } function wrapFunction(realMethod, mixins) { var fn = function fn() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } wrapper.call.apply(wrapper, [this, realMethod, mixins].concat(args)); }; return fn; } function patch(target, methodName) { var mixins = getMixins(target, methodName); for (var _len3 = arguments.length, mixinMethods = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) { mixinMethods[_key3 - 2] = arguments[_key3]; } for (var _i = 0; _i < mixinMethods.length; _i++) { var mixinMethod = mixinMethods[_i]; if (mixins.methods.indexOf(mixinMethod) < 0) { mixins.methods.push(mixinMethod); } } var oldDefinition = Object.getOwnPropertyDescriptor(target, methodName); if (oldDefinition && oldDefinition[mobxPatchedDefinition]) { // already patched definition, do not repatch return; } var originalMethod = target[methodName]; var newDefinition = createDefinition(target, methodName, oldDefinition ? oldDefinition.enumerable : undefined, mixins, originalMethod); Object.defineProperty(target, methodName, newDefinition); } function createDefinition(target, methodName, enumerable, mixins, originalMethod) { var _ref; var wrappedFunc = wrapFunction(originalMethod, mixins); return _ref = {}, _defineProperty(_ref, mobxPatchedDefinition, true), _defineProperty(_ref, "get", function get() { return wrappedFunc; }), _defineProperty(_ref, "set", function set(value) { if (this === target) { wrappedFunc = wrapFunction(value, mixins); } else { // when it is an instance of the prototype/a child prototype patch that particular case again separately // since we need to store separate values depending on wether it is the actual instance, the prototype, etc // e.g. the method for super might not be the same as the method for the prototype which might be not the same // as the method for the instance var newDefinition = createDefinition(this, methodName, enumerable, mixins, value); Object.defineProperty(this, methodName, newDefinition); } }), _defineProperty(_ref, "configurable", true), _defineProperty(_ref, "enumerable", enumerable), _ref; } var injectorContextTypes = { mobxStores: objectOrObservableObject }; Object.seal(injectorContextTypes); var proxiedInjectorProps = { contextTypes: { get: function get() { return injectorContextTypes; }, set: function set(_) { console.warn("Mobx Injector: you are trying to attach `contextTypes` on an component decorated with `inject` (or `observer`) HOC. Please specify the contextTypes on the wrapped component instead. It is accessible through the `wrappedComponent`"); }, configurable: true, enumerable: false }, isMobxInjector: { value: true, writable: true, configurable: true, enumerable: true } /** * Store Injection */ }; function createStoreInjector(grabStoresFn, component, injectNames) { var displayName = "inject-" + (component.displayName || component.name || component.constructor && component.constructor.name || "Unknown"); if (injectNames) displayName += "-with-" + injectNames; var Injector = /*#__PURE__*/ function (_Component) { _inherits(Injector, _Component); function Injector() { var _getPrototypeOf2; var _this; _classCallCheck(this, Injector); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Injector)).call.apply(_getPrototypeOf2, [this].concat(args))); _this.storeRef = function (instance) { _this.wrappedInstance = instance; }; return _this; } _createClass(Injector, [{ key: "render", value: function render() { // Optimization: it might be more efficient to apply the mapper function *outside* the render method // (if the mapper is a function), that could avoid expensive(?) re-rendering of the injector component // See this test: 'using a custom injector is not too reactive' in inject.js var newProps = {}; for (var key in this.props) { if (this.props.hasOwnProperty(key)) { newProps[key] = this.props[key]; } } var additionalProps = grabStoresFn(this.context.mobxStores || {}, newProps, this.context) || {}; for (var _key2 in additionalProps) { newProps[_key2] = additionalProps[_key2]; } if (!isStateless(component)) { newProps.ref = this.storeRef; } return React.createElement(component, newProps); } }]); return Injector; }(React.Component); // Static fields from component should be visible on the generated Injector Injector.displayName = displayName; hoistNonReactStatics_cjs(Injector, component); Injector.wrappedComponent = component; Object.defineProperties(Injector, proxiedInjectorProps); return Injector; } function grabStoresByName(storeNames) { return function (baseStores, nextProps) { storeNames.forEach(function (storeName) { if (storeName in nextProps // prefer props over stores ) return; if (!(storeName in baseStores)) throw new Error("MobX injector: Store '" + storeName + "' is not available! Make sure it is provided by some Provider"); nextProps[storeName] = baseStores[storeName]; }); return nextProps; }; } /** * higher order component that injects stores to a child. * takes either a varargs list of strings, which are stores read from the context, * or a function that manually maps the available stores from the context to props: * storesToProps(mobxStores, props, context) => newProps */ function inject() /* fn(stores, nextProps) or ...storeNames */ { var grabStoresFn; if (typeof arguments[0] === "function") { grabStoresFn = arguments[0]; return function (componentClass) { var injected = createStoreInjector(grabStoresFn, componentClass); injected.isMobxInjector = false; // supress warning // mark the Injector as observer, to make it react to expressions in `grabStoresFn`, // see #111 injected = observer(injected); injected.isMobxInjector = true; // restore warning return injected; }; } else { var storeNames = []; for (var i = 0; i < arguments.length; i++) { storeNames[i] = arguments[i]; } grabStoresFn = grabStoresByName(storeNames); return function (componentClass) { return createStoreInjector(grabStoresFn, componentClass, storeNames.join("-")); }; } } var mobxAdminProperty = mobx.$mobx || "$mobx"; var mobxIsUnmounted = newSymbol("isUnmounted"); /** * dev tool support */ var isDevtoolsEnabled = false; var isUsingStaticRendering = false; var warnedAboutObserverInjectDeprecation = false; // WeakMap<Node, Object>; var componentByNodeRegistry = typeof WeakMap !== "undefined" ? new WeakMap() : undefined; var renderReporter = new EventEmitter(); var skipRenderKey = newSymbol("skipRender"); var isForcingUpdateKey = newSymbol("isForcingUpdate"); /** * Helper to set `prop` to `this` as non-enumerable (hidden prop) * @param target * @param prop * @param value */ function setHiddenProp(target, prop, value) { if (!Object.hasOwnProperty.call(target, prop)) { Object.defineProperty(target, prop, { enumerable: false, configurable: true, writable: true, value: value }); } else { target[prop] = value; } } function findDOMNode$1(component) { return null; } function reportRendering(component) { var node = findDOMNode$1(component); if (node && componentByNodeRegistry) componentByNodeRegistry.set(node, component); renderReporter.emit({ event: "render", renderTime: component.__$mobRenderEnd - component.__$mobRenderStart, totalTime: Date.now() - component.__$mobRenderStart, component: component, node: node }); } function trackComponents() { if (typeof WeakMap === "undefined") throw new Error("[mobx-react] tracking components is not supported in this browser."); if (!isDevtoolsEnabled) isDevtoolsEnabled = true; } function useStaticRendering(useStaticRendering) { isUsingStaticRendering = useStaticRendering; } /** * Errors reporter */ var errorsReporter = new EventEmitter(); /** * Utilities */ function patch$1(target, funcName) { patch(target, funcName, reactiveMixin[funcName]); } function shallowEqual(objA, objB) { //From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js if (is(objA, objB)) return true; if (_typeof(objA) !== "object" || objA === null || _typeof(objB) !== "object" || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) return false; for (var i = 0; i < keysA.length; i++) { if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; } function is(x, y) { // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js if (x === y) { return x !== 0 || 1 / x === 1 / y; } else { return x !== x && y !== y; } } function makeComponentReactive(render) { var _this2 = this; if (isUsingStaticRendering === true) return render.call(this); function reactiveRender() { var _this = this; isRenderingPending = false; var exception = undefined; var rendering = undefined; reaction.track(function () { if (isDevtoolsEnabled) { _this.__$mobRenderStart = Date.now(); } try { rendering = mobx._allowStateChanges(false, baseRender); } catch (e) { exception = e; } if (isDevtoolsEnabled) { _this.__$mobRenderEnd = Date.now(); } }); if (exception) { errorsReporter.emit(exception); throw exception; } return rendering; } // Generate friendly name for debugging var initialName = this.displayName || this.name || this.constructor && (this.constructor.displayName || this.constructor.name) || "<component>"; var rootNodeID = this._reactInternalInstance && this._reactInternalInstance._rootNodeID || this._reactInternalInstance && this._reactInternalInstance._debugID || this._reactInternalFiber && this._reactInternalFiber._debugID; /** * If props are shallowly modified, react will render anyway, * so atom.reportChanged() should not result in yet another re-render */ setHiddenProp(this, skipRenderKey, false); /** * forceUpdate will re-assign this.props. We don't want that to cause a loop, * so detect these changes */ setHiddenProp(this, isForcingUpdateKey, false); // wire up reactive render var baseRender = render.bind(this); var isRenderingPending = false; var reaction = new mobx.Reaction("".concat(initialName, "#").concat(rootNodeID, ".render()"), function () { if (!isRenderingPending) { // N.B. Getting here *before mounting* means that a component constructor has side effects (see the relevant test in misc.js) // This unidiomatic React usage but React will correctly warn about this so we continue as usual // See #85 / Pull #44 isRenderingPending = true; if (typeof _this2.componentWillReact === "function") _this2.componentWillReact(); // TODO: wrap in action? if (_this2[mobxIsUnmounted] !== true) { // If we are unmounted at this point, componentWillReact() had a side effect causing the component to unmounted // TODO: remove this check? Then react will properly warn about the fact that this should not happen? See #73 // However, people also claim this migth happen during unit tests.. var hasError = true; try { setHiddenProp(_this2, isForcingUpdateKey, true); if (!_this2[skipRenderKey]) React.Component.prototype.forceUpdate.call(_this2); hasError = false; } finally { setHiddenProp(_this2, isForcingUpdateKey, false); if (hasError) reaction.dispose(); } } } }); reaction.reactComponent = this; reactiveRender[mobxAdminProperty] = reaction; this.render = reactiveRender; return reactiveRender.call(this); } /** * ReactiveMixin */ var reactiveMixin = { componentWillUnmount: function componentWillUnmount() { if (isUsingStaticRendering === true) return; this.render[mobxAdminProperty] && this.render[mobxAdminProperty].dispose(); this[mobxIsUnmounted] = true; if (isDevtoolsEnabled) { var node = findDOMNode$1(this); if (node && componentByNodeRegistry) { componentByNodeRegistry.delete(node); } renderReporter.emit({ event: "destroy", component: this, node: node }); } }, componentDidMount: function componentDidMount() { if (isDevtoolsEnabled) { reportRendering(this); } }, componentDidUpdate: function componentDidUpdate() { if (isDevtoolsEnabled) { reportRendering(this); } }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { if (isUsingStaticRendering) { console.warn("[mobx-react] It seems that a re-rendering of a React component is triggered while in static (server-side) mode. Please make sure components are rendered only once server-side."); } // update on any state changes (as is the default) if (this.state !== nextState) { return true; } // update if props are shallowly not equal, inspired by PureRenderMixin // we could return just 'false' here, and avoid the `skipRender` checks etc // however, it is nicer if lifecycle events are triggered like usually, // so we return true here if props are shallowly modified. return !shallowEqual(this.props, nextProps); } }; function makeObservableProp(target, propName) { var valueHolderKey = newSymbol("reactProp_".concat(propName, "_valueHolder")); var atomHolderKey = newSymbol("reactProp_".concat(propName, "_atomHolder")); function getAtom() { if (!this[atomHolderKey]) { setHiddenProp(this, atomHolderKey, mobx.createAtom("reactive " + propName)); } return this[atomHolderKey]; } Object.defineProperty(target, propName, { configurable: true, enumerable: true, get: function get() { getAtom.call(this).reportObserved(); return this[valueHolderKey]; }, set: function set(v) { if (!this[isForcingUpdateKey] && !shallowEqual(this[valueHolderKey], v)) { setHiddenProp(this, valueHolderKey, v); setHiddenProp(this, skipRenderKey, true); getAtom.call(this).reportChanged(); setHiddenProp(this, skipRenderKey, false); } else { setHiddenProp(this, valueHolderKey, v); } } }); } /** * Observer function / decorator */ function observer(arg1, arg2) { if (typeof arg1 === "string") { throw new Error("Store names should be provided as array"); } if (Array.isArray(arg1)) { // TODO: remove in next major // component needs stores if (!warnedAboutObserverInjectDeprecation) { warnedAboutObserverInjectDeprecation = true; console.warn('Mobx observer: Using observer to inject stores is deprecated since 4.0. Use `@inject("store1", "store2") @observer ComponentClass` or `inject("store1", "store2")(observer(componentClass))` instead of `@observer(["store1", "store2"]) ComponentClass`'); } if (!arg2) { // invoked as decorator return function (componentClass) { return observer(arg1, componentClass); }; } else { return inject.apply(null, arg1)(observer(arg2)); } } var componentClass = arg1; if (componentClass.isMobxInjector === true) { console.warn("Mobx observer: You are trying to use 'observer' on a component that already has 'inject'. Please apply 'observer' before applying 'inject'"); } if (componentClass.__proto__ === React.PureComponent) { console.warn("Mobx observer: You are using 'observer' on React.PureComponent. These two achieve two opposite goals and should not be used together"); } // Stateless function component: // If it is function but doesn't seem to be a react class constructor, // wrap it to a react class automatically if (typeof componentClass === "function" && (!componentClass.prototype || !componentClass.prototype.render) && !componentClass.isReactClass && !React.Component.isPrototypeOf(componentClass)) { var _class, _temp; var observerComponent = observer((_temp = _class = /*#__PURE__*/ function (_Component) { _inherits(_class, _Component); function _class() { _classCallCheck(this, _class); return _possibleConstructorReturn(this, _getPrototypeOf(_class).apply(this, arguments)); } _createClass(_class, [{ key: "render", value: function render() { return componentClass.call(this, this.props, this.context); } }]); return _class; }(React.Component), _class.displayName = componentClass.displayName || componentClass.name, _class.contextTypes = componentClass.contextTypes, _class.propTypes = componentClass.propTypes, _class.defaultProps = componentClass.defaultProps, _temp)); hoistNonReactStatics_cjs(observerComponent, componentClass); return observerComponent; } if (!componentClass) { throw new Error("Please pass a valid component to 'observer'"); } var target = componentClass.prototype || componentClass; mixinLifecycleEvents(target); componentClass.isMobXReactObserver = true; makeObservableProp(target, "props"); makeObservableProp(target, "state"); var baseRender = target.render; target.render = function () { return makeComponentReactive.call(this, baseRender); }; return componentClass; } function mixinLifecycleEvents(target) { ["componentDidMount", "componentWillUnmount", "componentDidUpdate"].forEach(function (funcName) { patch$1(target, funcName); }); if (!target.shouldComponentUpdate) { target.shouldComponentUpdate = reactiveMixin.shouldComponentUpdate; } else { if (target.shouldComponentUpdate !== reactiveMixin.shouldComponentUpdate) { // TODO: make throw in next major console.warn("Use `shouldComponentUpdate` in an `observer` based component breaks the behavior of `observer` and might lead to unexpected results. Manually implementing `sCU` should not be needed when using mobx-react."); } } } var Observer = observer(function (_ref) { var children = _ref.children, observerInject = _ref.inject, render = _ref.render; var component = children || render; if (typeof component === "undefined") { return null; } if (!observerInject) { return component(); } // TODO: remove in next major console.warn("<Observer inject=.../> is no longer supported. Please use inject on the enclosing component instead"); var InjectComponent = inject(observerInject)(component); return React__default.createElement(InjectComponent, null); }); Observer.displayName = "Observer"; var ObserverPropsCheck = function ObserverPropsCheck(props, key, componentName, location, propFullName) { var extraKey = key === "children" ? "render" : "children"; if (typeof props[key] === "function" && typeof props[extraKey] === "function") { return new Error("Invalid prop,do not use children and render in the same time in`" + componentName); } if (typeof props[key] === "function" || typeof props[extraKey] === "function") { return; } return new Error("Invalid prop `" + propFullName + "` of type `" + _typeof(props[key]) + "` supplied to" + " `" + componentName + "`, expected `function`."); }; Observer.propTypes = { render: ObserverPropsCheck, children: ObserverPropsCheck }; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ function componentWillMount() { // Call this.constructor.gDSFP to support sub-classes. var state = this.constructor.getDerivedStateFromProps(this.props, this.state); if (state !== null && state !== undefined) { this.setState(state); } } function componentWillReceiveProps(nextProps) { // Call this.constructor.gDSFP to support sub-classes. // Use the setState() updater to ensure state isn't stale in certain edge cases. function updater(prevState) { var state = this.constructor.getDerivedStateFromProps(nextProps, prevState); return state !== null && state !== undefined ? state : null; } // Binding "this" is important for shallow renderer support. this.setState(updater.bind(this)); } function componentWillUpdate(nextProps, nextState) { try { var prevProps = this.props; var prevState = this.state; this.props = nextProps; this.state = nextState; this.__reactInternalSnapshotFlag = true; this.__reactInternalSnapshot = this.getSnapshotBeforeUpdate( prevProps, prevState ); } finally { this.props = prevProps; this.state = prevState; } } // React may warn about cWM/cWRP/cWU methods being deprecated. // Add a flag to suppress these warnings for this special case. componentWillMount.__suppressDeprecationWarning = true; componentWillReceiveProps.__suppressDeprecationWarning = true; componentWillUpdate.__suppressDeprecationWarning = true; function polyfill(Component) { var prototype = Component.prototype; if (!prototype || !prototype.isReactComponent) { throw new Error('Can only polyfill class components'); } if ( typeof Component.getDerivedStateFromProps !== 'function' && typeof prototype.getSnapshotBeforeUpdate !== 'function' ) { return Component; } // If new component APIs are defined, "unsafe" lifecycles won't be called. // Error if any of these lifecycles are present, // Because they would work differently between older and newer (16.3+) versions of React. var foundWillMountName = null; var foundWillReceivePropsName = null; var foundWillUpdateName = null; if (typeof prototype.componentWillMount === 'function') { foundWillMountName = 'componentWillMount'; } else if (typeof prototype.UNSAFE_componentWillMount === 'function') { foundWillMountName = 'UNSAFE_componentWillMount'; } if (typeof prototype.componentWillReceiveProps === 'function') { foundWillReceivePropsName = 'componentWillReceiveProps'; } else if (typeof prototype.UNSAFE_componentWillReceiveProps === 'function') { foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps'; } if (typeof prototype.componentWillUpdate === 'function') { foundWillUpdateName = 'componentWillUpdate'; } else if (typeof prototype.UNSAFE_componentWillUpdate === 'function') { foundWillUpdateName = 'UNSAFE_componentWillUpdate'; } if ( foundWillMountName !== null || foundWillReceivePropsName !== null || foundWillUpdateName !== null ) { var componentName = Component.displayName || Component.name; var newApiName = typeof Component.getDerivedStateFromProps === 'function' ? 'getDerivedStateFromProps()' : 'getSnapshotBeforeUpdate()'; throw Error( 'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' + componentName + ' uses ' + newApiName + ' but also contains the following legacy lifecycles:' + (foundWillMountName !== null ? '\n ' + foundWillMountName : '') + (foundWillReceivePropsName !== null ? '\n ' + foundWillReceivePropsName : '') + (foundWillUpdateName !== null ? '\n ' + foundWillUpdateName : '') + '\n\nThe above lifecycles should be removed. Learn more about this warning here:\n' + 'https://fb.me/react-async-component-lifecycle-hooks' ); } // React <= 16.2 does not support static getDerivedStateFromProps. // As a workaround, use cWM and cWRP to invoke the new static lifecycle. // Newer versions of React will ignore these lifecycles if gDSFP exists. if (typeof Component.getDerivedStateFromProps === 'function') { prototype.componentWillMount = componentWillMount; prototype.componentWillReceiveProps = componentWillReceiveProps; } // React <= 16.2 does not support getSnapshotBeforeUpdate. // As a workaround, use cWU to invoke the new lifecycle. // Newer versions of React will ignore that lifecycle if gSBU exists. if (typeof prototype.getSnapshotBeforeUpdate === 'function') { if (typeof prototype.componentDidUpdate !== 'function') { throw new Error( 'Cannot polyfill getSnapshotBeforeUpdate() for components that do not define componentDidUpdate() on the prototype' ); } prototype.componentWillUpdate = componentWillUpdate; var componentDidUpdate = prototype.componentDidUpdate; prototype.componentDidUpdate = function componentDidUpdatePolyfill( prevProps, prevState, maybeSnapshot ) { // 16.3+ will not execute our will-update method; // It will pass a snapshot value to did-update though. // Older versions will require our polyfilled will-update value. // We need to handle both cases, but can't just check for the presence of "maybeSnapshot", // Because for <= 15.x versions this might be a "prevContext" object. // We also can't just check "__reactInternalSnapshot", // Because get-snapshot might return a falsy value. // So check for the explicit __reactInternalSnapshotFlag flag to determine behavior. var snapshot = this.__reactInternalSnapshotFlag ? this.__reactInternalSnapshot : maybeSnapshot; componentDidUpdate.call(this, prevProps, prevState, snapshot); }; } return Component; } var specialReactKeys = { children: true, key: true, ref: true }; var Provider = /*#__PURE__*/ function (_Component) { _inherits(Provider, _Component); function Provider(props, context) { var _this; _classCallCheck(this, Provider); _this = _possibleConstructorReturn(this, _getPrototypeOf(Provider).call(this, props, context)); _this.state = {}; copyStores(props, _this.state); return _this; } _createClass(Provider, [{ key: "render", value: function render() { return React.Children.only(this.props.children); } }, { key: "getChildContext", value: function getChildContext() { var stores = {}; // inherit stores copyStores(this.context.mobxStores, stores); // add own stores copyStores(this.props, stores); return { mobxStores: stores }; } }], [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(nextProps, prevState) { if (!nextProps) return null; if (!prevState) return nextProps; // Maybe this warning is too aggressive? if (Object.keys(nextProps).filter(validStoreName).length !== Object.keys(prevState).filter(validStoreName).length) console.warn("MobX Provider: The set of provided stores has changed. Please avoid changing stores as the change might not propagate to all children"); if (!nextProps.suppressChangedStoreWarning) for (var key in nextProps) { if (validStoreName(key) && prevState[key] !== nextProps[key]) console.warn("MobX Provider: Provided store '" + key + "' has changed. Please avoid replacing stores as the change might not propagate to all children"); } return nextProps; } }]); return Provider; }(React.Component); Provider.contextTypes = { mobxStores: objectOrObservableObject }; Provider.childContextTypes = { mobxStores: objectOrObservableObject.isRequired }; function copyStores(from, to) { if (!from) return; for (var key in from) { if (validStoreName(key)) to[key] = from[key]; } } function validStoreName(key) { return !specialReactKeys[key] && key !== "suppressChangedStoreWarning"; } // TODO: kill in next major polyfill(Provider); var storeKey = newSymbol("disposeOnUnmount"); function runDisposersOnWillUnmount() { var _this = this; if (!this[storeKey]) { // when disposeOnUnmount is only set to some instances of a component it will still patch the prototype return; } this[storeKey].forEach(function (propKeyOrFunction) { var prop = typeof propKeyOrFunction === "string" ? _this[propKeyOrFunction] : propKeyOrFunction; if (prop !== undefined && prop !== null) { if (typeof prop !== "function") { throw new Error("[mobx-react] disposeOnUnmount only works on functions such as disposers returned by reactions, autorun, etc."); } prop(); } }); this[storeKey] = []; } function disposeOnUnmount(target, propertyKeyOrFunction) { if (Array.isArray(propertyKeyOrFunction)) { return propertyKeyOrFunction.map(function (fn) { return disposeOnUnmount(target, fn); }); } if (!target instanceof React.Component) { throw new Error("[mobx-react] disposeOnUnmount only works on class based React components."); } if (typeof propertyKeyOrFunction !== "string" && typeof propertyKeyOrFunction !== "function") { throw new Error("[mobx-react] disposeOnUnmount only works if the parameter is either a property key or a function."); } // add property key / function we want run (disposed) to the store var componentWasAlreadyModified = !!target[storeKey]; var store = target[storeKey] || (target[storeKey] = []); store.push(propertyKeyOrFunction); // tweak the component class componentWillUnmount if not done already if (!componentWasAlreadyModified) { patch(target, "componentWillUnmount", runDisposersOnWillUnmount); } // return the disposer as is if invoked as a non decorator if (typeof propertyKeyOrFunction !== "string") { return propertyKeyOrFunction; } } if (!React.Component) throw new Error("mobx-react requires React to be available"); if (!mobx.spy) throw new Error("mobx-react requires mobx to be available"); if (typeof reactNative.unstable_batchedUpdates === "function") mobx.configure({ reactionScheduler: reactNative.unstable_batchedUpdates }); var onError = function onError(fn) { return errorsReporter.on(fn); }; if ((typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === "undefined" ? "undefined" : _typeof(__MOBX_DEVTOOLS_GLOBAL_HOOK__)) === "object") { var mobx$1 = { spy: mobx.spy, extras: { getDebugName: mobx.getDebugName } }; var mobxReact = { renderReporter: renderReporter, componentByNodeRegistry: componentByNodeRegistry, componentByNodeRegistery: componentByNodeRegistry, trackComponents: trackComponents }; __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobxReact(mobxReact, mobx$1); } exports.propTypes = propTypes; exports.PropTypes = propTypes; exports.onError = onError; exports.observer = observer; exports.Observer = Observer; exports.renderReporter = renderReporter; exports.componentByNodeRegistery = componentByNodeRegistry; exports.componentByNodeRegistry = componentByNodeRegistry; exports.trackComponents = trackComponents; exports.useStaticRendering = useStaticRendering; exports.Provider = Provider; exports.inject = inject; exports.disposeOnUnmount = disposeOnUnmount;
/* This example renders a treemap using the built in TreeDraw function. */ /** * Create the actual tree. * @return {mo.Tree} */ function makeTree(){ var tree = new mo.Tree(); var parent = new mo.Node('root', 'root'); var child1 = new mo.Node('c1', 'c1'); var child2 = new mo.Node('c2', 'c2'); tree.addNodeToTree(parent); tree.addNodeToTree(child1, parent); tree.addNodeToTree(child2, parent); return tree; } function displayTree() { var tree = makeTree(); var state = {}; // Since the methods are short, we will just define // our init and cycle functions inline. var g = new mo.Graphics({ 'container': '#container', 'dimensions': { width: 600, height: 500 }, init: function() { state.frame = new mo.Rectangle(20,20, 400, 400); state.colorList = new mo.ColorList('Azure', 'blue', 'green'); state.weights = new mo.NumberList(2,6); state.textColor = "black"; }, cycle: function() { // Draw the treemap with the built in functionality // this will also provide selection and zoom pan interaction // for free. mo.TreeDraw.drawTreemap( state.frame, tree, state.colorList, state.weights, state.textColor, null, this ); } }); g.setAlphaRefresh(1); g.setBackgroundColor("AntiqueWhite"); } window.onload = function() { displayTree(); };
// DATA_TEMPLATE: empty_table oTest.fnStart( "oLanguage.sProcessing" ); $(document).ready( function () { /* Check the default */ var oTable = $('#example').dataTable( { "sAjaxSource": "../../../examples/ajax/sources/arrays.txt", "bDeferRender": true, "bProcessing": true } ); var oSettings = oTable.fnSettings(); oTest.fnWaitTest( "Processing language is 'Processing...' by default", null, function () { return oSettings.oLanguage.sProcessing == "Processing..."; } ); oTest.fnTest( "Processing language default is in the DOM", null, function () { return document.getElementById('example_processing').innerHTML = "Processing..."; } ); oTest.fnWaitTest( "Processing language can be defined", function () { oSession.fnRestore(); oTable = $('#example').dataTable( { "sAjaxSource": "../../../examples/ajax/sources/arrays.txt", "bDeferRender": true, "bProcessing": true, "oLanguage": { "sProcessing": "unit test" } } ); oSettings = oTable.fnSettings(); }, function () { return oSettings.oLanguage.sProcessing == "unit test"; } ); oTest.fnTest( "Processing language definition is in the DOM", null, function () { return document.getElementById('example_processing').innerHTML = "unit test"; } ); oTest.fnComplete(); } );
import React from "react"; import { NotFoundRoute, Route } from "react-router"; import App from "./components/App"; import Home from "./components/Home"; import NotFound from "./components/NotFound"; import Stargazer from "./components/Stargazer"; import Stargazers from "./components/Stargazers"; export default ( <Route handler={App}> // Query-able URLs (for POSTs & crawlers) <Route name="query.repo" path="/repo" handler={Stargazers} /> // Canonical URLs <Route name="home" path="/" handler={Home} /> <Route name="user" path="/:user" handler={Stargazer} /> <Route name="repo" path="/:user/:repo" handler={Stargazers} /> <NotFoundRoute name="404" handler={NotFound} /> </Route> );
/** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } export default isLength;
/* html2canvas 0.5.0-alpha1 <http://html2canvas.hertzen.com> Copyright (c) 2015 Niklas von Hertzen Released under MIT License */ (function(window, document, exports, global, define, undefined){ /*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE * @version 2.0.1 */ (function(){function r(a,b){n[l]=a;n[l+1]=b;l+=2;2===l&&A()}function s(a){return"function"===typeof a}function F(){return function(){process.nextTick(t)}}function G(){var a=0,b=new B(t),c=document.createTextNode("");b.observe(c,{characterData:!0});return function(){c.data=a=++a%2}}function H(){var a=new MessageChannel;a.port1.onmessage=t;return function(){a.port2.postMessage(0)}}function I(){return function(){setTimeout(t,1)}}function t(){for(var a=0;a<l;a+=2)(0,n[a])(n[a+1]),n[a]=void 0,n[a+1]=void 0; l=0}function p(){}function J(a,b,c,d){try{a.call(b,c,d)}catch(e){return e}}function K(a,b,c){r(function(a){var e=!1,f=J(c,b,function(c){e||(e=!0,b!==c?q(a,c):m(a,c))},function(b){e||(e=!0,g(a,b))});!e&&f&&(e=!0,g(a,f))},a)}function L(a,b){1===b.a?m(a,b.b):2===a.a?g(a,b.b):u(b,void 0,function(b){q(a,b)},function(b){g(a,b)})}function q(a,b){if(a===b)g(a,new TypeError("You cannot resolve a promise with itself"));else if("function"===typeof b||"object"===typeof b&&null!==b)if(b.constructor===a.constructor)L(a, b);else{var c;try{c=b.then}catch(d){v.error=d,c=v}c===v?g(a,v.error):void 0===c?m(a,b):s(c)?K(a,b,c):m(a,b)}else m(a,b)}function M(a){a.f&&a.f(a.b);x(a)}function m(a,b){void 0===a.a&&(a.b=b,a.a=1,0!==a.e.length&&r(x,a))}function g(a,b){void 0===a.a&&(a.a=2,a.b=b,r(M,a))}function u(a,b,c,d){var e=a.e,f=e.length;a.f=null;e[f]=b;e[f+1]=c;e[f+2]=d;0===f&&a.a&&r(x,a)}function x(a){var b=a.e,c=a.a;if(0!==b.length){for(var d,e,f=a.b,g=0;g<b.length;g+=3)d=b[g],e=b[g+c],d?C(c,d,e,f):e(f);a.e.length=0}}function D(){this.error= null}function C(a,b,c,d){var e=s(c),f,k,h,l;if(e){try{f=c(d)}catch(n){y.error=n,f=y}f===y?(l=!0,k=f.error,f=null):h=!0;if(b===f){g(b,new TypeError("A promises callback cannot return that same promise."));return}}else f=d,h=!0;void 0===b.a&&(e&&h?q(b,f):l?g(b,k):1===a?m(b,f):2===a&&g(b,f))}function N(a,b){try{b(function(b){q(a,b)},function(b){g(a,b)})}catch(c){g(a,c)}}function k(a,b,c,d){this.n=a;this.c=new a(p,d);this.i=c;this.o(b)?(this.m=b,this.d=this.length=b.length,this.l(),0===this.length?m(this.c, this.b):(this.length=this.length||0,this.k(),0===this.d&&m(this.c,this.b))):g(this.c,this.p())}function h(a){O++;this.b=this.a=void 0;this.e=[];if(p!==a){if(!s(a))throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");if(!(this instanceof h))throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");N(this,a)}}var E=Array.isArray?Array.isArray:function(a){return"[object Array]"=== Object.prototype.toString.call(a)},l=0,w="undefined"!==typeof window?window:{},B=w.MutationObserver||w.WebKitMutationObserver,w="undefined"!==typeof Uint8ClampedArray&&"undefined"!==typeof importScripts&&"undefined"!==typeof MessageChannel,n=Array(1E3),A;A="undefined"!==typeof process&&"[object process]"==={}.toString.call(process)?F():B?G():w?H():I();var v=new D,y=new D;k.prototype.o=function(a){return E(a)};k.prototype.p=function(){return Error("Array Methods must be provided an Array")};k.prototype.l= function(){this.b=Array(this.length)};k.prototype.k=function(){for(var a=this.length,b=this.c,c=this.m,d=0;void 0===b.a&&d<a;d++)this.j(c[d],d)};k.prototype.j=function(a,b){var c=this.n;"object"===typeof a&&null!==a?a.constructor===c&&void 0!==a.a?(a.f=null,this.g(a.a,b,a.b)):this.q(c.resolve(a),b):(this.d--,this.b[b]=this.h(a))};k.prototype.g=function(a,b,c){var d=this.c;void 0===d.a&&(this.d--,this.i&&2===a?g(d,c):this.b[b]=this.h(c));0===this.d&&m(d,this.b)};k.prototype.h=function(a){return a}; k.prototype.q=function(a,b){var c=this;u(a,void 0,function(a){c.g(1,b,a)},function(a){c.g(2,b,a)})};var O=0;h.all=function(a,b){return(new k(this,a,!0,b)).c};h.race=function(a,b){function c(a){q(e,a)}function d(a){g(e,a)}var e=new this(p,b);if(!E(a))return (g(e,new TypeError("You must pass an array to race.")), e);for(var f=a.length,h=0;void 0===e.a&&h<f;h++)u(this.resolve(a[h]),void 0,c,d);return e};h.resolve=function(a,b){if(a&&"object"===typeof a&&a.constructor===this)return a;var c=new this(p,b); q(c,a);return c};h.reject=function(a,b){var c=new this(p,b);g(c,a);return c};h.prototype={constructor:h,then:function(a,b){var c=this.a;if(1===c&&!a||2===c&&!b)return this;var d=new this.constructor(p),e=this.b;if(c){var f=arguments[c-1];r(function(){C(c,d,f,e)})}else u(this,d,a,b);return d},"catch":function(a){return this.then(null,a)}};var z={Promise:h,polyfill:function(){var a;a="undefined"!==typeof global?global:"undefined"!==typeof window&&window.document?window:self;"Promise"in a&&"resolve"in a.Promise&&"reject"in a.Promise&&"all"in a.Promise&&"race"in a.Promise&&function(){var b;new a.Promise(function(a){b=a});return s(b)}()||(a.Promise=h)}};"function"===typeof define&&define.amd?define(function(){return z}):"undefined"!==typeof module&&module.exports?module.exports=z:"undefined"!==typeof this&&(this.ES6Promise=z);}).call(window); if (window) { window.ES6Promise.polyfill(); } if (typeof(document) === "undefined" || typeof(Object.create) !== "function" || typeof(document.createElement("canvas").getContext) !== "function") { (window || module.exports).html2canvas = function() { return Promise.reject("No canvas support"); }; return; } /*! https://mths.be/punycode v1.3.1 by @mathias */ ;(function(root) { /** Detect free variables */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; var freeModule = typeof module == 'object' && module && !module.nodeType && module; var freeGlobal = typeof global == 'object' && global; if ( freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal ) { root = freeGlobal; } /** * The `punycode` object. * @name punycode * @type Object */ var punycode, /** Highest positive signed 32-bit float value */ maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 /** Bootstring parameters */ base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128, // 0x80 delimiter = '-', // '\x2D' /** Regular expressions */ regexPunycode = /^xn--/, regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators /** Error messages */ errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' }, /** Convenience shortcuts */ baseMinusTMin = base - tMin, floor = Math.floor, stringFromCharCode = String.fromCharCode, /** Temporary variable */ key; /*--------------------------------------------------------------------------*/ /** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */ function error(type) { throw RangeError(errors[type]); } /** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */ function map(array, fn) { var length = array.length; var result = []; while (length--) { result[length] = fn(array[length]); } return result; } /** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */ function mapDomain(string, fn) { var parts = string.split('@'); var result = ''; if (parts.length > 1) { // In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result = parts[0] + '@'; string = parts[1]; } var labels = string.split(regexSeparators); var encoded = map(labels, fn).join('.'); return result + encoded; } /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see <https://mathiasbynens.be/notes/javascript-encoding> * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */ function ucs2decode(string) { var output = [], counter = 0, length = string.length, value, extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; } /** * Creates a string based on an array of numeric code points. * @see `punycode.ucs2.decode` * @memberOf punycode.ucs2 * @name encode * @param {Array} codePoints The array of numeric code points. * @returns {String} The new Unicode string (UCS-2). */ function ucs2encode(array) { return map(array, function(value) { var output = ''; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); return output; }).join(''); } /** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private * @param {Number} codePoint The basic numeric code point value. * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. */ function basicToDigit(codePoint) { if (codePoint - 48 < 10) { return codePoint - 22; } if (codePoint - 65 < 26) { return codePoint - 65; } if (codePoint - 97 < 26) { return codePoint - 97; } return base; } /** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. */ function digitToBasic(digit, flag) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); } /** * Bias adaptation function as per section 3.4 of RFC 3492. * http://tools.ietf.org/html/rfc3492#section-3.4 * @private */ function adapt(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); } /** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. * @memberOf punycode * @param {String} input The Punycode string of ASCII-only symbols. * @returns {String} The resulting string of Unicode symbols. */ function decode(input) { // Don't use UCS-2 var output = [], inputLength = input.length, out, i = 0, n = initialN, bias = initialBias, basic, j, index, oldi, w, k, digit, t, /** Cached calculation results */ baseMinusT; // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (j = 0; j < basic; ++j) { // if it's not a basic code point if (input.charCodeAt(j) >= 0x80) { error('not-basic'); } output.push(input.charCodeAt(j)); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { // `index` is the index of the next character to be consumed. // Decode a generalized variable-length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. for (oldi = i, w = 1, k = base; /* no condition */; k += base) { if (index >= inputLength) { error('invalid-input'); } digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } i += digit * w; t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (digit < t) { break; } baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } w *= baseMinusT; } out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor(i / out) > maxInt - n) { error('overflow'); } n += floor(i / out); i %= out; // Insert `n` at position `i` of the output output.splice(i++, 0, n); } return ucs2encode(output); } /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. */ function encode(input) { var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], /** `inputLength` will hold the number of code points in `input`. */ inputLength, /** Cached calculation results */ handledCPCountPlusOne, baseMinusT, qMinusT; // Convert the input in UCS-2 to Unicode input = ucs2decode(input); // Cache the length inputLength = input.length; // Initialize the state n = initialN; delta = 0; bias = initialBias; // Handle the basic code points for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } handledCPCount = basicLength = output.length; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string - if it is not empty - with a delimiter if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: for (m = maxInt, j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, // but guard against overflow handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) { // Represent delta as a generalized variable-length integer for (q = delta, k = base; /* no condition */; k += base) { t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (q < t) { break; } qMinusT = q - t; baseMinusT = base - t; output.push( stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) ); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); } /** * Converts a Punycode string representing a domain name or an email address * to Unicode. Only the Punycoded parts of the input will be converted, i.e. * it doesn't matter if you call it on a string that has already been * converted to Unicode. * @memberOf punycode * @param {String} input The Punycoded domain name or email address to * convert to Unicode. * @returns {String} The Unicode representation of the given Punycode * string. */ function toUnicode(input) { return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); } /** * Converts a Unicode string representing a domain name or an email address to * Punycode. Only the non-ASCII parts of the domain name will be converted, * i.e. it doesn't matter if you call it with a domain that's already in * ASCII. * @memberOf punycode * @param {String} input The domain name or email address to convert, as a * Unicode string. * @returns {String} The Punycode representation of the given domain name or * email address. */ function toASCII(input) { return mapDomain(input, function(string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; }); } /*--------------------------------------------------------------------------*/ /** Define the public API */ punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ 'version': '1.3.1', /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see <https://mathiasbynens.be/notes/javascript-encoding> * @memberOf punycode * @type Object */ 'ucs2': { 'decode': ucs2decode, 'encode': ucs2encode }, 'decode': decode, 'encode': encode, 'toASCII': toASCII, 'toUnicode': toUnicode }; /** Expose `punycode` */ // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( typeof define == 'function' && typeof define.amd == 'object' && define.amd ) { define('punycode', function() { return punycode; }); } else if (freeExports && freeModule) { if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+ freeModule.exports = punycode; } else { // in Narwhal or RingoJS v0.7.0- for (key in punycode) { punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); } } } else { // in Rhino or a web browser root.punycode = punycode; } }(this)); var html2canvasNodeAttribute = "data-html2canvas-node"; var html2canvasCanvasCloneAttribute = "data-html2canvas-canvas-clone"; var html2canvasCanvasCloneIndex = 0; var html2canvasCloneIndex = 0; window.html2canvas = function(nodeList, options) { var index = html2canvasCloneIndex++; options = options || {}; if (options.logging) { window.html2canvas.logging = true; window.html2canvas.start = Date.now(); } options.async = typeof(options.async) === "undefined" ? true : options.async; options.allowTaint = typeof(options.allowTaint) === "undefined" ? false : options.allowTaint; options.removeContainer = typeof(options.removeContainer) === "undefined" ? true : options.removeContainer; options.javascriptEnabled = typeof(options.javascriptEnabled) === "undefined" ? false : options.javascriptEnabled; options.imageTimeout = typeof(options.imageTimeout) === "undefined" ? 10000 : options.imageTimeout; options.renderer = typeof(options.renderer) === "function" ? options.renderer : CanvasRenderer; options.strict = !!options.strict; if (typeof(nodeList) === "string") { if (typeof(options.proxy) !== "string") { return Promise.reject("Proxy must be used when rendering url"); } var width = options.width != null ? options.width : window.innerWidth; var height = options.height != null ? options.height : window.innerHeight; return loadUrlDocument(absoluteUrl(nodeList), options.proxy, document, width, height, options).then(function(container) { return renderWindow(container.contentWindow.document.documentElement, container, options, width, height); }); } var node = ((nodeList === undefined) ? [document.documentElement] : ((nodeList.length) ? nodeList : [nodeList]))[0]; node.setAttribute(html2canvasNodeAttribute + index, index); return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) { if (typeof(options.onrendered) === "function") { log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas"); options.onrendered(canvas); } return canvas; }); }; window.html2canvas.punycode = this.punycode; window.html2canvas.proxy = {}; function renderDocument(document, options, windowWidth, windowHeight, html2canvasIndex) { return createWindowClone(document, document, windowWidth, windowHeight, options, document.defaultView.pageXOffset, document.defaultView.pageYOffset).then(function(container) { log("Document cloned"); var attributeName = html2canvasNodeAttribute + html2canvasIndex; var selector = "[" + attributeName + "='" + html2canvasIndex + "']"; document.querySelector(selector).removeAttribute(attributeName); var clonedWindow = container.contentWindow; var node = clonedWindow.document.querySelector(selector); var oncloneHandler = (typeof(options.onclone) === "function") ? Promise.resolve(options.onclone(clonedWindow.document)) : Promise.resolve(true); return oncloneHandler.then(function() { return renderWindow(node, container, options, windowWidth, windowHeight); }); }); } function renderWindow(node, container, options, windowWidth, windowHeight) { var clonedWindow = container.contentWindow; var support = new Support(clonedWindow.document); var imageLoader = new ImageLoader(options, support); var bounds = getBounds(node); var width = options.type === "view" ? windowWidth : documentWidth(clonedWindow.document); var height = options.type === "view" ? windowHeight : documentHeight(clonedWindow.document); var renderer = new options.renderer(width, height, imageLoader, options, document); var parser = new NodeParser(node, renderer, support, imageLoader, options); return parser.ready.then(function() { log("Finished rendering"); var canvas; if (options.type === "view") { canvas = crop(renderer.canvas, {width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0}); } else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) { canvas = renderer.canvas; } else { canvas = crop(renderer.canvas, {width: options.width != null ? options.width : bounds.width, height: options.height != null ? options.height : bounds.height, top: bounds.top, left: bounds.left, x: clonedWindow.pageXOffset, y: clonedWindow.pageYOffset}); } cleanupContainer(container, options); return canvas; }); } function cleanupContainer(container, options) { if (options.removeContainer) { container.parentNode.removeChild(container); log("Cleaned up container"); } } function crop(canvas, bounds) { var croppedCanvas = document.createElement("canvas"); var x1 = Math.min(canvas.width - 1, Math.max(0, bounds.left)); var x2 = Math.min(canvas.width, Math.max(1, bounds.left + bounds.width)); var y1 = Math.min(canvas.height - 1, Math.max(0, bounds.top)); var y2 = Math.min(canvas.height, Math.max(1, bounds.top + bounds.height)); croppedCanvas.width = bounds.width; croppedCanvas.height = bounds.height; log("Cropping canvas at:", "left:", bounds.left, "top:", bounds.top, "width:", (x2-x1), "height:", (y2-y1)); log("Resulting crop with width", bounds.width, "and height", bounds.height, " with x", x1, "and y", y1); croppedCanvas.getContext("2d").drawImage(canvas, x1, y1, x2-x1, y2-y1, bounds.x, bounds.y, x2-x1, y2-y1); return croppedCanvas; } function documentWidth (doc) { return Math.max( Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth), Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth), Math.max(doc.body.clientWidth, doc.documentElement.clientWidth) ); } function documentHeight (doc) { return Math.max( Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight), Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight), Math.max(doc.body.clientHeight, doc.documentElement.clientHeight) ); } function smallImage() { return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; } function isIE9() { return document.documentMode && document.documentMode <= 9; } // https://github.com/niklasvh/html2canvas/issues/503 function cloneNodeIE9(node, javascriptEnabled) { var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false); var child = node.firstChild; while(child) { if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') { clone.appendChild(cloneNodeIE9(child, javascriptEnabled)); } child = child.nextSibling; } return clone; } function createWindowClone(ownerDocument, containerDocument, width, height, options, x ,y) { labelCanvasElements(ownerDocument); var documentElement = isIE9() ? cloneNodeIE9(ownerDocument.documentElement, options.javascriptEnabled) : ownerDocument.documentElement.cloneNode(true); var container = containerDocument.createElement("iframe"); container.className = "html2canvas-container"; container.style.visibility = "hidden"; container.style.position = "fixed"; container.style.left = "-10000px"; container.style.top = "0px"; container.style.border = "0"; container.width = width; container.height = height; container.scrolling = "no"; // ios won't scroll without it containerDocument.body.appendChild(container); return new Promise(function(resolve) { var documentClone = container.contentWindow.document; cloneNodeValues(ownerDocument.documentElement, documentElement, "textarea"); cloneNodeValues(ownerDocument.documentElement, documentElement, "select"); /* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle if window url is about:blank, we can assign the url to current by writing onto the document */ container.contentWindow.onload = container.onload = function() { var interval = setInterval(function() { if (documentClone.body.childNodes.length > 0) { cloneCanvasContents(ownerDocument, documentClone); clearInterval(interval); if (options.type === "view") { container.contentWindow.scrollTo(x, y); } resolve(container); } }, 50); }; documentClone.open(); documentClone.write("<!DOCTYPE html><html></html>"); // Chrome scrolls the parent document for some reason after the write to the cloned window??? restoreOwnerScroll(ownerDocument, x, y); documentClone.replaceChild(options.javascriptEnabled === true ? documentClone.adoptNode(documentElement) : removeScriptNodes(documentClone.adoptNode(documentElement)), documentClone.documentElement); documentClone.close(); }); } function cloneNodeValues(document, clone, nodeName) { var originalNodes = document.getElementsByTagName(nodeName); var clonedNodes = clone.getElementsByTagName(nodeName); var count = originalNodes.length; for (var i = 0; i < count; i++) { clonedNodes[i].value = originalNodes[i].value; } } function restoreOwnerScroll(ownerDocument, x, y) { if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) { ownerDocument.defaultView.scrollTo(x, y); } } function loadUrlDocument(src, proxy, document, width, height, options) { return new Proxy(src, proxy, window.document).then(documentFromHTML(src)).then(function(doc) { return createWindowClone(doc, document, width, height, options, 0, 0); }); } function documentFromHTML(src) { return function(html) { var parser = new DOMParser(), doc; try { doc = parser.parseFromString(html, "text/html"); } catch(e) { log("DOMParser not supported, falling back to createHTMLDocument"); doc = document.implementation.createHTMLDocument(""); try { doc.open(); doc.write(html); doc.close(); } catch(ee) { log("createHTMLDocument write not supported, falling back to document.body.innerHTML"); doc.body.innerHTML = html; // ie9 doesnt support writing to documentElement } } var b = doc.querySelector("base"); if (!b || !b.href.host) { var base = doc.createElement("base"); base.href = src; doc.head.insertBefore(base, doc.head.firstChild); } return doc; }; } function labelCanvasElements(ownerDocument) { [].slice.call(ownerDocument.querySelectorAll("canvas"), 0).forEach(function(canvas) { canvas.setAttribute(html2canvasCanvasCloneAttribute, "canvas-" + html2canvasCanvasCloneIndex++); }); } function cloneCanvasContents(ownerDocument, documentClone) { [].slice.call(ownerDocument.querySelectorAll("[" + html2canvasCanvasCloneAttribute + "]"), 0).forEach(function(canvas) { try { var clonedCanvas = documentClone.querySelector('[' + html2canvasCanvasCloneAttribute + '="' + canvas.getAttribute(html2canvasCanvasCloneAttribute) + '"]'); if (clonedCanvas) { clonedCanvas.width = canvas.width; clonedCanvas.height = canvas.height; clonedCanvas.getContext("2d").putImageData(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height), 0, 0); } } catch(e) { log("Unable to copy canvas content from", canvas, e); } canvas.removeAttribute(html2canvasCanvasCloneAttribute); }); } function removeScriptNodes(parent) { [].slice.call(parent.childNodes, 0).filter(isElementNode).forEach(function(node) { if (node.tagName === "SCRIPT") { parent.removeChild(node); } else { removeScriptNodes(node); } }); return parent; } function isElementNode(node) { return node.nodeType === Node.ELEMENT_NODE; } function absoluteUrl(url) { var link = document.createElement("a"); link.href = url; link.href = link.href; return link; } // http://dev.w3.org/csswg/css-color/ function Color(value) { this.r = 0; this.g = 0; this.b = 0; this.a = null; var result = this.fromArray(value) || this.namedColor(value) || this.rgb(value) || this.rgba(value) || this.hex6(value) || this.hex3(value); } Color.prototype.darken = function(amount) { var a = 1 - amount; return new Color([ Math.round(this.r * a), Math.round(this.g * a), Math.round(this.b * a), this.a ]); }; Color.prototype.isTransparent = function() { return this.a === 0; }; Color.prototype.isBlack = function() { return this.r === 0 && this.g === 0 && this.b === 0; }; Color.prototype.fromArray = function(array) { if (Array.isArray(array)) { this.r = Math.min(array[0], 255); this.g = Math.min(array[1], 255); this.b = Math.min(array[2], 255); if (array.length > 3) { this.a = array[3]; } } return (Array.isArray(array)); }; var _hex3 = /^#([a-f0-9]{3})$/i; Color.prototype.hex3 = function(value) { var match = null; if ((match = value.match(_hex3)) !== null) { this.r = parseInt(match[1][0] + match[1][0], 16); this.g = parseInt(match[1][1] + match[1][1], 16); this.b = parseInt(match[1][2] + match[1][2], 16); } return match !== null; }; var _hex6 = /^#([a-f0-9]{6})$/i; Color.prototype.hex6 = function(value) { var match = null; if ((match = value.match(_hex6)) !== null) { this.r = parseInt(match[1].substring(0, 2), 16); this.g = parseInt(match[1].substring(2, 4), 16); this.b = parseInt(match[1].substring(4, 6), 16); } return match !== null; }; var _rgb = /^rgb\((\d{1,3}) *, *(\d{1,3}) *, *(\d{1,3})\)$/; Color.prototype.rgb = function(value) { var match = null; if ((match = value.match(_rgb)) !== null) { this.r = Number(match[1]); this.g = Number(match[2]); this.b = Number(match[3]); } return match !== null; }; var _rgba = /^rgba\((\d{1,3}) *, *(\d{1,3}) *, *(\d{1,3}) *, *(\d+\.?\d*)\)$/; Color.prototype.rgba = function(value) { var match = null; if ((match = value.match(_rgba)) !== null) { this.r = Number(match[1]); this.g = Number(match[2]); this.b = Number(match[3]); this.a = Number(match[4]); } return match !== null; }; Color.prototype.toString = function() { return this.a !== null && this.a !== 1 ? "rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" : "rgb(" + [this.r, this.g, this.b].join(",") + ")"; }; Color.prototype.namedColor = function(value) { var color = colors[value.toLowerCase()]; if (color) { this.r = color[0]; this.g = color[1]; this.b = color[2]; } else if (value.toLowerCase() === "transparent") { this.r = this.g = this.b = this.a = 0; return true; } return !!color; }; Color.prototype.isColor = true; // JSON.stringify([].slice.call($$('.named-color-table tr'), 1).map(function(row) { return [row.childNodes[3].textContent, row.childNodes[5].textContent.trim().split(",").map(Number)] }).reduce(function(data, row) {data[row[0]] = row[1]; return data}, {})) var colors = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; function DummyImageContainer(src) { this.src = src; log("DummyImageContainer for", src); if (!this.promise || !this.image) { log("Initiating DummyImageContainer"); DummyImageContainer.prototype.image = new Image(); var image = this.image; DummyImageContainer.prototype.promise = new Promise(function(resolve, reject) { image.onload = resolve; image.onerror = reject; image.src = smallImage(); if (image.complete === true) { resolve(image); } }); } } function Font(family, size) { var container = document.createElement('div'), img = document.createElement('img'), span = document.createElement('span'), sampleText = 'Hidden Text', baseline, middle; container.style.visibility = "hidden"; container.style.fontFamily = family; container.style.fontSize = size; container.style.margin = 0; container.style.padding = 0; document.body.appendChild(container); img.src = smallImage(); img.width = 1; img.height = 1; img.style.margin = 0; img.style.padding = 0; img.style.verticalAlign = "baseline"; span.style.fontFamily = family; span.style.fontSize = size; span.style.margin = 0; span.style.padding = 0; span.appendChild(document.createTextNode(sampleText)); container.appendChild(span); container.appendChild(img); baseline = (img.offsetTop - span.offsetTop) + 1; container.removeChild(span); container.appendChild(document.createTextNode(sampleText)); container.style.lineHeight = "normal"; img.style.verticalAlign = "super"; middle = (img.offsetTop-container.offsetTop) + 1; document.body.removeChild(container); this.baseline = baseline; this.lineWidth = 1; this.middle = middle; } function FontMetrics() { this.data = {}; } FontMetrics.prototype.getMetrics = function(family, size) { if (this.data[family + "-" + size] === undefined) { this.data[family + "-" + size] = new Font(family, size); } return this.data[family + "-" + size]; }; function FrameContainer(container, sameOrigin, options) { this.image = null; this.src = container; var self = this; var bounds = getBounds(container); this.promise = (!sameOrigin ? this.proxyLoad(options.proxy, bounds, options) : new Promise(function(resolve) { if (container.contentWindow.document.URL === "about:blank" || container.contentWindow.document.documentElement == null) { container.contentWindow.onload = container.onload = function() { resolve(container); }; } else { resolve(container); } })).then(function(container) { return html2canvas(container.contentWindow.document.documentElement, {type: 'view', width: container.width, height: container.height, proxy: options.proxy, javascriptEnabled: options.javascriptEnabled, removeContainer: options.removeContainer, allowTaint: options.allowTaint, imageTimeout: options.imageTimeout / 2}); }).then(function(canvas) { return self.image = canvas; }); } FrameContainer.prototype.proxyLoad = function(proxy, bounds, options) { var container = this.src; return loadUrlDocument(container.src, proxy, container.ownerDocument, bounds.width, bounds.height, options); }; function GradientContainer(imageData) { this.src = imageData.value; this.colorStops = []; this.type = null; this.x0 = 0.5; this.y0 = 0.5; this.x1 = 0.5; this.y1 = 0.5; this.promise = Promise.resolve(true); } GradientContainer.prototype.TYPES = { LINEAR: 1, RADIAL: 2 }; function ImageContainer(src, cors) { this.src = src; this.image = new Image(); var self = this; this.tainted = null; this.promise = new Promise(function(resolve, reject) { self.image.onload = resolve; self.image.onerror = reject; if (cors) { self.image.crossOrigin = "anonymous"; } self.image.src = src; if (self.image.complete === true) { resolve(self.image); } }); } function ImageLoader(options, support) { this.link = null; this.options = options; this.support = support; this.origin = this.getOrigin(window.location.href); } ImageLoader.prototype.findImages = function(nodes) { var images = []; nodes.reduce(function(imageNodes, container) { switch(container.node.nodeName) { case "IMG": return imageNodes.concat([{ args: [container.node.src], method: "url" }]); case "svg": case "IFRAME": return imageNodes.concat([{ args: [container.node], method: container.node.nodeName }]); } return imageNodes; }, []).forEach(this.addImage(images, this.loadImage), this); return images; }; ImageLoader.prototype.findBackgroundImage = function(images, container) { container.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(images, this.loadImage), this); return images; }; ImageLoader.prototype.addImage = function(images, callback) { return function(newImage) { newImage.args.forEach(function(image) { if (!this.imageExists(images, image)) { images.splice(0, 0, callback.call(this, newImage)); log('Added image #' + (images.length), typeof(image) === "string" ? image.substring(0, 100) : image); } }, this); }; }; ImageLoader.prototype.hasImageBackground = function(imageData) { return imageData.method !== "none"; }; ImageLoader.prototype.loadImage = function(imageData) { if (imageData.method === "url") { var src = imageData.args[0]; if (this.isSVG(src) && !this.support.svg && !this.options.allowTaint) { return new SVGContainer(src); } else if (src.match(/data:image\/.*;base64,/i)) { return new ImageContainer(src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, ''), false); } else if (this.isSameOrigin(src) || this.options.allowTaint === true || this.isSVG(src)) { return new ImageContainer(src, false); } else if (this.support.cors && !this.options.allowTaint && this.options.useCORS) { return new ImageContainer(src, true); } else if (this.options.proxy) { return new ProxyImageContainer(src, this.options.proxy); } else { return new DummyImageContainer(src); } } else if (imageData.method === "linear-gradient") { return new LinearGradientContainer(imageData); } else if (imageData.method === "gradient") { return new WebkitGradientContainer(imageData); } else if (imageData.method === "svg") { return new SVGNodeContainer(imageData.args[0], this.support.svg); } else if (imageData.method === "IFRAME") { return new FrameContainer(imageData.args[0], this.isSameOrigin(imageData.args[0].src), this.options); } else { return new DummyImageContainer(imageData); } }; ImageLoader.prototype.isSVG = function(src) { return src.substring(src.length - 3).toLowerCase() === "svg" || SVGContainer.prototype.isInline(src); }; ImageLoader.prototype.imageExists = function(images, src) { return images.some(function(image) { return image.src === src; }); }; ImageLoader.prototype.isSameOrigin = function(url) { return (this.getOrigin(url) === this.origin); }; ImageLoader.prototype.getOrigin = function(url) { var link = this.link || (this.link = document.createElement("a")); link.href = url; link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/ return link.protocol + link.hostname + link.port; }; ImageLoader.prototype.getPromise = function(container) { return this.timeout(container, this.options.imageTimeout)['catch'](function() { var dummy = new DummyImageContainer(container.src); return dummy.promise.then(function(image) { container.image = image; }); }); }; ImageLoader.prototype.get = function(src) { var found = null; return this.images.some(function(img) { return (found = img).src === src; }) ? found : null; }; ImageLoader.prototype.fetch = function(nodes) { this.images = nodes.reduce(bind(this.findBackgroundImage, this), this.findImages(nodes)); this.images.forEach(function(image, index) { image.promise.then(function() { log("Succesfully loaded image #"+ (index+1), image); }, function(e) { log("Failed loading image #"+ (index+1), image, e); }); }); this.ready = Promise.all(this.images.map(this.getPromise, this)); log("Finished searching images"); return this; }; ImageLoader.prototype.timeout = function(container, timeout) { var timer; var promise = Promise.race([container.promise, new Promise(function(res, reject) { timer = setTimeout(function() { log("Timed out loading image", container); reject(container); }, timeout); })]).then(function(container) { clearTimeout(timer); return container; }); promise['catch'](function() { clearTimeout(timer); }); return promise; }; function LinearGradientContainer(imageData) { GradientContainer.apply(this, arguments); this.type = this.TYPES.LINEAR; var hasDirection = imageData.args[0].match(this.stepRegExp) === null; if (hasDirection) { imageData.args[0].split(" ").reverse().forEach(function(position) { switch(position) { case "left": this.x0 = 0; this.x1 = 1; break; case "top": this.y0 = 0; this.y1 = 1; break; case "right": this.x0 = 1; this.x1 = 0; break; case "bottom": this.y0 = 1; this.y1 = 0; break; case "to": var y0 = this.y0; var x0 = this.x0; this.y0 = this.y1; this.x0 = this.x1; this.x1 = x0; this.y1 = y0; break; } }, this); } else { this.y0 = 0; this.y1 = 1; } this.colorStops = imageData.args.slice(hasDirection ? 1 : 0).map(function(colorStop) { var colorStopMatch = colorStop.match(this.stepRegExp); return { color: new Color(colorStopMatch[1]), stop: colorStopMatch[3] === "%" ? colorStopMatch[2] / 100 : null }; }, this); if (this.colorStops[0].stop === null) { this.colorStops[0].stop = 0; } if (this.colorStops[this.colorStops.length - 1].stop === null) { this.colorStops[this.colorStops.length - 1].stop = 1; } this.colorStops.forEach(function(colorStop, index) { if (colorStop.stop === null) { this.colorStops.slice(index).some(function(find, count) { if (find.stop !== null) { colorStop.stop = ((find.stop - this.colorStops[index - 1].stop) / (count + 1)) + this.colorStops[index - 1].stop; return true; } else { return false; } }, this); } }, this); } LinearGradientContainer.prototype = Object.create(GradientContainer.prototype); LinearGradientContainer.prototype.stepRegExp = /((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%|px)?/; function log() { if (window.html2canvas.logging && window.console && window.console.log) { Function.prototype.bind.call(window.console.log, (window.console)).apply(window.console, [(Date.now() - window.html2canvas.start) + "ms", "html2canvas:"].concat([].slice.call(arguments, 0))); } } function NodeContainer(node, parent) { this.node = node; this.parent = parent; this.stack = null; this.bounds = null; this.borders = null; this.clip = []; this.backgroundClip = []; this.offsetBounds = null; this.visible = null; this.computedStyles = null; this.colors = {}; this.styles = {}; this.backgroundImages = null; this.transformData = null; this.transformMatrix = null; this.isPseudoElement = false; this.opacity = null; } NodeContainer.prototype.cloneTo = function(stack) { stack.visible = this.visible; stack.borders = this.borders; stack.bounds = this.bounds; stack.clip = this.clip; stack.backgroundClip = this.backgroundClip; stack.computedStyles = this.computedStyles; stack.styles = this.styles; stack.backgroundImages = this.backgroundImages; stack.opacity = this.opacity; }; NodeContainer.prototype.getOpacity = function() { return this.opacity === null ? (this.opacity = this.cssFloat('opacity')) : this.opacity; }; NodeContainer.prototype.assignStack = function(stack) { this.stack = stack; stack.children.push(this); }; NodeContainer.prototype.isElementVisible = function() { return this.node.nodeType === Node.TEXT_NODE ? this.parent.visible : ( this.css('display') !== "none" && this.css('visibility') !== "hidden" && !this.node.hasAttribute("data-html2canvas-ignore") && (this.node.nodeName !== "INPUT" || this.node.getAttribute("type") !== "hidden") ); }; NodeContainer.prototype.css = function(attribute) { if (!this.computedStyles) { this.computedStyles = this.isPseudoElement ? this.parent.computedStyle(this.before ? ":before" : ":after") : this.computedStyle(null); } return this.styles[attribute] || (this.styles[attribute] = this.computedStyles[attribute]); }; NodeContainer.prototype.prefixedCss = function(attribute) { var prefixes = ["webkit", "moz", "ms", "o"]; var value = this.css(attribute); if (value === undefined) { prefixes.some(function(prefix) { value = this.css(prefix + attribute.substr(0, 1).toUpperCase() + attribute.substr(1)); return value !== undefined; }, this); } return value === undefined ? null : value; }; NodeContainer.prototype.computedStyle = function(type) { return this.node.ownerDocument.defaultView.getComputedStyle(this.node, type); }; NodeContainer.prototype.cssInt = function(attribute) { var value = parseInt(this.css(attribute), 10); return (isNaN(value)) ? 0 : value; // borders in old IE are throwing 'medium' for demo.html }; NodeContainer.prototype.color = function(attribute) { return this.colors[attribute] || (this.colors[attribute] = new Color(this.css(attribute))); }; NodeContainer.prototype.cssFloat = function(attribute) { var value = parseFloat(this.css(attribute)); return (isNaN(value)) ? 0 : value; }; NodeContainer.prototype.fontWeight = function() { var weight = this.css("fontWeight"); switch(parseInt(weight, 10)){ case 401: weight = "bold"; break; case 400: weight = "normal"; break; } return weight; }; NodeContainer.prototype.parseClip = function() { var matches = this.css('clip').match(this.CLIP); if (matches) { return { top: parseInt(matches[1], 10), right: parseInt(matches[2], 10), bottom: parseInt(matches[3], 10), left: parseInt(matches[4], 10) }; } return null; }; NodeContainer.prototype.parseBackgroundImages = function() { return this.backgroundImages || (this.backgroundImages = parseBackgrounds(this.css("backgroundImage"))); }; NodeContainer.prototype.cssList = function(property, index) { var value = (this.css(property) || '').split(','); value = value[index || 0] || value[0] || 'auto'; value = value.trim().split(' '); if (value.length === 1) { value = [value[0], value[0]]; } return value; }; NodeContainer.prototype.parseBackgroundSize = function(bounds, image, index) { var size = this.cssList("backgroundSize", index); var width, height; if (isPercentage(size[0])) { width = bounds.width * parseFloat(size[0]) / 100; } else if (/contain|cover/.test(size[0])) { var targetRatio = bounds.width / bounds.height, currentRatio = image.width / image.height; return (targetRatio < currentRatio ^ size[0] === 'contain') ? {width: bounds.height * currentRatio, height: bounds.height} : {width: bounds.width, height: bounds.width / currentRatio}; } else { width = parseInt(size[0], 10); } if (size[0] === 'auto' && size[1] === 'auto') { height = image.height; } else if (size[1] === 'auto') { height = width / image.width * image.height; } else if (isPercentage(size[1])) { height = bounds.height * parseFloat(size[1]) / 100; } else { height = parseInt(size[1], 10); } if (size[0] === 'auto') { width = height / image.height * image.width; } return {width: width, height: height}; }; NodeContainer.prototype.parseBackgroundPosition = function(bounds, image, index, backgroundSize) { var position = this.cssList('backgroundPosition', index); var left, top; if (isPercentage(position[0])){ left = (bounds.width - (backgroundSize || image).width) * (parseFloat(position[0]) / 100); } else { left = parseInt(position[0], 10); } if (position[1] === 'auto') { top = left / image.width * image.height; } else if (isPercentage(position[1])){ top = (bounds.height - (backgroundSize || image).height) * parseFloat(position[1]) / 100; } else { top = parseInt(position[1], 10); } if (position[0] === 'auto') { left = top / image.height * image.width; } return {left: left, top: top}; }; NodeContainer.prototype.parseBackgroundRepeat = function(index) { return this.cssList("backgroundRepeat", index)[0]; }; NodeContainer.prototype.parseTextShadows = function() { var textShadow = this.css("textShadow"); var results = []; if (textShadow && textShadow !== 'none') { var shadows = textShadow.match(this.TEXT_SHADOW_PROPERTY); for (var i = 0; shadows && (i < shadows.length); i++) { var s = shadows[i].match(this.TEXT_SHADOW_VALUES); results.push({ color: new Color(s[0]), offsetX: s[1] ? parseFloat(s[1].replace('px', '')) : 0, offsetY: s[2] ? parseFloat(s[2].replace('px', '')) : 0, blur: s[3] ? s[3].replace('px', '') : 0 }); } } return results; }; NodeContainer.prototype.parseTransform = function() { if (!this.transformData) { if (this.hasTransform()) { var offset = this.parseBounds(); var origin = this.prefixedCss("transformOrigin").split(" ").map(removePx).map(asFloat); origin[0] += offset.left; origin[1] += offset.top; this.transformData = { origin: origin, matrix: this.parseTransformMatrix() }; } else { this.transformData = { origin: [0, 0], matrix: [1, 0, 0, 1, 0, 0] }; } } return this.transformData; }; NodeContainer.prototype.parseTransformMatrix = function() { if (!this.transformMatrix) { var transform = this.prefixedCss("transform"); var matrix = transform ? parseMatrix(transform.match(this.MATRIX_PROPERTY)) : null; this.transformMatrix = matrix ? matrix : [1, 0, 0, 1, 0, 0]; } return this.transformMatrix; }; NodeContainer.prototype.parseBounds = function() { return this.bounds || (this.bounds = this.hasTransform() ? offsetBounds(this.node) : getBounds(this.node)); }; NodeContainer.prototype.hasTransform = function() { return this.parseTransformMatrix().join(",") !== "1,0,0,1,0,0" || (this.parent && this.parent.hasTransform()); }; NodeContainer.prototype.getValue = function() { var value = this.node.value || ""; if (this.node.tagName === "SELECT") { value = selectionValue(this.node); } else if (this.node.type === "password") { value = Array(value.length + 1).join('\u2022'); // jshint ignore:line } return value.length === 0 ? (this.node.placeholder || "") : value; }; NodeContainer.prototype.MATRIX_PROPERTY = /(matrix)\((.+)\)/; NodeContainer.prototype.TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g; NodeContainer.prototype.TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g; NodeContainer.prototype.CLIP = /^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/; function selectionValue(node) { var option = node.options[node.selectedIndex || 0]; return option ? (option.text || "") : ""; } function parseMatrix(match) { if (match && match[1] === "matrix") { return match[2].split(",").map(function(s) { return parseFloat(s.trim()); }); } } function isPercentage(value) { return value.toString().indexOf("%") !== -1; } function parseBackgrounds(backgroundImage) { var whitespace = ' \r\n\t', method, definition, prefix, prefix_i, block, results = [], mode = 0, numParen = 0, quote, args; var appendResult = function() { if(method) { if (definition.substr(0, 1) === '"') { definition = definition.substr(1, definition.length - 2); } if (definition) { args.push(definition); } if (method.substr(0, 1) === '-' && (prefix_i = method.indexOf('-', 1 ) + 1) > 0) { prefix = method.substr(0, prefix_i); method = method.substr(prefix_i); } results.push({ prefix: prefix, method: method.toLowerCase(), value: block, args: args, image: null }); } args = []; method = prefix = definition = block = ''; }; args = []; method = prefix = definition = block = ''; backgroundImage.split("").forEach(function(c) { if (mode === 0 && whitespace.indexOf(c) > -1) { return; } switch(c) { case '"': if(!quote) { quote = c; } else if(quote === c) { quote = null; } break; case '(': if(quote) { break; } else if(mode === 0) { mode = 1; block += c; return; } else { numParen++; } break; case ')': if (quote) { break; } else if(mode === 1) { if(numParen === 0) { mode = 0; block += c; appendResult(); return; } else { numParen--; } } break; case ',': if (quote) { break; } else if(mode === 0) { appendResult(); return; } else if (mode === 1) { if (numParen === 0 && !method.match(/^url$/i)) { args.push(definition); definition = ''; block += c; return; } } break; } block += c; if (mode === 0) { method += c; } else { definition += c; } }); appendResult(); return results; } function removePx(str) { return str.replace("px", ""); } function asFloat(str) { return parseFloat(str); } function getBounds(node) { if (node.getBoundingClientRect) { var clientRect = node.getBoundingClientRect(); var width = node.offsetWidth == null ? clientRect.width : node.offsetWidth; return { top: clientRect.top, bottom: clientRect.bottom || (clientRect.top + clientRect.height), right: clientRect.left + width, left: clientRect.left, width: width, height: node.offsetHeight == null ? clientRect.height : node.offsetHeight }; } return {}; } function offsetBounds(node) { var parent = node.offsetParent ? offsetBounds(node.offsetParent) : {top: 0, left: 0}; return { top: node.offsetTop + parent.top, bottom: node.offsetTop + node.offsetHeight + parent.top, right: node.offsetLeft + parent.left + node.offsetWidth, left: node.offsetLeft + parent.left, width: node.offsetWidth, height: node.offsetHeight }; } function NodeParser(element, renderer, support, imageLoader, options) { log("Starting NodeParser"); this.renderer = renderer; this.options = options; this.range = null; this.support = support; this.renderQueue = []; this.stack = new StackingContext(true, 1, element.ownerDocument, null); var parent = new NodeContainer(element, null); if (options.background) { renderer.rectangle(0, 0, renderer.width, renderer.height, new Color(options.background)); } if (element === element.ownerDocument.documentElement) { // http://www.w3.org/TR/css3-background/#special-backgrounds var canvasBackground = new NodeContainer(parent.color('backgroundColor').isTransparent() ? element.ownerDocument.body : element.ownerDocument.documentElement, null); renderer.rectangle(0, 0, renderer.width, renderer.height, canvasBackground.color('backgroundColor')); } parent.visibile = parent.isElementVisible(); this.createPseudoHideStyles(element.ownerDocument); this.disableAnimations(element.ownerDocument); this.nodes = flatten([parent].concat(this.getChildren(parent)).filter(function(container) { return container.visible = container.isElementVisible(); }).map(this.getPseudoElements, this)); this.fontMetrics = new FontMetrics(); log("Fetched nodes, total:", this.nodes.length); log("Calculate overflow clips"); this.calculateOverflowClips(); log("Start fetching images"); this.images = imageLoader.fetch(this.nodes.filter(isElement)); this.ready = this.images.ready.then(bind(function() { log("Images loaded, starting parsing"); log("Creating stacking contexts"); this.createStackingContexts(); log("Sorting stacking contexts"); this.sortStackingContexts(this.stack); this.parse(this.stack); log("Render queue created with " + this.renderQueue.length + " items"); return new Promise(bind(function(resolve) { if (!options.async) { this.renderQueue.forEach(this.paint, this); resolve(); } else if (typeof(options.async) === "function") { options.async.call(this, this.renderQueue, resolve); } else if (this.renderQueue.length > 0){ this.renderIndex = 0; this.asyncRenderer(this.renderQueue, resolve); } else { resolve(); } }, this)); }, this)); } NodeParser.prototype.calculateOverflowClips = function() { this.nodes.forEach(function(container) { if (isElement(container)) { if (isPseudoElement(container)) { container.appendToDOM(); } container.borders = this.parseBorders(container); var clip = (container.css('overflow') === "hidden") ? [container.borders.clip] : []; var cssClip = container.parseClip(); if (cssClip && ["absolute", "fixed"].indexOf(container.css('position')) !== -1) { clip.push([["rect", container.bounds.left + cssClip.left, container.bounds.top + cssClip.top, cssClip.right - cssClip.left, cssClip.bottom - cssClip.top ]]); } container.clip = hasParentClip(container) ? container.parent.clip.concat(clip) : clip; container.backgroundClip = (container.css('overflow') !== "hidden") ? container.clip.concat([container.borders.clip]) : container.clip; if (isPseudoElement(container)) { container.cleanDOM(); } } else if (isTextNode(container)) { container.clip = hasParentClip(container) ? container.parent.clip : []; } if (!isPseudoElement(container)) { container.bounds = null; } }, this); }; function hasParentClip(container) { return container.parent && container.parent.clip.length; } NodeParser.prototype.asyncRenderer = function(queue, resolve, asyncTimer) { asyncTimer = asyncTimer || Date.now(); this.paint(queue[this.renderIndex++]); if (queue.length === this.renderIndex) { resolve(); } else if (asyncTimer + 20 > Date.now()) { this.asyncRenderer(queue, resolve, asyncTimer); } else { setTimeout(bind(function() { this.asyncRenderer(queue, resolve); }, this), 0); } }; NodeParser.prototype.createPseudoHideStyles = function(document) { this.createStyles(document, '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ':before { content: "" !important; display: none !important; }' + '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER + ':after { content: "" !important; display: none !important; }'); }; NodeParser.prototype.disableAnimations = function(document) { this.createStyles(document, '* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; ' + '-webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}'); }; NodeParser.prototype.createStyles = function(document, styles) { var hidePseudoElements = document.createElement('style'); hidePseudoElements.innerHTML = styles; document.body.appendChild(hidePseudoElements); }; NodeParser.prototype.getPseudoElements = function(container) { var nodes = [[container]]; if (container.node.nodeType === Node.ELEMENT_NODE) { var before = this.getPseudoElement(container, ":before"); var after = this.getPseudoElement(container, ":after"); if (before) { nodes.push(before); } if (after) { nodes.push(after); } } return flatten(nodes); }; function toCamelCase(str) { return str.replace(/(\-[a-z])/g, function(match){ return match.toUpperCase().replace('-',''); }); } NodeParser.prototype.getPseudoElement = function(container, type) { var style = container.computedStyle(type); if(!style || !style.content || style.content === "none" || style.content === "-moz-alt-content" || style.display === "none") { return null; } var content = stripQuotes(style.content); var isImage = content.substr(0, 3) === 'url'; var pseudoNode = document.createElement(isImage ? 'img' : 'html2canvaspseudoelement'); var pseudoContainer = new PseudoElementContainer(pseudoNode, container, type); for (var i = style.length-1; i >= 0; i--) { var property = toCamelCase(style.item(i)); pseudoNode.style[property] = style[property]; } pseudoNode.className = PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER; if (isImage) { pseudoNode.src = parseBackgrounds(content)[0].args[0]; return [pseudoContainer]; } else { var text = document.createTextNode(content); pseudoNode.appendChild(text); return [pseudoContainer, new TextContainer(text, pseudoContainer)]; } }; NodeParser.prototype.getChildren = function(parentContainer) { return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) { var container = [node.nodeType === Node.TEXT_NODE ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement); return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container; }, this)); }; NodeParser.prototype.newStackingContext = function(container, hasOwnStacking) { var stack = new StackingContext(hasOwnStacking, container.getOpacity(), container.node, container.parent); container.cloneTo(stack); var parentStack = hasOwnStacking ? stack.getParentStack(this) : stack.parent.stack; parentStack.contexts.push(stack); container.stack = stack; }; NodeParser.prototype.createStackingContexts = function() { this.nodes.forEach(function(container) { if (isElement(container) && (this.isRootElement(container) || hasOpacity(container) || isPositionedForStacking(container) || this.isBodyWithTransparentRoot(container) || container.hasTransform())) { this.newStackingContext(container, true); } else if (isElement(container) && ((isPositioned(container) && zIndex0(container)) || isInlineBlock(container) || isFloating(container))) { this.newStackingContext(container, false); } else { container.assignStack(container.parent.stack); } }, this); }; NodeParser.prototype.isBodyWithTransparentRoot = function(container) { return container.node.nodeName === "BODY" && container.parent.color('backgroundColor').isTransparent(); }; NodeParser.prototype.isRootElement = function(container) { return container.parent === null; }; NodeParser.prototype.sortStackingContexts = function(stack) { stack.contexts.sort(zIndexSort(stack.contexts.slice(0))); stack.contexts.forEach(this.sortStackingContexts, this); }; NodeParser.prototype.parseTextBounds = function(container) { return function(text, index, textList) { if (container.parent.css("textDecoration").substr(0, 4) !== "none" || text.trim().length !== 0) { if (this.support.rangeBounds && !container.parent.hasTransform()) { var offset = textList.slice(0, index).join("").length; return this.getRangeBounds(container.node, offset, text.length); } else if (container.node && typeof(container.node.data) === "string") { var replacementNode = container.node.splitText(text.length); var bounds = this.getWrapperBounds(container.node, container.parent.hasTransform()); container.node = replacementNode; return bounds; } } else if(!this.support.rangeBounds || container.parent.hasTransform()){ container.node = container.node.splitText(text.length); } return {}; }; }; NodeParser.prototype.getWrapperBounds = function(node, transform) { var wrapper = node.ownerDocument.createElement('html2canvaswrapper'); var parent = node.parentNode, backupText = node.cloneNode(true); wrapper.appendChild(node.cloneNode(true)); parent.replaceChild(wrapper, node); var bounds = transform ? offsetBounds(wrapper) : getBounds(wrapper); parent.replaceChild(backupText, wrapper); return bounds; }; NodeParser.prototype.getRangeBounds = function(node, offset, length) { var range = this.range || (this.range = node.ownerDocument.createRange()); range.setStart(node, offset); range.setEnd(node, offset + length); return range.getBoundingClientRect(); }; function ClearTransform() {} NodeParser.prototype.parse = function(stack) { // http://www.w3.org/TR/CSS21/visuren.html#z-index var negativeZindex = stack.contexts.filter(negativeZIndex); // 2. the child stacking contexts with negative stack levels (most negative first). var descendantElements = stack.children.filter(isElement); var descendantNonFloats = descendantElements.filter(not(isFloating)); var nonInlineNonPositionedDescendants = descendantNonFloats.filter(not(isPositioned)).filter(not(inlineLevel)); // 3 the in-flow, non-inline-level, non-positioned descendants. var nonPositionedFloats = descendantElements.filter(not(isPositioned)).filter(isFloating); // 4. the non-positioned floats. var inFlow = descendantNonFloats.filter(not(isPositioned)).filter(inlineLevel); // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks. var stackLevel0 = stack.contexts.concat(descendantNonFloats.filter(isPositioned)).filter(zIndex0); // 6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0. var text = stack.children.filter(isTextNode).filter(hasText); var positiveZindex = stack.contexts.filter(positiveZIndex); // 7. the child stacking contexts with positive stack levels (least positive first). negativeZindex.concat(nonInlineNonPositionedDescendants).concat(nonPositionedFloats) .concat(inFlow).concat(stackLevel0).concat(text).concat(positiveZindex).forEach(function(container) { this.renderQueue.push(container); if (isStackingContext(container)) { this.parse(container); this.renderQueue.push(new ClearTransform()); } }, this); }; NodeParser.prototype.paint = function(container) { try { if (container instanceof ClearTransform) { this.renderer.ctx.restore(); } else if (isTextNode(container)) { if (isPseudoElement(container.parent)) { container.parent.appendToDOM(); } this.paintText(container); if (isPseudoElement(container.parent)) { container.parent.cleanDOM(); } } else { this.paintNode(container); } } catch(e) { log(e); if (this.options.strict) { throw e; } } }; NodeParser.prototype.paintNode = function(container) { if (isStackingContext(container)) { this.renderer.setOpacity(container.opacity); this.renderer.ctx.save(); if (container.hasTransform()) { this.renderer.setTransform(container.parseTransform()); } } if (container.node.nodeName === "INPUT" && container.node.type === "checkbox") { this.paintCheckbox(container); } else if (container.node.nodeName === "INPUT" && container.node.type === "radio") { this.paintRadio(container); } else { this.paintElement(container); } }; NodeParser.prototype.paintElement = function(container) { var bounds = container.parseBounds(); this.renderer.clip(container.backgroundClip, function() { this.renderer.renderBackground(container, bounds, container.borders.borders.map(getWidth)); }, this); this.renderer.clip(container.clip, function() { this.renderer.renderBorders(container.borders.borders); }, this); this.renderer.clip(container.backgroundClip, function() { switch (container.node.nodeName) { case "svg": case "IFRAME": var imgContainer = this.images.get(container.node); if (imgContainer) { this.renderer.renderImage(container, bounds, container.borders, imgContainer); } else { log("Error loading <" + container.node.nodeName + ">", container.node); } break; case "IMG": var imageContainer = this.images.get(container.node.src); if (imageContainer) { this.renderer.renderImage(container, bounds, container.borders, imageContainer); } else { log("Error loading <img>", container.node.src); } break; case "CANVAS": this.renderer.renderImage(container, bounds, container.borders, {image: container.node}); break; case "SELECT": case "INPUT": case "TEXTAREA": this.paintFormValue(container); break; } }, this); }; NodeParser.prototype.paintCheckbox = function(container) { var b = container.parseBounds(); var size = Math.min(b.width, b.height); var bounds = {width: size - 1, height: size - 1, top: b.top, left: b.left}; var r = [3, 3]; var radius = [r, r, r, r]; var borders = [1,1,1,1].map(function(w) { return {color: new Color('#A5A5A5'), width: w}; }); var borderPoints = calculateCurvePoints(bounds, radius, borders); this.renderer.clip(container.backgroundClip, function() { this.renderer.rectangle(bounds.left + 1, bounds.top + 1, bounds.width - 2, bounds.height - 2, new Color("#DEDEDE")); this.renderer.renderBorders(calculateBorders(borders, bounds, borderPoints, radius)); if (container.node.checked) { this.renderer.font(new Color('#424242'), 'normal', 'normal', 'bold', (size - 3) + "px", 'arial'); this.renderer.text("\u2714", bounds.left + size / 6, bounds.top + size - 1); } }, this); }; NodeParser.prototype.paintRadio = function(container) { var bounds = container.parseBounds(); var size = Math.min(bounds.width, bounds.height) - 2; this.renderer.clip(container.backgroundClip, function() { this.renderer.circleStroke(bounds.left + 1, bounds.top + 1, size, new Color('#DEDEDE'), 1, new Color('#A5A5A5')); if (container.node.checked) { this.renderer.circle(Math.ceil(bounds.left + size / 4) + 1, Math.ceil(bounds.top + size / 4) + 1, Math.floor(size / 2), new Color('#424242')); } }, this); }; NodeParser.prototype.paintFormValue = function(container) { var value = container.getValue(); if (value.length > 0) { var document = container.node.ownerDocument; var wrapper = document.createElement('html2canvaswrapper'); var properties = ['lineHeight', 'textAlign', 'fontFamily', 'fontWeight', 'fontSize', 'color', 'paddingLeft', 'paddingTop', 'paddingRight', 'paddingBottom', 'width', 'height', 'borderLeftStyle', 'borderTopStyle', 'borderLeftWidth', 'borderTopWidth', 'boxSizing', 'whiteSpace', 'wordWrap']; properties.forEach(function(property) { try { wrapper.style[property] = container.css(property); } catch(e) { // Older IE has issues with "border" log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message); } }); var bounds = container.parseBounds(); wrapper.style.position = "fixed"; wrapper.style.left = bounds.left + "px"; wrapper.style.top = bounds.top + "px"; wrapper.textContent = value; document.body.appendChild(wrapper); this.paintText(new TextContainer(wrapper.firstChild, container)); document.body.removeChild(wrapper); } }; NodeParser.prototype.paintText = function(container) { container.applyTextTransform(); var characters = window.html2canvas.punycode.ucs2.decode(container.node.data); var textList = (!this.options.letterRendering || noLetterSpacing(container)) && !hasUnicode(container.node.data) ? getWords(characters) : characters.map(function(character) { return window.html2canvas.punycode.ucs2.encode([character]); }); var weight = container.parent.fontWeight(); var size = container.parent.css('fontSize'); var family = container.parent.css('fontFamily'); var shadows = container.parent.parseTextShadows(); this.renderer.font(container.parent.color('color'), container.parent.css('fontStyle'), container.parent.css('fontVariant'), weight, size, family); if (shadows.length) { // TODO: support multiple text shadows this.renderer.fontShadow(shadows[0].color, shadows[0].offsetX, shadows[0].offsetY, shadows[0].blur); } else { this.renderer.clearShadow(); } this.renderer.clip(container.parent.clip, function() { textList.map(this.parseTextBounds(container), this).forEach(function(bounds, index) { if (bounds) { this.renderer.text(textList[index], bounds.left, bounds.bottom); this.renderTextDecoration(container.parent, bounds, this.fontMetrics.getMetrics(family, size)); } }, this); }, this); }; NodeParser.prototype.renderTextDecoration = function(container, bounds, metrics) { switch(container.css("textDecoration").split(" ")[0]) { case "underline": // Draws a line at the baseline of the font // TODO As some browsers display the line as more than 1px if the font-size is big, need to take that into account both in position and size this.renderer.rectangle(bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, container.color("color")); break; case "overline": this.renderer.rectangle(bounds.left, Math.round(bounds.top), bounds.width, 1, container.color("color")); break; case "line-through": // TODO try and find exact position for line-through this.renderer.rectangle(bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, container.color("color")); break; } }; var borderColorTransforms = { inset: [ ["darken", 0.60], ["darken", 0.10], ["darken", 0.10], ["darken", 0.60] ] }; NodeParser.prototype.parseBorders = function(container) { var nodeBounds = container.parseBounds(); var radius = getBorderRadiusData(container); var borders = ["Top", "Right", "Bottom", "Left"].map(function(side, index) { var style = container.css('border' + side + 'Style'); var color = container.color('border' + side + 'Color'); if (style === "inset" && color.isBlack()) { color = new Color([255, 255, 255, color.a]); // this is wrong, but } var colorTransform = borderColorTransforms[style] ? borderColorTransforms[style][index] : null; return { width: container.cssInt('border' + side + 'Width'), color: colorTransform ? color[colorTransform[0]](colorTransform[1]) : color, args: null }; }); var borderPoints = calculateCurvePoints(nodeBounds, radius, borders); return { clip: this.parseBackgroundClip(container, borderPoints, borders, radius, nodeBounds), borders: calculateBorders(borders, nodeBounds, borderPoints, radius) }; }; function calculateBorders(borders, nodeBounds, borderPoints, radius) { return borders.map(function(border, borderSide) { if (border.width > 0) { var bx = nodeBounds.left; var by = nodeBounds.top; var bw = nodeBounds.width; var bh = nodeBounds.height - (borders[2].width); switch(borderSide) { case 0: // top border bh = borders[0].width; border.args = drawSide({ c1: [bx, by], c2: [bx + bw, by], c3: [bx + bw - borders[1].width, by + bh], c4: [bx + borders[3].width, by + bh] }, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner); break; case 1: // right border bx = nodeBounds.left + nodeBounds.width - (borders[1].width); bw = borders[1].width; border.args = drawSide({ c1: [bx + bw, by], c2: [bx + bw, by + bh + borders[2].width], c3: [bx, by + bh], c4: [bx, by + borders[0].width] }, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner); break; case 2: // bottom border by = (by + nodeBounds.height) - (borders[2].width); bh = borders[2].width; border.args = drawSide({ c1: [bx + bw, by + bh], c2: [bx, by + bh], c3: [bx + borders[3].width, by], c4: [bx + bw - borders[3].width, by] }, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner); break; case 3: // left border bw = borders[3].width; border.args = drawSide({ c1: [bx, by + bh + borders[2].width], c2: [bx, by], c3: [bx + bw, by + borders[0].width], c4: [bx + bw, by + bh] }, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner); break; } } return border; }); } NodeParser.prototype.parseBackgroundClip = function(container, borderPoints, borders, radius, bounds) { var backgroundClip = container.css('backgroundClip'), borderArgs = []; switch(backgroundClip) { case "content-box": case "padding-box": parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width); parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width); parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width); parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width); break; default: parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top); parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top); parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height); parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height); break; } return borderArgs; }; function getCurvePoints(x, y, r1, r2) { var kappa = 4 * ((Math.sqrt(2) - 1) / 3); var ox = (r1) * kappa, // control point offset horizontal oy = (r2) * kappa, // control point offset vertical xm = x + r1, // x-middle ym = y + r2; // y-middle return { topLeft: bezierCurve({x: x, y: ym}, {x: x, y: ym - oy}, {x: xm - ox, y: y}, {x: xm, y: y}), topRight: bezierCurve({x: x, y: y}, {x: x + ox,y: y}, {x: xm, y: ym - oy}, {x: xm, y: ym}), bottomRight: bezierCurve({x: xm, y: y}, {x: xm, y: y + oy}, {x: x + ox, y: ym}, {x: x, y: ym}), bottomLeft: bezierCurve({x: xm, y: ym}, {x: xm - ox, y: ym}, {x: x, y: y + oy}, {x: x, y:y}) }; } function calculateCurvePoints(bounds, borderRadius, borders) { var x = bounds.left, y = bounds.top, width = bounds.width, height = bounds.height, tlh = borderRadius[0][0], tlv = borderRadius[0][1], trh = borderRadius[1][0], trv = borderRadius[1][1], brh = borderRadius[2][0], brv = borderRadius[2][1], blh = borderRadius[3][0], blv = borderRadius[3][1]; var topWidth = width - trh, rightHeight = height - brv, bottomWidth = width - brh, leftHeight = height - blv; return { topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5), topLeftInner: getCurvePoints(x + borders[3].width, y + borders[0].width, Math.max(0, tlh - borders[3].width), Math.max(0, tlv - borders[0].width)).topLeft.subdivide(0.5), topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5), topRightInner: getCurvePoints(x + Math.min(topWidth, width + borders[3].width), y + borders[0].width, (topWidth > width + borders[3].width) ? 0 :trh - borders[3].width, trv - borders[0].width).topRight.subdivide(0.5), bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5), bottomRightInner: getCurvePoints(x + Math.min(bottomWidth, width - borders[3].width), y + Math.min(rightHeight, height + borders[0].width), Math.max(0, brh - borders[1].width), brv - borders[2].width).bottomRight.subdivide(0.5), bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5), bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - borders[3].width), blv - borders[2].width).bottomLeft.subdivide(0.5) }; } function bezierCurve(start, startControl, endControl, end) { var lerp = function (a, b, t) { return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }; }; return { start: start, startControl: startControl, endControl: endControl, end: end, subdivide: function(t) { var ab = lerp(start, startControl, t), bc = lerp(startControl, endControl, t), cd = lerp(endControl, end, t), abbc = lerp(ab, bc, t), bccd = lerp(bc, cd, t), dest = lerp(abbc, bccd, t); return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)]; }, curveTo: function(borderArgs) { borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y]); }, curveToReversed: function(borderArgs) { borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y]); } }; } function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) { var borderArgs = []; if (radius1[0] > 0 || radius1[1] > 0) { borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]); outer1[1].curveTo(borderArgs); } else { borderArgs.push([ "line", borderData.c1[0], borderData.c1[1]]); } if (radius2[0] > 0 || radius2[1] > 0) { borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]); outer2[0].curveTo(borderArgs); borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]); inner2[0].curveToReversed(borderArgs); } else { borderArgs.push(["line", borderData.c2[0], borderData.c2[1]]); borderArgs.push(["line", borderData.c3[0], borderData.c3[1]]); } if (radius1[0] > 0 || radius1[1] > 0) { borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]); inner1[1].curveToReversed(borderArgs); } else { borderArgs.push(["line", borderData.c4[0], borderData.c4[1]]); } return borderArgs; } function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) { if (radius1[0] > 0 || radius1[1] > 0) { borderArgs.push(["line", corner1[0].start.x, corner1[0].start.y]); corner1[0].curveTo(borderArgs); corner1[1].curveTo(borderArgs); } else { borderArgs.push(["line", x, y]); } if (radius2[0] > 0 || radius2[1] > 0) { borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y]); } } function negativeZIndex(container) { return container.cssInt("zIndex") < 0; } function positiveZIndex(container) { return container.cssInt("zIndex") > 0; } function zIndex0(container) { return container.cssInt("zIndex") === 0; } function inlineLevel(container) { return ["inline", "inline-block", "inline-table"].indexOf(container.css("display")) !== -1; } function isStackingContext(container) { return (container instanceof StackingContext); } function hasText(container) { return container.node.data.trim().length > 0; } function noLetterSpacing(container) { return (/^(normal|none|0px)$/.test(container.parent.css("letterSpacing"))); } function getBorderRadiusData(container) { return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function(side) { var value = container.css('border' + side + 'Radius'); var arr = value.split(" "); if (arr.length <= 1) { arr[1] = arr[0]; } return arr.map(asInt); }); } function renderableNode(node) { return (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE); } function isPositionedForStacking(container) { var position = container.css("position"); var zIndex = (["absolute", "relative", "fixed"].indexOf(position) !== -1) ? container.css("zIndex") : "auto"; return zIndex !== "auto"; } function isPositioned(container) { return container.css("position") !== "static"; } function isFloating(container) { return container.css("float") !== "none"; } function isInlineBlock(container) { return ["inline-block", "inline-table"].indexOf(container.css("display")) !== -1; } function not(callback) { var context = this; return function() { return !callback.apply(context, arguments); }; } function isElement(container) { return container.node.nodeType === Node.ELEMENT_NODE; } function isPseudoElement(container) { return container.isPseudoElement === true; } function isTextNode(container) { return container.node.nodeType === Node.TEXT_NODE; } function zIndexSort(contexts) { return function(a, b) { return (a.cssInt("zIndex") + (contexts.indexOf(a) / contexts.length)) - (b.cssInt("zIndex") + (contexts.indexOf(b) / contexts.length)); }; } function hasOpacity(container) { return container.getOpacity() < 1; } function bind(callback, context) { return function() { return callback.apply(context, arguments); }; } function asInt(value) { return parseInt(value, 10); } function getWidth(border) { return border.width; } function nonIgnoredElement(nodeContainer) { return (nodeContainer.node.nodeType !== Node.ELEMENT_NODE || ["SCRIPT", "HEAD", "TITLE", "OBJECT", "BR", "OPTION"].indexOf(nodeContainer.node.nodeName) === -1); } function flatten(arrays) { return [].concat.apply([], arrays); } function stripQuotes(content) { var first = content.substr(0, 1); return (first === content.substr(content.length - 1) && first.match(/'|"/)) ? content.substr(1, content.length - 2) : content; } function getWords(characters) { var words = [], i = 0, onWordBoundary = false, word; while(characters.length) { if (isWordBoundary(characters[i]) === onWordBoundary) { word = characters.splice(0, i); if (word.length) { words.push(window.html2canvas.punycode.ucs2.encode(word)); } onWordBoundary =! onWordBoundary; i = 0; } else { i++; } if (i >= characters.length) { word = characters.splice(0, i); if (word.length) { words.push(window.html2canvas.punycode.ucs2.encode(word)); } } } return words; } function isWordBoundary(characterCode) { return [ 32, // <space> 13, // \r 10, // \n 9, // \t 45 // - ].indexOf(characterCode) !== -1; } function hasUnicode(string) { return (/[^\u0000-\u00ff]/).test(string); } function Proxy(src, proxyUrl, document) { if (!proxyUrl) { return Promise.reject("No proxy configured"); } var callback = createCallback(supportsCORS); var url = createProxyUrl(proxyUrl, src, callback); return supportsCORS ? XHR(url) : (jsonp(document, url, callback).then(function(response) { return decode64(response.content); })); } var proxyCount = 0; var supportsCORS = ('withCredentials' in new XMLHttpRequest()); var supportsCORSImage = ('crossOrigin' in new Image()); function ProxyURL(src, proxyUrl, document) { var callback = createCallback(supportsCORSImage); var url = createProxyUrl(proxyUrl, src, callback); return (supportsCORSImage ? Promise.resolve(url) : jsonp(document, url, callback).then(function(response) { return "data:" + response.type + ";base64," + response.content; })); } function jsonp(document, url, callback) { return new Promise(function(resolve, reject) { var s = document.createElement("script"); var cleanup = function() { delete window.html2canvas.proxy[callback]; document.body.removeChild(s); }; window.html2canvas.proxy[callback] = function(response) { cleanup(); resolve(response); }; s.src = url; s.onerror = function(e) { cleanup(); reject(e); }; document.body.appendChild(s); }); } function createCallback(useCORS) { return !useCORS ? "html2canvas_" + Date.now() + "_" + (++proxyCount) + "_" + Math.round(Math.random() * 100000) : ""; } function createProxyUrl(proxyUrl, src, callback) { return proxyUrl + "?url=" + encodeURIComponent(src) + (callback.length ? "&callback=html2canvas.proxy." + callback : ""); } function ProxyImageContainer(src, proxy) { var script = document.createElement("script"); var link = document.createElement("a"); link.href = src; src = link.href; this.src = src; this.image = new Image(); var self = this; this.promise = new Promise(function(resolve, reject) { self.image.crossOrigin = "Anonymous"; self.image.onload = resolve; self.image.onerror = reject; new ProxyURL(src, proxy, document).then(function(url) { self.image.src = url; })['catch'](reject); }); } function PseudoElementContainer(node, parent, type) { NodeContainer.call(this, node, parent); this.isPseudoElement = true; this.before = type === ":before"; } PseudoElementContainer.prototype.cloneTo = function(stack) { PseudoElementContainer.prototype.cloneTo.call(this, stack); stack.isPseudoElement = true; stack.before = this.before; }; PseudoElementContainer.prototype = Object.create(NodeContainer.prototype); PseudoElementContainer.prototype.appendToDOM = function() { if (this.before) { this.parent.node.insertBefore(this.node, this.parent.node.firstChild); } else { this.parent.node.appendChild(this.node); } this.parent.node.className += " " + this.getHideClass(); }; PseudoElementContainer.prototype.cleanDOM = function() { this.node.parentNode.removeChild(this.node); this.parent.node.className = this.parent.node.className.replace(this.getHideClass(), ""); }; PseudoElementContainer.prototype.getHideClass = function() { return this["PSEUDO_HIDE_ELEMENT_CLASS_" + (this.before ? "BEFORE" : "AFTER")]; }; PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before"; PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after"; function Renderer(width, height, images, options, document) { this.width = width; this.height = height; this.images = images; this.options = options; this.document = document; } Renderer.prototype.renderImage = function(container, bounds, borderData, imageContainer) { var paddingLeft = container.cssInt('paddingLeft'), paddingTop = container.cssInt('paddingTop'), paddingRight = container.cssInt('paddingRight'), paddingBottom = container.cssInt('paddingBottom'), borders = borderData.borders; var width = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight); var height = bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom); this.drawImage( imageContainer, 0, 0, imageContainer.image.width || width, imageContainer.image.height || height, bounds.left + paddingLeft + borders[3].width, bounds.top + paddingTop + borders[0].width, width, height ); }; Renderer.prototype.renderBackground = function(container, bounds, borderData) { if (bounds.height > 0 && bounds.width > 0) { this.renderBackgroundColor(container, bounds); this.renderBackgroundImage(container, bounds, borderData); } }; Renderer.prototype.renderBackgroundColor = function(container, bounds) { var color = container.color("backgroundColor"); if (!color.isTransparent()) { this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, color); } }; Renderer.prototype.renderBorders = function(borders) { borders.forEach(this.renderBorder, this); }; Renderer.prototype.renderBorder = function(data) { if (!data.color.isTransparent() && data.args !== null) { this.drawShape(data.args, data.color); } }; Renderer.prototype.renderBackgroundImage = function(container, bounds, borderData) { var backgroundImages = container.parseBackgroundImages(); backgroundImages.reverse().forEach(function(backgroundImage, index, arr) { switch(backgroundImage.method) { case "url": var image = this.images.get(backgroundImage.args[0]); if (image) { this.renderBackgroundRepeating(container, bounds, image, arr.length - (index+1), borderData); } else { log("Error loading background-image", backgroundImage.args[0]); } break; case "linear-gradient": case "gradient": var gradientImage = this.images.get(backgroundImage.value); if (gradientImage) { this.renderBackgroundGradient(gradientImage, bounds, borderData); } else { log("Error loading background-image", backgroundImage.args[0]); } break; case "none": break; default: log("Unknown background-image type", backgroundImage.args[0]); } }, this); }; Renderer.prototype.renderBackgroundRepeating = function(container, bounds, imageContainer, index, borderData) { var size = container.parseBackgroundSize(bounds, imageContainer.image, index); var position = container.parseBackgroundPosition(bounds, imageContainer.image, index, size); var repeat = container.parseBackgroundRepeat(index); switch (repeat) { case "repeat-x": case "repeat no-repeat": this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + borderData[3], bounds.top + position.top + borderData[0], 99999, size.height, borderData); break; case "repeat-y": case "no-repeat repeat": this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + borderData[0], size.width, 99999, borderData); break; case "no-repeat": this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + position.top + borderData[0], size.width, size.height, borderData); break; default: this.renderBackgroundRepeat(imageContainer, position, size, {top: bounds.top, left: bounds.left}, borderData[3], borderData[0]); break; } }; function StackingContext(hasOwnStacking, opacity, element, parent) { NodeContainer.call(this, element, parent); this.ownStacking = hasOwnStacking; this.contexts = []; this.children = []; this.opacity = (this.parent ? this.parent.stack.opacity : 1) * opacity; } StackingContext.prototype = Object.create(NodeContainer.prototype); StackingContext.prototype.getParentStack = function(context) { var parentStack = (this.parent) ? this.parent.stack : null; return parentStack ? (parentStack.ownStacking ? parentStack : parentStack.getParentStack(context)) : context.stack; }; function Support(document) { this.rangeBounds = this.testRangeBounds(document); this.cors = this.testCORS(); this.svg = this.testSVG(); } Support.prototype.testRangeBounds = function(document) { var range, testElement, rangeBounds, rangeHeight, support = false; if (document.createRange) { range = document.createRange(); if (range.getBoundingClientRect) { testElement = document.createElement('boundtest'); testElement.style.height = "123px"; testElement.style.display = "block"; document.body.appendChild(testElement); range.selectNode(testElement); rangeBounds = range.getBoundingClientRect(); rangeHeight = rangeBounds.height; if (rangeHeight === 123) { support = true; } document.body.removeChild(testElement); } } return support; }; Support.prototype.testCORS = function() { return typeof((new Image()).crossOrigin) !== "undefined"; }; Support.prototype.testSVG = function() { var img = new Image(); var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>"; try { ctx.drawImage(img, 0, 0); canvas.toDataURL(); } catch(e) { return false; } return true; }; function SVGContainer(src) { this.src = src; this.image = null; var self = this; this.promise = this.hasFabric().then(function() { return (self.isInline(src) ? Promise.resolve(self.inlineFormatting(src)) : XHR(src)); }).then(function(svg) { return new Promise(function(resolve) { html2canvas.fabric.loadSVGFromString(svg, self.createCanvas.call(self, resolve)); }); }); } SVGContainer.prototype.hasFabric = function() { return !html2canvas.fabric ? Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg")) : Promise.resolve(); }; SVGContainer.prototype.inlineFormatting = function(src) { return (/^data:image\/svg\+xml;base64,/.test(src)) ? this.decode64(this.removeContentType(src)) : this.removeContentType(src); }; SVGContainer.prototype.removeContentType = function(src) { return src.replace(/^data:image\/svg\+xml(;base64)?,/,''); }; SVGContainer.prototype.isInline = function(src) { return (/^data:image\/svg\+xml/i.test(src)); }; SVGContainer.prototype.createCanvas = function(resolve) { var self = this; return function (objects, options) { var canvas = new html2canvas.fabric.StaticCanvas('c'); self.image = canvas.lowerCanvasEl; canvas .setWidth(options.width) .setHeight(options.height) .add(html2canvas.fabric.util.groupSVGElements(objects, options)) .renderAll(); resolve(canvas.lowerCanvasEl); }; }; SVGContainer.prototype.decode64 = function(str) { return (typeof(window.atob) === "function") ? window.atob(str) : decode64(str); }; /* * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ function decode64(base64) { var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var len = base64.length, i, encoded1, encoded2, encoded3, encoded4, byte1, byte2, byte3; var output = ""; for (i = 0; i < len; i+=4) { encoded1 = chars.indexOf(base64[i]); encoded2 = chars.indexOf(base64[i+1]); encoded3 = chars.indexOf(base64[i+2]); encoded4 = chars.indexOf(base64[i+3]); byte1 = (encoded1 << 2) | (encoded2 >> 4); byte2 = ((encoded2 & 15) << 4) | (encoded3 >> 2); byte3 = ((encoded3 & 3) << 6) | encoded4; if (encoded3 === 64) { output += String.fromCharCode(byte1); } else if (encoded4 === 64 || encoded4 === -1) { output += String.fromCharCode(byte1, byte2); } else{ output += String.fromCharCode(byte1, byte2, byte3); } } return output; } function SVGNodeContainer(node, native) { this.src = node; this.image = null; var self = this; this.promise = native ? new Promise(function(resolve, reject) { self.image = new Image(); self.image.onload = resolve; self.image.onerror = reject; self.image.src = "data:image/svg+xml," + (new XMLSerializer()).serializeToString(node); if (self.image.complete === true) { resolve(self.image); } }) : this.hasFabric().then(function() { return new Promise(function(resolve) { html2canvas.fabric.parseSVGDocument(node, self.createCanvas.call(self, resolve)); }); }); } SVGNodeContainer.prototype = Object.create(SVGContainer.prototype); function TextContainer(node, parent) { NodeContainer.call(this, node, parent); } TextContainer.prototype = Object.create(NodeContainer.prototype); TextContainer.prototype.applyTextTransform = function() { this.node.data = this.transform(this.parent.css("textTransform")); }; TextContainer.prototype.transform = function(transform) { var text = this.node.data; switch(transform){ case "lowercase": return text.toLowerCase(); case "capitalize": return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize); case "uppercase": return text.toUpperCase(); default: return text; } }; function capitalize(m, p1, p2) { if (m.length > 0) { return p1 + p2.toUpperCase(); } } function WebkitGradientContainer(imageData) { GradientContainer.apply(this, arguments); this.type = (imageData.args[0] === "linear") ? this.TYPES.LINEAR : this.TYPES.RADIAL; } WebkitGradientContainer.prototype = Object.create(GradientContainer.prototype); function XHR(url) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onload = function() { if (xhr.status === 200) { resolve(xhr.responseText); } else { reject(new Error(xhr.statusText)); } }; xhr.onerror = function() { reject(new Error("Network Error")); }; xhr.send(); }); } function CanvasRenderer(width, height) { Renderer.apply(this, arguments); this.canvas = this.options.canvas || this.document.createElement("canvas"); if (!this.options.canvas) { this.canvas.width = width; this.canvas.height = height; } this.ctx = this.canvas.getContext("2d"); this.taintCtx = this.document.createElement("canvas").getContext("2d"); this.ctx.textBaseline = "bottom"; this.variables = {}; log("Initialized CanvasRenderer with size", width, "x", height); } CanvasRenderer.prototype = Object.create(Renderer.prototype); CanvasRenderer.prototype.setFillStyle = function(fillStyle) { this.ctx.fillStyle = typeof(fillStyle) === "object" && !!fillStyle.isColor ? fillStyle.toString() : fillStyle; return this.ctx; }; CanvasRenderer.prototype.rectangle = function(left, top, width, height, color) { this.setFillStyle(color).fillRect(left, top, width, height); }; CanvasRenderer.prototype.circle = function(left, top, size, color) { this.setFillStyle(color); this.ctx.beginPath(); this.ctx.arc(left + size / 2, top + size / 2, size / 2, 0, Math.PI*2, true); this.ctx.closePath(); this.ctx.fill(); }; CanvasRenderer.prototype.circleStroke = function(left, top, size, color, stroke, strokeColor) { this.circle(left, top, size, color); this.ctx.strokeStyle = strokeColor.toString(); this.ctx.stroke(); }; CanvasRenderer.prototype.drawShape = function(shape, color) { this.shape(shape); this.setFillStyle(color).fill(); }; CanvasRenderer.prototype.taints = function(imageContainer) { if (imageContainer.tainted === null) { this.taintCtx.drawImage(imageContainer.image, 0, 0); try { this.taintCtx.getImageData(0, 0, 1, 1); imageContainer.tainted = false; } catch(e) { this.taintCtx = document.createElement("canvas").getContext("2d"); imageContainer.tainted = true; } } return imageContainer.tainted; }; CanvasRenderer.prototype.drawImage = function(imageContainer, sx, sy, sw, sh, dx, dy, dw, dh) { if (!this.taints(imageContainer) || this.options.allowTaint) { this.ctx.drawImage(imageContainer.image, sx, sy, sw, sh, dx, dy, dw, dh); } }; CanvasRenderer.prototype.clip = function(shapes, callback, context) { this.ctx.save(); shapes.filter(hasEntries).forEach(function(shape) { this.shape(shape).clip(); }, this); callback.call(context); this.ctx.restore(); }; CanvasRenderer.prototype.shape = function(shape) { this.ctx.beginPath(); shape.forEach(function(point, index) { if (point[0] === "rect") { this.ctx.rect.apply(this.ctx, point.slice(1)); } else { this.ctx[(index === 0) ? "moveTo" : point[0] + "To" ].apply(this.ctx, point.slice(1)); } }, this); this.ctx.closePath(); return this.ctx; }; CanvasRenderer.prototype.font = function(color, style, variant, weight, size, family) { this.setFillStyle(color).font = [style, variant, weight, size, family].join(" ").split(",")[0]; }; CanvasRenderer.prototype.fontShadow = function(color, offsetX, offsetY, blur) { this.setVariable("shadowColor", color.toString()) .setVariable("shadowOffsetY", offsetX) .setVariable("shadowOffsetX", offsetY) .setVariable("shadowBlur", blur); }; CanvasRenderer.prototype.clearShadow = function() { this.setVariable("shadowColor", "rgba(0,0,0,0)"); }; CanvasRenderer.prototype.setOpacity = function(opacity) { this.ctx.globalAlpha = opacity; }; CanvasRenderer.prototype.setTransform = function(transform) { this.ctx.translate(transform.origin[0], transform.origin[1]); this.ctx.transform.apply(this.ctx, transform.matrix); this.ctx.translate(-transform.origin[0], -transform.origin[1]); }; CanvasRenderer.prototype.setVariable = function(property, value) { if (this.variables[property] !== value) { this.variables[property] = this.ctx[property] = value; } return this; }; CanvasRenderer.prototype.text = function(text, left, bottom) { this.ctx.fillText(text, left, bottom); }; CanvasRenderer.prototype.backgroundRepeatShape = function(imageContainer, backgroundPosition, size, bounds, left, top, width, height, borderData) { var shape = [ ["line", Math.round(left), Math.round(top)], ["line", Math.round(left + width), Math.round(top)], ["line", Math.round(left + width), Math.round(height + top)], ["line", Math.round(left), Math.round(height + top)] ]; this.clip([shape], function() { this.renderBackgroundRepeat(imageContainer, backgroundPosition, size, bounds, borderData[3], borderData[0]); }, this); }; CanvasRenderer.prototype.renderBackgroundRepeat = function(imageContainer, backgroundPosition, size, bounds, borderLeft, borderTop) { var offsetX = Math.round(bounds.left + backgroundPosition.left + borderLeft), offsetY = Math.round(bounds.top + backgroundPosition.top + borderTop); this.setFillStyle(this.ctx.createPattern(this.resizeImage(imageContainer, size), "repeat")); this.ctx.translate(offsetX, offsetY); this.ctx.fill(); this.ctx.translate(-offsetX, -offsetY); }; CanvasRenderer.prototype.renderBackgroundGradient = function(gradientImage, bounds) { if (gradientImage instanceof LinearGradientContainer) { var gradient = this.ctx.createLinearGradient( bounds.left + bounds.width * gradientImage.x0, bounds.top + bounds.height * gradientImage.y0, bounds.left + bounds.width * gradientImage.x1, bounds.top + bounds.height * gradientImage.y1); gradientImage.colorStops.forEach(function(colorStop) { gradient.addColorStop(colorStop.stop, colorStop.color.toString()); }); this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, gradient); } }; CanvasRenderer.prototype.resizeImage = function(imageContainer, size) { var image = imageContainer.image; if(image.width === size.width && image.height === size.height) { return image; } var ctx, canvas = document.createElement('canvas'); canvas.width = size.width; canvas.height = size.height; ctx = canvas.getContext("2d"); ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height ); return canvas; }; function hasEntries(array) { return array.length > 0; } }).call({}, typeof(window) !== "undefined" ? window : undefined, typeof(document) !== "undefined" ? document : undefined);
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _moment = require('moment'); var _moment2 = _interopRequireDefault(_moment); var _en_US = require('rc-pagination/lib/locale/en_US'); var _en_US2 = _interopRequireDefault(_en_US); var _en_US3 = require('../date-picker/locale/en_US'); var _en_US4 = _interopRequireDefault(_en_US3); var _en_US5 = require('../time-picker/locale/en_US'); var _en_US6 = _interopRequireDefault(_en_US5); var _en_US7 = require('../calendar/locale/en_US'); var _en_US8 = _interopRequireDefault(_en_US7); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } _moment2['default'].locale('en'); exports['default'] = { locale: 'en', Pagination: _en_US2['default'], DatePicker: _en_US4['default'], TimePicker: _en_US6['default'], Calendar: _en_US8['default'], Table: { filterTitle: 'Filter menu', filterConfirm: 'OK', filterReset: 'Reset', emptyText: 'No data', selectAll: 'Select current page', selectInvert: 'Invert current page' }, Modal: { okText: 'OK', cancelText: 'Cancel', justOkText: 'OK' }, Popconfirm: { okText: 'OK', cancelText: 'Cancel' }, Transfer: { notFoundContent: 'Not Found', searchPlaceholder: 'Search here', itemUnit: 'item', itemsUnit: 'items' }, Select: { notFoundContent: 'Not Found' }, Upload: { uploading: 'Uploading...', removeFile: 'Remove file', uploadError: 'Upload error', previewFile: 'Preview file' } }; module.exports = exports['default'];
;(function(){ // CommonJS require() function require(p){ var path = require.resolve(p) , mod = require.modules[path]; if (!mod) throw new Error('failed to require "' + p + '"'); if (!mod.exports) { mod.exports = {}; mod.call(mod.exports, mod, mod.exports, require.relative(path)); } return mod.exports; } require.modules = {}; require.resolve = function (path){ var orig = path , reg = path + '.js' , index = path + '/index.js'; return require.modules[reg] && reg || require.modules[index] && index || orig; }; require.register = function (path, fn){ require.modules[path] = fn; }; require.relative = function (parent) { return function(p){ if ('.' != p.charAt(0)) return require(p); var path = parent.split('/') , segs = p.split('/'); path.pop(); for (var i = 0; i < segs.length; i++) { var seg = segs[i]; if ('..' == seg) path.pop(); else if ('.' != seg) path.push(seg); } return require(path.join('/')); }; }; require.register("browser/debug.js", function(module, exports, require){ module.exports = function(type){ return function(){ } }; }); // module: browser/debug.js require.register("browser/diff.js", function(module, exports, require){ /* See LICENSE file for terms of use */ /* * Text diff implementation. * * This library supports the following APIS: * JsDiff.diffChars: Character by character diff * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace * JsDiff.diffLines: Line based diff * * JsDiff.diffCss: Diff targeted at CSS content * * These methods are based on the implementation proposed in * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 */ var JsDiff = (function() { /*jshint maxparams: 5*/ function clonePath(path) { return { newPos: path.newPos, components: path.components.slice(0) }; } function removeEmpty(array) { var ret = []; for (var i = 0; i < array.length; i++) { if (array[i]) { ret.push(array[i]); } } return ret; } function escapeHTML(s) { var n = s; n = n.replace(/&/g, '&amp;'); n = n.replace(/</g, '&lt;'); n = n.replace(/>/g, '&gt;'); n = n.replace(/"/g, '&quot;'); return n; } var Diff = function(ignoreWhitespace) { this.ignoreWhitespace = ignoreWhitespace; }; Diff.prototype = { diff: function(oldString, newString) { // Handle the identity case (this is due to unrolling editLength == 0 if (newString === oldString) { return [{ value: newString }]; } if (!newString) { return [{ value: oldString, removed: true }]; } if (!oldString) { return [{ value: newString, added: true }]; } newString = this.tokenize(newString); oldString = this.tokenize(oldString); var newLen = newString.length, oldLen = oldString.length; var maxEditLength = newLen + oldLen; var bestPath = [{ newPos: -1, components: [] }]; // Seed editLength = 0 var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) { return bestPath[0].components; } for (var editLength = 1; editLength <= maxEditLength; editLength++) { for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) { var basePath; var addPath = bestPath[diagonalPath-1], removePath = bestPath[diagonalPath+1]; oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; if (addPath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath-1] = undefined; } var canAdd = addPath && addPath.newPos+1 < newLen; var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; if (!canAdd && !canRemove) { bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the new string is the farthest from the origin // and does not pass the bounds of the diff graph if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { basePath = clonePath(removePath); this.pushComponent(basePath.components, oldString[oldPos], undefined, true); } else { basePath = clonePath(addPath); basePath.newPos++; this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined); } var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath); if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) { return basePath.components; } else { bestPath[diagonalPath] = basePath; } } } }, pushComponent: function(components, value, added, removed) { var last = components[components.length-1]; if (last && last.added === added && last.removed === removed) { // We need to clone here as the component clone operation is just // as shallow array clone components[components.length-1] = {value: this.join(last.value, value), added: added, removed: removed }; } else { components.push({value: value, added: added, removed: removed }); } }, extractCommon: function(basePath, newString, oldString, diagonalPath) { var newLen = newString.length, oldLen = oldString.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath; while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) { newPos++; oldPos++; this.pushComponent(basePath.components, newString[newPos], undefined, undefined); } basePath.newPos = newPos; return oldPos; }, equals: function(left, right) { var reWhitespace = /\S/; if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) { return true; } else { return left === right; } }, join: function(left, right) { return left + right; }, tokenize: function(value) { return value; } }; var CharDiff = new Diff(); var WordDiff = new Diff(true); var WordWithSpaceDiff = new Diff(); WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) { return removeEmpty(value.split(/(\s+|\b)/)); }; var CssDiff = new Diff(true); CssDiff.tokenize = function(value) { return removeEmpty(value.split(/([{}:;,]|\s+)/)); }; var LineDiff = new Diff(); LineDiff.tokenize = function(value) { var retLines = [], lines = value.split(/^/m); for(var i = 0; i < lines.length; i++) { var line = lines[i], lastLine = lines[i - 1]; // Merge lines that may contain windows new lines if (line == '\n' && lastLine && lastLine[lastLine.length - 1] === '\r') { retLines[retLines.length - 1] += '\n'; } else if (line) { retLines.push(line); } } return retLines; }; return { Diff: Diff, diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); }, diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); }, diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); }, diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); }, diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); }, createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { var ret = []; ret.push('Index: ' + fileName); ret.push('==================================================================='); ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader)); ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader)); var diff = LineDiff.diff(oldStr, newStr); if (!diff[diff.length-1].value) { diff.pop(); // Remove trailing newline add } diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier function contextLines(lines) { return lines.map(function(entry) { return ' ' + entry; }); } function eofNL(curRange, i, current) { var last = diff[diff.length-2], isLast = i === diff.length-2, isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed); // Figure out if this is the last line for the given file and missing NL if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { curRange.push('\\ No newline at end of file'); } } var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; for (var i = 0; i < diff.length; i++) { var current = diff[i], lines = current.lines || current.value.replace(/\n$/, '').split('\n'); current.lines = lines; if (current.added || current.removed) { if (!oldRangeStart) { var prev = diff[i-1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = contextLines(prev.lines.slice(-4)); oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; })); eofNL(curRange, i, current); if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= 8 && i < diff.length-2) { // Overlapping curRange.push.apply(curRange, contextLines(lines)); } else { // end the range and output var contextSize = Math.min(lines.length, 4); ret.push( '@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize) + ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize) + ' @@'); ret.push.apply(ret, curRange); ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); if (lines.length <= 4) { eofNL(ret, i, current); } oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } } return ret.join('\n') + '\n'; }, applyPatch: function(oldStr, uniDiff) { var diffstr = uniDiff.split('\n'); var diff = []; var remEOFNL = false, addEOFNL = false; for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) { if(diffstr[i][0] === '@') { var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/); diff.unshift({ start:meh[3], oldlength:meh[2], oldlines:[], newlength:meh[4], newlines:[] }); } else if(diffstr[i][0] === '+') { diff[0].newlines.push(diffstr[i].substr(1)); } else if(diffstr[i][0] === '-') { diff[0].oldlines.push(diffstr[i].substr(1)); } else if(diffstr[i][0] === ' ') { diff[0].newlines.push(diffstr[i].substr(1)); diff[0].oldlines.push(diffstr[i].substr(1)); } else if(diffstr[i][0] === '\\') { if (diffstr[i-1][0] === '+') { remEOFNL = true; } else if(diffstr[i-1][0] === '-') { addEOFNL = true; } } } var str = oldStr.split('\n'); for (var i = diff.length - 1; i >= 0; i--) { var d = diff[i]; for (var j = 0; j < d.oldlength; j++) { if(str[d.start-1+j] !== d.oldlines[j]) { return false; } } Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines)); } if (remEOFNL) { while (!str[str.length-1]) { str.pop(); } } else if (addEOFNL) { str.push(''); } return str.join('\n'); }, convertChangesToXML: function(changes){ var ret = []; for ( var i = 0; i < changes.length; i++) { var change = changes[i]; if (change.added) { ret.push('<ins>'); } else if (change.removed) { ret.push('<del>'); } ret.push(escapeHTML(change.value)); if (change.added)
module.exports = require('./lib/knox');
//>>built define("dijit/tree/_dndSelector",["dojo/_base/array","dojo/_base/connect","dojo/_base/declare","dojo/_base/Deferred","dojo/_base/kernel","dojo/_base/lang","dojo/cookie","dojo/mouse","dojo/on","dojo/touch","./_dndContainer"],function(_1,_2,_3,_4,_5,_6,_7,_8,on,_9,_a){ return _3("dijit.tree._dndSelector",_a,{constructor:function(){ this.selection={}; this.anchor=null; if(!this.cookieName&&this.tree.id){ this.cookieName=this.tree.id+"SaveSelectedCookie"; } this.events.push(on(this.tree.domNode,_9.press,_6.hitch(this,"onMouseDown")),on(this.tree.domNode,_9.release,_6.hitch(this,"onMouseUp")),on(this.tree.domNode,_9.move,_6.hitch(this,"onMouseMove"))); },singular:false,getSelectedTreeNodes:function(){ var _b=[],_c=this.selection; for(var i in _c){ _b.push(_c[i]); } return _b; },selectNone:function(){ this.setSelection([]); return this; },destroy:function(){ this.inherited(arguments); this.selection=this.anchor=null; },addTreeNode:function(_d,_e){ this.setSelection(this.getSelectedTreeNodes().concat([_d])); if(_e){ this.anchor=_d; } return _d; },removeTreeNode:function(_f){ this.setSelection(this._setDifference(this.getSelectedTreeNodes(),[_f])); return _f; },isTreeNodeSelected:function(_10){ return _10.id&&!!this.selection[_10.id]; },setSelection:function(_11){ var _12=this.getSelectedTreeNodes(); _1.forEach(this._setDifference(_12,_11),_6.hitch(this,function(_13){ _13.setSelected(false); if(this.anchor==_13){ delete this.anchor; } delete this.selection[_13.id]; })); _1.forEach(this._setDifference(_11,_12),_6.hitch(this,function(_14){ _14.setSelected(true); this.selection[_14.id]=_14; })); this._updateSelectionProperties(); },_setDifference:function(xs,ys){ _1.forEach(ys,function(y){ y.__exclude__=true; }); var ret=_1.filter(xs,function(x){ return !x.__exclude__; }); _1.forEach(ys,function(y){ delete y["__exclude__"]; }); return ret; },_updateSelectionProperties:function(){ var _15=this.getSelectedTreeNodes(); var _16=[],_17=[],_18=[]; _1.forEach(_15,function(_19){ var ary=_19.getTreePath(),_1a=this.tree.model; _17.push(_19); _16.push(ary); ary=_1.map(ary,function(_1b){ return _1a.getIdentity(_1b); },this); _18.push(ary.join("/")); },this); var _1c=_1.map(_17,function(_1d){ return _1d.item; }); this.tree._set("paths",_16); this.tree._set("path",_16[0]||[]); this.tree._set("selectedNodes",_17); this.tree._set("selectedNode",_17[0]||null); this.tree._set("selectedItems",_1c); this.tree._set("selectedItem",_1c[0]||null); if(this.tree.persist&&_18.length>0){ _7(this.cookieName,_18.join(","),{expires:365}); } },_getSavedPaths:function(){ var _1e=this.tree; if(_1e.persist&&_1e.dndController.cookieName){ var _1f,_20=[]; _1f=_7(_1e.dndController.cookieName); if(_1f){ _20=_1.map(_1f.split(","),function(_21){ return _21.split("/"); }); } return _20; } },onMouseDown:function(e){ if(!this.current||this.tree.isExpandoNode(e.target,this.current)){ return; } if(e.type!="touchstart"&&!_8.isLeft(e)){ return; } var _22=this.current,_23=_2.isCopyKey(e),id=_22.id; if(!this.singular&&!e.shiftKey&&this.selection[id]){ this._doDeselect=true; return; }else{ this._doDeselect=false; } this.userSelect(_22,_23,e.shiftKey); },onMouseUp:function(e){ if(!this._doDeselect){ return; } this._doDeselect=false; this.userSelect(this.current,_2.isCopyKey(e),e.shiftKey); },onMouseMove:function(){ this._doDeselect=false; },_compareNodes:function(n1,n2){ if(n1===n2){ return 0; } if("sourceIndex" in document.documentElement){ return n1.sourceIndex-n2.sourceIndex; }else{ if("compareDocumentPosition" in document.documentElement){ return n1.compareDocumentPosition(n2)&2?1:-1; }else{ if(document.createRange){ var r1=doc.createRange(); r1.setStartBefore(n1); var r2=doc.createRange(); r2.setStartBefore(n2); return r1.compareBoundaryPoints(r1.END_TO_END,r2); }else{ throw Error("dijit.tree._compareNodes don't know how to compare two different nodes in this browser"); } } } },userSelect:function(_24,_25,_26){ if(this.singular){ if(this.anchor==_24&&_25){ this.selectNone(); }else{ this.setSelection([_24]); this.anchor=_24; } }else{ if(_26&&this.anchor){ var cr=this._compareNodes(this.anchor.rowNode,_24.rowNode),_27,end,_28=this.anchor; if(cr<0){ _27=_28; end=_24; }else{ _27=_24; end=_28; } var _29=[]; while(_27!=end){ _29.push(_27); _27=this.tree._getNextNode(_27); } _29.push(end); this.setSelection(_29); }else{ if(this.selection[_24.id]&&_25){ this.removeTreeNode(_24); }else{ if(_25){ this.addTreeNode(_24,true); }else{ this.setSelection([_24]); this.anchor=_24; } } } } },getItem:function(key){ var _2a=this.selection[key]; return {data:_2a,type:["treeNode"]}; },forInSelectedItems:function(f,o){ o=o||_5.global; for(var id in this.selection){ f.call(o,this.getItem(id),id,this); } }}); });
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * 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 Ajax.org B.V. 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 AJAX.ORG B.V. 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. * * ***** END LICENSE BLOCK ***** */ define('ace/theme/solarized_dark', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) { exports.isDark = true; exports.cssClass = "ace-solarized-dark"; exports.cssText = ".ace-solarized-dark .ace_editor {\ border: 2px solid rgb(159, 159, 159)\ }\ \ .ace-solarized-dark .ace_editor.ace_focus {\ border: 2px solid #327fbd\ }\ \ .ace-solarized-dark .ace_gutter {\ background: #01313f;\ color: #d0edf7\ }\ \ .ace-solarized-dark .ace_print_margin {\ width: 1px;\ background: #33555E\ }\ \ .ace-solarized-dark .ace_scroller {\ background-color: #002B36\ }\ \ .ace-solarized-dark .ace_entity.ace_other.ace_attribute-name,\ .ace-solarized-dark .ace_storage,\ .ace-solarized-dark .ace_text-layer {\ color: #93A1A1\ }\ \ .ace-solarized-dark .ace_cursor {\ border-left: 2px solid #D30102\ }\ \ .ace-solarized-dark .ace_cursor.ace_overwrite {\ border-left: 0px;\ border-bottom: 1px solid #D30102\ }\ \ .ace-solarized-dark .ace_marker-layer .ace_active_line,\ .ace-solarized-dark .ace_marker-layer .ace_selection {\ background: rgba(255, 255, 255, 0.1)\ }\ \ .ace-solarized-dark.multiselect .ace_selection.start {\ box-shadow: 0 0 3px 0px #002B36;\ border-radius: 2px\ }\ \ .ace-solarized-dark .ace_marker-layer .ace_step {\ background: rgb(102, 82, 0)\ }\ \ .ace-solarized-dark .ace_marker-layer .ace_bracket {\ margin: -1px 0 0 -1px;\ border: 1px solid rgba(147, 161, 161, 0.50)\ }\ \ .ace-solarized-dark .ace_gutter_active_line {\ background-color: #0d3440\ }\ \ .ace-solarized-dark .ace_marker-layer .ace_selected_word {\ border: 1px solid #073642\ }\ \ .ace-solarized-dark .ace_invisible {\ color: rgba(147, 161, 161, 0.50)\ }\ \ .ace-solarized-dark .ace_keyword,\ .ace-solarized-dark .ace_meta,\ .ace-solarized-dark .ace_support.ace_class,\ .ace-solarized-dark .ace_support.ace_type {\ color: #859900\ }\ \ .ace-solarized-dark .ace_constant.ace_character,\ .ace-solarized-dark .ace_constant.ace_other {\ color: #CB4B16\ }\ \ .ace-solarized-dark .ace_constant.ace_language {\ color: #B58900\ }\ \ .ace-solarized-dark .ace_constant.ace_numeric {\ color: #D33682\ }\ \ .ace-solarized-dark .ace_fold {\ background-color: #268BD2;\ border-color: #93A1A1\ }\ \ .ace-solarized-dark .ace_entity.ace_name.ace_function,\ .ace-solarized-dark .ace_entity.ace_name.ace_tag,\ .ace-solarized-dark .ace_support.ace_function,\ .ace-solarized-dark .ace_variable,\ .ace-solarized-dark .ace_variable.ace_language {\ color: #268BD2\ }\ \ .ace-solarized-dark .ace_string {\ color: #2AA198\ }\ \ .ace-solarized-dark .ace_string.ace_regexp {\ color: #D30102\ }\ \ .ace-solarized-dark .ace_comment {\ font-style: italic;\ color: #657B83\ }\ \ .ace-solarized-dark .ace_markup.ace_underline {\ text-decoration: underline\ }\ \ .ace-solarized-dark .ace_indent-guide {\ background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNg0Db7zzBz5sz/AA82BCv7wOIDAAAAAElFTkSuQmCC) right repeat-y\ }"; var dom = require("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
var ContactUs = function () { return { //main function to initiate the module init: function () { var map; $(document).ready(function(){ map = new GMaps({ div: '#map', lat: -13.004333, lng: -38.494333, }); var marker = map.addMarker({ lat: -13.004333, lng: -38.494333, title: 'Loop, Inc.', infoWindow: { content: "<b>Loop, Inc.</b> 795 Park Ave, Suite 120<br>San Francisco, CA 94107" } }); marker.infoWindow.open(map, marker); }); } }; }();
/* My Profile link: https://app.roll20.net/users/262130/dxwarlock GIT link: https://github.com/dxwarlock/Roll20/blob/master/Public/HeathColors Roll20Link: https://app.roll20.net/forum/post/4630083/script-aura-slash-tint-healthcolor Last Updated 2/27/2017 */ /*global createObj getAttrByName spawnFxWithDefinition getObj state playerIsGM sendChat _ findObjs log on*/ var HealthColors = HealthColors || (function() { 'use strict'; var version = '1.2.0', ScriptName = "HealthColors", schemaVersion = '1.0.3', Updated = "Feb 27 2017", /*-------- ON TOKEN UPDATE --------*/ handleToken = function(obj, prev) { var ColorOn = state.HealthColors.auraColorOn; var bar = state.HealthColors.auraBar; var tint = state.HealthColors.auraTint; var onPerc = state.HealthColors.auraPerc; var dead = state.HealthColors.auraDead; if (obj.get("represents") !== "" || (obj.get("represents") == "" && state.HealthColors.OneOff == true)) { if (ColorOn !== true) return; //Check Toggle //ATTRIBUTE CHECK------------ var oCharacter = getObj('character', obj.get("_represents")); if (oCharacter !== undefined) { //SET BLOOD ATTRIB------------ if (getAttrByName(oCharacter.id, 'BLOODCOLOR') === undefined) CreateAttrib(oCharacter, 'BLOODCOLOR', 'DEFAULT'); var Blood = findObjs({name: 'BLOODCOLOR',_type: "attribute",characterid: oCharacter.id}, {caseInsensitive: true})[0]; var UseBlood = Blood.get("current"); UseBlood = UseBlood.toString().toUpperCase(); //SET DISABLED AURA/TINT ATTRIB------------ if (getAttrByName(oCharacter.id, 'USECOLOR') === undefined) CreateAttrib(oCharacter, 'USECOLOR', 'YES'); var UseAuraAtt = findObjs({name: "USECOLOR",_type: "attribute",characterid: oCharacter.id}, {caseInsensitive: true})[0]; var UseAura = UseAuraAtt.get("current"); UseAura = UseAura.toString().toUpperCase(); //DISABLE OR ENABLE AURA/TINT ON TOKEN------------ if (UseAura != "YES" && UseAura != "NO") { UseAuraAtt.set('current', "YES"); var name = oCharacter.get('name'); GMW(name + ": USECOLOR NOT SET TO YES or NO, SETTING TO YES"); } UseAura = UseAuraAtt.get("current").toUpperCase(); if (UseAura == "NO") return; } //CHECK BARS------------ if (obj.get(bar + "_max") === "" || obj.get(bar + "_value") === "") return; var maxValue = parseInt(obj.get(bar + "_max"), 10); var curValue = parseInt(obj.get(bar + "_value"), 10); var prevValue = prev[bar + "_value"]; if (isNaN(maxValue) && isNaN(curValue)) return; //CALC PERCENTAGE------------ var perc = Math.round((curValue / maxValue) * 100); var percReal = Math.min(100, perc); //PERCENTAGE OFF------------ if (percReal > onPerc) { SetAuraNone(obj); return; } //SET DEAD------------ if (curValue <= 0 && dead === true) { obj.set("status_dead", true); SetAuraNone(obj); if (state.HealthColors.auraDeadFX !== "None") PlayDeath(state.HealthColors.auraDeadFX); return; } else if (dead === true) obj.set("status_dead", false); //CHECK MONSTER OR PLAYER------------ var type = (oCharacter === undefined || oCharacter.get("controlledby") === "") ? 'Monster' : 'Player'; //IF PLAYER------------ var GM = '', PC = ''; var markerColor = PercentToRGB(Math.min(100, percReal)); var pColor = '#ffffff'; if (type == 'Player') { if (state.HealthColors.PCAura === false) return; var cBy = oCharacter.get('controlledby'); var player = getObj('player', cBy); pColor = '#000000'; if (player !== undefined) pColor = player.get('color'); GM = state.HealthColors.GM_PCNames; if (GM != 'Off') { GM = (GM == "Yes") ? true : false; obj.set({'showname': GM}); } PC = state.HealthColors.PCNames; if (PC != 'Off') { PC = (PC == "Yes") ? true : false; obj.set({'showplayers_name': PC}); } } //IF MONSTER------------ if (type == 'Monster') { if (state.HealthColors.NPCAura === false) return; GM = state.HealthColors.GM_NPCNames; if (GM != 'Off') { GM = (GM == "Yes") ? true : false; obj.set({'showname': GM}); } PC = state.HealthColors.NPCNames; if (PC != 'Off') { PC = (PC == "Yes") ? true : false; obj.set({'showplayers_name': PC}); } } //SET AURA|TINT------------ if (tint === true) obj.set({'tint_color': markerColor,}); else { TokenSet(obj, state.HealthColors.AuraSize, markerColor, pColor); } //SPURT FX------------ if (state.HealthColors.FX == true && obj.get("layer") == "objects" && UseBlood !== "OFF") { if (curValue == prevValue || prevValue == "") return; var amount = Math.abs(curValue - prevValue); var HitSizeCalc = Math.min((amount / maxValue) * 4, 1); var HitSize = Math.max(HitSizeCalc, 0.2) * (_.random(60, 100) / 100); var HealColor = HEXtoRGB(state.HealthColors.HealFX); var HurtColor = HEXtoRGB(state.HealthColors.HurtFX); if (UseBlood !== "DEFAULT") HurtColor = HEXtoRGB(UseBlood); var size = obj.get("height"); var multi = size / 70; var StartColor; var EndColor; var HITS; if (curValue > prevValue && prevValue !== "") { StartColor = HealColor; EndColor = [255, 255, 255, 0]; HITS = Heal(HitSize, multi, StartColor, EndColor, size); } else { StartColor = HurtColor; EndColor = [0, 0, 0, 0]; HITS = Hurt(HitSize, multi, StartColor, EndColor, size); } spawnFxWithDefinition(obj.get("left"), obj.get("top"), HITS, obj.get("_pageid")); } } }, /*-------- CHAT MESSAGES --------*/ handleInput = function(msg) { var msgFormula = msg.content.split(/\s+/); var command = msgFormula[0].toUpperCase(); if (msg.type == "api" && command.indexOf("!AURA") !== -1) { if (!playerIsGM(msg.playerid)) { sendChat('HealthColors', "/w " + msg.who + " you must be a GM to use this command!"); return; } else { var option = msgFormula[1]; if (option === undefined) { aurahelp(); return; } switch (msgFormula[1].toUpperCase()) { case "ON": state.HealthColors.auraColorOn = !state.HealthColors.auraColorOn; aurahelp(); break; case "BAR": state.HealthColors.auraBar = "bar" + msgFormula[2]; aurahelp(); break; case "TINT": state.HealthColors.auraTint = !state.HealthColors.auraTint; aurahelp(); break; case "PERC": state.HealthColors.auraPerc = parseInt(msgFormula[2], 10); aurahelp(); break; case "PC": state.HealthColors.PCAura = !state.HealthColors.PCAura; aurahelp(); break; case "NPC": state.HealthColors.NPCAura = !state.HealthColors.NPCAura; aurahelp(); break; case "GMNPC": state.HealthColors.GM_NPCNames = msgFormula[2]; aurahelp(); break; case "GMPC": state.HealthColors.GM_PCNames = msgFormula[2]; aurahelp(); break; case "PCNPC": state.HealthColors.NPCNames = msgFormula[2]; aurahelp(); break; case "PCPC": state.HealthColors.PCNames = msgFormula[2]; aurahelp(); break; case "DEAD": state.HealthColors.auraDead = !state.HealthColors.auraDead; aurahelp(); break; case "DEADFX": state.HealthColors.auraDeadFX = msgFormula[2]; aurahelp(); break; case "SIZE": state.HealthColors.AuraSize = parseFloat(msgFormula[2]); aurahelp(); break; case "ONEOFF": state.HealthColors.OneOff = !state.HealthColors.OneOff; aurahelp(); break; case "FX": state.HealthColors.FX = !state.HealthColors.FX; aurahelp(); break; case "HEAL": var UPPER = msgFormula[2]; UPPER = UPPER.toUpperCase(); state.HealthColors.HealFX = UPPER; aurahelp(); break; case "HURT": var UPPER = msgFormula[2]; UPPER = UPPER.toUpperCase(); state.HealthColors.HurtFX = UPPER; aurahelp(); break; default: return; } } } }, /*-------- FUNCTIONS --------*/ //HURT FX---------- Hurt = function(HitSize, multi, StartColor, EndColor, size) { var FX = { "maxParticles": 150, "duration": 70 * HitSize, "size": size / 10 * HitSize, "sizeRandom": 3, "lifeSpan": 25, "lifeSpanRandom": 5, "speed": multi * 8, "speedRandom": multi * 3, "gravity": { "x": multi * 0.01, "y": multi * 0.65 }, "angle": 270, "angleRandom": 25, "emissionRate": 100 * HitSize, "startColour": StartColor, "endColour": EndColor, }; return FX; }, //HEAL FX---------- Heal = function(HitSize, multi, StartColor, EndColor, size) { var FX = { "maxParticles": 150, "duration": 50 * HitSize, "size": size / 10 * HitSize, "sizeRandom": 15 * HitSize, "lifeSpan": multi * 50, "lifeSpanRandom": 30, "speed": multi * 0.5, "speedRandom": multi / 2 * 1.1, "angle": 0, "angleRandom": 180, "emissionRate": 1000, "startColour": StartColor, "endColour": EndColor, }; return FX; }, //WHISPER GM------------ GMW = function(text) { sendChat('HealthColors', "/w GM <br><b> " + text + "</b>"); }, //DEATH SOUND------------ PlayDeath = function(trackname) { var track = findObjs({type: 'jukeboxtrack',title: trackname})[0]; if (track) { track.set('playing', false); track.set('softstop', false); track.set('volume', 50); track.set('playing', true); } else { log("No track found"); } }, //CREATE USECOLOR ATTR------------ CreateAttrib = function(oCharacter, attrib, value) { log("Creating "+ attrib); createObj("attribute", {name: attrib,current: value,characterid: oCharacter.id}); }, //SET TOKEN COLORS------------ TokenSet = function(obj, sizeSet, markerColor, pColor) { var Pageon = getObj("page", obj.get("_pageid")); var scale = Pageon.get("scale_number") / 10; obj.set({ 'aura1_radius': sizeSet * scale * 1.8, 'aura2_radius': sizeSet * scale * 0.1, 'aura1_color': markerColor, 'aura2_color': pColor, 'showplayers_aura1': true, 'showplayers_aura2': true, }); }, //HELP MENU------------ aurahelp = function() { var img = "background-image: -webkit-linear-gradient(-45deg, #a7c7dc 0%,#85b2d3 100%);"; var tshadow = "-1px -1px #000, 1px -1px #000, -1px 1px #000, 1px 1px #000 , 2px 2px #222;"; var style = 'style="padding-top: 1px; text-align:center; font-size: 9pt; width: 45px; height: 14px; border: 1px solid black; margin: 1px; background-color: #6FAEC7;border-radius: 4px; box-shadow: 1px 1px 1px #707070;'; var off = "#A84D4D"; var disable = "#D6D6D6"; var HR = "<hr style='background-color: #000000; margin: 5px; border-width:0;color: #000000;height: 1px;'/>"; var FX = state.HealthColors.auraDeadFX.substring(0, 4); sendChat('HealthColors', "/w GM <b><br>" + '<div style="border-radius: 8px 8px 8px 8px; padding: 5px; font-size: 9pt; text-shadow: ' + tshadow + '; box-shadow: 3px 3px 1px #707070; '+img+' color:#FFF; border:2px solid black; text-align:right; vertical-align:middle;">' + '<u>HealthColors Version: ' + version + '</u><br>' + //-- HR + //-- 'Is On: <a ' + style + 'background-color:' + (state.HealthColors.auraColorOn !== true ? off : "") + ';" href="!aura on">' + (state.HealthColors.auraColorOn !== true ? "No" : "Yes") + '</a><br>' + //-- 'Bar: <a ' + style + '" href="!aura bar ?{Bar|1|2|3}">' + state.HealthColors.auraBar + '</a><br>' + //-- 'Use Tint: <a ' + style + 'background-color:' + (state.HealthColors.auraTint !== true ? off : "") + ';" href="!aura tint">' + (state.HealthColors.auraTint !== true ? "No" : "Yes") + '</a><br>' + //-- 'Percentage: <a ' + style + '" href="!aura perc ?{Percent?|100}">' + state.HealthColors.auraPerc + '</a><br>' + //-- 'Show on PC: <a ' + style + 'background-color:' + (state.HealthColors.PCAura !== true ? off : "") + ';" href="!aura pc">' + (state.HealthColors.PCAura !== true ? "No" : "Yes") + '</a><br>' + //-- 'Show on NPC: <a ' + style + 'background-color:' + (state.HealthColors.NPCAura !== true ? off : "") + ';" href="!aura npc">' + (state.HealthColors.NPCAura !== true ? "No" : "Yes") + '</a><br>' + //-- 'Show Dead: <a ' + style + 'background-color:' + (state.HealthColors.auraDead !== true ? off : "") + ';" href="!aura dead">' + (state.HealthColors.auraDead !== true ? "No" : "Yes") + '</a><br>' + //-- 'DeathSFX: <a ' + style + '" href="!aura deadfx ?{Sound Name?|None}">' + FX + '</a><br>' + //-- HR + //-- 'GM Sees all NPC Names: <a ' + style + 'background-color:' + ButtonColor(state.HealthColors.GM_NPCNames, off, disable) + ';" href="!aura gmnpc ?{Setting|Yes|No|Off}">' + state.HealthColors.GM_NPCNames + '</a><br>' + //--- 'GM Sees all PC Names: <a ' + style + 'background-color:' + ButtonColor(state.HealthColors.GM_PCNames, off, disable) + ';" href="!aura gmpc ?{Setting|Yes|No|Off}">' + state.HealthColors.GM_PCNames + '</a><br>' + //-- HR + //-- 'PC Sees all NPC Names: <a ' + style + 'background-color:' + ButtonColor(state.HealthColors.NPCNames, off, disable) + ';" href="!aura pcnpc ?{Setting|Yes|No|Off}">' + state.HealthColors.NPCNames + '</a><br>' + //-- 'PC Sees all PC Names: <a ' + style + 'background-color:' + ButtonColor(state.HealthColors.PCNames, off, disable) + ';" href="!aura pcpc ?{Setting|Yes|No|Off}">' + state.HealthColors.PCNames + '</a><br>' + //-- HR + //-- 'Aura Size: <a ' + style + '" href="!aura size ?{Size?|0.7}">' + state.HealthColors.AuraSize + '</a><br>' + //-- 'One Offs: <a ' + style + 'background-color:' + (state.HealthColors.OneOff !== true ? off : "") + ';" href="!aura ONEOFF">' + (state.HealthColors.OneOff !== true ? "No" : "Yes") + '</a><br>' + //-- 'FX: <a ' + style + 'background-color:' + (state.HealthColors.FX !== true ? off : "") + ';" href="!aura FX">' + (state.HealthColors.FX !== true ? "No" : "Yes") + '</a><br>' + //-- 'HealFX Color: <a ' + style + 'background-color:#' + state.HealthColors.HealFX + ';""href="!aura HEAL ?{Color?|00FF00}">' + state.HealthColors.HealFX + '</a><br>' + //-- 'HurtFX Color: <a ' + style + 'background-color:#' + state.HealthColors.HurtFX + ';""href="!aura HURT ?{Color?|FF0000}">' + state.HealthColors.HurtFX + '</a><br>' + //-- HR + //-- '</div>'); }, //OFF BUTTON COLORS------------ ButtonColor = function(state, off, disable) { var color; if (state == "No") color = off; if (state == "Off") color = disable; return color; }, //REMOVE ALL------------ SetAuraNone = function(obj) { var tint = state.HealthColors.auraTint; if (tint === true) { obj.set({'tint_color': "transparent",}); } else { obj.set({ 'aura1_color': "", 'aura2_color': "", }); } }, //PERC TO RGB------------ PercentToRGB = function(percent) { if (percent === 100) percent = 99; var r, g, b; if (percent < 50) { g = Math.floor(255 * (percent / 50)); r = 255; } else { g = 255; r = Math.floor(255 * ((50 - percent % 50) / 50)); } b = 0; var Gradient = rgbToHex(r, g, b); return Gradient; }, //RGB TO HEX------------ rgbToHex = function(r, g, b) { var Color = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); return Color; }, //HEX TO RGB------------ HEXtoRGB = function(hex) { let parts = hex.match(/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/); if (parts) { let rgb = _.chain(parts) .rest() .map((d) => parseInt(d, 16)) .value(); rgb.push(1.0); return rgb; } return [0, 0, 0, 1.0]; }, //CHECK INSTALL & SET STATE------------ checkInstall = function() { log('<' + ScriptName + ' v' + version + ' Ready [Updated: '+ Updated+']>'); if (!_.has(state, 'HealthColors') || state.HealthColors.schemaVersion !== schemaVersion) { log('<' + ScriptName + ' Updating Schema to v' + schemaVersion + '>'); state.HealthColors = { schemaVersion: schemaVersion }; state.HealthColors.version = version; } if (_.isUndefined(state.HealthColors.auraColorOn)) state.HealthColors.auraColorOn = true; //global on or off if (_.isUndefined(state.HealthColors.auraBar)) state.HealthColors.auraBar = "bar1"; //bar to use if (_.isUndefined(state.HealthColors.PCAura)) state.HealthColors.PCAura = true; //show players Health? if (_.isUndefined(state.HealthColors.NPCAura)) state.HealthColors.NPCAura = true; //show NPC Health? if (_.isUndefined(state.HealthColors.auraTint)) state.HealthColors.auraTint = false; //use tint instead? if (_.isUndefined(state.HealthColors.auraPerc)) state.HealthColors.auraPerc = 100; //precent to start showing if (_.isUndefined(state.HealthColors.auraDead)) state.HealthColors.auraDead = true; //show dead X status if (_.isUndefined(state.HealthColors.auraDeadFX)) state.HealthColors.auraDeadFX = 'None'; //Sound FX Name if (_.isUndefined(state.HealthColors.GM_NPCNames)) state.HealthColors.GM_NPCNames = "Yes"; //show GM NPC names? if (_.isUndefined(state.HealthColors.NPCNames)) state.HealthColors.NPCNames = "Yes"; //show players NPC Names? if (_.isUndefined(state.HealthColors.GM_PCNames)) state.HealthColors.GM_PCNames = "Yes"; //show GM PC names? if (_.isUndefined(state.HealthColors.PCNames)) state.HealthColors.PCNames = "Yes"; //show players PC Names? if (_.isUndefined(state.HealthColors.AuraSize)) state.HealthColors.AuraSize = 0.7; //set aura size? if (_.isUndefined(state.HealthColors.FX)) state.HealthColors.FX = true; //set FX ON/OFF? if (_.isUndefined(state.HealthColors.HealFX)) state.HealthColors.HealFX = "00FF00"; //set FX HEAL COLOR if (_.isUndefined(state.HealthColors.HurtFX)) state.HealthColors.HurtFX = "FF0000"; //set FX HURT COLOR? }, registerEventHandlers = function() { on('chat:message', handleInput); on("change:token", handleToken); }; /*------------- RETURN OUTSIDE FUNCTIONS -----------*/ return { CheckInstall: checkInstall, RegisterEventHandlers: registerEventHandlers }; }()); //On Ready on('ready', function() { 'use strict'; HealthColors.CheckInstall(); HealthColors.RegisterEventHandlers(); });
describe('paging', function(){ var welcomeHolder = app.PageStore.welcome; var roomsHolder = app.PageStore.rooms; beforeEach(function(){ app.PageStore.welcome = welcomeHolder; app.PageStore.rooms = roomsHolder; }); it('should have a welcome route that invokes a callback', function(){ var counter = 0; app.PageStore.welcome = function(){counter++;}; app.PageActions.navigate({ dest: 'welcome' }); expect(counter).to.equal(1); }); it('should have a rooms route that passes the roomId to a callback', function(){ var id; app.PageStore.rooms = function(roomId){id = roomId;}; app.PageActions.navigate({ dest: 'rooms', props: '0' }); expect(id).to.equal('0'); }); it('should emit events when routing', function(){ var callcount = 0; var callback = function(){callcount++;}; app.PageStore.addChangeListener(callback); app.PageActions.navigate({ dest: 'welcome' }); expect(callcount).to.equal(1); app.PageActions.navigate({ dest: 'rooms' }); expect(callcount).to.equal(2); app.PageStore.removeChangeListener(callback); }); });
/** * * Copyright 2005 Sabre Airline Solutions * * 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. **/ //-------------------- rico.js var Rico = { Version: '1.1.2', prototypeVersion: parseFloat(Prototype.Version.split(".")[0] + "." + Prototype.Version.split(".")[1]) } if((typeof Prototype=='undefined') || Rico.prototypeVersion < 1.3) throw("Rico requires the Prototype JavaScript framework >= 1.3"); Rico.ArrayExtensions = new Array(); if (Object.prototype.extend) { Rico.ArrayExtensions[ Rico.ArrayExtensions.length ] = Object.prototype.extend; }else{ Object.prototype.extend = function(object) { return Object.extend.apply(this, [this, object]); } Rico.ArrayExtensions[ Rico.ArrayExtensions.length ] = Object.prototype.extend; } if (Array.prototype.push) { Rico.ArrayExtensions[ Rico.ArrayExtensions.length ] = Array.prototype.push; } if (!Array.prototype.remove) { Array.prototype.remove = function(dx) { if( isNaN(dx) || dx > this.length ) return false; for( var i=0,n=0; i<this.length; i++ ) if( i != dx ) this[n++]=this[i]; this.length-=1; }; Rico.ArrayExtensions[ Rico.ArrayExtensions.length ] = Array.prototype.remove; } if (!Array.prototype.removeItem) { Array.prototype.removeItem = function(item) { for ( var i = 0 ; i < this.length ; i++ ) if ( this[i] == item ) { this.remove(i); break; } }; Rico.ArrayExtensions[ Rico.ArrayExtensions.length ] = Array.prototype.removeItem; } if (!Array.prototype.indices) { Array.prototype.indices = function() { var indexArray = new Array(); for ( index in this ) { var ignoreThis = false; for ( var i = 0 ; i < Rico.ArrayExtensions.length ; i++ ) { if ( this[index] == Rico.ArrayExtensions[i] ) { ignoreThis = true; break; } } if ( !ignoreThis ) indexArray[ indexArray.length ] = index; } return indexArray; } Rico.ArrayExtensions[ Rico.ArrayExtensions.length ] = Array.prototype.indices; } // Create the loadXML method and xml getter for Mozilla if ( window.DOMParser && window.XMLSerializer && window.Node && Node.prototype && Node.prototype.__defineGetter__ ) { if (!Document.prototype.loadXML) { Document.prototype.loadXML = function (s) { var doc2 = (new DOMParser()).parseFromString(s, "text/xml"); while (this.hasChildNodes()) this.removeChild(this.lastChild); for (var i = 0; i < doc2.childNodes.length; i++) { this.appendChild(this.importNode(doc2.childNodes[i], true)); } }; } Document.prototype.__defineGetter__( "xml", function () { return (new XMLSerializer()).serializeToString(this); } ); } document.getElementsByTagAndClassName = function(tagName, className) { if ( tagName == null ) tagName = '*'; var children = document.getElementsByTagName(tagName) || document.all; var elements = new Array(); if ( className == null ) return children; for (var i = 0; i < children.length; i++) { var child = children[i]; var classNames = child.className.split(' '); for (var j = 0; j < classNames.length; j++) { if (classNames[j] == className) { elements.push(child); break; } } } return elements; } //-------------------- ricoAccordion.js Rico.Accordion = Class.create(); Rico.Accordion.prototype = { initialize: function(container, options) { this.container = $(container); this.lastExpandedTab = null; this.accordionTabs = new Array(); this.setOptions(options); this._attachBehaviors(); if(!container) return; this.container.style.borderBottom = '1px solid ' + this.options.borderColor; // validate onloadShowTab if (this.options.onLoadShowTab >= this.accordionTabs.length) this.options.onLoadShowTab = 0; // set the initial visual state... for ( var i=0 ; i < this.accordionTabs.length ; i++ ) { if (i != this.options.onLoadShowTab){ this.accordionTabs[i].collapse(); this.accordionTabs[i].content.style.display = 'none'; } } this.lastExpandedTab = this.accordionTabs[this.options.onLoadShowTab]; if (this.options.panelHeight == 'auto'){ var tabToCheck = (this.options.onloadShowTab === 0)? 1 : 0; var titleBarSize = parseInt(RicoUtil.getElementsComputedStyle(this.accordionTabs[tabToCheck].titleBar, 'height')); if (isNaN(titleBarSize)) titleBarSize = this.accordionTabs[tabToCheck].titleBar.offsetHeight; var totalTitleBarSize = this.accordionTabs.length * titleBarSize; var parentHeight = parseInt(RicoUtil.getElementsComputedStyle(this.container.parentNode, 'height')); if (isNaN(parentHeight)) parentHeight = this.container.parentNode.offsetHeight; this.options.panelHeight = parentHeight - totalTitleBarSize-2; } this.lastExpandedTab.content.style.height = this.options.panelHeight + "px"; this.lastExpandedTab.showExpanded(); this.lastExpandedTab.titleBar.style.fontWeight = this.options.expandedFontWeight; }, setOptions: function(options) { this.options = { expandedBg : '#545985', hoverBg : '#63699c', collapsedBg : '#6b79a5', expandedTextColor : '#ffffff', expandedFontWeight : 'bold', hoverTextColor : '#ffffff', collapsedTextColor : '#ced7ef', collapsedFontWeight : 'normal', hoverTextColor : '#ffffff', borderColor : '#ffffff', panelHeight : 200, onHideTab : null, onShowTab : null, onLoadShowTab : 0 } Object.extend(this.options, options || {}); }, showTabByIndex: function( anIndex, animate ) { var doAnimate = arguments.length == 1 ? true : animate; this.showTab( this.accordionTabs[anIndex], doAnimate ); }, showTab: function( accordionTab, animate ) { if ( this.lastExpandedTab == accordionTab ) return; var doAnimate = arguments.length == 1 ? true : animate; if ( this.options.onHideTab ) this.options.onHideTab(this.lastExpandedTab); this.lastExpandedTab.showCollapsed(); var accordion = this; var lastExpandedTab = this.lastExpandedTab; this.lastExpandedTab.content.style.height = (this.options.panelHeight - 1) + 'px'; accordionTab.content.style.display = ''; accordionTab.titleBar.style.fontWeight = this.options.expandedFontWeight; if ( doAnimate ) { new Rico.Effect.AccordionSize( this.lastExpandedTab.content, accordionTab.content, 1, this.options.panelHeight, 100, 10, { complete: function() {accordion.showTabDone(lastExpandedTab)} } ); this.lastExpandedTab = accordionTab; } else { this.lastExpandedTab.content.style.height = "1px"; accordionTab.content.style.height = this.options.panelHeight + "px"; this.lastExpandedTab = accordionTab; this.showTabDone(lastExpandedTab); } }, showTabDone: function(collapsedTab) { collapsedTab.content.style.display = 'none'; this.lastExpandedTab.showExpanded(); if ( this.options.onShowTab ) this.options.onShowTab(this.lastExpandedTab); }, _attachBehaviors: function() { var panels = this._getDirectChildrenByTag(this.container, 'DIV'); for ( var i = 0 ; i < panels.length ; i++ ) { var tabChildren = this._getDirectChildrenByTag(panels[i],'DIV'); if ( tabChildren.length != 2 ) continue; // unexpected var tabTitleBar = tabChildren[0]; var tabContentBox = tabChildren[1]; this.accordionTabs.push( new Rico.Accordion.Tab(this,tabTitleBar,tabContentBox) ); } }, _getDirectChildrenByTag: function(e, tagName) { var kids = new Array(); var allKids = e.childNodes; for( var i = 0 ; i < allKids.length ; i++ ) if ( allKids[i] && allKids[i].tagName && allKids[i].tagName == tagName ) kids.push(allKids[i]); return kids; } }; Rico.Accordion.Tab = Class.create(); Rico.Accordion.Tab.prototype = { initialize: function(accordion, titleBar, content) { this.accordion = accordion; this.titleBar = titleBar; this.content = content; this._attachBehaviors(); }, collapse: function() { this.showCollapsed(); this.content.style.height = "1px"; }, showCollapsed: function() { this.expanded = false; this.titleBar.style.backgroundColor = this.accordion.options.collapsedBg; this.titleBar.style.color = this.accordion.options.collapsedTextColor; this.titleBar.style.fontWeight = this.accordion.options.collapsedFontWeight; this.content.style.overflow = "hidden"; }, showExpanded: function() { this.expanded = true; this.titleBar.style.backgroundColor = this.accordion.options.expandedBg; this.titleBar.style.color = this.accordion.options.expandedTextColor; this.content.style.overflow = "auto"; }, titleBarClicked: function(e) { if ( this.accordion.lastExpandedTab == this ) return; this.accordion.showTab(this); }, hover: function(e) { this.titleBar.style.backgroundColor = this.accordion.options.hoverBg; this.titleBar.style.color = this.accordion.options.hoverTextColor; }, unhover: function(e) { if ( this.expanded ) { this.titleBar.style.backgroundColor = this.accordion.options.expandedBg; this.titleBar.style.color = this.accordion.options.expandedTextColor; } else { this.titleBar.style.backgroundColor = this.accordion.options.collapsedBg; this.titleBar.style.color = this.accordion.options.collapsedTextColor; } }, _attachBehaviors: function() { this.content.style.border = "1px solid " + this.accordion.options.borderColor; this.content.style.borderTopWidth = "0px"; this.content.style.borderBottomWidth = "0px"; this.content.style.margin = "0px"; this.titleBar.onclick = this.titleBarClicked.bindAsEventListener(this); this.titleBar.onmouseover = this.hover.bindAsEventListener(this); this.titleBar.onmouseout = this.unhover.bindAsEventListener(this); } }; //-------------------- ricoAjaxEngine.js Rico.AjaxEngine = Class.create(); Rico.AjaxEngine.prototype = { initialize: function() { this.ajaxElements = new Array(); this.ajaxObjects = new Array(); this.requestURLS = new Array(); this.options = {}; }, registerAjaxElement: function( anId, anElement ) { if ( !anElement ) anElement = $(anId); this.ajaxElements[anId] = anElement; }, registerAjaxObject: function( anId, anObject ) { this.ajaxObjects[anId] = anObject; }, registerRequest: function (requestLogicalName, requestURL) { this.requestURLS[requestLogicalName] = requestURL; }, sendRequest: function(requestName, options) { // Allow for backwards Compatibility if ( arguments.length >= 2 ) if (typeof arguments[1] == 'string') options = {parameters: this._createQueryString(arguments, 1)}; this.sendRequestWithData(requestName, null, options); }, sendRequestWithData: function(requestName, xmlDocument, options) { var requestURL = this.requestURLS[requestName]; if ( requestURL == null ) return; // Allow for backwards Compatibility if ( arguments.length >= 3 ) if (typeof arguments[2] == 'string') options.parameters = this._createQueryString(arguments, 2); new Ajax.Request(requestURL, this._requestOptions(options,xmlDocument)); }, sendRequestAndUpdate: function(requestName,container,options) { // Allow for backwards Compatibility if ( arguments.length >= 3 ) if (typeof arguments[2] == 'string') options.parameters = this._createQueryString(arguments, 2); this.sendRequestWithDataAndUpdate(requestName, null, container, options); }, sendRequestWithDataAndUpdate: function(requestName,xmlDocument,container,options) { var requestURL = this.requestURLS[requestName]; if ( requestURL == null ) return; // Allow for backwards Compatibility if ( arguments.length >= 4 ) if (typeof arguments[3] == 'string') options.parameters = this._createQueryString(arguments, 3); var updaterOptions = this._requestOptions(options,xmlDocument); new Ajax.Updater(container, requestURL, updaterOptions); }, // Private -- not part of intended engine API -------------------------------------------------------------------- _requestOptions: function(options,xmlDoc) { var requestHeaders = ['X-Rico-Version', Rico.Version ]; var sendMethod = 'post'; if ( xmlDoc == null ) if (Rico.prototypeVersion < 1.4) requestHeaders.push( 'Content-type', 'text/xml' ); else sendMethod = 'get'; (!options) ? options = {} : ''; if (!options._RicoOptionsProcessed){ // Check and keep any user onComplete functions if (options.onComplete) options.onRicoComplete = options.onComplete; // Fix onComplete if (options.overrideOnComplete) options.onComplete = options.overrideOnComplete; else options.onComplete = this._onRequestComplete.bind(this); options._RicoOptionsProcessed = true; } // Set the default options and extend with any user options this.options = { requestHeaders: requestHeaders, parameters: options.parameters, postBody: xmlDoc, method: sendMethod, onComplete: options.onComplete }; // Set any user options: Object.extend(this.options, options); return this.options; }, _createQueryString: function( theArgs, offset ) { var queryString = "" for ( var i = offset ; i < theArgs.length ; i++ ) { if ( i != offset ) queryString += "&"; var anArg = theArgs[i]; if ( anArg.name != undefined && anArg.value != undefined ) { queryString += anArg.name + "=" + escape(anArg.value); } else { var ePos = anArg.indexOf('='); var argName = anArg.substring( 0, ePos ); var argValue = anArg.substring( ePos + 1 ); queryString += argName + "=" + escape(argValue); } } return queryString; }, _onRequestComplete : function(request) { if(!request) return; // User can set an onFailure option - which will be called by prototype if (request.status != 200) return; var response = request.responseXML.getElementsByTagName("ajax-response"); if (response == null || response.length != 1) return; this._processAjaxResponse( response[0].childNodes ); // Check if user has set a onComplete function var onRicoComplete = this.options.onRicoComplete; if (onRicoComplete != null) onRicoComplete(); }, _processAjaxResponse: function( xmlResponseElements ) { for ( var i = 0 ; i < xmlResponseElements.length ; i++ ) { var responseElement = xmlResponseElements[i]; // only process nodes of type element..... if ( responseElement.nodeType != 1 ) continue; var responseType = responseElement.getAttribute("type"); var responseId = responseElement.getAttribute("id"); if ( responseType == "object" ) this._processAjaxObjectUpdate( this.ajaxObjects[ responseId ], responseElement ); else if ( responseType == "element" ) this._processAjaxElementUpdate( this.ajaxElements[ responseId ], responseElement ); else alert('unrecognized AjaxResponse type : ' + responseType ); } }, _processAjaxObjectUpdate: function( ajaxObject, responseElement ) { ajaxObject.ajaxUpdate( responseElement ); }, _processAjaxElementUpdate: function( ajaxElement, responseElement ) { ajaxElement.innerHTML = RicoUtil.getContentAsString(responseElement); } } var ajaxEngine = new Rico.AjaxEngine(); //-------------------- ricoColor.js Rico.Color = Class.create(); Rico.Color.prototype = { initialize: function(red, green, blue) { this.rgb = { r: red, g : green, b : blue }; }, setRed: function(r) { this.rgb.r = r; }, setGreen: function(g) { this.rgb.g = g; }, setBlue: function(b) { this.rgb.b = b; }, setHue: function(h) { // get an HSB model, and set the new hue... var hsb = this.asHSB(); hsb.h = h; // convert back to RGB... this.rgb = Rico.Color.HSBtoRGB(hsb.h, hsb.s, hsb.b); }, setSaturation: function(s) { // get an HSB model, and set the new hue... var hsb = this.asHSB(); hsb.s = s; // convert back to RGB and set values... this.rgb = Rico.Color.HSBtoRGB(hsb.h, hsb.s, hsb.b); }, setBrightness: function(b) { // get an HSB model, and set the new hue... var hsb = this.asHSB(); hsb.b = b; // convert back to RGB and set values... this.rgb = Rico.Color.HSBtoRGB( hsb.h, hsb.s, hsb.b ); }, darken: function(percent) { var hsb = this.asHSB(); this.rgb = Rico.Color.HSBtoRGB(hsb.h, hsb.s, Math.max(hsb.b - percent,0)); }, brighten: function(percent) { var hsb = this.asHSB(); this.rgb = Rico.Color.HSBtoRGB(hsb.h, hsb.s, Math.min(hsb.b + percent,1)); }, blend: function(other) { this.rgb.r = Math.floor((this.rgb.r + other.rgb.r)/2); this.rgb.g = Math.floor((this.rgb.g + other.rgb.g)/2); this.rgb.b = Math.floor((this.rgb.b + other.rgb.b)/2); }, isBright: function() { var hsb = this.asHSB(); return this.asHSB().b > 0.5; }, isDark: function() { return ! this.isBright(); }, asRGB: function() { return "rgb(" + this.rgb.r + "," + this.rgb.g + "," + this.rgb.b + ")"; }, asHex: function() { return "#" + this.rgb.r.toColorPart() + this.rgb.g.toColorPart() + this.rgb.b.toColorPart(); }, asHSB: function() { return Rico.Color.RGBtoHSB(this.rgb.r, this.rgb.g, this.rgb.b); }, toString: function() { return this.asHex(); } }; Rico.Color.createFromHex = function(hexCode) { if(hexCode.length==4) { var shortHexCode = hexCode; var hexCode = '#'; for(var i=1;i<4;i++) hexCode += (shortHexCode.charAt(i) + shortHexCode.charAt(i)); } if ( hexCode.indexOf('#') == 0 ) hexCode = hexCode.substring(1); var red = hexCode.substring(0,2); var green = hexCode.substring(2,4); var blue = hexCode.substring(4,6); return new Rico.Color( parseInt(red,16), parseInt(green,16), parseInt(blue,16) ); } /** * Factory method for creating a color from the background of * an HTML element. */ Rico.Color.createColorFromBackground = function(elem) { var actualColor = RicoUtil.getElementsComputedStyle($(elem), "backgroundColor", "background-color"); if ( actualColor == "transparent" && elem.parentNode ) return Rico.Color.createColorFromBackground(elem.parentNode); if ( actualColor == null ) return new Rico.Color(255,255,255); if ( actualColor.indexOf("rgb(") == 0 ) { var colors = actualColor.substring(4, actualColor.length - 1 ); var colorArray = colors.split(","); return new Rico.Color( parseInt( colorArray[0] ), parseInt( colorArray[1] ), parseInt( colorArray[2] ) ); } else if ( actualColor.indexOf("#") == 0 ) { return Rico.Color.createFromHex(actualColor); } else return new Rico.Color(255,255,255); } Rico.Color.HSBtoRGB = function(hue, saturation, brightness) { var red = 0; var green = 0; var blue = 0; if (saturation == 0) { red = parseInt(brightness * 255.0 + 0.5); green = red; blue = red; } else { var h = (hue - Math.floor(hue)) * 6.0; var f = h - Math.floor(h); var p = brightness * (1.0 - saturation); var q = brightness * (1.0 - saturation * f); var t = brightness * (1.0 - (saturation * (1.0 - f))); switch (parseInt(h)) { case 0: red = (brightness * 255.0 + 0.5); green = (t * 255.0 + 0.5); blue = (p * 255.0 + 0.5); break; case 1: red = (q * 255.0 + 0.5); green = (brightness * 255.0 + 0.5); blue = (p * 255.0 + 0.5); break; case 2: red = (p * 255.0 + 0.5); green = (brightness * 255.0 + 0.5); blue = (t * 255.0 + 0.5); break; case 3: red = (p * 255.0 + 0.5); green = (q * 255.0 + 0.5); blue = (brightness * 255.0 + 0.5); break; case 4: red = (t * 255.0 + 0.5); green = (p * 255.0 + 0.5); blue = (brightness * 255.0 + 0.5); break; case 5: red = (brightness * 255.0 + 0.5); green = (p * 255.0 + 0.5); blue = (q * 255.0 + 0.5); break; } } return { r : parseInt(red), g : parseInt(green) , b : parseInt(blue) }; } Rico.Color.RGBtoHSB = function(r, g, b) { var hue; var saturation; var brightness; var cmax = (r > g) ? r : g; if (b > cmax) cmax = b; var cmin = (r < g) ? r : g; if (b < cmin) cmin = b; brightness = cmax / 255.0; if (cmax != 0) saturation = (cmax - cmin)/cmax; else saturation = 0; if (saturation == 0) hue = 0; else { var redc = (cmax - r)/(cmax - cmin); var greenc = (cmax - g)/(cmax - cmin); var bluec = (cmax - b)/(cmax - cmin); if (r == cmax) hue = bluec - greenc; else if (g == cmax) hue = 2.0 + redc - bluec; else hue = 4.0 + greenc - redc; hue = hue / 6.0; if (hue < 0) hue = hue + 1.0; } return { h : hue, s : saturation, b : brightness }; } //-------------------- ricoCorner.js Rico.Corner = { round: function(e, options) { var e = $(e); this._setOptions(options); var color = this.options.color; if ( this.options.color == "fromElement" ) color = this._background(e); var bgColor = this.options.bgColor; if ( this.options.bgColor == "fromParent" ) bgColor = this._background(e.offsetParent); this._roundCornersImpl(e, color, bgColor); }, _roundCornersImpl: function(e, color, bgColor) { if(this.options.border) this._renderBorder(e,bgColor); if(this._isTopRounded()) this._roundTopCorners(e,color,bgColor); if(this._isBottomRounded()) this._roundBottomCorners(e,color,bgColor); }, _renderBorder: function(el,bgColor) { var borderValue = "1px solid " + this._borderColor(bgColor); var borderL = "border-left: " + borderValue; var borderR = "border-right: " + borderValue; var style = "style='" + borderL + ";" + borderR + "'"; el.innerHTML = "<div " + style + ">" + el.innerHTML + "</div>" }, _roundTopCorners: function(el, color, bgColor) { var corner = this._createCorner(bgColor); for(var i=0 ; i < this.options.numSlices ; i++ ) corner.appendChild(this._createCornerSlice(color,bgColor,i,"top")); el.style.paddingTop = 0; el.insertBefore(corner,el.firstChild); }, _roundBottomCorners: function(el, color, bgColor) { var corner = this._createCorner(bgColor); for(var i=(this.options.numSlices-1) ; i >= 0 ; i-- ) corner.appendChild(this._createCornerSlice(color,bgColor,i,"bottom")); el.style.paddingBottom = 0; el.appendChild(corner); }, _createCorner: function(bgColor) { var corner = document.createElement("div"); corner.style.backgroundColor = (this._isTransparent() ? "transparent" : bgColor); return corner; }, _createCornerSlice: function(color,bgColor, n, position) { var slice = document.createElement("span"); var inStyle = slice.style; inStyle.backgroundColor = color; inStyle.display = "block"; inStyle.height = "1px"; inStyle.overflow = "hidden"; inStyle.fontSize = "1px"; var borderColor = this._borderColor(color,bgColor); if ( this.options.border && n == 0 ) { inStyle.borderTopStyle = "solid"; inStyle.borderTopWidth = "1px"; inStyle.borderLeftWidth = "0px"; inStyle.borderRightWidth = "0px"; inStyle.borderBottomWidth = "0px"; inStyle.height = "0px"; // assumes css compliant box model inStyle.borderColor = borderColor; } else if(borderColor) { inStyle.borderColor = borderColor; inStyle.borderStyle = "solid"; inStyle.borderWidth = "0px 1px"; } if ( !this.options.compact && (n == (this.options.numSlices-1)) ) inStyle.height = "2px"; this._setMargin(slice, n, position); this._setBorder(slice, n, position); return slice; }, _setOptions: function(options) { this.options = { corners : "all", color : "fromElement", bgColor : "fromParent", blend : true, border : false, compact : false } Object.extend(this.options, options || {}); this.options.numSlices = this.options.compact ? 2 : 4; if ( this._isTransparent() ) this.options.blend = false; }, _whichSideTop: function() { if ( this._hasString(this.options.corners, "all", "top") ) return ""; if ( this.options.corners.indexOf("tl") >= 0 && this.options.corners.indexOf("tr") >= 0 ) return ""; if (this.options.corners.indexOf("tl") >= 0) return "left"; else if (this.options.corners.indexOf("tr") >= 0) return "right"; return ""; }, _whichSideBottom: function() { if ( this._hasString(this.options.corners, "all", "bottom") ) return ""; if ( this.options.corners.indexOf("bl")>=0 && this.options.corners.indexOf("br")>=0 ) return ""; if(this.options.corners.indexOf("bl") >=0) return "left"; else if(this.options.corners.indexOf("br")>=0) return "right"; return ""; }, _borderColor : function(color,bgColor) { if ( color == "transparent" ) return bgColor; else if ( this.options.border ) return this.options.border; else if ( this.options.blend ) return this._blend( bgColor, color ); else return ""; }, _setMargin: function(el, n, corners) { var marginSize = this._marginSize(n); var whichSide = corners == "top" ? this._whichSideTop() : this._whichSideBottom(); if ( whichSide == "left" ) { el.style.marginLeft = marginSize + "px"; el.style.marginRight = "0px"; } else if ( whichSide == "right" ) { el.style.marginRight = marginSize + "px"; el.style.marginLeft = "0px"; } else { el.style.marginLeft = marginSize + "px"; el.style.marginRight = marginSize + "px"; } }, _setBorder: function(el,n,corners) { var borderSize = this._borderSize(n); var whichSide = corners == "top" ? this._whichSideTop() : this._whichSideBottom(); if ( whichSide == "left" ) { el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = "0px"; } else if ( whichSide == "right" ) { el.style.borderRightWidth = borderSize + "px"; el.style.borderLeftWidth = "0px"; } else { el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = borderSize + "px"; } if (this.options.border != false) el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = borderSize + "px"; }, _marginSize: function(n) { if ( this._isTransparent() ) return 0; var marginSizes = [ 5, 3, 2, 1 ]; var blendedMarginSizes = [ 3, 2, 1, 0 ]; var compactMarginSizes = [ 2, 1 ]; var smBlendedMarginSizes = [ 1, 0 ]; if ( this.options.compact && this.options.blend ) return smBlendedMarginSizes[n]; else if ( this.options.compact ) return compactMarginSizes[n]; else if ( this.options.blend ) return blendedMarginSizes[n]; else return marginSizes[n]; }, _borderSize: function(n) { var transparentBorderSizes = [ 5, 3, 2, 1 ]; var blendedBorderSizes = [ 2, 1, 1, 1 ]; var compactBorderSizes = [ 1, 0 ]; var actualBorderSizes = [ 0, 2, 0, 0 ]; if ( this.options.compact && (this.options.blend || this._isTransparent()) ) return 1; else if ( this.options.compact ) return compactBorderSizes[n]; else if ( this.options.blend ) return blendedBorderSizes[n]; else if ( this.options.border ) return actualBorderSizes[n]; else if ( this._isTransparent() ) return transparentBorderSizes[n]; return 0; }, _hasString: function(str) { for(var i=1 ; i<arguments.length ; i++) if (str.indexOf(arguments[i]) >= 0) return true; return false; }, _blend: function(c1, c2) { var cc1 = Rico.Color.createFromHex(c1); cc1.blend(Rico.Color.createFromHex(c2)); return cc1; }, _background: function(el) { try { return Rico.Color.createColorFromBackground(el).asHex(); } catch(err) { return "#ffffff"; } }, _isTransparent: function() { return this.options.color == "transparent"; }, _isTopRounded: function() { return this._hasString(this.options.corners, "all", "top", "tl", "tr"); }, _isBottomRounded: function() { return this._hasString(this.options.corners, "all", "bottom", "bl", "br"); }, _hasSingleTextChild: function(el) { return el.childNodes.length == 1 && el.childNodes[0].nodeType == 3; } } //-------------------- ricoDragAndDrop.js Rico.DragAndDrop = Class.create(); Rico.DragAndDrop.prototype = { initialize: function() { this.dropZones = new Array(); this.draggables = new Array(); this.currentDragObjects = new Array(); this.dragElement = null; this.lastSelectedDraggable = null; this.currentDragObjectVisible = false; this.interestedInMotionEvents = false; this._mouseDown = this._mouseDownHandler.bindAsEventListener(this); this._mouseMove = this._mouseMoveHandler.bindAsEventListener(this); this._mouseUp = this._mouseUpHandler.bindAsEventListener(this); }, registerDropZone: function(aDropZone) { this.dropZones[ this.dropZones.length ] = aDropZone; }, deregisterDropZone: function(aDropZone) { var newDropZones = new Array(); var j = 0; for ( var i = 0 ; i < this.dropZones.length ; i++ ) { if ( this.dropZones[i] != aDropZone ) newDropZones[j++] = this.dropZones[i]; } this.dropZones = newDropZones; }, clearDropZones: function() { this.dropZones = new Array(); }, registerDraggable: function( aDraggable ) { this.draggables[ this.draggables.length ] = aDraggable; this._addMouseDownHandler( aDraggable ); }, clearSelection: function() { for ( var i = 0 ; i < this.currentDragObjects.length ; i++ ) this.currentDragObjects[i].deselect(); this.currentDragObjects = new Array(); this.lastSelectedDraggable = null; }, hasSelection: function() { return this.currentDragObjects.length > 0; }, setStartDragFromElement: function( e, mouseDownElement ) { this.origPos = RicoUtil.toDocumentPosition(mouseDownElement); this.startx = e.screenX - this.origPos.x this.starty = e.screenY - this.origPos.y //this.startComponentX = e.layerX ? e.layerX : e.offsetX; //this.startComponentY = e.layerY ? e.layerY : e.offsetY; //this.adjustedForDraggableSize = false; this.interestedInMotionEvents = this.hasSelection(); this._terminateEvent(e); }, updateSelection: function( draggable, extendSelection ) { if ( ! extendSelection ) this.clearSelection(); if ( draggable.isSelected() ) { this.currentDragObjects.removeItem(draggable); draggable.deselect(); if ( draggable == this.lastSelectedDraggable ) this.lastSelectedDraggable = null; } else { this.currentDragObjects[ this.currentDragObjects.length ] = draggable; draggable.select(); this.lastSelectedDraggable = draggable; } }, _mouseDownHandler: function(e) { if ( arguments.length == 0 ) e = event; // if not button 1 ignore it... var nsEvent = e.which != undefined; if ( (nsEvent && e.which != 1) || (!nsEvent && e.button != 1)) return; var eventTarget = e.target ? e.target : e.srcElement; var draggableObject = eventTarget.draggable; var candidate = eventTarget; while (draggableObject == null && candidate.parentNode) { candidate = candidate.parentNode; draggableObject = candidate.draggable; } if ( draggableObject == null ) return; this.updateSelection( draggableObject, e.ctrlKey ); // clear the drop zones postion cache... if ( this.hasSelection() ) for ( var i = 0 ; i < this.dropZones.length ; i++ ) this.dropZones[i].clearPositionCache(); this.setStartDragFromElement( e, draggableObject.getMouseDownHTMLElement() ); }, _mouseMoveHandler: function(e) { var nsEvent = e.which != undefined; if ( !this.interestedInMotionEvents ) { //this._terminateEvent(e); return; } if ( ! this.hasSelection() ) return; if ( ! this.currentDragObjectVisible ) this._startDrag(e); if ( !this.activatedDropZones ) this._activateRegisteredDropZones(); //if ( !this.adjustedForDraggableSize ) // this._adjustForDraggableSize(e); this._updateDraggableLocation(e); this._updateDropZonesHover(e); this._terminateEvent(e); }, _makeDraggableObjectVisible: function(e) { if ( !this.hasSelection() ) return; var dragElement; if ( this.currentDragObjects.length > 1 ) dragElement = this.currentDragObjects[0].getMultiObjectDragGUI(this.currentDragObjects); else dragElement = this.currentDragObjects[0].getSingleObjectDragGUI(); // go ahead and absolute position it... if ( RicoUtil.getElementsComputedStyle(dragElement, "position") != "absolute" ) dragElement.style.position = "absolute"; // need to parent him into the document... if ( dragElement.parentNode == null || dragElement.parentNode.nodeType == 11 ) document.body.appendChild(dragElement); this.dragElement = dragElement; this._updateDraggableLocation(e); this.currentDragObjectVisible = true; }, /** _adjustForDraggableSize: function(e) { var dragElementWidth = this.dragElement.offsetWidth; var dragElementHeight = this.dragElement.offsetHeight; if ( this.startComponentX > dragElementWidth ) this.startx -= this.startComponentX - dragElementWidth + 2; if ( e.offsetY ) { if ( this.startComponentY > dragElementHeight ) this.starty -= this.startComponentY - dragElementHeight + 2; } this.adjustedForDraggableSize = true; }, **/ _leftOffset: function(e) { return e.offsetX ? document.body.scrollLeft : 0 }, _topOffset: function(e) { return e.offsetY ? document.body.scrollTop:0 }, _updateDraggableLocation: function(e) { var dragObjectStyle = this.dragElement.style; dragObjectStyle.left = (e.screenX + this._leftOffset(e) - this.startx) + "px" dragObjectStyle.top = (e.screenY + this._topOffset(e) - this.starty) + "px"; }, _updateDropZonesHover: function(e) { var n = this.dropZones.length; for ( var i = 0 ; i < n ; i++ ) { if ( ! this._mousePointInDropZone( e, this.dropZones[i] ) ) this.dropZones[i].hideHover(); } for ( var i = 0 ; i < n ; i++ ) { if ( this._mousePointInDropZone( e, this.dropZones[i] ) ) { if ( this.dropZones[i].canAccept(this.currentDragObjects) ) this.dropZones[i].showHover(); } } }, _startDrag: function(e) { for ( var i = 0 ; i < this.currentDragObjects.length ; i++ ) this.currentDragObjects[i].startDrag(); this._makeDraggableObjectVisible(e); }, _mouseUpHandler: function(e) { if ( ! this.hasSelection() ) return; var nsEvent = e.which != undefined; if ( (nsEvent && e.which != 1) || (!nsEvent && e.button != 1)) return; this.interestedInMotionEvents = false; if ( this.dragElement == null ) { this._terminateEvent(e); return; } if ( this._placeDraggableInDropZone(e) ) this._completeDropOperation(e); else { this._terminateEvent(e); new Rico.Effect.Position( this.dragElement, this.origPos.x, this.origPos.y, 200, 20, { complete : this._doCancelDragProcessing.bind(this) } ); } Event.stopObserving(document.body, "mousemove", this._mouseMove); Event.stopObserving(document.body, "mouseup", this._mouseUp); }, _retTrue: function () { return true; }, _completeDropOperation: function(e) { if ( this.dragElement != this.currentDragObjects[0].getMouseDownHTMLElement() ) { if ( this.dragElement.parentNode != null ) this.dragElement.parentNode.removeChild(this.dragElement); } this._deactivateRegisteredDropZones(); this._endDrag(); this.clearSelection(); this.dragElement = null; this.currentDragObjectVisible = false; this._terminateEvent(e); }, _doCancelDragProcessing: function() { this._cancelDrag(); if ( this.dragElement != this.currentDragObjects[0].getMouseDownHTMLElement() && this.dragElement) if ( this.dragElement.parentNode != null ) this.dragElement.parentNode.removeChild(this.dragElement); this._deactivateRegisteredDropZones(); this.dragElement = null; this.currentDragObjectVisible = false; }, _placeDraggableInDropZone: function(e) { var foundDropZone = false; var n = this.dropZones.length; for ( var i = 0 ; i < n ; i++ ) { if ( this._mousePointInDropZone( e, this.dropZones[i] ) ) { if ( this.dropZones[i].canAccept(this.currentDragObjects) ) { this.dropZones[i].hideHover(); this.dropZones[i].accept(this.currentDragObjects); foundDropZone = true; break; } } } return foundDropZone; }, _cancelDrag: function() { for ( var i = 0 ; i < this.currentDragObjects.length ; i++ ) this.currentDragObjects[i].cancelDrag(); }, _endDrag: function() { for ( var i = 0 ; i < this.currentDragObjects.length ; i++ ) this.currentDragObjects[i].endDrag(); }, _mousePointInDropZone: function( e, dropZone ) { var absoluteRect = dropZone.getAbsoluteRect(); return e.clientX > absoluteRect.left + this._leftOffset(e) && e.clientX < absoluteRect.right + this._leftOffset(e) && e.clientY > absoluteRect.top + this._topOffset(e) && e.clientY < absoluteRect.bottom + this._topOffset(e); }, _addMouseDownHandler: function( aDraggable ) { htmlElement = aDraggable.getMouseDownHTMLElement(); if ( htmlElement != null ) { htmlElement.draggable = aDraggable; Event.observe(htmlElement , "mousedown", this._onmousedown.bindAsEventListener(this)); Event.observe(htmlElement, "mousedown", this._mouseDown); } }, _activateRegisteredDropZones: function() { var n = this.dropZones.length; for ( var i = 0 ; i < n ; i++ ) { var dropZone = this.dropZones[i]; if ( dropZone.canAccept(this.currentDragObjects) ) dropZone.activate(); } this.activatedDropZones = true; }, _deactivateRegisteredDropZones: function() { var n = this.dropZones.length; for ( var i = 0 ; i < n ; i++ ) this.dropZones[i].deactivate(); this.activatedDropZones = false; }, _onmousedown: function () { Event.observe(document.body, "mousemove", this._mouseMove); Event.observe(document.body, "mouseup", this._mouseUp); }, _terminateEvent: function(e) { if ( e.stopPropagation != undefined ) e.stopPropagation(); else if ( e.cancelBubble != undefined ) e.cancelBubble = true; if ( e.preventDefault != undefined ) e.preventDefault(); else e.returnValue = false; }, initializeEventHandlers: function() { if ( typeof document.implementation != "undefined" && document.implementation.hasFeature("HTML", "1.0") && document.implementation.hasFeature("Events", "2.0") && document.implementation.hasFeature("CSS", "2.0") ) { document.addEventListener("mouseup", this._mouseUpHandler.bindAsEventListener(this), false); document.addEventListener("mousemove", this._mouseMoveHandler.bindAsEventListener(this), false); } else { document.attachEvent( "onmouseup", this._mouseUpHandler.bindAsEventListener(this) ); document.attachEvent( "onmousemove", this._mouseMoveHandler.bindAsEventListener(this) ); } } } var dndMgr = new Rico.DragAndDrop(); dndMgr.initializeEventHandlers(); //-------------------- ricoDraggable.js Rico.Draggable = Class.create(); Rico.Draggable.prototype = { initialize: function( type, htmlElement ) { this.type = type; this.htmlElement = $(htmlElement); this.selected = false; }, /** * Returns the HTML element that should have a mouse down event * added to it in order to initiate a drag operation * **/ getMouseDownHTMLElement: function() { return this.htmlElement; }, select: function() { this.selected = true; if ( this.showingSelected ) return; var htmlElement = this.getMouseDownHTMLElement(); var color = Rico.Color.createColorFromBackground(htmlElement); color.isBright() ? color.darken(0.033) : color.brighten(0.033); this.saveBackground = RicoUtil.getElementsComputedStyle(htmlElement, "backgroundColor", "background-color"); htmlElement.style.backgroundColor = color.asHex(); this.showingSelected = true; }, deselect: function() { this.selected = false; if ( !this.showingSelected ) return; var htmlElement = this.getMouseDownHTMLElement(); htmlElement.style.backgroundColor = this.saveBackground; this.showingSelected = false; }, isSelected: function() { return this.selected; }, startDrag: function() { }, cancelDrag: function() { }, endDrag: function() { }, getSingleObjectDragGUI: function() { return this.htmlElement; }, getMultiObjectDragGUI: function( draggables ) { return this.htmlElement; }, getDroppedGUI: function() { return this.htmlElement; }, toString: function() { return this.type + ":" + this.htmlElement + ":"; } } //-------------------- ricoDropzone.js Rico.Dropzone = Class.create(); Rico.Dropzone.prototype = { initialize: function( htmlElement ) { this.htmlElement = $(htmlElement); this.absoluteRect = null; }, getHTMLElement: function() { return this.htmlElement; }, clearPositionCache: function() { this.absoluteRect = null; }, getAbsoluteRect: function() { if ( this.absoluteRect == null ) { var htmlElement = this.getHTMLElement(); var pos = RicoUtil.toViewportPosition(htmlElement); this.absoluteRect = { top: pos.y, left: pos.x, bottom: pos.y + htmlElement.offsetHeight, right: pos.x + htmlElement.offsetWidth }; } return this.absoluteRect; }, activate: function() { var htmlElement = this.getHTMLElement(); if (htmlElement == null || this.showingActive) return; this.showingActive = true; this.saveBackgroundColor = htmlElement.style.backgroundColor; var fallbackColor = "#ffea84"; var currentColor = Rico.Color.createColorFromBackground(htmlElement); if ( currentColor == null ) htmlElement.style.backgroundColor = fallbackColor; else { currentColor.isBright() ? currentColor.darken(0.2) : currentColor.brighten(0.2); htmlElement.style.backgroundColor = currentColor.asHex(); } }, deactivate: function() { var htmlElement = this.getHTMLElement(); if (htmlElement == null || !this.showingActive) return; htmlElement.style.backgroundColor = this.saveBackgroundColor; this.showingActive = false; this.saveBackgroundColor = null; }, showHover: function() { var htmlElement = this.getHTMLElement(); if ( htmlElement == null || this.showingHover ) return; this.saveBorderWidth = htmlElement.style.borderWidth; this.saveBorderStyle = htmlElement.style.borderStyle; this.saveBorderColor = htmlElement.style.borderColor; this.showingHover = true; htmlElement.style.borderWidth = "1px"; htmlElement.style.borderStyle = "solid"; //htmlElement.style.borderColor = "#ff9900"; htmlElement.style.borderColor = "#ffff00"; }, hideHover: function() { var htmlElement = this.getHTMLElement(); if ( htmlElement == null || !this.showingHover ) return; htmlElement.style.borderWidth = this.saveBorderWidth; htmlElement.style.borderStyle = this.saveBorderStyle; htmlElement.style.borderColor = this.saveBorderColor; this.showingHover = false; }, canAccept: function(draggableObjects) { return true; }, accept: function(draggableObjects) { var htmlElement = this.getHTMLElement(); if ( htmlElement == null ) return; n = draggableObjects.length; for ( var i = 0 ; i < n ; i++ ) { var theGUI = draggableObjects[i].getDroppedGUI(); if ( RicoUtil.getElementsComputedStyle( theGUI, "position" ) == "absolute" ) { theGUI.style.position = "static"; theGUI.style.top = ""; theGUI.style.top = ""; } htmlElement.appendChild(theGUI); } } } //-------------------- ricoEffects.js Rico.Effect = {}; Rico.Effect.SizeAndPosition = Class.create(); Rico.Effect.SizeAndPosition.prototype = { initialize: function(element, x, y, w, h, duration, steps, options) { this.element = $(element); this.x = x; this.y = y; this.w = w; this.h = h; this.duration = duration; this.steps = steps; this.options = arguments[7] || {}; this.sizeAndPosition(); }, sizeAndPosition: function() { if (this.isFinished()) { if(this.options.complete) this.options.complete(this); return; } if (this.timer) clearTimeout(this.timer); var stepDuration = Math.round(this.duration/this.steps) ; // Get original values: x,y = top left corner; w,h = width height var currentX = this.element.offsetLeft; var currentY = this.element.offsetTop; var currentW = this.element.offsetWidth; var currentH = this.element.offsetHeight; // If values not set, or zero, we do not modify them, and take original as final as well this.x = (this.x) ? this.x : currentX; this.y = (this.y) ? this.y : currentY; this.w = (this.w) ? this.w : currentW; this.h = (this.h) ? this.h : currentH; // how much do we need to modify our values for each step? var difX = this.steps > 0 ? (this.x - currentX)/this.steps : 0; var difY = this.steps > 0 ? (this.y - currentY)/this.steps : 0; var difW = this.steps > 0 ? (this.w - currentW)/this.steps : 0; var difH = this.steps > 0 ? (this.h - currentH)/this.steps : 0; this.moveBy(difX, difY); this.resizeBy(difW, difH); this.duration -= stepDuration; this.steps--; this.timer = setTimeout(this.sizeAndPosition.bind(this), stepDuration); }, isFinished: function() { return this.steps <= 0; }, moveBy: function( difX, difY ) { var currentLeft = this.element.offsetLeft; var currentTop = this.element.offsetTop; var intDifX = parseInt(difX); var intDifY = parseInt(difY); var style = this.element.style; if ( intDifX != 0 ) style.left = (currentLeft + intDifX) + "px"; if ( intDifY != 0 ) style.top = (currentTop + intDifY) + "px"; }, resizeBy: function( difW, difH ) { var currentWidth = this.element.offsetWidth; var currentHeight = this.element.offsetHeight; var intDifW = parseInt(difW); var intDifH = parseInt(difH); var style = this.element.style; if ( intDifW != 0 ) style.width = (currentWidth + intDifW) + "px"; if ( intDifH != 0 ) style.height = (currentHeight + intDifH) + "px"; } } Rico.Effect.Size = Class.create(); Rico.Effect.Size.prototype = { initialize: function(element, w, h, duration, steps, options) { new Rico.Effect.SizeAndPosition(element, null, null, w, h, duration, steps, options); } } Rico.Effect.Position = Class.create(); Rico.Effect.Position.prototype = { initialize: function(element, x, y, duration, steps, options) { new Rico.Effect.SizeAndPosition(element, x, y, null, null, duration, steps, options); } } Rico.Effect.Round = Class.create(); Rico.Effect.Round.prototype = { initialize: function(tagName, className, options) { var elements = document.getElementsByTagAndClassName(tagName,className); for ( var i = 0 ; i < elements.length ; i++ ) Rico.Corner.round( elements[i], options ); } }; Rico.Effect.FadeTo = Class.create(); Rico.Effect.FadeTo.prototype = { initialize: function( element, opacity, duration, steps, options) { this.element = $(element); this.opacity = opacity; this.duration = duration; this.steps = steps; this.options = arguments[4] || {}; this.fadeTo(); }, fadeTo: function() { if (this.isFinished()) { if(this.options.complete) this.options.complete(this); return; } if (this.timer) clearTimeout(this.timer); var stepDuration = Math.round(this.duration/this.steps) ; var currentOpacity = this.getElementOpacity(); var delta = this.steps > 0 ? (this.opacity - currentOpacity)/this.steps : 0; this.changeOpacityBy(delta); this.duration -= stepDuration; this.steps--; this.timer = setTimeout(this.fadeTo.bind(this), stepDuration); }, changeOpacityBy: function(v) { var currentOpacity = this.getElementOpacity(); var newOpacity = Math.max(0, Math.min(currentOpacity+v, 1)); this.element.ricoOpacity = newOpacity; this.element.style.filter = "alpha(opacity:"+Math.round(newOpacity*100)+")"; this.element.style.opacity = newOpacity; /*//*/; }, isFinished: function() { return this.steps <= 0; }, getElementOpacity: function() { if ( this.element.ricoOpacity == undefined ) { var opacity = RicoUtil.getElementsComputedStyle(this.element, 'opacity'); this.element.ricoOpacity = opacity != undefined ? opacity : 1.0; } return parseFloat(this.element.ricoOpacity); } } Rico.Effect.AccordionSize = Class.create(); Rico.Effect.AccordionSize.prototype = { initialize: function(e1, e2, start, end, duration, steps, options) { this.e1 = $(e1); this.e2 = $(e2); this.start = start; this.end = end; this.duration = duration; this.steps = steps; this.options = arguments[6] || {}; this.accordionSize(); }, accordionSize: function() { if (this.isFinished()) { // just in case there are round errors or such... this.e1.style.height = this.start + "px"; this.e2.style.height = this.end + "px"; if(this.options.complete) this.options.complete(this); return; } if (this.timer) clearTimeout(this.timer); var stepDuration = Math.round(this.duration/this.steps) ; var diff = this.steps > 0 ? (parseInt(this.e1.offsetHeight) - this.start)/this.steps : 0; this.resizeBy(diff); this.duration -= stepDuration; this.steps--; this.timer = setTimeout(this.accordionSize.bind(this), stepDuration); }, isFinished: function() { return this.steps <= 0; }, resizeBy: function(diff) { var h1Height = this.e1.offsetHeight; var h2Height = this.e2.offsetHeight; var intDiff = parseInt(diff); if ( diff != 0 ) { this.e1.style.height = (h1Height - intDiff) + "px"; this.e2.style.height = (h2Height + intDiff) + "px"; } } }; //-------------------- ricoLiveGrid.js // Rico.LiveGridMetaData ----------------------------------------------------- Rico.LiveGridMetaData = Class.create(); Rico.LiveGridMetaData.prototype = { initialize: function( pageSize, totalRows, columnCount, options ) { this.pageSize = pageSize; this.totalRows = totalRows; this.setOptions(options); this.ArrowHeight = 16; this.columnCount = columnCount; }, setOptions: function(options) { this.options = { largeBufferSize : 7.0, // 7 pages nearLimitFactor : 0.2 // 20% of buffer }; Object.extend(this.options, options || {}); }, getPageSize: function() { return this.pageSize; }, getTotalRows: function() { return this.totalRows; }, setTotalRows: function(n) { this.totalRows = n; }, getLargeBufferSize: function() { return parseInt(this.options.largeBufferSize * this.pageSize); }, getLimitTolerance: function() { return parseInt(this.getLargeBufferSize() * this.options.nearLimitFactor); } }; // Rico.LiveGridScroller ----------------------------------------------------- Rico.LiveGridScroller = Class.create(); Rico.LiveGridScroller.prototype = { initialize: function(liveGrid, viewPort) { this.isIE = navigator.userAgent.toLowerCase().indexOf("msie") >= 0; this.liveGrid = liveGrid; this.metaData = liveGrid.metaData; this.createScrollBar(); this.scrollTimeout = null; this.lastScrollPos = 0; this.viewPort = viewPort; this.rows = new Array(); }, isUnPlugged: function() { return this.scrollerDiv.onscroll == null; }, plugin: function() { this.scrollerDiv.onscroll = this.handleScroll.bindAsEventListener(this); }, unplug: function() { this.scrollerDiv.onscroll = null; }, sizeIEHeaderHack: function() { if ( !this.isIE ) return; var headerTable = $(this.liveGrid.tableId + "_header"); if ( headerTable ) headerTable.rows[0].cells[0].style.width = (headerTable.rows[0].cells[0].offsetWidth + 1) + "px"; }, createScrollBar: function() { var visibleHeight = this.liveGrid.viewPort.visibleHeight(); // create the outer div... this.scrollerDiv = document.createElement("div"); var scrollerStyle = this.scrollerDiv.style; scrollerStyle.borderRight = this.liveGrid.options.scrollerBorderRight; scrollerStyle.position = "relative"; scrollerStyle.left = this.isIE ? "-6px" : "-3px"; scrollerStyle.width = "19px"; scrollerStyle.height = visibleHeight + "px"; scrollerStyle.overflow = "auto"; // create the inner div... this.heightDiv = document.createElement("div"); this.heightDiv.style.width = "1px"; this.heightDiv.style.height = parseInt(visibleHeight * this.metaData.getTotalRows()/this.metaData.getPageSize()) + "px" ; this.scrollerDiv.appendChild(this.heightDiv); this.scrollerDiv.onscroll = this.handleScroll.bindAsEventListener(this); var table = this.liveGrid.table; table.parentNode.parentNode.insertBefore( this.scrollerDiv, table.parentNode.nextSibling ); var eventName = this.isIE ? "mousewheel" : "DOMMouseScroll"; Event.observe(table, eventName, function(evt) { if (evt.wheelDelta>=0 || evt.detail < 0) //wheel-up this.scrollerDiv.scrollTop -= (2*this.viewPort.rowHeight); else this.scrollerDiv.scrollTop += (2*this.viewPort.rowHeight); this.handleScroll(false); }.bindAsEventListener(this), false); }, updateSize: function() { var table = this.liveGrid.table; var visibleHeight = this.viewPort.visibleHeight(); this.heightDiv.style.height = parseInt(visibleHeight * this.metaData.getTotalRows()/this.metaData.getPageSize()) + "px"; }, rowToPixel: function(rowOffset) { return (rowOffset / this.metaData.getTotalRows()) * this.heightDiv.offsetHeight }, moveScroll: function(rowOffset) { this.scrollerDiv.scrollTop = this.rowToPixel(rowOffset); if ( this.metaData.options.onscroll ) this.metaData.options.onscroll( this.liveGrid, rowOffset ); }, handleScroll: function() { if ( this.scrollTimeout ) clearTimeout( this.scrollTimeout ); var scrollDiff = this.lastScrollPos-this.scrollerDiv.scrollTop; if (scrollDiff != 0.00) { var r = this.scrollerDiv.scrollTop % this.viewPort.rowHeight; if (r != 0) { this.unplug(); if ( scrollDiff < 0 ) { this.scrollerDiv.scrollTop += (this.viewPort.rowHeight-r); } else { this.scrollerDiv.scrollTop -= r; } this.plugin(); } } var contentOffset = parseInt(this.scrollerDiv.scrollTop / this.viewPort.rowHeight); this.liveGrid.requestContentRefresh(contentOffset); this.viewPort.scrollTo(this.scrollerDiv.scrollTop); if ( this.metaData.options.onscroll ) this.metaData.options.onscroll( this.liveGrid, contentOffset ); this.scrollTimeout = setTimeout(this.scrollIdle.bind(this), 1200 ); this.lastScrollPos = this.scrollerDiv.scrollTop; }, scrollIdle: function() { if ( this.metaData.options.onscrollidle ) this.metaData.options.onscrollidle(); } }; // Rico.LiveGridBuffer ----------------------------------------------------- Rico.LiveGridBuffer = Class.create(); Rico.LiveGridBuffer.prototype = { initialize: function(metaData, viewPort) { this.startPos = 0; this.size = 0; this.metaData = metaData; this.rows = new Array(); this.updateInProgress = false; this.viewPort = viewPort; this.maxBufferSize = metaData.getLargeBufferSize() * 2; this.maxFetchSize = metaData.getLargeBufferSize(); this.lastOffset = 0; }, getBlankRow: function() { if (!this.blankRow ) { this.blankRow = new Array(); for ( var i=0; i < this.metaData.columnCount ; i++ ) this.blankRow[i] = "&nbsp;"; } return this.blankRow; }, loadRows: function(ajaxResponse) { var rowsElement = ajaxResponse.getElementsByTagName('rows')[0]; this.updateUI = rowsElement.getAttribute("update_ui") == "true" var newRows = new Array() var trs = rowsElement.getElementsByTagName("tr"); for ( var i=0 ; i < trs.length; i++ ) { var row = newRows[i] = new Array(); var cells = trs[i].getElementsByTagName("td"); for ( var j=0; j < cells.length ; j++ ) { var cell = cells[j]; var convertSpaces = cell.getAttribute("convert_spaces") == "true"; var cellContent = RicoUtil.getContentAsString(cell); row[j] = convertSpaces ? this.convertSpaces(cellContent) : cellContent; if (!row[j]) row[j] = '&nbsp;'; } } return newRows; }, update: function(ajaxResponse, start) { var newRows = this.loadRows(ajaxResponse); if (this.rows.length == 0) { // initial load this.rows = newRows; this.size = this.rows.length; this.startPos = start; return; } if (start > this.startPos) { //appending if (this.startPos + this.rows.length < start) { this.rows = newRows; this.startPos = start;// } else { this.rows = this.rows.concat( newRows.slice(0, newRows.length)); if (this.rows.length > this.maxBufferSize) { var fullSize = this.rows.length; this.rows = this.rows.slice(this.rows.length - this.maxBufferSize, this.rows.length) this.startPos = this.startPos + (fullSize - this.rows.length); } } } else { //prepending if (start + newRows.length < this.startPos) { this.rows = newRows; } else { this.rows = newRows.slice(0, this.startPos).concat(this.rows); if (this.rows.length > this.maxBufferSize) this.rows = this.rows.slice(0, this.maxBufferSize) } this.startPos = start; } this.size = this.rows.length; }, clear: function() { this.rows = new Array(); this.startPos = 0; this.size = 0; }, isOverlapping: function(start, size) { return ((start < this.endPos()) && (this.startPos < start + size)) || (this.endPos() == 0) }, isInRange: function(position) { return (position >= this.startPos) && (position + this.metaData.getPageSize() <= this.endPos()); //&& this.size() != 0; }, isNearingTopLimit: function(position) { return position - this.startPos < this.metaData.getLimitTolerance(); }, endPos: function() { return this.startPos + this.rows.length; }, isNearingBottomLimit: function(position) { return this.endPos() - (position + this.metaData.getPageSize()) < this.metaData.getLimitTolerance(); }, isAtTop: function() { return this.startPos == 0; }, isAtBottom: function() { return this.endPos() == this.metaData.getTotalRows(); }, isNearingLimit: function(position) { return ( !this.isAtTop() && this.isNearingTopLimit(position)) || ( !this.isAtBottom() && this.isNearingBottomLimit(position) ) }, getFetchSize: function(offset) { var adjustedOffset = this.getFetchOffset(offset); var adjustedSize = 0; if (adjustedOffset >= this.startPos) { //apending var endFetchOffset = this.maxFetchSize + adjustedOffset; if (endFetchOffset > this.metaData.totalRows) endFetchOffset = this.metaData.totalRows; adjustedSize = endFetchOffset - adjustedOffset; if(adjustedOffset == 0 && adjustedSize < this.maxFetchSize){ adjustedSize = this.maxFetchSize; } } else {//prepending var adjustedSize = this.startPos - adjustedOffset; if (adjustedSize > this.maxFetchSize) adjustedSize = this.maxFetchSize; } return adjustedSize; }, getFetchOffset: function(offset) { var adjustedOffset = offset; if (offset > this.startPos) //apending adjustedOffset = (offset > this.endPos()) ? offset : this.endPos(); else { //prepending if (offset + this.maxFetchSize >= this.startPos) { var adjustedOffset = this.startPos - this.maxFetchSize; if (adjustedOffset < 0) adjustedOffset = 0; } } this.lastOffset = adjustedOffset; return adjustedOffset; }, getRows: function(start, count) { var begPos = start - this.startPos var endPos = begPos + count // er? need more data... if ( endPos > this.size ) endPos = this.size var results = new Array() var index = 0; for ( var i=begPos ; i < endPos; i++ ) { results[index++] = this.rows[i] } return results }, convertSpaces: function(s) { return s.split(" ").join("&nbsp;"); } }; //Rico.GridViewPort -------------------------------------------------- Rico.GridViewPort = Class.create(); Rico.GridViewPort.prototype = { initialize: function(table, rowHeight, visibleRows, buffer, liveGrid) { this.lastDisplayedStartPos = 0; this.div = table.parentNode; this.table = table this.rowHeight = rowHeight; this.div.style.height = (this.rowHeight * visibleRows) + "px"; this.div.style.overflow = "hidden"; this.buffer = buffer; this.liveGrid = liveGrid; this.visibleRows = visibleRows + 1; this.lastPixelOffset = 0; this.startPos = 0; }, populateRow: function(htmlRow, row) { for (var j=0; j < row.length; j++) { htmlRow.cells[j].innerHTML = row[j] } }, bufferChanged: function() { this.refreshContents( parseInt(this.lastPixelOffset / this.rowHeight)); }, clearRows: function() { if (!this.isBlank) { this.liveGrid.table.className = this.liveGrid.options.loadingClass; for (var i=0; i < this.visibleRows; i++) this.populateRow(this.table.rows[i], this.buffer.getBlankRow()); this.isBlank = true; } }, clearContents: function() { this.clearRows(); this.scrollTo(0); this.startPos = 0; this.lastStartPos = -1; }, refreshContents: function(startPos) { if (startPos == this.lastRowPos && !this.isPartialBlank && !this.isBlank) { return; } if ((startPos + this.visibleRows < this.buffer.startPos) || (this.buffer.startPos + this.buffer.size < startPos) || (this.buffer.size == 0)) { this.clearRows(); return; } this.isBlank = false; var viewPrecedesBuffer = this.buffer.startPos > startPos var contentStartPos = viewPrecedesBuffer ? this.buffer.startPos: startPos; var contentEndPos = (this.buffer.startPos + this.buffer.size < startPos + this.visibleRows) ? this.buffer.startPos + this.buffer.size : startPos + this.visibleRows; var rowSize = contentEndPos - contentStartPos; var rows = this.buffer.getRows(contentStartPos, rowSize ); var blankSize = this.visibleRows - rowSize; var blankOffset = viewPrecedesBuffer ? 0: rowSize; var contentOffset = viewPrecedesBuffer ? blankSize: 0; for (var i=0; i < rows.length; i++) {//initialize what we have this.populateRow(this.table.rows[i + contentOffset], rows[i]); } for (var i=0; i < blankSize; i++) {// blank out the rest this.populateRow(this.table.rows[i + blankOffset], this.buffer.getBlankRow()); } this.isPartialBlank = blankSize > 0; this.lastRowPos = startPos; this.liveGrid.table.className = this.liveGrid.options.tableClass; // Check if user has set a onRefreshComplete function var onRefreshComplete = this.liveGrid.options.onRefreshComplete; if (onRefreshComplete != null) onRefreshComplete(); }, scrollTo: function(pixelOffset) { if (this.lastPixelOffset == pixelOffset) return; this.refreshContents(parseInt(pixelOffset / this.rowHeight)) this.div.scrollTop = pixelOffset % this.rowHeight this.lastPixelOffset = pixelOffset; }, visibleHeight: function() { return parseInt(RicoUtil.getElementsComputedStyle(this.div, 'height')); } }; Rico.LiveGridRequest = Class.create(); Rico.LiveGridRequest.prototype = { initialize: function( requestOffset, options ) { this.requestOffset = requestOffset; } }; // Rico.LiveGrid ----------------------------------------------------- Rico.LiveGrid = Class.create(); Rico.LiveGrid.prototype = { initialize: function( tableId, visibleRows, totalRows, url, options, ajaxOptions ) { this.options = { tableClass: $(tableId).className, loadingClass: $(tableId).className, scrollerBorderRight: '1px solid #ababab', bufferTimeout: 20000, sortAscendImg: 'images/sort_asc.gif', sortDescendImg: 'images/sort_desc.gif', sortImageWidth: 9, sortImageHeight: 5, ajaxSortURLParms: [], onRefreshComplete: null, requestParameters: null, inlineStyles: true }; Object.extend(this.options, options || {}); this.ajaxOptions = {parameters: null}; Object.extend(this.ajaxOptions, ajaxOptions || {}); this.tableId = tableId; this.table = $(tableId); this.addLiveGridHtml(); var columnCount = this.table.rows[0].cells.length; this.metaData = new Rico.LiveGridMetaData(visibleRows, totalRows, columnCount, options); this.buffer = new Rico.LiveGridBuffer(this.metaData); var rowCount = this.table.rows.length; this.viewPort = new Rico.GridViewPort(this.table, this.table.offsetHeight/rowCount, visibleRows, this.buffer, this); this.scroller = new Rico.LiveGridScroller(this,this.viewPort); this.options.sortHandler = this.sortHandler.bind(this); if ( $(tableId + '_header') ) this.sort = new Rico.LiveGridSort(tableId + '_header', this.options) this.processingRequest = null; this.unprocessedRequest = null; this.initAjax(url); if ( this.options.prefetchBuffer || this.options.prefetchOffset > 0) { var offset = 0; if (this.options.offset ) { offset = this.options.offset; this.scroller.moveScroll(offset); this.viewPort.scrollTo(this.scroller.rowToPixel(offset)); } if (this.options.sortCol) { this.sortCol = options.sortCol; this.sortDir = options.sortDir; } this.requestContentRefresh(offset); } }, addLiveGridHtml: function() { // Check to see if need to create a header table. if (this.table.getElementsByTagName("thead").length > 0){ // Create Table this.tableId+'_header' var tableHeader = this.table.cloneNode(true); tableHeader.setAttribute('id', this.tableId+'_header'); tableHeader.setAttribute('class', this.table.className+'_header'); // Clean up and insert for( var i = 0; i < tableHeader.tBodies.length; i++ ) tableHeader.removeChild(tableHeader.tBodies[i]); this.table.deleteTHead(); this.table.parentNode.insertBefore(tableHeader,this.table); } new Insertion.Before(this.table, "<div id='"+this.tableId+"_container'></div>"); this.table.previousSibling.appendChild(this.table); new Insertion.Before(this.table,"<div id='"+this.tableId+"_viewport' style='float:left;'></div>"); this.table.previousSibling.appendChild(this.table); }, resetContents: function() { this.scroller.moveScroll(0); this.buffer.clear(); this.viewPort.clearContents(); }, sortHandler: function(column) { if(!column) return ; this.sortCol = column.name; this.sortDir = column.currentSort; this.resetContents(); this.requestContentRefresh(0) }, adjustRowSize: function() { }, setTotalRows: function( newTotalRows ) { this.resetContents(); this.metaData.setTotalRows(newTotalRows); this.scroller.updateSize(); }, initAjax: function(url) { ajaxEngine.registerRequest( this.tableId + '_request', url ); ajaxEngine.registerAjaxObject( this.tableId + '_updater', this ); }, invokeAjax: function() { }, handleTimedOut: function() { //server did not respond in 4 seconds... assume that there could have been //an error or something, and allow requests to be processed again... this.processingRequest = null; this.processQueuedRequest(); }, fetchBuffer: function(offset) { if ( this.buffer.isInRange(offset) && !this.buffer.isNearingLimit(offset)) { return; } if (this.processingRequest) { this.unprocessedRequest = new Rico.LiveGridRequest(offset); return; } var bufferStartPos = this.buffer.getFetchOffset(offset); this.processingRequest = new Rico.LiveGridRequest(offset); this.processingRequest.bufferOffset = bufferStartPos; var fetchSize = this.buffer.getFetchSize(offset); var partialLoaded = false; var queryString if (this.options.requestParameters) queryString = this._createQueryString(this.options.requestParameters, 0); queryString = (queryString == null) ? '' : queryString+'&'; queryString = queryString+'id='+this.tableId+'&page_size='+fetchSize+'&offset='+bufferStartPos; if (this.sortCol) queryString = queryString+'&sort_col='+escape(this.sortCol)+'&sort_dir='+this.sortDir; this.ajaxOptions.parameters = queryString; ajaxEngine.sendRequest( this.tableId + '_request', this.ajaxOptions ); this.timeoutHandler = setTimeout( this.handleTimedOut.bind(this), this.options.bufferTimeout); }, setRequestParams: function() { this.options.requestParameters = []; for ( var i=0 ; i < arguments.length ; i++ ) this.options.requestParameters[i] = arguments[i]; }, requestContentRefresh: function(contentOffset) { this.fetchBuffer(contentOffset); }, ajaxUpdate: function(ajaxResponse) { try { clearTimeout( this.timeoutHandler ); this.buffer.update(ajaxResponse,this.processingRequest.bufferOffset); this.viewPort.bufferChanged(); } catch(err) {} finally {this.processingRequest = null; } this.processQueuedRequest(); }, _createQueryString: function( theArgs, offset ) { var queryString = "" if (!theArgs) return queryString; for ( var i = offset ; i < theArgs.length ; i++ ) { if ( i != offset ) queryString += "&"; var anArg = theArgs[i]; if ( anArg.name != undefined && anArg.value != undefined ) { queryString += anArg.name + "=" + escape(anArg.value); } else { var ePos = anArg.indexOf('='); var argName = anArg.substring( 0, ePos ); var argValue = anArg.substring( ePos + 1 ); queryString += argName + "=" + escape(argValue); } } return queryString; }, processQueuedRequest: function() { if (this.unprocessedRequest != null) { this.requestContentRefresh(this.unprocessedRequest.requestOffset); this.unprocessedRequest = null } } }; //-------------------- ricoLiveGridSort.js Rico.LiveGridSort = Class.create(); Rico.LiveGridSort.prototype = { initialize: function(headerTableId, options) { this.headerTableId = headerTableId; this.headerTable = $(headerTableId); this.options = options; this.setOptions(); this.applySortBehavior(); if ( this.options.sortCol ) { this.setSortUI( this.options.sortCol, this.options.sortDir ); } }, setSortUI: function( columnName, sortDirection ) { var cols = this.options.columns; for ( var i = 0 ; i < cols.length ; i++ ) { if ( cols[i].name == columnName ) { this.setColumnSort(i, sortDirection); break; } } }, setOptions: function() { // preload the images... new Image().src = this.options.sortAscendImg; new Image().src = this.options.sortDescendImg; this.sort = this.options.sortHandler; if ( !this.options.columns ) this.options.columns = this.introspectForColumnInfo(); else { // allow client to pass { columns: [ ["a", true], ["b", false] ] } // and convert to an array of Rico.TableColumn objs... this.options.columns = this.convertToTableColumns(this.options.columns); } }, applySortBehavior: function() { var headerRow = this.headerTable.rows[0]; var headerCells = headerRow.cells; for ( var i = 0 ; i < headerCells.length ; i++ ) { this.addSortBehaviorToColumn( i, headerCells[i] ); } }, addSortBehaviorToColumn: function( n, cell ) { if ( this.options.columns[n].isSortable() ) { cell.id = this.headerTableId + '_' + n; cell.style.cursor = 'pointer'; cell.onclick = this.headerCellClicked.bindAsEventListener(this); cell.innerHTML = cell.innerHTML + '<span id="' + this.headerTableId + '_img_' + n + '">' + '&nbsp;&nbsp;&nbsp;</span>'; } }, // event handler.... headerCellClicked: function(evt) { var eventTarget = evt.target ? evt.target : evt.srcElement; var cellId = eventTarget.id; var columnNumber = parseInt(cellId.substring( cellId.lastIndexOf('_') + 1 )); var sortedColumnIndex = this.getSortedColumnIndex(); if ( sortedColumnIndex != -1 ) { if ( sortedColumnIndex != columnNumber ) { this.removeColumnSort(sortedColumnIndex); this.setColumnSort(columnNumber, Rico.TableColumn.SORT_ASC); } else this.toggleColumnSort(sortedColumnIndex); } else this.setColumnSort(columnNumber, Rico.TableColumn.SORT_ASC); if (this.options.sortHandler) { this.options.sortHandler(this.options.columns[columnNumber]); } }, removeColumnSort: function(n) { this.options.columns[n].setUnsorted(); this.setSortImage(n); }, setColumnSort: function(n, direction) { if(isNaN(n)) return ; this.options.columns[n].setSorted(direction); this.setSortImage(n); }, toggleColumnSort: function(n) { this.options.columns[n].toggleSort(); this.setSortImage(n); }, setSortImage: function(n) { var sortDirection = this.options.columns[n].getSortDirection(); var sortImageSpan = $( this.headerTableId + '_img_' + n ); if ( sortDirection == Rico.TableColumn.UNSORTED ) sortImageSpan.innerHTML = '&nbsp;&nbsp;'; else if ( sortDirection == Rico.TableColumn.SORT_ASC ) sortImageSpan.innerHTML = '&nbsp;&nbsp;<img width="' + this.options.sortImageWidth + '" ' + 'height="'+ this.options.sortImageHeight + '" ' + 'src="' + this.options.sortAscendImg + '"/>'; else if ( sortDirection == Rico.TableColumn.SORT_DESC ) sortImageSpan.innerHTML = '&nbsp;&nbsp;<img width="' + this.options.sortImageWidth + '" ' + 'height="'+ this.options.sortImageHeight + '" ' + 'src="' + this.options.sortDescendImg + '"/>'; }, getSortedColumnIndex: function() { var cols = this.options.columns; for ( var i = 0 ; i < cols.length ; i++ ) { if ( cols[i].isSorted() ) return i; } return -1; }, introspectForColumnInfo: function() { var columns = new Array(); var headerRow = this.headerTable.rows[0]; var headerCells = headerRow.cells; for ( var i = 0 ; i < headerCells.length ; i++ ) columns.push( new Rico.TableColumn( this.deriveColumnNameFromCell(headerCells[i],i), true ) ); return columns; }, convertToTableColumns: function(cols) { var columns = new Array(); for ( var i = 0 ; i < cols.length ; i++ ) columns.push( new Rico.TableColumn( cols[i][0], cols[i][1] ) ); return columns; }, deriveColumnNameFromCell: function(cell,columnNumber) { var cellContent = cell.innerText != undefined ? cell.innerText : cell.textContent; return cellContent ? cellContent.toLowerCase().split(' ').join('_') : "col_" + columnNumber; } }; Rico.TableColumn = Class.create(); Rico.TableColumn.UNSORTED = 0; Rico.TableColumn.SORT_ASC = "ASC"; Rico.TableColumn.SORT_DESC = "DESC"; Rico.TableColumn.prototype = { initialize: function(name, sortable) { this.name = name; this.sortable = sortable; this.currentSort = Rico.TableColumn.UNSORTED; }, isSortable: function() { return this.sortable; }, isSorted: function() { return this.currentSort != Rico.TableColumn.UNSORTED; }, getSortDirection: function() { return this.currentSort; }, toggleSort: function() { if ( this.currentSort == Rico.TableColumn.UNSORTED || this.currentSort == Rico.TableColumn.SORT_DESC ) this.currentSort = Rico.TableColumn.SORT_ASC; else if ( this.currentSort == Rico.TableColumn.SORT_ASC ) this.currentSort = Rico.TableColumn.SORT_DESC; }, setUnsorted: function(direction) { this.setSorted(Rico.TableColumn.UNSORTED); }, setSorted: function(direction) { // direction must by one of Rico.TableColumn.UNSORTED, .SORT_ASC, or .SORT_DESC... this.currentSort = direction; } }; //-------------------- ricoUtil.js var RicoUtil = { getElementsComputedStyle: function ( htmlElement, cssProperty, mozillaEquivalentCSS) { if ( arguments.length == 2 ) mozillaEquivalentCSS = cssProperty; var el = $(htmlElement); if ( el.currentStyle ) return el.currentStyle[cssProperty]; else return document.defaultView.getComputedStyle(el, null).getPropertyValue(mozillaEquivalentCSS); }, createXmlDocument : function() { if (document.implementation && document.implementation.createDocument) { var doc = document.implementation.createDocument("", "", null); if (doc.readyState == null) { doc.readyState = 1; doc.addEventListener("load", function () { doc.readyState = 4; if (typeof doc.onreadystatechange == "function") doc.onreadystatechange(); }, false); } return doc; } if (window.ActiveXObject) return Try.these( function() { return new ActiveXObject('MSXML2.DomDocument') }, function() { return new ActiveXObject('Microsoft.DomDocument')}, function() { return new ActiveXObject('MSXML.DomDocument') }, function() { return new ActiveXObject('MSXML3.DomDocument') } ) || false; return null; }, getContentAsString: function( parentNode ) { return parentNode.xml != undefined ? this._getContentAsStringIE(parentNode) : this._getContentAsStringMozilla(parentNode); }, _getContentAsStringIE: function(parentNode) { var contentStr = ""; for ( var i = 0 ; i < parentNode.childNodes.length ; i++ ) { var n = parentNode.childNodes[i]; if (n.nodeType == 4) { contentStr += n.nodeValue; } else { contentStr += n.xml; } } return contentStr; }, _getContentAsStringMozilla: function(parentNode) { var xmlSerializer = new XMLSerializer(); var contentStr = ""; for ( var i = 0 ; i < parentNode.childNodes.length ; i++ ) { var n = parentNode.childNodes[i]; if (n.nodeType == 4) { // CDATA node contentStr += n.nodeValue; } else { contentStr += xmlSerializer.serializeToString(n); } } return contentStr; }, toViewportPosition: function(element) { return this._toAbsolute(element,true); }, toDocumentPosition: function(element) { return this._toAbsolute(element,false); }, /** * Compute the elements position in terms of the window viewport * so that it can be compared to the position of the mouse (dnd) * This is additions of all the offsetTop,offsetLeft values up the * offsetParent hierarchy, ...taking into account any scrollTop, * scrollLeft values along the way... * * IE has a bug reporting a correct offsetLeft of elements within a * a relatively positioned parent!!! **/ _toAbsolute: function(element,accountForDocScroll) { if ( navigator.userAgent.toLowerCase().indexOf("msie") == -1 ) return this._toAbsoluteMozilla(element,accountForDocScroll); var x = 0; var y = 0; var parent = element; while ( parent ) { var borderXOffset = 0; var borderYOffset = 0; if ( parent != element ) { var borderXOffset = parseInt(this.getElementsComputedStyle(parent, "borderLeftWidth" )); var borderYOffset = parseInt(this.getElementsComputedStyle(parent, "borderTopWidth" )); borderXOffset = isNaN(borderXOffset) ? 0 : borderXOffset; borderYOffset = isNaN(borderYOffset) ? 0 : borderYOffset; } x += parent.offsetLeft - parent.scrollLeft + borderXOffset; y += parent.offsetTop - parent.scrollTop + borderYOffset; parent = parent.offsetParent; } if ( accountForDocScroll ) { x -= this.docScrollLeft(); y -= this.docScrollTop(); } return { x:x, y:y }; }, /** * Mozilla did not report all of the parents up the hierarchy via the * offsetParent property that IE did. So for the calculation of the * offsets we use the offsetParent property, but for the calculation of * the scrollTop/scrollLeft adjustments we navigate up via the parentNode * property instead so as to get the scroll offsets... * **/ _toAbsoluteMozilla: function(element,accountForDocScroll) { var x = 0; var y = 0; var parent = element; while ( parent ) { x += parent.offsetLeft; y += parent.offsetTop; parent = parent.offsetParent; } parent = element; while ( parent && parent != document.body && parent != document.documentElement ) { if ( parent.scrollLeft ) x -= parent.scrollLeft; if ( parent.scrollTop ) y -= parent.scrollTop; parent = parent.parentNode; } if ( accountForDocScroll ) { x -= this.docScrollLeft(); y -= this.docScrollTop(); } return { x:x, y:y }; }, docScrollLeft: function() { if ( window.pageXOffset ) return window.pageXOffset; else if ( document.documentElement && document.documentElement.scrollLeft ) return document.documentElement.scrollLeft; else if ( document.body ) return document.body.scrollLeft; else return 0; }, docScrollTop: function() { if ( window.pageYOffset ) return window.pageYOffset; else if ( document.documentElement && document.documentElement.scrollTop ) return document.documentElement.scrollTop; else if ( document.body ) return document.body.scrollTop; else return 0; } };
var struct_jmcpp_1_1_group_info_updated_event = [ [ "fromUser", "struct_jmcpp_1_1_group_info_updated_event.html#a01d445e6f171e3f38103f38d1f82e041", null ], [ "groupId", "struct_jmcpp_1_1_group_info_updated_event.html#a7775458e8f2504cbdea378e5005a544a", null ], [ "users", "struct_jmcpp_1_1_group_info_updated_event.html#a58c9232407bf86989e54d824182fe5f4", null ] ];
define({ "unit": "Jedinica", "style": "Stil", "dual": "dvostruki", "english": "engleski", "metric": "metrički", "ruler": "ravnalo", "line": "linija", "number": "broj", "spinnerLabel": "Zaokruži broj mjerila na: ", "decimalPlace": "decimalno mjesto", "separator": "Prikaži razdjelnik tisućica" });
var fs = require('fs'); var path = require('path'); module.exports = function(grunt) { 'use strict'; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), copy: { main: { files: [ {src: 'numbro.js', dest: 'dist/numbro.js'}, ] } }, concat: { languages: { src: [ 'languages/**/*.js', ], dest: 'dist/languages.js', }, }, uglify: { target: { files: [ { src: [ 'dist/languages.js' ], dest: 'dist/languages.min.js', }, { src: [ 'numbro.js' ], dest: 'dist/numbro.min.js', }, ].concat( fs.readdirSync('./languages').map(function (fileName) { var lang = path.basename(fileName, '.js'); return { src: [path.join('languages/', fileName)], dest: path.join('dist/languages/', lang + '.min.js'), }; })) }, options: { preserveComments: 'some', }, }, bump: { options: { files: [ 'package.json', 'bower.json', 'component.json', 'numbro.js', ], updateConfigs: ['pkg'], commit: false, createTag: false, push: false, globalReplace: true, regExp: new RegExp('([\'|\"]?version[\'|\"]?[ ]*[:=][ ]*[\'|\"]?)'+ '(\\d+\\.\\d+\\.\\d+(-\\.\\d+)?(-\\d+)?)[\\d||A-a|.|-]*([\'|\"]?)') }, }, confirm: { release: { options: { question: 'Are you sure you want to publish a new release' + ' with version <%= pkg.version %>? (yes/no)', continue: function(answer) { return ['yes', 'y'].indexOf(answer.toLowerCase()) !== -1; } } } }, release:{ options: { bump: false, commit: false, tagName: '<%= version %>', }, }, nodeunit: { all: ['tests/**/*.js'], }, jshint: { options: { jshintrc : '.jshintrc' }, all: [ 'Gruntfile.js', 'numbro.js', 'languages/**/*.js' ] }, jscs: { src: [ 'Gruntfile.js', 'numbro.js', 'languages/**/*.js' ], options: { config: '.jscsrc', esnext: true, // If you use ES6 http://jscs.info/overview.html#esnext verbose: true, // If you need output with rule names http://jscs.info/overview.html#verbose validateIndentation: 4 } } }); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-bump'); grunt.loadNpmTasks('grunt-confirm'); grunt.loadNpmTasks('grunt-release'); grunt.loadNpmTasks('grunt-jscs'); grunt.registerTask('default', [ 'test' ]); grunt.registerTask('lint', [ 'jshint', 'jscs' ]); grunt.registerTask('test', [ 'lint', 'nodeunit' ]); grunt.registerTask('build', [ 'test', 'copy:main', 'concat', 'uglify' ]); // wrap grunt-release with confirmation grunt.registerTask('publish', [ 'confirm:release', 'release', ]); // Travis CI task. grunt.registerTask('travis', ['test']); };
module.exports={title:"RubyGems",slug:"rubygems",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>RubyGems icon</title><path d="M7.81 7.9l-2.97 2.95 7.19 7.18 2.96-2.95 4.22-4.23-2.96-2.96v-.01H7.8zM12 0L1.53 6v12L12 24l10.47-6V6L12 0zm8.47 16.85L12 21.73l-8.47-4.88V7.12L12 2.24l8.47 4.88v9.73z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://rubygems.org/pages/about",hex:"E9573F",license:void 0};
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.run = undefined; var _asyncToGenerator2; function _load_asyncToGenerator() { return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator')); } let updateCwd = (() => { var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config) { yield config.init({ cwd: config.globalFolder, binLinks: true, globalFolder: config.globalFolder, cacheFolder: config.cacheFolder, linkFolder: config.linkFolder }); }); return function updateCwd(_x) { return _ref.apply(this, arguments); }; })(); let getBins = (() => { var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config) { // build up list of registry folders to search for binaries const dirs = []; for (const registryName of Object.keys((_index || _load_index()).registries)) { const registry = config.registries[registryName]; dirs.push(registry.loc); } // build up list of binary files const paths = new Set(); for (const dir of dirs) { const binDir = path.join(dir, '.bin'); if (!(yield (_fs || _load_fs()).exists(binDir))) { continue; } for (const name of yield (_fs || _load_fs()).readdir(binDir)) { paths.add(path.join(binDir, name)); } } return paths; }); return function getBins(_x2) { return _ref2.apply(this, arguments); }; })(); let initUpdateBins = (() => { var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags) { const beforeBins = yield getBins(config); const binFolder = getBinFolder(config, flags); function throwPermError(err, dest) { if (err.code === 'EACCES') { throw new (_errors || _load_errors()).MessageError(reporter.lang('noFilePermission', dest)); } else { throw err; } } return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { const afterBins = yield getBins(config); // remove old bins for (const src of beforeBins) { if (afterBins.has(src)) { // not old continue; } // remove old bin const dest = path.join(binFolder, path.basename(src)); try { yield (_fs || _load_fs()).unlink(dest); } catch (err) { throwPermError(err, dest); } } // add new bins for (const src of afterBins) { if (beforeBins.has(src)) { // already inserted continue; } // insert new bin const dest = path.join(binFolder, path.basename(src)); try { yield (_fs || _load_fs()).unlink(dest); yield (0, (_packageLinker || _load_packageLinker()).linkBin)(src, dest); if (process.platform === 'win32' && dest.indexOf('.cmd') !== -1) { yield (_fs || _load_fs()).rename(dest + '.cmd', dest); } } catch (err) { throwPermError(err, dest); } } }); }); return function initUpdateBins(_x3, _x4, _x5) { return _ref3.apply(this, arguments); }; })(); exports.hasWrapper = hasWrapper; exports.getBinFolder = getBinFolder; exports.setFlags = setFlags; var _errors; function _load_errors() { return _errors = require('../../errors.js'); } var _index; function _load_index() { return _index = require('../../registries/index.js'); } var _baseReporter; function _load_baseReporter() { return _baseReporter = _interopRequireDefault(require('../../reporters/base-reporter.js')); } var _buildSubCommands2; function _load_buildSubCommands() { return _buildSubCommands2 = _interopRequireDefault(require('./_build-sub-commands.js')); } var _wrapper; function _load_wrapper() { return _wrapper = _interopRequireDefault(require('../../lockfile/wrapper.js')); } var _install; function _load_install() { return _install = require('./install.js'); } var _add; function _load_add() { return _add = require('./add.js'); } var _remove; function _load_remove() { return _remove = require('./remove.js'); } var _upgrade; function _load_upgrade() { return _upgrade = require('./upgrade.js'); } var _packageLinker; function _load_packageLinker() { return _packageLinker = require('../../package-linker.js'); } var _fs; function _load_fs() { return _fs = _interopRequireWildcard(require('../../util/fs.js')); } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } class GlobalAdd extends (_add || _load_add()).Add { maybeOutputSaveTree() { for (const pattern of this.addedPatterns) { const manifest = this.resolver.getStrictResolvedPattern(pattern); ls(manifest, this.reporter, true); } return Promise.resolve(); } _logSuccessSaveLockfile() { // noop } } const path = require('path'); function hasWrapper(flags, args) { return args[0] !== 'bin'; } function getGlobalPrefix(config, flags) { if (flags.prefix) { return flags.prefix; } else if (config.getOption('prefix')) { return String(config.getOption('prefix')); } else if (process.env.PREFIX) { return process.env.PREFIX; } else if (process.platform === 'win32') { // c:\node\node.exe --> prefix=c:\node\ return path.dirname(process.execPath); } else { // /usr/local/bin/node --> prefix=/usr/local let prefix = path.dirname(path.dirname(process.execPath)); // destdir only is respected on Unix if (process.env.DESTDIR) { prefix = path.join(process.env.DESTDIR, prefix); } return prefix; } } function getBinFolder(config, flags) { const prefix = getGlobalPrefix(config, flags); if (process.platform === 'win32') { return prefix; } else { return path.resolve(prefix, 'bin'); } } function ls(manifest, reporter, saved) { const bins = manifest.bin ? Object.keys(manifest.bin) : []; const human = `${manifest.name}@${manifest.version}`; if (bins.length) { if (saved) { reporter.success(reporter.lang('packageInstalledWithBinaries', human)); } else { reporter.info(reporter.lang('packageHasBinaries', human)); } reporter.list(`bins-${manifest.name}`, bins); } else if (saved) { reporter.warn(reporter.lang('packageHasNoBinaries')); } } var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('global', { add(config, reporter, flags, args) { return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { yield updateCwd(config); const updateBins = yield initUpdateBins(config, reporter, flags); // install module const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd); const install = new GlobalAdd(args, flags, config, reporter, lockfile); yield install.init(); // link binaries yield updateBins(); })(); }, bin(config, reporter, flags, args) { console.log(getBinFolder(config, flags)); }, ls(config, reporter, flags, args) { return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { yield updateCwd(config); // install so we get hard file paths const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd); const install = new (_install || _load_install()).Install({ skipIntegrity: true }, config, new (_baseReporter || _load_baseReporter()).default(), lockfile); const patterns = yield install.init(); // dump global modules for (const pattern of patterns) { const manifest = install.resolver.getStrictResolvedPattern(pattern); ls(manifest, reporter, false); } })(); }, remove(config, reporter, flags, args) { return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { yield updateCwd(config); const updateBins = yield initUpdateBins(config, reporter, flags); // remove module yield (0, (_remove || _load_remove()).run)(config, reporter, flags, args); // remove binaries yield updateBins(); })(); }, upgrade(config, reporter, flags, args) { return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { yield updateCwd(config); const updateBins = yield initUpdateBins(config, reporter, flags); // upgrade module yield (0, (_upgrade || _load_upgrade()).run)(config, reporter, flags, args); // update binaries yield updateBins(); })(); } }); const run = _buildSubCommands.run, _setFlags = _buildSubCommands.setFlags; exports.run = run; function setFlags(commander) { _setFlags(commander); commander.option('--prefix <prefix>', 'bin prefix to use to install binaries'); }
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import invariant from 'fbjs/lib/invariant'; import warning from 'fbjs/lib/warning'; import {isEndish, isMoveish, isStartish} from './EventPluginUtils'; /** * Tracks the position and time of each active touch by `touch.identifier`. We * should typically only see IDs in the range of 1-20 because IDs get recycled * when touches end and start again. */ type TouchRecord = { touchActive: boolean, startPageX: number, startPageY: number, startTimeStamp: number, currentPageX: number, currentPageY: number, currentTimeStamp: number, previousPageX: number, previousPageY: number, previousTimeStamp: number, }; const MAX_TOUCH_BANK = 20; const touchBank: Array<TouchRecord> = []; const touchHistory = { touchBank, numberActiveTouches: 0, // If there is only one active touch, we remember its location. This prevents // us having to loop through all of the touches all the time in the most // common case. indexOfSingleActiveTouch: -1, mostRecentTimeStamp: 0, }; type Touch = { identifier: ?number, pageX: number, pageY: number, timestamp: number, }; type TouchEvent = { changedTouches: Array<Touch>, touches: Array<Touch>, }; function timestampForTouch(touch: Touch): number { // The legacy internal implementation provides "timeStamp", which has been // renamed to "timestamp". Let both work for now while we iron it out // TODO (evv): rename timeStamp to timestamp in internal code return (touch: any).timeStamp || touch.timestamp; } /** * TODO: Instead of making gestures recompute filtered velocity, we could * include a built in velocity computation that can be reused globally. */ function createTouchRecord(touch: Touch): TouchRecord { return { touchActive: true, startPageX: touch.pageX, startPageY: touch.pageY, startTimeStamp: timestampForTouch(touch), currentPageX: touch.pageX, currentPageY: touch.pageY, currentTimeStamp: timestampForTouch(touch), previousPageX: touch.pageX, previousPageY: touch.pageY, previousTimeStamp: timestampForTouch(touch), }; } function resetTouchRecord(touchRecord: TouchRecord, touch: Touch): void { touchRecord.touchActive = true; touchRecord.startPageX = touch.pageX; touchRecord.startPageY = touch.pageY; touchRecord.startTimeStamp = timestampForTouch(touch); touchRecord.currentPageX = touch.pageX; touchRecord.currentPageY = touch.pageY; touchRecord.currentTimeStamp = timestampForTouch(touch); touchRecord.previousPageX = touch.pageX; touchRecord.previousPageY = touch.pageY; touchRecord.previousTimeStamp = timestampForTouch(touch); } function getTouchIdentifier({identifier}: Touch): number { invariant(identifier != null, 'Touch object is missing identifier.'); if (__DEV__) { warning( identifier <= MAX_TOUCH_BANK, 'Touch identifier %s is greater than maximum supported %s which causes ' + 'performance issues backfilling array locations for all of the indices.', identifier, MAX_TOUCH_BANK, ); } return identifier; } function recordTouchStart(touch: Touch): void { const identifier = getTouchIdentifier(touch); const touchRecord = touchBank[identifier]; if (touchRecord) { resetTouchRecord(touchRecord, touch); } else { touchBank[identifier] = createTouchRecord(touch); } touchHistory.mostRecentTimeStamp = timestampForTouch(touch); } function recordTouchMove(touch: Touch): void { const touchRecord = touchBank[getTouchIdentifier(touch)]; if (touchRecord) { touchRecord.touchActive = true; touchRecord.previousPageX = touchRecord.currentPageX; touchRecord.previousPageY = touchRecord.currentPageY; touchRecord.previousTimeStamp = touchRecord.currentTimeStamp; touchRecord.currentPageX = touch.pageX; touchRecord.currentPageY = touch.pageY; touchRecord.currentTimeStamp = timestampForTouch(touch); touchHistory.mostRecentTimeStamp = timestampForTouch(touch); } else { console.error( 'Cannot record touch move without a touch start.\n' + 'Touch Move: %s\n', 'Touch Bank: %s', printTouch(touch), printTouchBank(), ); } } function recordTouchEnd(touch: Touch): void { const touchRecord = touchBank[getTouchIdentifier(touch)]; if (touchRecord) { touchRecord.touchActive = false; touchRecord.previousPageX = touchRecord.currentPageX; touchRecord.previousPageY = touchRecord.currentPageY; touchRecord.previousTimeStamp = touchRecord.currentTimeStamp; touchRecord.currentPageX = touch.pageX; touchRecord.currentPageY = touch.pageY; touchRecord.currentTimeStamp = timestampForTouch(touch); touchHistory.mostRecentTimeStamp = timestampForTouch(touch); } else { console.error( 'Cannot record touch end without a touch start.\n' + 'Touch End: %s\n', 'Touch Bank: %s', printTouch(touch), printTouchBank(), ); } } function printTouch(touch: Touch): string { return JSON.stringify({ identifier: touch.identifier, pageX: touch.pageX, pageY: touch.pageY, timestamp: timestampForTouch(touch), }); } function printTouchBank(): string { let printed = JSON.stringify(touchBank.slice(0, MAX_TOUCH_BANK)); if (touchBank.length > MAX_TOUCH_BANK) { printed += ' (original size: ' + touchBank.length + ')'; } return printed; } const ResponderTouchHistoryStore = { recordTouchTrack(topLevelType: string, nativeEvent: TouchEvent): void { if (isMoveish(topLevelType)) { nativeEvent.changedTouches.forEach(recordTouchMove); } else if (isStartish(topLevelType)) { nativeEvent.changedTouches.forEach(recordTouchStart); touchHistory.numberActiveTouches = nativeEvent.touches.length; if (touchHistory.numberActiveTouches === 1) { touchHistory.indexOfSingleActiveTouch = nativeEvent.touches[0].identifier; } } else if (isEndish(topLevelType)) { nativeEvent.changedTouches.forEach(recordTouchEnd); touchHistory.numberActiveTouches = nativeEvent.touches.length; if (touchHistory.numberActiveTouches === 1) { for (let i = 0; i < touchBank.length; i++) { const touchTrackToCheck = touchBank[i]; if (touchTrackToCheck != null && touchTrackToCheck.touchActive) { touchHistory.indexOfSingleActiveTouch = i; break; } } if (__DEV__) { const activeRecord = touchBank[touchHistory.indexOfSingleActiveTouch]; warning( activeRecord != null && activeRecord.touchActive, 'Cannot find single active touch.', ); } } } }, touchHistory, }; export default ResponderTouchHistoryStore;
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import 'babel-polyfill'; import path from 'path'; import express from 'express'; import cookieParser from 'cookie-parser'; import bodyParser from 'body-parser'; import expressJwt from 'express-jwt'; import expressGraphQL from 'express-graphql'; import jwt from 'jsonwebtoken'; import ReactDOM from 'react-dom/server'; import { match } from 'universal-router'; import PrettyError from 'pretty-error'; import passport from './core/passport'; import models from './data/models'; import schema from './data/schema'; import routes from './routes'; import assets from './assets'; import { port, auth, analytics } from './config'; const app = express(); // // Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the // user agent is not known. // ----------------------------------------------------------------------------- global.navigator = global.navigator || {}; global.navigator.userAgent = global.navigator.userAgent || 'all'; // // Register Node.js middleware // ----------------------------------------------------------------------------- app.use(express.static(path.join(__dirname, 'public'))); app.use(cookieParser()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // // Authentication // ----------------------------------------------------------------------------- app.use(expressJwt({ secret: auth.jwt.secret, credentialsRequired: false, /* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */ getToken: req => req.cookies.id_token, /* jscs:enable requireCamelCaseOrUpperCaseIdentifiers */ })); app.use(passport.initialize()); app.get('/login/facebook', passport.authenticate('facebook', { scope: ['email', 'user_location'], session: false }) ); app.get('/login/facebook/return', passport.authenticate('facebook', { failureRedirect: '/login', session: false }), (req, res) => { const expiresIn = 60 * 60 * 24 * 180; // 180 days const token = jwt.sign(req.user, auth.jwt.secret, { expiresIn }); res.cookie('id_token', token, { maxAge: 1000 * expiresIn, httpOnly: true }); res.redirect('/'); } ); // // Register API middleware // ----------------------------------------------------------------------------- app.use('/graphql', expressGraphQL(req => ({ schema, graphiql: true, rootValue: { request: req }, pretty: process.env.NODE_ENV !== 'production', }))); // // Register server-side rendering middleware // ----------------------------------------------------------------------------- app.get('*', async (req, res, next) => { try { let css = []; let statusCode = 200; const template = require('./views/index.jade'); const data = { title: '', description: '', css: '', body: '', entry: assets.main.js }; if (process.env.NODE_ENV === 'production') { data.trackingId = analytics.google.trackingId; } await match(routes, { path: req.path, query: req.query, context: { insertCss: styles => css.push(styles._getCss()), setTitle: value => (data.title = value), setMeta: (key, value) => (data[key] = value), }, render(component, status = 200) { css = []; statusCode = status; data.body = ReactDOM.renderToString(component); data.css = css.join(''); return true; }, }); res.status(statusCode); res.send(template(data)); } catch (err) { next(err); } }); // // Error handling // ----------------------------------------------------------------------------- const pe = new PrettyError(); pe.skipNodeFiles(); pe.skipPackage('express'); app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars console.log(pe.render(err)); // eslint-disable-line no-console const template = require('./views/error.jade'); const statusCode = err.status || 500; res.status(statusCode); res.send(template({ message: err.message, stack: process.env.NODE_ENV === 'production' ? '' : err.stack, })); }); // // Launch the server // ----------------------------------------------------------------------------- /* eslint-disable no-console */ models.sync().catch(err => console.error(err.stack)).then(() => { app.listen(port, () => { console.log(`The server is running at http://localhost:${port}/`); }); }); /* eslint-enable no-console */
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _ErrorHandler = require('../utils/ErrorHandler'); var startActivity = function startActivity(appPackage, appActivity) { if (typeof appPackage !== 'string' || typeof appActivity !== 'string') { throw new _ErrorHandler.ProtocolError('startActivity command requires two parameter (appPackage, appActivity) from type string'); } return this.requestHandler.create('/session/:sessionId/appium/device/start_activity', { appPackage: appPackage, appActivity: appActivity }); }; /** * * Start an arbitrary Android activity during a session. * * <example> :startActivity.js browser.startActivity({ appPackage: 'io.appium.android.apis', appActivity: '.view.DragAndDropDemo' }); * </example> * * @param {String} appPackage name of app * @param {String} appActivity name of activity * @type mobile * @for android * */ exports.default = startActivity; module.exports = exports['default'];
tinyMCE.addI18n('en.asciimath',{ desc : 'Add New Math' }); tinyMCE.addI18n('en.asciimathcharmap',{ desc : 'Math Symbols' });
import { Meteor } from 'meteor/meteor'; import bugsnag from 'bugsnag'; import { settings } from '../../../settings'; import { Info } from '../../../utils'; settings.get('Bugsnag_api_key', (key, value) => { if (value) { bugsnag.register(value); } }); const notify = function(message, stack) { if (typeof stack === 'string') { message += ` ${ stack }`; } let options = {}; if (Info) { options = { app: { version: Info.version, info: Info } }; } const error = new Error(message); error.stack = stack; bugsnag.notify(error, options); }; process.on('uncaughtException', Meteor.bindEnvironment((error) => { notify(error.message, error.stack); throw error; })); const originalMeteorDebug = Meteor._debug; Meteor._debug = function(...args) { notify(...args); return originalMeteorDebug(...args); };
var module = module; //this keeps the module file from doing anything inside the jasmine tests. //We could avoid this by making all the source be in a specific directory, but that would break backwards compatibility. if (module) { module.exports = function (grunt) { 'use strict'; var config, debug, environment, spec; grunt.loadNpmTasks('grunt-contrib-jasmine'); grunt.registerTask('default', ['jasmine']); spec = grunt.option('spec') || '*'; config = grunt.file.readJSON('config.json'); return grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jasmine: { dev: { src: "./*.js", options: { vendor:["https://rally1.rallydev.com/apps/"+config.sdk+"/sdk-debug.js"], template: 'test/specs.tmpl', specs: "test/**/" + spec + "Spec.js", helpers: [] } } }, rallydeploy: { options: { server: config.server, projectOid: 0, deployFile: "deploy.json", credentialsFile: "credentials.json", timeboxFilter: "none" }, prod: { options: { tab: "myhome", pageName: config.name, shared: false } } } }); }; }
import { CONSTANT_TAG, DirtyableTag } from 'glimmer-reference'; import { meta as metaFor } from './meta'; import require from 'require'; import { isProxy } from './is_proxy'; let hasViews = () => false; export function setHasViews(fn) { hasViews = fn; } function makeTag() { return new DirtyableTag(); } export function tagForProperty(object, propertyKey, _meta) { if (isProxy(object)) { return tagFor(object, _meta); } if (typeof object === 'object' && object) { let meta = _meta || metaFor(object); let tags = meta.writableTags(); let tag = tags[propertyKey]; if (tag) { return tag; } return tags[propertyKey] = makeTag(); } else { return CONSTANT_TAG; } } export function tagFor(object, _meta) { if (typeof object === 'object' && object) { let meta = _meta || metaFor(object); return meta.writableTag(makeTag); } else { return CONSTANT_TAG; } } export function markObjectAsDirty(meta, propertyKey) { let objectTag = meta && meta.readableTag(); if (objectTag) { objectTag.dirty(); } let tags = meta && meta.readableTags(); let propertyTag = tags && tags[propertyKey]; if (propertyTag) { propertyTag.dirty(); } if (objectTag || propertyTag) { ensureRunloop(); } } let run; function K() {} function ensureRunloop() { if (!run) { run = require('ember-metal/run_loop').default; } if (hasViews() && !run.backburner.currentInstance) { run.schedule('actions', K); } }
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'liststyle', 'fr', { armenian: 'Numération arménienne', bulletedTitle: 'Propriétés de la liste à puces', circle: 'Cercle', decimal: 'Décimal (1, 2, 3, etc.)', decimalLeadingZero: 'Décimal précédé par un 0 (01, 02, 03, etc.)', disc: 'Disque', georgian: 'Numération géorgienne (an, ban, gan, etc.)', lowerAlpha: 'Alphabétique minuscules (a, b, c, d, e, etc.)', lowerGreek: 'Grec minuscule (alpha, beta, gamma, etc.)', lowerRoman: 'Nombres romains minuscules (i, ii, iii, iv, v, etc.)', none: 'Aucun', notset: '<Non défini>', numberedTitle: 'Propriétés de la liste numérotée', square: 'Carré', start: 'Début', type: 'Type', upperAlpha: 'Alphabétique majuscules (A, B, C, D, E, etc.)', upperRoman: 'Nombres romains majuscules (I, II, III, IV, V, etc.)', validateStartNumber: 'Le premier élément de la liste doit être un nombre entier.' });
#!/usr/bin/env mocha -R spec var assert = require("assert"); var msgpackJS = "../index"; var isBrowser = ("undefined" !== typeof window); var msgpack = isBrowser && window.msgpack || require(msgpackJS); var TITLE = __filename.replace(/^.*\//, ""); var HAS_UINT8ARRAY = ("undefined" !== typeof Uint8Array); describe(TITLE, function() { it("createCodec()", function() { var codec = msgpack.createCodec(); var options = {codec: codec}; assert.ok(codec); // this codec does not have preset codec for (var i = 0; i < 256; i++) { test(i); } function test(type) { // fixext 1 -- 0xd4 var source = new Buffer([0xd4, type, type]); var decoded = msgpack.decode(source, options); assert.equal(decoded.type, type); assert.equal(decoded.buffer.length, 1); var encoded = msgpack.encode(decoded, options); assert.deepEqual(toArray(encoded), toArray(source)); } }); it("addExtPacker()", function() { var codec = msgpack.createCodec(); codec.addExtPacker(0, MyClass, myClassPacker); codec.addExtUnpacker(0, myClassUnpacker); var options = {codec: codec}; [0, 1, 127, 255].forEach(test); function test(type) { var source = new MyClass(type); var encoded = msgpack.encode(source, options); var decoded = msgpack.decode(encoded, options); assert.ok(decoded instanceof MyClass); assert.equal(decoded.value, type); } }); // The safe mode works as same as the default mode. It'd be hard for test it. it("createCodec({safe: true})", function() { var options = {codec: msgpack.createCodec({safe: true})}; var source = 1; var encoded = msgpack.encode(source, options); var decoded = msgpack.decode(encoded, options); assert.equal(decoded, source); }); it("createCodec({preset: true})", function() { var options1 = {codec: msgpack.createCodec({preset: true})}; var options2 = {codec: msgpack.createCodec({preset: false})}; var source = new Date(); var encoded = msgpack.encode(source, options1); assert.equal(encoded[0], 0xC7, "preset ext format failure. (128 means map format)"); // ext 8 assert.equal(encoded[1], 0x09); // 1+8 assert.equal(encoded[2], 0x0D); // Date // decode as Boolean instance var decoded = msgpack.decode(encoded, options1); assert.equal(decoded - 0, source - 0); assert.ok(decoded instanceof Date); // decode as ExtBuffer decoded = msgpack.decode(encoded, options2); assert.ok(!(decoded instanceof Date)); assert.equal(decoded.type, 0x0D); }); }); function MyClass(value) { this.value = value & 0xFF; } function myClassPacker(obj) { return new Buffer([obj.value]); } function myClassUnpacker(buffer) { return new MyClass(buffer[0]); } function toArray(array) { if (HAS_UINT8ARRAY && array instanceof ArrayBuffer) array = new Uint8Array(array); return Array.prototype.slice.call(array); }
function dec(target, name, descriptor) { assert(target); assert.equal(typeof name, "string"); assert.equal(typeof descriptor, "object"); target.decoratedProps = (target.decoratedProps || []).concat([name]); let initializer = descriptor.initializer; return { enumerable: name.indexOf('enum') !== -1, configurable: name.indexOf('conf') !== -1, writable: name.indexOf('write') !== -1, initializer: function(...args){ return '__' + initializer.apply(this, args) + '__'; }, }; } const inst = { @dec enumconfwrite: 1, @dec enumconf: 2, @dec enumwrite: 3, @dec enum: 4, @dec confwrite: 5, @dec conf: 6, @dec write: 7, @dec _: 8, }; assert(inst.hasOwnProperty("decoratedProps")); assert.deepEqual(inst.decoratedProps, [ "enumconfwrite", "enumconf", "enumwrite", "enum", "confwrite", "conf", "write", "_", ]); const descs = Object.getOwnPropertyDescriptors(inst); assert(descs.enumconfwrite.enumerable); assert(descs.enumconfwrite.writable); assert(descs.enumconfwrite.configurable); assert.equal(inst.enumconfwrite, "__1__"); assert(descs.enumconf.enumerable); assert.equal(descs.enumconf.writable, false); assert(descs.enumconf.configurable); assert.equal(inst.enumconf, "__2__"); assert(descs.enumwrite.enumerable); assert(descs.enumwrite.writable); assert.equal(descs.enumwrite.configurable, false); assert.equal(inst.enumwrite, "__3__"); assert(descs.enum.enumerable); assert.equal(descs.enum.writable, false); assert.equal(descs.enum.configurable, false); assert.equal(inst.enum, "__4__"); assert.equal(descs.confwrite.enumerable, false); assert(descs.confwrite.writable); assert(descs.confwrite.configurable); assert.equal(inst.confwrite, "__5__"); assert.equal(descs.conf.enumerable, false); assert.equal(descs.conf.writable, false); assert(descs.conf.configurable); assert.equal(inst.conf, "__6__"); assert.equal(descs.write.enumerable, false); assert(descs.write.writable); assert.equal(descs.write.configurable, false); assert.equal(inst.write, "__7__"); assert.equal(descs._.enumerable, false); assert.equal(descs._.writable, false); assert.equal(descs._.configurable, false); assert.equal(inst._, "__8__");
/* Highcharts JS v6.1.1 (2018-06-27) Plugin for displaying a message when there is no data visible in chart. (c) 2010-2017 Highsoft AS Author: Oystein Moseng License: www.highcharts.com/license */ (function(d){"object"===typeof module&&module.exports?module.exports=d:d(Highcharts)})(function(d){(function(c){var d=c.seriesTypes,e=c.Chart.prototype,f=c.getOptions(),g=c.extend,h=c.each;g(f.lang,{noData:"No data to display"});f.noData={position:{x:0,y:0,align:"center",verticalAlign:"middle"}};h("bubble gauge heatmap pie sankey treemap waterfall".split(" "),function(b){d[b]&&(d[b].prototype.hasData=function(){return!!this.points.length})});c.Series.prototype.hasData=function(){return this.visible&& void 0!==this.dataMax&&void 0!==this.dataMin};e.showNoData=function(b){var a=this.options;b=b||a&&a.lang.noData;a=a&&a.noData;!this.noDataLabel&&this.renderer&&(this.noDataLabel=this.renderer.label(b,0,0,null,null,null,a.useHTML,null,"no-data"),this.noDataLabel.add(),this.noDataLabel.align(g(this.noDataLabel.getBBox(),a.position),!1,"plotBox"))};e.hideNoData=function(){this.noDataLabel&&(this.noDataLabel=this.noDataLabel.destroy())};e.hasData=function(){for(var b=this.series||[],a=b.length;a--;)if(b[a].hasData()&& !b[a].options.isInternal)return!0;return this.loadingShown};c.addEvent(c.Chart,"render",function(){this.hasData()?this.hideNoData():this.showNoData()})})(d)});
/** * @license * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/> * Build: `lodash -o ./dist/lodash.compat.js` * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE> * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <http://lodash.com/license> */ ;(function() { /** Used as a safe reference for `undefined` in pre ES5 environments */ var undefined; /** Used to pool arrays and objects used internally */ var arrayPool = [], objectPool = []; /** Used to generate unique IDs */ var idCounter = 0; /** Used internally to indicate various things */ var indicatorObject = {}; /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */ var keyPrefix = +new Date + ''; /** Used as the size when optimizations are enabled for large arrays */ var largeArraySize = 75; /** Used as the max size of the `arrayPool` and `objectPool` */ var maxPoolSize = 40; /** Used to detect and test whitespace */ var whitespace = ( // whitespace ' \t\x0B\f\xA0\ufeff' + // line terminators '\n\r\u2028\u2029' + // unicode category "Zs" space separators '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000' ); /** Used to match empty string literals in compiled template source */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** * Used to match ES6 template delimiters * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-literals-string-literals */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match regexp flags from their coerced string values */ var reFlags = /\w*$/; /** Used to detected named functions */ var reFuncName = /^\s*function[ \n\r\t]+\w/; /** Used to match "interpolate" template delimiters */ var reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match leading whitespace and zeros to be removed */ var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)'); /** Used to ensure capturing order of template delimiters */ var reNoMatch = /($^)/; /** Used to detect functions containing a `this` reference */ var reThis = /\bthis\b/; /** Used to match unescaped characters in compiled string literals */ var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g; /** Used to assign default `context` object properties */ var contextProps = [ 'Array', 'Boolean', 'Date', 'Error', 'Function', 'Math', 'Number', 'Object', 'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN', 'parseInt', 'setTimeout' ]; /** Used to fix the JScript [[DontEnum]] bug */ var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; /** Used to make template sourceURLs easier to identify */ var templateCounter = 0; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; /** Used to identify object classifications that `_.clone` supports */ var cloneableClasses = {}; cloneableClasses[funcClass] = false; cloneableClasses[argsClass] = cloneableClasses[arrayClass] = cloneableClasses[boolClass] = cloneableClasses[dateClass] = cloneableClasses[numberClass] = cloneableClasses[objectClass] = cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true; /** Used as an internal `_.debounce` options object */ var debounceOptions = { 'leading': false, 'maxWait': 0, 'trailing': false }; /** Used as the property descriptor for `__bindData__` */ var descriptor = { 'configurable': false, 'enumerable': false, 'value': null, 'writable': false }; /** Used as the data object for `iteratorTemplate` */ var iteratorData = { 'args': '', 'array': null, 'bottom': '', 'firstArg': '', 'init': '', 'keys': null, 'loop': '', 'shadowedProps': null, 'support': null, 'top': '', 'useHas': false }; /** Used to determine if values are of the language type Object */ var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; /** Used to escape characters for inclusion in compiled string literals */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\t': 't', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Used as a reference to the global object */ var root = (objectTypes[typeof window] && window) || this; /** Detect free variable `exports` */ var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; /** Detect free variable `module` */ var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports` */ var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */ var freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } /*--------------------------------------------------------------------------*/ /** * The base implementation of `_.indexOf` without support for binary searches * or `fromIndex` constraints. * * @private * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value or `-1`. */ function baseIndexOf(array, value, fromIndex) { var index = (fromIndex || 0) - 1, length = array ? array.length : 0; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * An implementation of `_.contains` for cache objects that mimics the return * signature of `_.indexOf` by returning `0` if the value is found, else `-1`. * * @private * @param {Object} cache The cache object to inspect. * @param {*} value The value to search for. * @returns {number} Returns `0` if `value` is found, else `-1`. */ function cacheIndexOf(cache, value) { var type = typeof value; cache = cache.cache; if (type == 'boolean' || value == null) { return cache[value] ? 0 : -1; } if (type != 'number' && type != 'string') { type = 'object'; } var key = type == 'number' ? value : keyPrefix + value; cache = (cache = cache[type]) && cache[key]; return type == 'object' ? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1) : (cache ? 0 : -1); } /** * Adds a given value to the corresponding cache object. * * @private * @param {*} value The value to add to the cache. */ function cachePush(value) { var cache = this.cache, type = typeof value; if (type == 'boolean' || value == null) { cache[value] = true; } else { if (type != 'number' && type != 'string') { type = 'object'; } var key = type == 'number' ? value : keyPrefix + value, typeCache = cache[type] || (cache[type] = {}); if (type == 'object') { (typeCache[key] || (typeCache[key] = [])).push(value); } else { typeCache[key] = true; } } } /** * Used by `_.max` and `_.min` as the default callback when a given * collection is a string value. * * @private * @param {string} value The character to inspect. * @returns {number} Returns the code unit of given character. */ function charAtCallback(value) { return value.charCodeAt(0); } /** * Used by `sortBy` to compare transformed `collection` elements, stable sorting * them in ascending order. * * @private * @param {Object} a The object to compare to `b`. * @param {Object} b The object to compare to `a`. * @returns {number} Returns the sort order indicator of `1` or `-1`. */ function compareAscending(a, b) { var ac = a.criteria, bc = b.criteria, index = -1, length = ac.length; while (++index < length) { var value = ac[index], other = bc[index]; if (value !== other) { if (value > other || typeof value == 'undefined') { return 1; } if (value < other || typeof other == 'undefined') { return -1; } } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to return the same value for // `a` and `b`. See https://github.com/jashkenas/underscore/pull/1247 // // This also ensures a stable sort in V8 and other engines. // See http://code.google.com/p/v8/issues/detail?id=90 return a.index - b.index; } /** * Creates a cache object to optimize linear searches of large arrays. * * @private * @param {Array} [array=[]] The array to search. * @returns {null|Object} Returns the cache object or `null` if caching should not be used. */ function createCache(array) { var index = -1, length = array.length, first = array[0], mid = array[(length / 2) | 0], last = array[length - 1]; if (first && typeof first == 'object' && mid && typeof mid == 'object' && last && typeof last == 'object') { return false; } var cache = getObject(); cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false; var result = getObject(); result.array = array; result.cache = cache; result.push = cachePush; while (++index < length) { result.push(array[index]); } return result; } /** * Used by `template` to escape characters for inclusion in compiled * string literals. * * @private * @param {string} match The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(match) { return '\\' + stringEscapes[match]; } /** * Gets an array from the array pool or creates a new one if the pool is empty. * * @private * @returns {Array} The array from the pool. */ function getArray() { return arrayPool.pop() || []; } /** * Gets an object from the object pool or creates a new one if the pool is empty. * * @private * @returns {Object} The object from the pool. */ function getObject() { return objectPool.pop() || { 'array': null, 'cache': null, 'criteria': null, 'false': false, 'index': 0, 'null': false, 'number': null, 'object': null, 'push': null, 'string': null, 'true': false, 'undefined': false, 'value': null }; } /** * Checks if `value` is a DOM node in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a DOM node, else `false`. */ function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } /** * Releases the given array back to the array pool. * * @private * @param {Array} [array] The array to release. */ function releaseArray(array) { array.length = 0; if (arrayPool.length < maxPoolSize) { arrayPool.push(array); } } /** * Releases the given object back to the object pool. * * @private * @param {Object} [object] The object to release. */ function releaseObject(object) { var cache = object.cache; if (cache) { releaseObject(cache); } object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null; if (objectPool.length < maxPoolSize) { objectPool.push(object); } } /** * Slices the `collection` from the `start` index up to, but not including, * the `end` index. * * Note: This function is used instead of `Array#slice` to support node lists * in IE < 9 and to ensure dense arrays are returned. * * @private * @param {Array|Object|string} collection The collection to slice. * @param {number} start The start index. * @param {number} end The end index. * @returns {Array} Returns the new array. */ function slice(array, start, end) { start || (start = 0); if (typeof end == 'undefined') { end = array ? array.length : 0; } var index = -1, length = end - start || 0, result = Array(length < 0 ? 0 : length); while (++index < length) { result[index] = array[start + index]; } return result; } /*--------------------------------------------------------------------------*/ /** * Create a new `lodash` function using the given context object. * * @static * @memberOf _ * @category Utilities * @param {Object} [context=root] The context object. * @returns {Function} Returns the `lodash` function. */ function runInContext(context) { // Avoid issues with some ES3 environments that attempt to use values, named // after built-in constructors like `Object`, for the creation of literals. // ES5 clears this up by stating that literals must use built-in constructors. // See http://es5.github.io/#x11.1.5. context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; /** Native constructor references */ var Array = context.Array, Boolean = context.Boolean, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Number = context.Number, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** * Used for `Array` method references. * * Normally `Array.prototype` would suffice, however, using an array literal * avoids issues in Narwhal. */ var arrayRef = []; /** Used for native method references */ var errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype; /** Used to restore the original `_` reference in `noConflict` */ var oldDash = context._; /** Used to resolve the internal [[Class]] of values */ var toString = objectProto.toString; /** Used to detect if a method is native */ var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); /** Native method shortcuts */ var ceil = Math.ceil, clearTimeout = context.clearTimeout, floor = Math.floor, fnToString = Function.prototype.toString, getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, hasOwnProperty = objectProto.hasOwnProperty, push = arrayRef.push, propertyIsEnumerable = objectProto.propertyIsEnumerable, setTimeout = context.setTimeout, splice = arrayRef.splice, unshift = arrayRef.unshift; /** Used to set meta data on functions */ var defineProperty = (function() { // IE 8 only accepts DOM elements try { var o = {}, func = isNative(func = Object.defineProperty) && func, result = func(o, o, o) && func; } catch(e) { } return result; }()); /* Native method shortcuts for methods with the same name as other `lodash` methods */ var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate, nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray, nativeIsFinite = context.isFinite, nativeIsNaN = context.isNaN, nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys, nativeMax = Math.max, nativeMin = Math.min, nativeParseInt = context.parseInt, nativeRandom = Math.random; /** Used to lookup a built-in constructor by [[Class]] */ var ctorByClass = {}; ctorByClass[arrayClass] = Array; ctorByClass[boolClass] = Boolean; ctorByClass[dateClass] = Date; ctorByClass[funcClass] = Function; ctorByClass[objectClass] = Object; ctorByClass[numberClass] = Number; ctorByClass[regexpClass] = RegExp; ctorByClass[stringClass] = String; /** Used to avoid iterating non-enumerable properties in IE < 9 */ var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; (function() { var length = shadowedProps.length; while (length--) { var key = shadowedProps[length]; for (var className in nonEnumProps) { if (hasOwnProperty.call(nonEnumProps, className) && !hasOwnProperty.call(nonEnumProps[className], key)) { nonEnumProps[className][key] = false; } } } }()); /*--------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps the given value to enable intuitive * method chaining. * * In addition to Lo-Dash methods, wrappers also have the following `Array` methods: * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`, * and `unshift` * * Chaining is supported in custom builds as long as the `value` method is * implicitly or explicitly included in the build. * * The chainable wrapper functions are: * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`, * `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`, * `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`, * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`, * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`, * `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, * `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`, * `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`, * and `zip` * * The non-chainable wrapper functions are: * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`, * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`, * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`, * `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`, * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`, * `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`, * `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`, * `template`, `unescape`, `uniqueId`, and `value` * * The wrapper functions `first` and `last` return wrapped values when `n` is * provided, otherwise they return unwrapped values. * * Explicit chaining can be enabled by using the `_.chain` method. * * @name _ * @constructor * @category Chaining * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns a `lodash` instance. * @example * * var wrapped = _([1, 2, 3]); * * // returns an unwrapped value * wrapped.reduce(function(sum, num) { * return sum + num; * }); * // => 6 * * // returns a wrapped value * var squares = wrapped.map(function(num) { * return num * num; * }); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__')) ? value : new lodashWrapper(value); } /** * A fast path for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap in a `lodash` instance. * @param {boolean} chainAll A flag to enable chaining for all methods * @returns {Object} Returns a `lodash` instance. */ function lodashWrapper(value, chainAll) { this.__chain__ = !!chainAll; this.__wrapped__ = value; } // ensure `new lodashWrapper` is an instance of `lodash` lodashWrapper.prototype = lodash.prototype; /** * An object used to flag environments features. * * @static * @memberOf _ * @type Object */ var support = lodash.support = {}; (function() { var ctor = function() { this.x = 1; }, object = { '0': 1, 'length': 1 }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } /** * Detect if an `arguments` object's [[Class]] is resolvable (all but Firefox < 4, IE < 9). * * @memberOf _.support * @type boolean */ support.argsClass = toString.call(arguments) == argsClass; /** * Detect if `arguments` objects are `Object` objects (all but Narwhal and Opera < 10.5). * * @memberOf _.support * @type boolean */ support.argsObject = arguments.constructor == Object && !(arguments instanceof Array); /** * Detect if `name` or `message` properties of `Error.prototype` are * enumerable by default. (IE < 9, Safari < 5.1) * * @memberOf _.support * @type boolean */ support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); /** * Detect if `prototype` properties are enumerable by default. * * Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 * (if the prototype or a property on the prototype has been set) * incorrectly sets a function's `prototype` property [[Enumerable]] * value to `true`. * * @memberOf _.support * @type boolean */ support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); /** * Detect if functions can be decompiled by `Function#toString` * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps). * * @memberOf _.support * @type boolean */ support.funcDecomp = !isNative(context.WinRTError) && reThis.test(runInContext); /** * Detect if `Function#name` is supported (all but IE). * * @memberOf _.support * @type boolean */ support.funcNames = typeof Function.name == 'string'; /** * Detect if `arguments` object indexes are non-enumerable * (Firefox < 4, IE < 9, PhantomJS, Safari < 5.1). * * @memberOf _.support * @type boolean */ support.nonEnumArgs = key != 0; /** * Detect if properties shadowing those on `Object.prototype` are non-enumerable. * * In IE < 9 an objects own properties, shadowing non-enumerable ones, are * made non-enumerable as well (a.k.a the JScript [[DontEnum]] bug). * * @memberOf _.support * @type boolean */ support.nonEnumShadows = !/valueOf/.test(props); /** * Detect if own properties are iterated after inherited properties (all but IE < 9). * * @memberOf _.support * @type boolean */ support.ownLast = props[0] != 'x'; /** * Detect if `Array#shift` and `Array#splice` augment array-like objects correctly. * * Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array `shift()` * and `splice()` functions that fail to remove the last element, `value[0]`, * of array-like objects even though the `length` property is set to `0`. * The `shift()` method is buggy in IE 8 compatibility mode, while `splice()` * is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9. * * @memberOf _.support * @type boolean */ support.spliceObjects = (arrayRef.splice.call(object, 0, 1), !object[0]); /** * Detect lack of support for accessing string characters by index. * * IE < 8 can't access characters by index and IE 8 can only access * characters by index on string literals. * * @memberOf _.support * @type boolean */ support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx'; /** * Detect if a DOM node's [[Class]] is resolvable (all but IE < 9) * and that the JS engine errors when attempting to coerce an object to * a string without a `toString` function. * * @memberOf _.support * @type boolean */ try { support.nodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { support.nodeClass = true; } }(1)); /** * By default, the template delimiters used by Lo-Dash are similar to those in * embedded Ruby (ERB). Change the following template settings to use alternative * delimiters. * * @static * @memberOf _ * @type Object */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type RegExp */ 'escape': /<%-([\s\S]+?)%>/g, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type RegExp */ 'evaluate': /<%([\s\S]+?)%>/g, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type RegExp */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type string */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type Object */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type Function */ '_': lodash } }; /*--------------------------------------------------------------------------*/ /** * The template used to create iterator functions. * * @private * @param {Object} data The data object used to populate the text. * @returns {string} Returns the interpolated text. */ var iteratorTemplate = function(obj) { var __p = 'var index, iterable = ' + (obj.firstArg) + ', result = ' + (obj.init) + ';\nif (!iterable) return result;\n' + (obj.top) + ';'; if (obj.array) { __p += '\nvar length = iterable.length; index = -1;\nif (' + (obj.array) + ') { '; if (support.unindexedChars) { __p += '\n if (isString(iterable)) {\n iterable = iterable.split(\'\')\n } '; } __p += '\n while (++index < length) {\n ' + (obj.loop) + ';\n }\n}\nelse { '; } else if (support.nonEnumArgs) { __p += '\n var length = iterable.length; index = -1;\n if (length && isArguments(iterable)) {\n while (++index < length) {\n index += \'\';\n ' + (obj.loop) + ';\n }\n } else { '; } if (support.enumPrototypes) { __p += '\n var skipProto = typeof iterable == \'function\';\n '; } if (support.enumErrorProps) { __p += '\n var skipErrorProps = iterable === errorProto || iterable instanceof Error;\n '; } var conditions = []; if (support.enumPrototypes) { conditions.push('!(skipProto && index == "prototype")'); } if (support.enumErrorProps) { conditions.push('!(skipErrorProps && (index == "message" || index == "name"))'); } if (obj.useHas && obj.keys) { __p += '\n var ownIndex = -1,\n ownProps = objectTypes[typeof iterable] && keys(iterable),\n length = ownProps ? ownProps.length : 0;\n\n while (++ownIndex < length) {\n index = ownProps[ownIndex];\n'; if (conditions.length) { __p += ' if (' + (conditions.join(' && ')) + ') {\n '; } __p += (obj.loop) + '; '; if (conditions.length) { __p += '\n }'; } __p += '\n } '; } else { __p += '\n for (index in iterable) {\n'; if (obj.useHas) { conditions.push("hasOwnProperty.call(iterable, index)"); } if (conditions.length) { __p += ' if (' + (conditions.join(' && ')) + ') {\n '; } __p += (obj.loop) + '; '; if (conditions.length) { __p += '\n }'; } __p += '\n } '; if (support.nonEnumShadows) { __p += '\n\n if (iterable !== objectProto) {\n var ctor = iterable.constructor,\n isProto = iterable === (ctor && ctor.prototype),\n className = iterable === stringProto ? stringClass : iterable === errorProto ? errorClass : toString.call(iterable),\n nonEnum = nonEnumProps[className];\n '; for (k = 0; k < 7; k++) { __p += '\n index = \'' + (obj.shadowedProps[k]) + '\';\n if ((!(isProto && nonEnum[index]) && hasOwnProperty.call(iterable, index))'; if (!obj.useHas) { __p += ' || (!nonEnum[index] && iterable[index] !== objectProto[index])'; } __p += ') {\n ' + (obj.loop) + ';\n } '; } __p += '\n } '; } } if (obj.array || support.nonEnumArgs) { __p += '\n}'; } __p += (obj.bottom) + ';\nreturn result'; return __p }; /*--------------------------------------------------------------------------*/ /** * The base implementation of `_.bind` that creates the bound function and * sets its meta data. * * @private * @param {Array} bindData The bind data array. * @returns {Function} Returns the new bound function. */ function baseBind(bindData) { var func = bindData[0], partialArgs = bindData[2], thisArg = bindData[4]; function bound() { // `Function#bind` spec // http://es5.github.io/#x15.3.4.5 if (partialArgs) { // avoid `arguments` object deoptimizations by using `slice` instead // of `Array.prototype.slice.call` and not assigning `arguments` to a // variable as a ternary expression var args = slice(partialArgs); push.apply(args, arguments); } // mimic the constructor's `return` behavior // http://es5.github.io/#x13.2.2 if (this instanceof bound) { // ensure `new bound` is an instance of `func` var thisBinding = baseCreate(func.prototype), result = func.apply(thisBinding, args || arguments); return isObject(result) ? result : thisBinding; } return func.apply(thisArg, args || arguments); } setBindData(bound, bindData); return bound; } /** * The base implementation of `_.clone` without argument juggling or support * for `thisArg` binding. * * @private * @param {*} value The value to clone. * @param {boolean} [isDeep=false] Specify a deep clone. * @param {Function} [callback] The function to customize cloning values. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates clones with source counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, isDeep, callback, stackA, stackB) { if (callback) { var result = callback(value); if (typeof result != 'undefined') { return result; } } // inspect [[Class]] var isObj = isObject(value); if (isObj) { var className = toString.call(value); if (!cloneableClasses[className] || (!support.nodeClass && isNode(value))) { return value; } var ctor = ctorByClass[className]; switch (className) { case boolClass: case dateClass: return new ctor(+value); case numberClass: case stringClass: return new ctor(value); case regexpClass: result = ctor(value.source, reFlags.exec(value)); result.lastIndex = value.lastIndex; return result; } } else { return value; } var isArr = isArray(value); if (isDeep) { // check for circular references and return corresponding clone var initedStack = !stackA; stackA || (stackA = getArray()); stackB || (stackB = getArray()); var length = stackA.length; while (length--) { if (stackA[length] == value) { return stackB[length]; } } result = isArr ? ctor(value.length) : {}; } else { result = isArr ? slice(value) : assign({}, value); } // add array properties assigned by `RegExp#exec` if (isArr) { if (hasOwnProperty.call(value, 'index')) { result.index = value.index; } if (hasOwnProperty.call(value, 'input')) { result.input = value.input; } } // exit for shallow clone if (!isDeep) { return result; } // add the source value to the stack of traversed objects // and associate it with its clone stackA.push(value); stackB.push(result); // recursively populate clone (susceptible to call stack limits) (isArr ? baseEach : forOwn)(value, function(objValue, key) { result[key] = baseClone(objValue, isDeep, callback, stackA, stackB); }); if (initedStack) { releaseArray(stackA); releaseArray(stackB); } return result; } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} prototype The object to inherit from. * @returns {Object} Returns the new object. */ function baseCreate(prototype, properties) { return isObject(prototype) ? nativeCreate(prototype) : {}; } // fallback for browsers without `Object.create` if (!nativeCreate) { baseCreate = (function() { function Object() {} return function(prototype) { if (isObject(prototype)) { Object.prototype = prototype; var result = new Object; Object.prototype = null; } return result || context.Object(); }; }()); } /** * The base implementation of `_.createCallback` without support for creating * "_.pluck" or "_.where" style callbacks. * * @private * @param {*} [func=identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of the created callback. * @param {number} [argCount] The number of arguments the callback accepts. * @returns {Function} Returns a callback function. */ function baseCreateCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } // exit early for no `thisArg` or already bound by `Function#bind` if (typeof thisArg == 'undefined' || !('prototype' in func)) { return func; } var bindData = func.__bindData__; if (typeof bindData == 'undefined') { if (support.funcNames) { bindData = !func.name; } bindData = bindData || !support.funcDecomp; if (!bindData) { var source = fnToString.call(func); if (!support.funcNames) { bindData = !reFuncName.test(source); } if (!bindData) { // checks if `func` references the `this` keyword and stores the result bindData = reThis.test(source); setBindData(func, bindData); } } } // exit early if there are no `this` references or `func` is bound if (bindData === false || (bindData !== true && bindData[1] & 1)) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 2: return function(a, b) { return func.call(thisArg, a, b); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; } return bind(func, thisArg); } /** * The base implementation of `createWrapper` that creates the wrapper and * sets its meta data. * * @private * @param {Array} bindData The bind data array. * @returns {Function} Returns the new function. */ function baseCreateWrapper(bindData) { var func = bindData[0], bitmask = bindData[1], partialArgs = bindData[2], partialRightArgs = bindData[3], thisArg = bindData[4], arity = bindData[5]; var isBind = bitmask & 1, isBindKey = bitmask & 2, isCurry = bitmask & 4, isCurryBound = bitmask & 8, key = func; function bound() { var thisBinding = isBind ? thisArg : this; if (partialArgs) { var args = slice(partialArgs); push.apply(args, arguments); } if (partialRightArgs || isCurry) { args || (args = slice(arguments)); if (partialRightArgs) { push.apply(args, partialRightArgs); } if (isCurry && args.length < arity) { bitmask |= 16 & ~32; return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]); } } args || (args = arguments); if (isBindKey) { func = thisBinding[key]; } if (this instanceof bound) { thisBinding = baseCreate(func.prototype); var result = func.apply(thisBinding, args); return isObject(result) ? result : thisBinding; } return func.apply(thisBinding, args); } setBindData(bound, bindData); return bound; } /** * The base implementation of `_.difference` that accepts a single array * of values to exclude. * * @private * @param {Array} array The array to process. * @param {Array} [values] The array of values to exclude. * @returns {Array} Returns a new array of filtered values. */ function baseDifference(array, values) { var index = -1, indexOf = getIndexOf(), length = array ? array.length : 0, isLarge = length >= largeArraySize && indexOf === baseIndexOf, result = []; if (isLarge) { var cache = createCache(values); if (cache) { indexOf = cacheIndexOf; values = cache; } else { isLarge = false; } } while (++index < length) { var value = array[index]; if (indexOf(values, value) < 0) { result.push(value); } } if (isLarge) { releaseObject(values); } return result; } /** * The base implementation of `_.flatten` without support for callback * shorthands or `thisArg` binding. * * @private * @param {Array} array The array to flatten. * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. * @param {boolean} [isStrict=false] A flag to restrict flattening to arrays and `arguments` objects. * @param {number} [fromIndex=0] The index to start from. * @returns {Array} Returns a new flattened array. */ function baseFlatten(array, isShallow, isStrict, fromIndex) { var index = (fromIndex || 0) - 1, length = array ? array.length : 0, result = []; while (++index < length) { var value = array[index]; if (value && typeof value == 'object' && typeof value.length == 'number' && (isArray(value) || isArguments(value))) { // recursively flatten arrays (susceptible to call stack limits) if (!isShallow) { value = baseFlatten(value, isShallow, isStrict); } var valIndex = -1, valLength = value.length, resIndex = result.length; result.length += valLength; while (++valIndex < valLength) { result[resIndex++] = value[valIndex]; } } else if (!isStrict) { result.push(value); } } return result; } /** * The base implementation of `_.isEqual`, without support for `thisArg` binding, * that allows partial "_.where" style comparisons. * * @private * @param {*} a The value to compare. * @param {*} b The other value to compare. * @param {Function} [callback] The function to customize comparing values. * @param {Function} [isWhere=false] A flag to indicate performing partial comparisons. * @param {Array} [stackA=[]] Tracks traversed `a` objects. * @param {Array} [stackB=[]] Tracks traversed `b` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(a, b, callback, isWhere, stackA, stackB) { // used to indicate that when comparing objects, `a` has at least the properties of `b` if (callback) { var result = callback(a, b); if (typeof result != 'undefined') { return !!result; } } // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && !(a && objectTypes[type]) && !(b && objectTypes[otherType])) { return false; } // exit early for `null` and `undefined` avoiding ES3's Function#call behavior // http://es5.github.io/#x15.3.4.4 if (a == null || b == null) { return a === b; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `+0` vs. `-0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // unwrap any `lodash` wrapped values var aWrapped = hasOwnProperty.call(a, '__wrapped__'), bWrapped = hasOwnProperty.call(b, '__wrapped__'); if (aWrapped || bWrapped) { return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, callback, isWhere, stackA, stackB); } // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = getArray()); stackB || (stackB = getArray()); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result || isWhere) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (isWhere) { while (index--) { if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) { break; } } } else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly forIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB)); } }); if (result && !isWhere) { // ensure both objects have the same number of properties forIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); if (initedStack) { releaseArray(stackA); releaseArray(stackB); } return result; } /** * The base implementation of `_.merge` without argument juggling or support * for `thisArg` binding. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {Function} [callback] The function to customize merging properties. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. */ function baseMerge(object, source, callback, stackA, stackB) { (isArray(source) ? forEach : forOwn)(source, function(source, key) { var found, isArr, result = source, value = object[key]; if (source && ((isArr = isArray(source)) || isPlainObject(source))) { // avoid merging previously merged cyclic sources var stackLength = stackA.length; while (stackLength--) { if ((found = stackA[stackLength] == source)) { value = stackB[stackLength]; break; } } if (!found) { var isShallow; if (callback) { result = callback(value, source); if ((isShallow = typeof result != 'undefined')) { value = result; } } if (!isShallow) { value = isArr ? (isArray(value) ? value : []) : (isPlainObject(value) ? value : {}); } // add `source` and associated `value` to the stack of traversed objects stackA.push(source); stackB.push(value); // recursively merge objects and arrays (susceptible to call stack limits) if (!isShallow) { baseMerge(value, source, callback, stackA, stackB); } } } else { if (callback) { result = callback(value, source); if (typeof result == 'undefined') { result = source; } } if (typeof result != 'undefined') { value = result; } } object[key] = value; }); } /** * The base implementation of `_.random` without argument juggling or support * for returning floating-point numbers. * * @private * @param {number} min The minimum possible value. * @param {number} max The maximum possible value. * @returns {number} Returns a random number. */ function baseRandom(min, max) { return min + floor(nativeRandom() * (max - min + 1)); } /** * The base implementation of `_.uniq` without support for callback shorthands * or `thisArg` binding. * * @private * @param {Array} array The array to process. * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. * @param {Function} [callback] The function called per iteration. * @returns {Array} Returns a duplicate-value-free array. */ function baseUniq(array, isSorted, callback) { var index = -1, indexOf = getIndexOf(), length = array ? array.length : 0, result = []; var isLarge = !isSorted && length >= largeArraySize && indexOf === baseIndexOf, seen = (callback || isLarge) ? getArray() : result; if (isLarge) { var cache = createCache(seen); indexOf = cacheIndexOf; seen = cache; } while (++index < length) { var value = array[index], computed = callback ? callback(value, index, array) : value; if (isSorted ? !index || seen[seen.length - 1] !== computed : indexOf(seen, computed) < 0 ) { if (callback || isLarge) { seen.push(computed); } result.push(value); } } if (isLarge) { releaseArray(seen.array); releaseObject(seen); } else if (callback) { releaseArray(seen); } return result; } /** * Creates a function that aggregates a collection, creating an object composed * of keys generated from the results of running each element of the collection * through a callback. The given `setter` function sets the keys and values * of the composed object. * * @private * @param {Function} setter The setter function. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter) { return function(collection, callback, thisArg) { var result = {}; callback = lodash.createCallback(callback, thisArg, 3); if (isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; setter(result, value, callback(value, index, collection), collection); } } else { baseEach(collection, function(value, key, collection) { setter(result, value, callback(value, key, collection), collection); }); } return result; }; } /** * Creates a function that, when called, either curries or invokes `func` * with an optional `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to reference. * @param {number} bitmask The bitmask of method flags to compose. * The bitmask may be composed of the following flags: * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` * 8 - `_.curry` (bound) * 16 - `_.partial` * 32 - `_.partialRight` * @param {Array} [partialArgs] An array of arguments to prepend to those * provided to the new function. * @param {Array} [partialRightArgs] An array of arguments to append to those * provided to the new function. * @param {*} [thisArg] The `this` binding of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new function. */ function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) { var isBind = bitmask & 1, isBindKey = bitmask & 2, isCurry = bitmask & 4, isCurryBound = bitmask & 8, isPartial = bitmask & 16, isPartialRight = bitmask & 32; if (!isBindKey && !isFunction(func)) { throw new TypeError; } if (isPartial && !partialArgs.length) { bitmask &= ~16; isPartial = partialArgs = false; } if (isPartialRight && !partialRightArgs.length) { bitmask &= ~32; isPartialRight = partialRightArgs = false; } var bindData = func && func.__bindData__; if (bindData && bindData !== true) { // clone `bindData` bindData = slice(bindData); if (bindData[2]) { bindData[2] = slice(bindData[2]); } if (bindData[3]) { bindData[3] = slice(bindData[3]); } // set `thisBinding` is not previously bound if (isBind && !(bindData[1] & 1)) { bindData[4] = thisArg; } // set if previously bound but not currently (subsequent curried functions) if (!isBind && bindData[1] & 1) { bitmask |= 8; } // set curried arity if not yet set if (isCurry && !(bindData[1] & 4)) { bindData[5] = arity; } // append partial left arguments if (isPartial) { push.apply(bindData[2] || (bindData[2] = []), partialArgs); } // append partial right arguments if (isPartialRight) { unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs); } // merge flags bindData[1] |= bitmask; return createWrapper.apply(null, bindData); } // fast path for `_.bind` var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper; return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]); } /** * Creates compiled iteration functions. * * @private * @param {...Object} [options] The compile options object(s). * @param {string} [options.array] Code to determine if the iterable is an array or array-like. * @param {boolean} [options.useHas] Specify using `hasOwnProperty` checks in the object loop. * @param {Function} [options.keys] A reference to `_.keys` for use in own property iteration. * @param {string} [options.args] A comma separated string of iteration function arguments. * @param {string} [options.top] Code to execute before the iteration branches. * @param {string} [options.loop] Code to execute in the object loop. * @param {string} [options.bottom] Code to execute after the iteration branches. * @returns {Function} Returns the compiled function. */ function createIterator() { // data properties iteratorData.shadowedProps = shadowedProps; // iterator options iteratorData.array = iteratorData.bottom = iteratorData.loop = iteratorData.top = ''; iteratorData.init = 'iterable'; iteratorData.useHas = true; // merge options into a template data object for (var object, index = 0; object = arguments[index]; index++) { for (var key in object) { iteratorData[key] = object[key]; } } var args = iteratorData.args; iteratorData.firstArg = /^[^,]+/.exec(args)[0]; // create the function factory var factory = Function( 'baseCreateCallback, errorClass, errorProto, hasOwnProperty, ' + 'indicatorObject, isArguments, isArray, isString, keys, objectProto, ' + 'objectTypes, nonEnumProps, stringClass, stringProto, toString', 'return function(' + args + ') {\n' + iteratorTemplate(iteratorData) + '\n}' ); // return the compiled function return factory( baseCreateCallback, errorClass, errorProto, hasOwnProperty, indicatorObject, isArguments, isArray, isString, iteratorData.keys, objectProto, objectTypes, nonEnumProps, stringClass, stringProto, toString ); } /** * Used by `escape` to convert characters to HTML entities. * * @private * @param {string} match The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeHtmlChar(match) { return htmlEscapes[match]; } /** * Gets the appropriate "indexOf" function. If the `_.indexOf` method is * customized, this method returns the custom method, otherwise it returns * the `baseIndexOf` function. * * @private * @returns {Function} Returns the "indexOf" function. */ function getIndexOf() { var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result; return result; } /** * Checks if `value` is a native function. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a native function, else `false`. */ function isNative(value) { return typeof value == 'function' && reNative.test(value); } /** * Sets `this` binding data on a given function. * * @private * @param {Function} func The function to set data on. * @param {Array} value The data array to set. */ var setBindData = !defineProperty ? noop : function(func, value) { descriptor.value = value; defineProperty(func, '__bindData__', descriptor); }; /** * A fallback implementation of `isPlainObject` which checks if a given value * is an object created by the `Object` constructor, assuming objects created * by the `Object` constructor have no inherited enumerable properties and that * there are no `Object.prototype` extensions. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. */ function shimIsPlainObject(value) { var ctor, result; // avoid non Object objects, `arguments` objects, and DOM elements if (!(value && toString.call(value) == objectClass) || (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor)) || (!support.argsClass && isArguments(value)) || (!support.nodeClass && isNode(value))) { return false; } // IE < 9 iterates inherited properties before own properties. If the first // iterated property is an object's own property then there are no inherited // enumerable properties. if (support.ownLast) { forIn(value, function(value, key, object) { result = hasOwnProperty.call(object, key); return false; }); return result !== false; } // In most environments an object's own properties are iterated before // its inherited properties. If the last iterated property is an object's // own property then there are no inherited enumerable properties. forIn(value, function(value, key) { result = key; }); return typeof result == 'undefined' || hasOwnProperty.call(value, result); } /** * Used by `unescape` to convert HTML entities to characters. * * @private * @param {string} match The matched character to unescape. * @returns {string} Returns the unescaped character. */ function unescapeHtmlChar(match) { return htmlUnescapes[match]; } /*--------------------------------------------------------------------------*/ /** * Checks if `value` is an `arguments` object. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`. * @example * * (function() { return _.isArguments(arguments); })(1, 2, 3); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { return value && typeof value == 'object' && typeof value.length == 'number' && toString.call(value) == argsClass || false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!support.argsClass) { isArguments = function(value) { return value && typeof value == 'object' && typeof value.length == 'number' && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee') || false; }; } /** * Checks if `value` is an array. * * @static * @memberOf _ * @type Function * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is an array, else `false`. * @example * * (function() { return _.isArray(arguments); })(); * // => false * * _.isArray([1, 2, 3]); * // => true */ var isArray = nativeIsArray || function(value) { return value && typeof value == 'object' && typeof value.length == 'number' && toString.call(value) == arrayClass || false; }; /** * A fallback implementation of `Object.keys` which produces an array of the * given object's own enumerable property names. * * @private * @type Function * @param {Object} object The object to inspect. * @returns {Array} Returns an array of property names. */ var shimKeys = createIterator({ 'args': 'object', 'init': '[]', 'top': 'if (!(objectTypes[typeof object])) return result', 'loop': 'result.push(index)' }); /** * Creates an array composed of the own enumerable property names of an object. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns an array of property names. * @example * * _.keys({ 'one': 1, 'two': 2, 'three': 3 }); * // => ['one', 'two', 'three'] (property order is not guaranteed across environments) */ var keys = !nativeKeys ? shimKeys : function(object) { if (!isObject(object)) { return []; } if ((support.enumPrototypes && typeof object == 'function') || (support.nonEnumArgs && object.length && isArguments(object))) { return shimKeys(object); } return nativeKeys(object); }; /** Reusable iterator options shared by `each`, `forIn`, and `forOwn` */ var eachIteratorOptions = { 'args': 'collection, callback, thisArg', 'top': "callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3)", 'array': "typeof length == 'number'", 'keys': keys, 'loop': 'if (callback(iterable[index], index, collection) === false) return result' }; /** Reusable iterator options for `assign` and `defaults` */ var defaultsIteratorOptions = { 'args': 'object, source, guard', 'top': 'var args = arguments,\n' + ' argsIndex = 0,\n' + " argsLength = typeof guard == 'number' ? 2 : args.length;\n" + 'while (++argsIndex < argsLength) {\n' + ' iterable = args[argsIndex];\n' + ' if (iterable && objectTypes[typeof iterable]) {', 'keys': keys, 'loop': "if (typeof result[index] == 'undefined') result[index] = iterable[index]", 'bottom': ' }\n}' }; /** Reusable iterator options for `forIn` and `forOwn` */ var forOwnIteratorOptions = { 'top': 'if (!objectTypes[typeof iterable]) return result;\n' + eachIteratorOptions.top, 'array': false }; /** * Used to convert characters to HTML entities: * * Though the `>` character is escaped for symmetry, characters like `>` and `/` * don't require escaping in HTML and have no special meaning unless they're part * of a tag or an unquoted attribute value. * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact") */ var htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }; /** Used to convert HTML entities to characters */ var htmlUnescapes = invert(htmlEscapes); /** Used to match HTML entities and HTML characters */ var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g'), reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g'); /** * A function compiled to iterate `arguments` objects, arrays, objects, and * strings consistenly across environments, executing the callback for each * element in the collection. The callback is bound to `thisArg` and invoked * with three arguments; (value, index|key, collection). Callbacks may exit * iteration early by explicitly returning `false`. * * @private * @type Function * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array|Object|string} Returns `collection`. */ var baseEach = createIterator(eachIteratorOptions); /*--------------------------------------------------------------------------*/ /** * Assigns own enumerable properties of source object(s) to the destination * object. Subsequent sources will overwrite property assignments of previous * sources. If a callback is provided it will be executed to produce the * assigned values. The callback is bound to `thisArg` and invoked with two * arguments; (objectValue, sourceValue). * * @static * @memberOf _ * @type Function * @alias extend * @category Objects * @param {Object} object The destination object. * @param {...Object} [source] The source objects. * @param {Function} [callback] The function to customize assigning values. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the destination object. * @example * * _.assign({ 'name': 'fred' }, { 'employer': 'slate' }); * // => { 'name': 'fred', 'employer': 'slate' } * * var defaults = _.partialRight(_.assign, function(a, b) { * return typeof a == 'undefined' ? b : a; * }); * * var object = { 'name': 'barney' }; * defaults(object, { 'name': 'fred', 'employer': 'slate' }); * // => { 'name': 'barney', 'employer': 'slate' } */ var assign = createIterator(defaultsIteratorOptions, { 'top': defaultsIteratorOptions.top.replace(';', ';\n' + "if (argsLength > 3 && typeof args[argsLength - 2] == 'function') {\n" + ' var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2);\n' + "} else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {\n" + ' callback = args[--argsLength];\n' + '}' ), 'loop': 'result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]' }); /** * Creates a clone of `value`. If `isDeep` is `true` nested objects will also * be cloned, otherwise they will be assigned by reference. If a callback * is provided it will be executed to produce the cloned values. If the * callback returns `undefined` cloning will be handled by the method instead. * The callback is bound to `thisArg` and invoked with one argument; (value). * * @static * @memberOf _ * @category Objects * @param {*} value The value to clone. * @param {boolean} [isDeep=false] Specify a deep clone. * @param {Function} [callback] The function to customize cloning values. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the cloned value. * @example * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * var shallow = _.clone(characters); * shallow[0] === characters[0]; * // => true * * var deep = _.clone(characters, true); * deep[0] === characters[0]; * // => false * * _.mixin({ * 'clone': _.partialRight(_.clone, function(value) { * return _.isElement(value) ? value.cloneNode(false) : undefined; * }) * }); * * var clone = _.clone(document.body); * clone.childNodes.length; * // => 0 */ function clone(value, isDeep, callback, thisArg) { // allows working with "Collections" methods without using their `index` // and `collection` arguments for `isDeep` and `callback` if (typeof isDeep != 'boolean' && isDeep != null) { thisArg = callback; callback = isDeep; isDeep = false; } return baseClone(value, isDeep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); } /** * Creates a deep clone of `value`. If a callback is provided it will be * executed to produce the cloned values. If the callback returns `undefined` * cloning will be handled by the method instead. The callback is bound to * `thisArg` and invoked with one argument; (value). * * Note: This method is loosely based on the structured clone algorithm. Functions * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and * objects created by constructors other than `Object` are cloned to plain `Object` objects. * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm. * * @static * @memberOf _ * @category Objects * @param {*} value The value to deep clone. * @param {Function} [callback] The function to customize cloning values. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the deep cloned value. * @example * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * var deep = _.cloneDeep(characters); * deep[0] === characters[0]; * // => false * * var view = { * 'label': 'docs', * 'node': element * }; * * var clone = _.cloneDeep(view, function(value) { * return _.isElement(value) ? value.cloneNode(true) : undefined; * }); * * clone.node == view.node; * // => false */ function cloneDeep(value, callback, thisArg) { return baseClone(value, true, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); } /** * Creates an object that inherits from the given `prototype` object. If a * `properties` object is provided its own enumerable properties are assigned * to the created object. * * @static * @memberOf _ * @category Objects * @param {Object} prototype The object to inherit from. * @param {Object} [properties] The properties to assign to the object. * @returns {Object} Returns the new object. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * function Circle() { * Shape.call(this); * } * * Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle }); * * var circle = new Circle; * circle instanceof Circle; * // => true * * circle instanceof Shape; * // => true */ function create(prototype, properties) { var result = baseCreate(prototype); return properties ? assign(result, properties) : result; } /** * Assigns own enumerable properties of source object(s) to the destination * object for all destination properties that resolve to `undefined`. Once a * property is set, additional defaults of the same property will be ignored. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The destination object. * @param {...Object} [source] The source objects. * @param- {Object} [guard] Allows working with `_.reduce` without using its * `key` and `object` arguments as sources. * @returns {Object} Returns the destination object. * @example * * var object = { 'name': 'barney' }; * _.defaults(object, { 'name': 'fred', 'employer': 'slate' }); * // => { 'name': 'barney', 'employer': 'slate' } */ var defaults = createIterator(defaultsIteratorOptions); /** * This method is like `_.findIndex` except that it returns the key of the * first element that passes the callback check, instead of the element itself. * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to search. * @param {Function|Object|string} [callback=identity] The function called per * iteration. If a property name or object is provided it will be used to * create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {string|undefined} Returns the key of the found element, else `undefined`. * @example * * var characters = { * 'barney': { 'age': 36, 'blocked': false }, * 'fred': { 'age': 40, 'blocked': true }, * 'pebbles': { 'age': 1, 'blocked': false } * }; * * _.findKey(characters, function(chr) { * return chr.age < 40; * }); * // => 'barney' (property order is not guaranteed across environments) * * // using "_.where" callback shorthand * _.findKey(characters, { 'age': 1 }); * // => 'pebbles' * * // using "_.pluck" callback shorthand * _.findKey(characters, 'blocked'); * // => 'fred' */ function findKey(object, callback, thisArg) { var result; callback = lodash.createCallback(callback, thisArg, 3); forOwn(object, function(value, key, object) { if (callback(value, key, object)) { result = key; return false; } }); return result; } /** * This method is like `_.findKey` except that it iterates over elements * of a `collection` in the opposite order. * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to search. * @param {Function|Object|string} [callback=identity] The function called per * iteration. If a property name or object is provided it will be used to * create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {string|undefined} Returns the key of the found element, else `undefined`. * @example * * var characters = { * 'barney': { 'age': 36, 'blocked': true }, * 'fred': { 'age': 40, 'blocked': false }, * 'pebbles': { 'age': 1, 'blocked': true } * }; * * _.findLastKey(characters, function(chr) { * return chr.age < 40; * }); * // => returns `pebbles`, assuming `_.findKey` returns `barney` * * // using "_.where" callback shorthand * _.findLastKey(characters, { 'age': 40 }); * // => 'fred' * * // using "_.pluck" callback shorthand * _.findLastKey(characters, 'blocked'); * // => 'pebbles' */ function findLastKey(object, callback, thisArg) { var result; callback = lodash.createCallback(callback, thisArg, 3); forOwnRight(object, function(value, key, object) { if (callback(value, key, object)) { result = key; return false; } }); return result; } /** * Iterates over own and inherited enumerable properties of an object, * executing the callback for each property. The callback is bound to `thisArg` * and invoked with three arguments; (value, key, object). Callbacks may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * Shape.prototype.move = function(x, y) { * this.x += x; * this.y += y; * }; * * _.forIn(new Shape, function(value, key) { * console.log(key); * }); * // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments) */ var forIn = createIterator(eachIteratorOptions, forOwnIteratorOptions, { 'useHas': false }); /** * This method is like `_.forIn` except that it iterates over elements * of a `collection` in the opposite order. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * Shape.prototype.move = function(x, y) { * this.x += x; * this.y += y; * }; * * _.forInRight(new Shape, function(value, key) { * console.log(key); * }); * // => logs 'move', 'y', and 'x' assuming `_.forIn ` logs 'x', 'y', and 'move' */ function forInRight(object, callback, thisArg) { var pairs = []; forIn(object, function(value, key) { pairs.push(key, value); }); var length = pairs.length; callback = baseCreateCallback(callback, thisArg, 3); while (length--) { if (callback(pairs[length--], pairs[length], object) === false) { break; } } return object; } /** * Iterates over own enumerable properties of an object, executing the callback * for each property. The callback is bound to `thisArg` and invoked with three * arguments; (value, key, object). Callbacks may exit iteration early by * explicitly returning `false`. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { * console.log(key); * }); * // => logs '0', '1', and 'length' (property order is not guaranteed across environments) */ var forOwn = createIterator(eachIteratorOptions, forOwnIteratorOptions); /** * This method is like `_.forOwn` except that it iterates over elements * of a `collection` in the opposite order. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { * console.log(key); * }); * // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length' */ function forOwnRight(object, callback, thisArg) { var props = keys(object), length = props.length; callback = baseCreateCallback(callback, thisArg, 3); while (length--) { var key = props[length]; if (callback(object[key], key, object) === false) { break; } } return object; } /** * Creates a sorted array of property names of all enumerable properties, * own and inherited, of `object` that have function values. * * @static * @memberOf _ * @alias methods * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns an array of property names that have function values. * @example * * _.functions(_); * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...] */ function functions(object) { var result = []; forIn(object, function(value, key) { if (isFunction(value)) { result.push(key); } }); return result.sort(); } /** * Checks if the specified property name exists as a direct property of `object`, * instead of an inherited property. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @param {string} key The name of the property to check. * @returns {boolean} Returns `true` if key is a direct property, else `false`. * @example * * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); * // => true */ function has(object, key) { return object ? hasOwnProperty.call(object, key) : false; } /** * Creates an object composed of the inverted keys and values of the given object. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to invert. * @returns {Object} Returns the created inverted object. * @example * * _.invert({ 'first': 'fred', 'second': 'barney' }); * // => { 'fred': 'first', 'barney': 'second' } */ function invert(object) { var index = -1, props = keys(object), length = props.length, result = {}; while (++index < length) { var key = props[index]; result[object[key]] = key; } return result; } /** * Checks if `value` is a boolean value. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`. * @example * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || value && typeof value == 'object' && toString.call(value) == boolClass || false; } /** * Checks if `value` is a date. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a date, else `false`. * @example * * _.isDate(new Date); * // => true */ function isDate(value) { return value && typeof value == 'object' && toString.call(value) == dateClass || false; } /** * Checks if `value` is a DOM element. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true */ function isElement(value) { return value && value.nodeType === 1 || false; } /** * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a * length of `0` and objects with no own enumerable properties are considered * "empty". * * @static * @memberOf _ * @category Objects * @param {Array|Object|string} value The value to inspect. * @returns {boolean} Returns `true` if the `value` is empty, else `false`. * @example * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({}); * // => true * * _.isEmpty(''); * // => true */ function isEmpty(value) { var result = true; if (!value) { return result; } var className = toString.call(value), length = value.length; if ((className == arrayClass || className == stringClass || (support.argsClass ? className == argsClass : isArguments(value))) || (className == objectClass && typeof length == 'number' && isFunction(value.splice))) { return !length; } forOwn(value, function() { return (result = false); }); return result; } /** * Performs a deep comparison between two values to determine if they are * equivalent to each other. If a callback is provided it will be executed * to compare values. If the callback returns `undefined` comparisons will * be handled by the method instead. The callback is bound to `thisArg` and * invoked with two arguments; (a, b). * * @static * @memberOf _ * @category Objects * @param {*} a The value to compare. * @param {*} b The other value to compare. * @param {Function} [callback] The function to customize comparing values. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'name': 'fred' }; * var copy = { 'name': 'fred' }; * * object == copy; * // => false * * _.isEqual(object, copy); * // => true * * var words = ['hello', 'goodbye']; * var otherWords = ['hi', 'goodbye']; * * _.isEqual(words, otherWords, function(a, b) { * var reGreet = /^(?:hello|hi)$/i, * aGreet = _.isString(a) && reGreet.test(a), * bGreet = _.isString(b) && reGreet.test(b); * * return (aGreet || bGreet) ? (aGreet == bGreet) : undefined; * }); * // => true */ function isEqual(a, b, callback, thisArg) { return baseIsEqual(a, b, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 2)); } /** * Checks if `value` is, or can be coerced to, a finite number. * * Note: This is not the same as native `isFinite` which will return true for * booleans and empty strings. See http://es5.github.io/#x15.1.2.5. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is finite, else `false`. * @example * * _.isFinite(-101); * // => true * * _.isFinite('10'); * // => true * * _.isFinite(true); * // => false * * _.isFinite(''); * // => false * * _.isFinite(Infinity); * // => false */ function isFinite(value) { return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value)); } /** * Checks if `value` is a function. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true */ function isFunction(value) { return typeof value == 'function'; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } /** * Checks if `value` is the language type of Object. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // http://code.google.com/p/v8/issues/detail?id=2291 return !!(value && objectTypes[typeof value]); } /** * Checks if `value` is `NaN`. * * Note: This is not the same as native `isNaN` which will return `true` for * `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // `NaN` as a primitive is the only value that is not equal to itself // (perform the [[Class]] check first to avoid errors with some host objects in IE) return isNumber(value) && value != +value; } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(undefined); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is a number. * * Note: `NaN` is considered a number. See http://es5.github.io/#x8.5. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a number, else `false`. * @example * * _.isNumber(8.4 * 5); * // => true */ function isNumber(value) { return typeof value == 'number' || value && typeof value == 'object' && toString.call(value) == numberClass || false; } /** * Checks if `value` is an object created by the `Object` constructor. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * _.isPlainObject(new Shape); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true */ var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { if (!(value && toString.call(value) == objectClass) || (!support.argsClass && isArguments(value))) { return false; } var valueOf = value.valueOf, objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); return objProto ? (value == objProto || getPrototypeOf(value) == objProto) : shimIsPlainObject(value); }; /** * Checks if `value` is a regular expression. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`. * @example * * _.isRegExp(/fred/); * // => true */ function isRegExp(value) { return value && objectTypes[typeof value] && toString.call(value) == regexpClass || false; } /** * Checks if `value` is a string. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a string, else `false`. * @example * * _.isString('fred'); * // => true */ function isString(value) { return typeof value == 'string' || value && typeof value == 'object' && toString.call(value) == stringClass || false; } /** * Checks if `value` is `undefined`. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true */ function isUndefined(value) { return typeof value == 'undefined'; } /** * Creates an object with the same keys as `object` and values generated by * running each own enumerable property of `object` through the callback. * The callback is bound to `thisArg` and invoked with three arguments; * (value, key, object). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new object with values of the results of each `callback` execution. * @example * * _.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; }); * // => { 'a': 3, 'b': 6, 'c': 9 } * * var characters = { * 'fred': { 'name': 'fred', 'age': 40 }, * 'pebbles': { 'name': 'pebbles', 'age': 1 } * }; * * // using "_.pluck" callback shorthand * _.mapValues(characters, 'age'); * // => { 'fred': 40, 'pebbles': 1 } */ function mapValues(object, callback, thisArg) { var result = {}; callback = lodash.createCallback(callback, thisArg, 3); forOwn(object, function(value, key, object) { result[key] = callback(value, key, object); }); return result; } /** * Recursively merges own enumerable properties of the source object(s), that * don't resolve to `undefined` into the destination object. Subsequent sources * will overwrite property assignments of previous sources. If a callback is * provided it will be executed to produce the merged values of the destination * and source properties. If the callback returns `undefined` merging will * be handled by the method instead. The callback is bound to `thisArg` and * invoked with two arguments; (objectValue, sourceValue). * * @static * @memberOf _ * @category Objects * @param {Object} object The destination object. * @param {...Object} [source] The source objects. * @param {Function} [callback] The function to customize merging properties. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the destination object. * @example * * var names = { * 'characters': [ * { 'name': 'barney' }, * { 'name': 'fred' } * ] * }; * * var ages = { * 'characters': [ * { 'age': 36 }, * { 'age': 40 } * ] * }; * * _.merge(names, ages); * // => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] } * * var food = { * 'fruits': ['apple'], * 'vegetables': ['beet'] * }; * * var otherFood = { * 'fruits': ['banana'], * 'vegetables': ['carrot'] * }; * * _.merge(food, otherFood, function(a, b) { * return _.isArray(a) ? a.concat(b) : undefined; * }); * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] } */ function merge(object) { var args = arguments, length = 2; if (!isObject(object)) { return object; } // allows working with `_.reduce` and `_.reduceRight` without using // their `index` and `collection` arguments if (typeof args[2] != 'number') { length = args.length; } if (length > 3 && typeof args[length - 2] == 'function') { var callback = baseCreateCallback(args[--length - 1], args[length--], 2); } else if (length > 2 && typeof args[length - 1] == 'function') { callback = args[--length]; } var sources = slice(arguments, 1, length), index = -1, stackA = getArray(), stackB = getArray(); while (++index < length) { baseMerge(object, sources[index], callback, stackA, stackB); } releaseArray(stackA); releaseArray(stackB); return object; } /** * Creates a shallow clone of `object` excluding the specified properties. * Property names may be specified as individual arguments or as arrays of * property names. If a callback is provided it will be executed for each * property of `object` omitting the properties the callback returns truey * for. The callback is bound to `thisArg` and invoked with three arguments; * (value, key, object). * * @static * @memberOf _ * @category Objects * @param {Object} object The source object. * @param {Function|...string|string[]} [callback] The properties to omit or the * function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns an object without the omitted properties. * @example * * _.omit({ 'name': 'fred', 'age': 40 }, 'age'); * // => { 'name': 'fred' } * * _.omit({ 'name': 'fred', 'age': 40 }, function(value) { * return typeof value == 'number'; * }); * // => { 'name': 'fred' } */ function omit(object, callback, thisArg) { var result = {}; if (typeof callback != 'function') { var props = []; forIn(object, function(value, key) { props.push(key); }); props = baseDifference(props, baseFlatten(arguments, true, false, 1)); var index = -1, length = props.length; while (++index < length) { var key = props[index]; result[key] = object[key]; } } else { callback = lodash.createCallback(callback, thisArg, 3); forIn(object, function(value, key, object) { if (!callback(value, key, object)) { result[key] = value; } }); } return result; } /** * Creates a two dimensional array of an object's key-value pairs, * i.e. `[[key1, value1], [key2, value2]]`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns new array of key-value pairs. * @example * * _.pairs({ 'barney': 36, 'fred': 40 }); * // => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments) */ function pairs(object) { var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { var key = props[index]; result[index] = [key, object[key]]; } return result; } /** * Creates a shallow clone of `object` composed of the specified properties. * Property names may be specified as individual arguments or as arrays of * property names. If a callback is provided it will be executed for each * property of `object` picking the properties the callback returns truey * for. The callback is bound to `thisArg` and invoked with three arguments; * (value, key, object). * * @static * @memberOf _ * @category Objects * @param {Object} object The source object. * @param {Function|...string|string[]} [callback] The function called per * iteration or property names to pick, specified as individual property * names or arrays of property names. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns an object composed of the picked properties. * @example * * _.pick({ 'name': 'fred', '_userid': 'fred1' }, 'name'); * // => { 'name': 'fred' } * * _.pick({ 'name': 'fred', '_userid': 'fred1' }, function(value, key) { * return key.charAt(0) != '_'; * }); * // => { 'name': 'fred' } */ function pick(object, callback, thisArg) { var result = {}; if (typeof callback != 'function') { var index = -1, props = baseFlatten(arguments, true, false, 1), length = isObject(object) ? props.length : 0; while (++index < length) { var key = props[index]; if (key in object) { result[key] = object[key]; } } } else { callback = lodash.createCallback(callback, thisArg, 3); forIn(object, function(value, key, object) { if (callback(value, key, object)) { result[key] = value; } }); } return result; } /** * An alternative to `_.reduce` this method transforms `object` to a new * `accumulator` object which is the result of running each of its own * enumerable properties through a callback, with each callback execution * potentially mutating the `accumulator` object. The callback is bound to * `thisArg` and invoked with four arguments; (accumulator, value, key, object). * Callbacks may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ * @category Objects * @param {Array|Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [accumulator] The custom accumulator value. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the accumulated value. * @example * * var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) { * num *= num; * if (num % 2) { * return result.push(num) < 3; * } * }); * // => [1, 9, 25] * * var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { * result[key] = num * 3; * }); * // => { 'a': 3, 'b': 6, 'c': 9 } */ function transform(object, callback, accumulator, thisArg) { var isArr = isArray(object); if (accumulator == null) { if (isArr) { accumulator = []; } else { var ctor = object && object.constructor, proto = ctor && ctor.prototype; accumulator = baseCreate(proto); } } if (callback) { callback = lodash.createCallback(callback, thisArg, 4); (isArr ? baseEach : forOwn)(object, function(value, index, object) { return callback(accumulator, value, index, object); }); } return accumulator; } /** * Creates an array composed of the own enumerable property values of `object`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns an array of property values. * @example * * _.values({ 'one': 1, 'two': 2, 'three': 3 }); * // => [1, 2, 3] (property order is not guaranteed across environments) */ function values(object) { var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { result[index] = object[props[index]]; } return result; } /*--------------------------------------------------------------------------*/ /** * Creates an array of elements from the specified indexes, or keys, of the * `collection`. Indexes may be specified as individual arguments or as arrays * of indexes. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {...(number|number[]|string|string[])} [index] The indexes of `collection` * to retrieve, specified as individual indexes or arrays of indexes. * @returns {Array} Returns a new array of elements corresponding to the * provided indexes. * @example * * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]); * // => ['a', 'c', 'e'] * * _.at(['fred', 'barney', 'pebbles'], 0, 2); * // => ['fred', 'pebbles'] */ function at(collection) { var args = arguments, index = -1, props = baseFlatten(args, true, false, 1), length = (args[2] && args[2][args[1]] === collection) ? 1 : props.length, result = Array(length); if (support.unindexedChars && isString(collection)) { collection = collection.split(''); } while(++index < length) { result[index] = collection[props[index]]; } return result; } /** * Checks if a given value is present in a collection using strict equality * for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the * offset from the end of the collection. * * @static * @memberOf _ * @alias include * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {*} target The value to check for. * @param {number} [fromIndex=0] The index to search from. * @returns {boolean} Returns `true` if the `target` element is found, else `false`. * @example * * _.contains([1, 2, 3], 1); * // => true * * _.contains([1, 2, 3], 1, 2); * // => false * * _.contains({ 'name': 'fred', 'age': 40 }, 'fred'); * // => true * * _.contains('pebbles', 'eb'); * // => true */ function contains(collection, target, fromIndex) { var index = -1, indexOf = getIndexOf(), length = collection ? collection.length : 0, result = false; fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0; if (isArray(collection)) { result = indexOf(collection, target, fromIndex) > -1; } else if (typeof length == 'number') { result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex)) > -1; } else { baseEach(collection, function(value) { if (++index >= fromIndex) { return !(result = value === target); } }); } return result; } /** * Creates an object composed of keys generated from the results of running * each element of `collection` through the callback. The corresponding value * of each key is the number of times the key was returned by the callback. * The callback is bound to `thisArg` and invoked with three arguments; * (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); * // => { '4': 1, '6': 2 } * * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math); * // => { '4': 1, '6': 2 } * * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1); }); /** * Checks if the given callback returns truey value for **all** elements of * a collection. The callback is bound to `thisArg` and invoked with three * arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias all * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {boolean} Returns `true` if all elements passed the callback check, * else `false`. * @example * * _.every([true, 1, null, 'yes']); * // => false * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * // using "_.pluck" callback shorthand * _.every(characters, 'age'); * // => true * * // using "_.where" callback shorthand * _.every(characters, { 'age': 36 }); * // => false */ function every(collection, callback, thisArg) { var result = true; callback = lodash.createCallback(callback, thisArg, 3); if (isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { if (!(result = !!callback(collection[index], index, collection))) { break; } } } else { baseEach(collection, function(value, index, collection) { return (result = !!callback(value, index, collection)); }); } return result; } /** * Iterates over elements of a collection, returning an array of all elements * the callback returns truey for. The callback is bound to `thisArg` and * invoked with three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias select * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of elements that passed the callback check. * @example * * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); * // => [2, 4, 6] * * var characters = [ * { 'name': 'barney', 'age': 36, 'blocked': false }, * { 'name': 'fred', 'age': 40, 'blocked': true } * ]; * * // using "_.pluck" callback shorthand * _.filter(characters, 'blocked'); * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] * * // using "_.where" callback shorthand * _.filter(characters, { 'age': 36 }); * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] */ function filter(collection, callback, thisArg) { var result = []; callback = lodash.createCallback(callback, thisArg, 3); if (isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; if (callback(value, index, collection)) { result.push(value); } } } else { baseEach(collection, function(value, index, collection) { if (callback(value, index, collection)) { result.push(value); } }); } return result; } /** * Iterates over elements of a collection, returning the first element that * the callback returns truey for. The callback is bound to `thisArg` and * invoked with three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias detect, findWhere * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the found element, else `undefined`. * @example * * var characters = [ * { 'name': 'barney', 'age': 36, 'blocked': false }, * { 'name': 'fred', 'age': 40, 'blocked': true }, * { 'name': 'pebbles', 'age': 1, 'blocked': false } * ]; * * _.find(characters, function(chr) { * return chr.age < 40; * }); * // => { 'name': 'barney', 'age': 36, 'blocked': false } * * // using "_.where" callback shorthand * _.find(characters, { 'age': 1 }); * // => { 'name': 'pebbles', 'age': 1, 'blocked': false } * * // using "_.pluck" callback shorthand * _.find(characters, 'blocked'); * // => { 'name': 'fred', 'age': 40, 'blocked': true } */ function find(collection, callback, thisArg) { callback = lodash.createCallback(callback, thisArg, 3); if (isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; if (callback(value, index, collection)) { return value; } } } else { var result; baseEach(collection, function(value, index, collection) { if (callback(value, index, collection)) { result = value; return false; } }); return result; } } /** * This method is like `_.find` except that it iterates over elements * of a `collection` from right to left. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the found element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(num) { * return num % 2 == 1; * }); * // => 3 */ function findLast(collection, callback, thisArg) { var result; callback = lodash.createCallback(callback, thisArg, 3); forEachRight(collection, function(value, index, collection) { if (callback(value, index, collection)) { result = value; return false; } }); return result; } /** * Iterates over elements of a collection, executing the callback for each * element. The callback is bound to `thisArg` and invoked with three arguments; * (value, index|key, collection). Callbacks may exit iteration early by * explicitly returning `false`. * * Note: As with other "Collections" methods, objects with a `length` property * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn` * may be used for object iteration. * * @static * @memberOf _ * @alias each * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array|Object|string} Returns `collection`. * @example * * _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(','); * // => logs each number and returns '1,2,3' * * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); * // => logs each number and returns the object (property order is not guaranteed across environments) */ function forEach(collection, callback, thisArg) { if (callback && typeof thisArg == 'undefined' && isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { if (callback(collection[index], index, collection) === false) { break; } } } else { baseEach(collection, callback, thisArg); } return collection; } /** * This method is like `_.forEach` except that it iterates over elements * of a `collection` from right to left. * * @static * @memberOf _ * @alias eachRight * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array|Object|string} Returns `collection`. * @example * * _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(','); * // => logs each number from right to left and returns '3,2,1' */ function forEachRight(collection, callback, thisArg) { var iterable = collection, length = collection ? collection.length : 0; callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); if (isArray(collection)) { while (length--) { if (callback(collection[length], length, collection) === false) { break; } } } else { if (typeof length != 'number') { var props = keys(collection); length = props.length; } else if (support.unindexedChars && isString(collection)) { iterable = collection.split(''); } baseEach(collection, function(value, key, collection) { key = props ? props[--length] : --length; return callback(iterable[key], key, collection); }); } return collection; } /** * Creates an object composed of keys generated from the results of running * each element of a collection through the callback. The corresponding value * of each key is an array of the elements responsible for generating the key. * The callback is bound to `thisArg` and invoked with three arguments; * (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false` * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); }); * // => { '4': [4.2], '6': [6.1, 6.4] } * * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); * // => { '4': [4.2], '6': [6.1, 6.4] } * * // using "_.pluck" callback shorthand * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value); }); /** * Creates an object composed of keys generated from the results of running * each element of the collection through the given callback. The corresponding * value of each key is the last element responsible for generating the key. * The callback is bound to `thisArg` and invoked with three arguments; * (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the composed aggregate object. * @example * * var keys = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.indexBy(keys, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } * * _.indexBy(keys, function(key) { return String.fromCharCode(key.code); }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.indexBy(characters, function(key) { this.fromCharCode(key.code); }, String); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } */ var indexBy = createAggregator(function(result, value, key) { result[key] = value; }); /** * Invokes the method named by `methodName` on each element in the `collection` * returning an array of the results of each invoked method. Additional arguments * will be provided to each invoked method. If `methodName` is a function it * will be invoked for, and `this` bound to, each element in the `collection`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|string} methodName The name of the method to invoke or * the function invoked per iteration. * @param {...*} [arg] Arguments to invoke the method with. * @returns {Array} Returns a new array of the results of each invoked method. * @example * * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invoke([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ function invoke(collection, methodName) { var args = slice(arguments, 2), index = -1, isFunc = typeof methodName == 'function', length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); forEach(collection, function(value) { result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args); }); return result; } /** * Creates an array of values by running each element in the collection * through the callback. The callback is bound to `thisArg` and invoked with * three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias collect * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of the results of each `callback` execution. * @example * * _.map([1, 2, 3], function(num) { return num * 3; }); * // => [3, 6, 9] * * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); * // => [3, 6, 9] (property order is not guaranteed across environments) * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * // using "_.pluck" callback shorthand * _.map(characters, 'name'); * // => ['barney', 'fred'] */ function map(collection, callback, thisArg) { var index = -1, length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); callback = lodash.createCallback(callback, thisArg, 3); if (isArray(collection)) { while (++index < length) { result[index] = callback(collection[index], index, collection); } } else { baseEach(collection, function(value, key, collection) { result[++index] = callback(value, key, collection); }); } return result; } /** * Retrieves the maximum value of a collection. If the collection is empty or * falsey `-Infinity` is returned. If a callback is provided it will be executed * for each value in the collection to generate the criterion by which the value * is ranked. The callback is bound to `thisArg` and invoked with three * arguments; (value, index, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the maximum value. * @example * * _.max([4, 2, 8, 6]); * // => 8 * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * _.max(characters, function(chr) { return chr.age; }); * // => { 'name': 'fred', 'age': 40 }; * * // using "_.pluck" callback shorthand * _.max(characters, 'age'); * // => { 'name': 'fred', 'age': 40 }; */ function max(collection, callback, thisArg) { var computed = -Infinity, result = computed; // allows working with functions like `_.map` without using // their `index` argument as a callback if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) { callback = null; } if (callback == null && isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; if (value > result) { result = value; } } } else { callback = (callback == null && isString(collection)) ? charAtCallback : lodash.createCallback(callback, thisArg, 3); baseEach(collection, function(value, index, collection) { var current = callback(value, index, collection); if (current > computed) { computed = current; result = value; } }); } return result; } /** * Retrieves the minimum value of a collection. If the collection is empty or * falsey `Infinity` is returned. If a callback is provided it will be executed * for each value in the collection to generate the criterion by which the value * is ranked. The callback is bound to `thisArg` and invoked with three * arguments; (value, index, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the minimum value. * @example * * _.min([4, 2, 8, 6]); * // => 2 * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * _.min(characters, function(chr) { return chr.age; }); * // => { 'name': 'barney', 'age': 36 }; * * // using "_.pluck" callback shorthand * _.min(characters, 'age'); * // => { 'name': 'barney', 'age': 36 }; */ function min(collection, callback, thisArg) { var computed = Infinity, result = computed; // allows working with functions like `_.map` without using // their `index` argument as a callback if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) { callback = null; } if (callback == null && isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; if (value < result) { result = value; } } } else { callback = (callback == null && isString(collection)) ? charAtCallback : lodash.createCallback(callback, thisArg, 3); baseEach(collection, function(value, index, collection) { var current = callback(value, index, collection); if (current < computed) { computed = current; result = value; } }); } return result; } /** * Retrieves the value of a specified property from all elements in the collection. * * @static * @memberOf _ * @type Function * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {string} property The name of the property to pluck. * @returns {Array} Returns a new array of property values. * @example * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * _.pluck(characters, 'name'); * // => ['barney', 'fred'] */ var pluck = map; /** * Reduces a collection to a value which is the accumulated result of running * each element in the collection through the callback, where each successive * callback execution consumes the return value of the previous execution. If * `accumulator` is not provided the first element of the collection will be * used as the initial `accumulator` value. The callback is bound to `thisArg` * and invoked with four arguments; (accumulator, value, index|key, collection). * * @static * @memberOf _ * @alias foldl, inject * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [accumulator] Initial value of the accumulator. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the accumulated value. * @example * * var sum = _.reduce([1, 2, 3], function(sum, num) { * return sum + num; * }); * // => 6 * * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { * result[key] = num * 3; * return result; * }, {}); * // => { 'a': 3, 'b': 6, 'c': 9 } */ function reduce(collection, callback, accumulator, thisArg) { var noaccum = arguments.length < 3; callback = lodash.createCallback(callback, thisArg, 4); if (isArray(collection)) { var index = -1, length = collection.length; if (noaccum) { accumulator = collection[++index]; } while (++index < length) { accumulator = callback(accumulator, collection[index], index, collection); } } else { baseEach(collection, function(value, index, collection) { accumulator = noaccum ? (noaccum = false, value) : callback(accumulator, value, index, collection) }); } return accumulator; } /** * This method is like `_.reduce` except that it iterates over elements * of a `collection` from right to left. * * @static * @memberOf _ * @alias foldr * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [accumulator] Initial value of the accumulator. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the accumulated value. * @example * * var list = [[0, 1], [2, 3], [4, 5]]; * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, callback, accumulator, thisArg) { var noaccum = arguments.length < 3; callback = lodash.createCallback(callback, thisArg, 4); forEachRight(collection, function(value, index, collection) { accumulator = noaccum ? (noaccum = false, value) : callback(accumulator, value, index, collection); }); return accumulator; } /** * The opposite of `_.filter` this method returns the elements of a * collection that the callback does **not** return truey for. * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of elements that failed the callback check. * @example * * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); * // => [1, 3, 5] * * var characters = [ * { 'name': 'barney', 'age': 36, 'blocked': false }, * { 'name': 'fred', 'age': 40, 'blocked': true } * ]; * * // using "_.pluck" callback shorthand * _.reject(characters, 'blocked'); * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] * * // using "_.where" callback shorthand * _.reject(characters, { 'age': 36 }); * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] */ function reject(collection, callback, thisArg) { callback = lodash.createCallback(callback, thisArg, 3); return filter(collection, function(value, index, collection) { return !callback(value, index, collection); }); } /** * Retrieves a random element or `n` random elements from a collection. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to sample. * @param {number} [n] The number of elements to sample. * @param- {Object} [guard] Allows working with functions like `_.map` * without using their `index` arguments as `n`. * @returns {Array} Returns the random sample(s) of `collection`. * @example * * _.sample([1, 2, 3, 4]); * // => 2 * * _.sample([1, 2, 3, 4], 2); * // => [3, 1] */ function sample(collection, n, guard) { if (collection && typeof collection.length != 'number') { collection = values(collection); } else if (support.unindexedChars && isString(collection)) { collection = collection.split(''); } if (n == null || guard) { return collection ? collection[baseRandom(0, collection.length - 1)] : undefined; } var result = shuffle(collection); result.length = nativeMin(nativeMax(0, n), result.length); return result; } /** * Creates an array of shuffled values, using a version of the Fisher-Yates * shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to shuffle. * @returns {Array} Returns a new shuffled collection. * @example * * _.shuffle([1, 2, 3, 4, 5, 6]); * // => [4, 1, 6, 3, 5, 2] */ function shuffle(collection) { var index = -1, length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); forEach(collection, function(value) { var rand = baseRandom(0, ++index); result[index] = result[rand]; result[rand] = value; }); return result; } /** * Gets the size of the `collection` by returning `collection.length` for arrays * and array-like objects or the number of own enumerable properties for objects. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns `collection.length` or number of own enumerable properties. * @example * * _.size([1, 2]); * // => 2 * * _.size({ 'one': 1, 'two': 2, 'three': 3 }); * // => 3 * * _.size('pebbles'); * // => 7 */ function size(collection) { var length = collection ? collection.length : 0; return typeof length == 'number' ? length : keys(collection).length; } /** * Checks if the callback returns a truey value for **any** element of a * collection. The function returns as soon as it finds a passing value and * does not iterate over the entire collection. The callback is bound to * `thisArg` and invoked with three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias any * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {boolean} Returns `true` if any element passed the callback check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var characters = [ * { 'name': 'barney', 'age': 36, 'blocked': false }, * { 'name': 'fred', 'age': 40, 'blocked': true } * ]; * * // using "_.pluck" callback shorthand * _.some(characters, 'blocked'); * // => true * * // using "_.where" callback shorthand * _.some(characters, { 'age': 1 }); * // => false */ function some(collection, callback, thisArg) { var result; callback = lodash.createCallback(callback, thisArg, 3); if (isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { if ((result = callback(collection[index], index, collection))) { break; } } } else { baseEach(collection, function(value, index, collection) { return !(result = callback(value, index, collection)); }); } return !!result; } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection through the callback. This method * performs a stable sort, that is, it will preserve the original sort order * of equal elements. The callback is bound to `thisArg` and invoked with * three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an array of property names is provided for `callback` the collection * will be sorted by each property value. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Array|Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of sorted elements. * @example * * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); * // => [3, 1, 2] * * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); * // => [3, 1, 2] * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 }, * { 'name': 'barney', 'age': 26 }, * { 'name': 'fred', 'age': 30 } * ]; * * // using "_.pluck" callback shorthand * _.map(_.sortBy(characters, 'age'), _.values); * // => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]] * * // sorting by multiple properties * _.map(_.sortBy(characters, ['name', 'age']), _.values); * // = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]] */ function sortBy(collection, callback, thisArg) { var index = -1, isArr = isArray(callback), length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); if (!isArr) { callback = lodash.createCallback(callback, thisArg, 3); } forEach(collection, function(value, key, collection) { var object = result[++index] = getObject(); if (isArr) { object.criteria = map(callback, function(key) { return value[key]; }); } else { (object.criteria = getArray())[0] = callback(value, key, collection); } object.index = index; object.value = value; }); length = result.length; result.sort(compareAscending); while (length--) { var object = result[length]; result[length] = object.value; if (!isArr) { releaseArray(object.criteria); } releaseObject(object); } return result; } /** * Converts the `collection` to an array. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to convert. * @returns {Array} Returns the new converted array. * @example * * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); * // => [2, 3, 4] */ function toArray(collection) { if (collection && typeof collection.length == 'number') { return (support.unindexedChars && isString(collection)) ? collection.split('') : slice(collection); } return values(collection); } /** * Performs a deep comparison of each element in a `collection` to the given * `properties` object, returning an array of all elements that have equivalent * property values. * * @static * @memberOf _ * @type Function * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Object} props The object of property values to filter by. * @returns {Array} Returns a new array of elements that have the given properties. * @example * * var characters = [ * { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }, * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] } * ]; * * _.where(characters, { 'age': 36 }); * // => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }] * * _.where(characters, { 'pets': ['dino'] }); * // => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }] */ var where = filter; /*--------------------------------------------------------------------------*/ /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are all falsey. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to compact. * @returns {Array} Returns a new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array ? array.length : 0, result = []; while (++index < length) { var value = array[index]; if (value) { result.push(value); } } return result; } /** * Creates an array excluding all values of the provided arrays using strict * equality for comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to process. * @param {...Array} [values] The arrays of values to exclude. * @returns {Array} Returns a new array of filtered values. * @example * * _.difference([1, 2, 3, 4, 5], [5, 2, 10]); * // => [1, 3, 4] */ function difference(array) { return baseDifference(array, baseFlatten(arguments, true, true, 1)); } /** * This method is like `_.find` except that it returns the index of the first * element that passes the callback check, instead of the element itself. * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var characters = [ * { 'name': 'barney', 'age': 36, 'blocked': false }, * { 'name': 'fred', 'age': 40, 'blocked': true }, * { 'name': 'pebbles', 'age': 1, 'blocked': false } * ]; * * _.findIndex(characters, function(chr) { * return chr.age < 20; * }); * // => 2 * * // using "_.where" callback shorthand * _.findIndex(characters, { 'age': 36 }); * // => 0 * * // using "_.pluck" callback shorthand * _.findIndex(characters, 'blocked'); * // => 1 */ function findIndex(array, callback, thisArg) { var index = -1, length = array ? array.length : 0; callback = lodash.createCallback(callback, thisArg, 3); while (++index < length) { if (callback(array[index], index, array)) { return index; } } return -1; } /** * This method is like `_.findIndex` except that it iterates over elements * of a `collection` from right to left. * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var characters = [ * { 'name': 'barney', 'age': 36, 'blocked': true }, * { 'name': 'fred', 'age': 40, 'blocked': false }, * { 'name': 'pebbles', 'age': 1, 'blocked': true } * ]; * * _.findLastIndex(characters, function(chr) { * return chr.age > 30; * }); * // => 1 * * // using "_.where" callback shorthand * _.findLastIndex(characters, { 'age': 36 }); * // => 0 * * // using "_.pluck" callback shorthand * _.findLastIndex(characters, 'blocked'); * // => 2 */ function findLastIndex(array, callback, thisArg) { var length = array ? array.length : 0; callback = lodash.createCallback(callback, thisArg, 3); while (length--) { if (callback(array[length], length, array)) { return length; } } return -1; } /** * Gets the first element or first `n` elements of an array. If a callback * is provided elements at the beginning of the array are returned as long * as the callback returns truey. The callback is bound to `thisArg` and * invoked with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias head, take * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|number|string} [callback] The function called * per element or the number of elements to return. If a property name or * object is provided it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the first element(s) of `array`. * @example * * _.first([1, 2, 3]); * // => 1 * * _.first([1, 2, 3], 2); * // => [1, 2] * * _.first([1, 2, 3], function(num) { * return num < 3; * }); * // => [1, 2] * * var characters = [ * { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, * { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } * ]; * * // using "_.pluck" callback shorthand * _.first(characters, 'blocked'); * // => [{ 'name': 'barney', 'blocked': true, 'employer': 'slate' }] * * // using "_.where" callback shorthand * _.pluck(_.first(characters, { 'employer': 'slate' }), 'name'); * // => ['barney', 'fred'] */ function first(array, callback, thisArg) { var n = 0, length = array ? array.length : 0; if (typeof callback != 'number' && callback != null) { var index = -1; callback = lodash.createCallback(callback, thisArg, 3); while (++index < length && callback(array[index], index, array)) { n++; } } else { n = callback; if (n == null || thisArg) { return array ? array[0] : undefined; } } return slice(array, 0, nativeMin(nativeMax(0, n), length)); } /** * Flattens a nested array (the nesting can be to any depth). If `isShallow` * is truey, the array will only be flattened a single level. If a callback * is provided each element of the array is passed through the callback before * flattening. The callback is bound to `thisArg` and invoked with three * arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to flatten. * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new flattened array. * @example * * _.flatten([1, [2], [3, [[4]]]]); * // => [1, 2, 3, 4]; * * _.flatten([1, [2], [3, [[4]]]], true); * // => [1, 2, 3, [[4]]]; * * var characters = [ * { 'name': 'barney', 'age': 30, 'pets': ['hoppy'] }, * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] } * ]; * * // using "_.pluck" callback shorthand * _.flatten(characters, 'pets'); * // => ['hoppy', 'baby puss', 'dino'] */ function flatten(array, isShallow, callback, thisArg) { // juggle arguments if (typeof isShallow != 'boolean' && isShallow != null) { thisArg = callback; callback = (typeof isShallow != 'function' && thisArg && thisArg[isShallow] === array) ? null : isShallow; isShallow = false; } if (callback != null) { array = map(array, callback, thisArg); } return baseFlatten(array, isShallow); } /** * Gets the index at which the first occurrence of `value` is found using * strict equality for comparisons, i.e. `===`. If the array is already sorted * providing `true` for `fromIndex` will run a faster binary search. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {boolean|number} [fromIndex=0] The index to search from or `true` * to perform a binary search on a sorted array. * @returns {number} Returns the index of the matched value or `-1`. * @example * * _.indexOf([1, 2, 3, 1, 2, 3], 2); * // => 1 * * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); * // => 4 * * _.indexOf([1, 1, 2, 2, 3, 3], 2, true); * // => 2 */ function indexOf(array, value, fromIndex) { if (typeof fromIndex == 'number') { var length = array ? array.length : 0; fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0); } else if (fromIndex) { var index = sortedIndex(array, value); return array[index] === value ? index : -1; } return baseIndexOf(array, value, fromIndex); } /** * Gets all but the last element or last `n` elements of an array. If a * callback is provided elements at the end of the array are excluded from * the result as long as the callback returns truey. The callback is bound * to `thisArg` and invoked with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|number|string} [callback=1] The function called * per element or the number of elements to exclude. If a property name or * object is provided it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] * * _.initial([1, 2, 3], 2); * // => [1] * * _.initial([1, 2, 3], function(num) { * return num > 1; * }); * // => [1] * * var characters = [ * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } * ]; * * // using "_.pluck" callback shorthand * _.initial(characters, 'blocked'); * // => [{ 'name': 'barney', 'blocked': false, 'employer': 'slate' }] * * // using "_.where" callback shorthand * _.pluck(_.initial(characters, { 'employer': 'na' }), 'name'); * // => ['barney', 'fred'] */ function initial(array, callback, thisArg) { var n = 0, length = array ? array.length : 0; if (typeof callback != 'number' && callback != null) { var index = length; callback = lodash.createCallback(callback, thisArg, 3); while (index-- && callback(array[index], index, array)) { n++; } } else { n = (callback == null || thisArg) ? 1 : callback || n; } return slice(array, 0, nativeMin(nativeMax(0, length - n), length)); } /** * Creates an array of unique values present in all provided arrays using * strict equality for comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {...Array} [array] The arrays to inspect. * @returns {Array} Returns an array of shared values. * @example * * _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]); * // => [1, 2] */ function intersection() { var args = [], argsIndex = -1, argsLength = arguments.length, caches = getArray(), indexOf = getIndexOf(), trustIndexOf = indexOf === baseIndexOf, seen = getArray(); while (++argsIndex < argsLength) { var value = arguments[argsIndex]; if (isArray(value) || isArguments(value)) { args.push(value); caches.push(trustIndexOf && value.length >= largeArraySize && createCache(argsIndex ? args[argsIndex] : seen)); } } var array = args[0], index = -1, length = array ? array.length : 0, result = []; outer: while (++index < length) { var cache = caches[0]; value = array[index]; if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) { argsIndex = argsLength; (cache || seen).push(value); while (--argsIndex) { cache = caches[argsIndex]; if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) { continue outer; } } result.push(value); } } while (argsLength--) { cache = caches[argsLength]; if (cache) { releaseObject(cache); } } releaseArray(caches); releaseArray(seen); return result; } /** * Gets the last element or last `n` elements of an array. If a callback is * provided elements at the end of the array are returned as long as the * callback returns truey. The callback is bound to `thisArg` and invoked * with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|number|string} [callback] The function called * per element or the number of elements to return. If a property name or * object is provided it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the last element(s) of `array`. * @example * * _.last([1, 2, 3]); * // => 3 * * _.last([1, 2, 3], 2); * // => [2, 3] * * _.last([1, 2, 3], function(num) { * return num > 1; * }); * // => [2, 3] * * var characters = [ * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } * ]; * * // using "_.pluck" callback shorthand * _.pluck(_.last(characters, 'blocked'), 'name'); * // => ['fred', 'pebbles'] * * // using "_.where" callback shorthand * _.last(characters, { 'employer': 'na' }); * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] */ function last(array, callback, thisArg) { var n = 0, length = array ? array.length : 0; if (typeof callback != 'number' && callback != null) { var index = length; callback = lodash.createCallback(callback, thisArg, 3); while (index-- && callback(array[index], index, array)) { n++; } } else { n = callback; if (n == null || thisArg) { return array ? array[length - 1] : undefined; } } return slice(array, nativeMax(0, length - n)); } /** * Gets the index at which the last occurrence of `value` is found using strict * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used * as the offset from the end of the collection. * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the matched value or `-1`. * @example * * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); * // => 4 * * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var index = array ? array.length : 0; if (typeof fromIndex == 'number') { index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1; } while (index--) { if (array[index] === value) { return index; } } return -1; } /** * Removes all provided values from the given array using strict equality for * comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to modify. * @param {...*} [value] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3, 1, 2, 3]; * _.pull(array, 2, 3); * console.log(array); * // => [1, 1] */ function pull(array) { var args = arguments, argsIndex = 0, argsLength = args.length, length = array ? array.length : 0; while (++argsIndex < argsLength) { var index = -1, value = args[argsIndex]; while (++index < length) { if (array[index] === value) { splice.call(array, index--, 1); length--; } } } return array; } /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to but not including `end`. If `start` is less than `stop` a * zero-length range is created unless a negative `step` is specified. * * @static * @memberOf _ * @category Arrays * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns a new range array. * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ function range(start, end, step) { start = +start || 0; step = typeof step == 'number' ? step : (+step || 1); if (end == null) { end = start; start = 0; } // use `Array(length)` so engines like Chakra and V8 avoid slower modes // http://youtu.be/XAqIpGU8ZZk#t=17m25s var index = -1, length = nativeMax(0, ceil((end - start) / (step || 1))), result = Array(length); while (++index < length) { result[index] = start; start += step; } return result; } /** * Removes all elements from an array that the callback returns truey for * and returns an array of removed elements. The callback is bound to `thisArg` * and invoked with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to modify. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of removed elements. * @example * * var array = [1, 2, 3, 4, 5, 6]; * var evens = _.remove(array, function(num) { return num % 2 == 0; }); * * console.log(array); * // => [1, 3, 5] * * console.log(evens); * // => [2, 4, 6] */ function remove(array, callback, thisArg) { var index = -1, length = array ? array.length : 0, result = []; callback = lodash.createCallback(callback, thisArg, 3); while (++index < length) { var value = array[index]; if (callback(value, index, array)) { result.push(value); splice.call(array, index--, 1); length--; } } return result; } /** * The opposite of `_.initial` this method gets all but the first element or * first `n` elements of an array. If a callback function is provided elements * at the beginning of the array are excluded from the result as long as the * callback returns truey. The callback is bound to `thisArg` and invoked * with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias drop, tail * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|number|string} [callback=1] The function called * per element or the number of elements to exclude. If a property name or * object is provided it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a slice of `array`. * @example * * _.rest([1, 2, 3]); * // => [2, 3] * * _.rest([1, 2, 3], 2); * // => [3] * * _.rest([1, 2, 3], function(num) { * return num < 3; * }); * // => [3] * * var characters = [ * { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, * { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } * ]; * * // using "_.pluck" callback shorthand * _.pluck(_.rest(characters, 'blocked'), 'name'); * // => ['fred', 'pebbles'] * * // using "_.where" callback shorthand * _.rest(characters, { 'employer': 'slate' }); * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] */ function rest(array, callback, thisArg) { if (typeof callback != 'number' && callback != null) { var n = 0, index = -1, length = array ? array.length : 0; callback = lodash.createCallback(callback, thisArg, 3); while (++index < length && callback(array[index], index, array)) { n++; } } else { n = (callback == null || thisArg) ? 1 : nativeMax(0, callback); } return slice(array, n); } /** * Uses a binary search to determine the smallest index at which a value * should be inserted into a given sorted array in order to maintain the sort * order of the array. If a callback is provided it will be executed for * `value` and each element of `array` to compute their sort ranking. The * callback is bound to `thisArg` and invoked with one argument; (value). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to inspect. * @param {*} value The value to evaluate. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([20, 30, 50], 40); * // => 2 * * // using "_.pluck" callback shorthand * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); * // => 2 * * var dict = { * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } * }; * * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { * return dict.wordToNumber[word]; * }); * // => 2 * * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { * return this.wordToNumber[word]; * }, dict); * // => 2 */ function sortedIndex(array, value, callback, thisArg) { var low = 0, high = array ? array.length : low; // explicitly reference `identity` for better inlining in Firefox callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity; value = callback(value); while (low < high) { var mid = (low + high) >>> 1; (callback(array[mid]) < value) ? low = mid + 1 : high = mid; } return low; } /** * Creates an array of unique values, in order, of the provided arrays using * strict equality for comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {...Array} [array] The arrays to inspect. * @returns {Array} Returns an array of combined values. * @example * * _.union([1, 2, 3], [5, 2, 1, 4], [2, 1]); * // => [1, 2, 3, 5, 4] */ function union() { return baseUniq(baseFlatten(arguments, true, true)); } /** * Creates a duplicate-value-free version of an array using strict equality * for comparisons, i.e. `===`. If the array is sorted, providing * `true` for `isSorted` will use a faster algorithm. If a callback is provided * each element of `array` is passed through the callback before uniqueness * is computed. The callback is bound to `thisArg` and invoked with three * arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias unique * @category Arrays * @param {Array} array The array to process. * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a duplicate-value-free array. * @example * * _.uniq([1, 2, 1, 3, 1]); * // => [1, 2, 3] * * _.uniq([1, 1, 2, 2, 3], true); * // => [1, 2, 3] * * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); }); * // => ['A', 'b', 'C'] * * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math); * // => [1, 2.5, 3] * * // using "_.pluck" callback shorthand * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniq(array, isSorted, callback, thisArg) { // juggle arguments if (typeof isSorted != 'boolean' && isSorted != null) { thisArg = callback; callback = (typeof isSorted != 'function' && thisArg && thisArg[isSorted] === array) ? null : isSorted; isSorted = false; } if (callback != null) { callback = lodash.createCallback(callback, thisArg, 3); } return baseUniq(array, isSorted, callback); } /** * Creates an array excluding all provided values using strict equality for * comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to filter. * @param {...*} [value] The values to exclude. * @returns {Array} Returns a new array of filtered values. * @example * * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); * // => [2, 3, 4] */ function without(array) { return baseDifference(array, slice(arguments, 1)); } /** * Creates an array that is the symmetric difference of the provided arrays. * See http://en.wikipedia.org/wiki/Symmetric_difference. * * @static * @memberOf _ * @category Arrays * @param {...Array} [array] The arrays to inspect. * @returns {Array} Returns an array of values. * @example * * _.xor([1, 2, 3], [5, 2, 1, 4]); * // => [3, 5, 4] * * _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]); * // => [1, 4, 5] */ function xor() { var index = -1, length = arguments.length; while (++index < length) { var array = arguments[index]; if (isArray(array) || isArguments(array)) { var result = result ? baseUniq(baseDifference(result, array).concat(baseDifference(array, result))) : array; } } return result || []; } /** * Creates an array of grouped elements, the first of which contains the first * elements of the given arrays, the second of which contains the second * elements of the given arrays, and so on. * * @static * @memberOf _ * @alias unzip * @category Arrays * @param {...Array} [array] Arrays to process. * @returns {Array} Returns a new array of grouped elements. * @example * * _.zip(['fred', 'barney'], [30, 40], [true, false]); * // => [['fred', 30, true], ['barney', 40, false]] */ function zip() { var array = arguments.length > 1 ? arguments : arguments[0], index = -1, length = array ? max(pluck(array, 'length')) : 0, result = Array(length < 0 ? 0 : length); while (++index < length) { result[index] = pluck(array, index); } return result; } /** * Creates an object composed from arrays of `keys` and `values`. Provide * either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]` * or two arrays, one of `keys` and one of corresponding `values`. * * @static * @memberOf _ * @alias object * @category Arrays * @param {Array} keys The array of keys. * @param {Array} [values=[]] The array of values. * @returns {Object} Returns an object composed of the given keys and * corresponding values. * @example * * _.zipObject(['fred', 'barney'], [30, 40]); * // => { 'fred': 30, 'barney': 40 } */ function zipObject(keys, values) { var index = -1, length = keys ? keys.length : 0, result = {}; if (!values && length && !isArray(keys[0])) { values = []; } while (++index < length) { var key = keys[index]; if (values) { result[key] = values[index]; } else if (key) { result[key[0]] = key[1]; } } return result; } /*--------------------------------------------------------------------------*/ /** * Creates a function that executes `func`, with the `this` binding and * arguments of the created function, only after being called `n` times. * * @static * @memberOf _ * @category Functions * @param {number} n The number of times the function must be called before * `func` is executed. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('Done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => logs 'Done saving!', after all saves have completed */ function after(n, func) { if (!isFunction(func)) { throw new TypeError; } return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that, when called, invokes `func` with the `this` * binding of `thisArg` and prepends any additional `bind` arguments to those * provided to the bound function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to bind. * @param {*} [thisArg] The `this` binding of `func`. * @param {...*} [arg] Arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var func = function(greeting) { * return greeting + ' ' + this.name; * }; * * func = _.bind(func, { 'name': 'fred' }, 'hi'); * func(); * // => 'hi fred' */ function bind(func, thisArg) { return arguments.length > 2 ? createWrapper(func, 17, slice(arguments, 2), null, thisArg) : createWrapper(func, 1, null, null, thisArg); } /** * Binds methods of an object to the object itself, overwriting the existing * method. Method names may be specified as individual arguments or as arrays * of method names. If no method names are provided all the function properties * of `object` will be bound. * * @static * @memberOf _ * @category Functions * @param {Object} object The object to bind and assign the bound methods to. * @param {...string} [methodName] The object method names to * bind, specified as individual method names or arrays of method names. * @returns {Object} Returns `object`. * @example * * var view = { * 'label': 'docs', * 'onClick': function() { console.log('clicked ' + this.label); } * }; * * _.bindAll(view); * jQuery('#docs').on('click', view.onClick); * // => logs 'clicked docs', when the button is clicked */ function bindAll(object) { var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object), index = -1, length = funcs.length; while (++index < length) { var key = funcs[index]; object[key] = createWrapper(object[key], 1, null, null, object); } return object; } /** * Creates a function that, when called, invokes the method at `object[key]` * and prepends any additional `bindKey` arguments to those provided to the bound * function. This method differs from `_.bind` by allowing bound functions to * reference methods that will be redefined or don't yet exist. * See http://michaux.ca/articles/lazy-function-definition-pattern. * * @static * @memberOf _ * @category Functions * @param {Object} object The object the method belongs to. * @param {string} key The key of the method. * @param {...*} [arg] Arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'name': 'fred', * 'greet': function(greeting) { * return greeting + ' ' + this.name; * } * }; * * var func = _.bindKey(object, 'greet', 'hi'); * func(); * // => 'hi fred' * * object.greet = function(greeting) { * return greeting + 'ya ' + this.name + '!'; * }; * * func(); * // => 'hiya fred!' */ function bindKey(object, key) { return arguments.length > 2 ? createWrapper(key, 19, slice(arguments, 2), null, object) : createWrapper(key, 3, null, null, object); } /** * Creates a function that is the composition of the provided functions, * where each function consumes the return value of the function that follows. * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. * Each function is executed with the `this` binding of the composed function. * * @static * @memberOf _ * @category Functions * @param {...Function} [func] Functions to compose. * @returns {Function} Returns the new composed function. * @example * * var realNameMap = { * 'pebbles': 'penelope' * }; * * var format = function(name) { * name = realNameMap[name.toLowerCase()] || name; * return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase(); * }; * * var greet = function(formatted) { * return 'Hiya ' + formatted + '!'; * }; * * var welcome = _.compose(greet, format); * welcome('pebbles'); * // => 'Hiya Penelope!' */ function compose() { var funcs = arguments, length = funcs.length; while (length--) { if (!isFunction(funcs[length])) { throw new TypeError; } } return function() { var args = arguments, length = funcs.length; while (length--) { args = [funcs[length].apply(this, args)]; } return args[0]; }; } /** * Creates a function which accepts one or more arguments of `func` that when * invoked either executes `func` returning its result, if all `func` arguments * have been provided, or returns a function that accepts one or more of the * remaining `func` arguments, and so on. The arity of `func` can be specified * if `func.length` is not sufficient. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @returns {Function} Returns the new curried function. * @example * * var curried = _.curry(function(a, b, c) { * console.log(a + b + c); * }); * * curried(1)(2)(3); * // => 6 * * curried(1, 2)(3); * // => 6 * * curried(1, 2, 3); * // => 6 */ function curry(func, arity) { arity = typeof arity == 'number' ? arity : (+arity || func.length); return createWrapper(func, 4, null, null, null, arity); } /** * Creates a function that will delay the execution of `func` until after * `wait` milliseconds have elapsed since the last time it was invoked. * Provide an options object to indicate that `func` should be invoked on * the leading and/or trailing edge of the `wait` timeout. Subsequent calls * to the debounced function will return the result of the last `func` call. * * Note: If `leading` and `trailing` options are `true` `func` will be called * on the trailing edge of the timeout only if the the debounced function is * invoked more than once during the `wait` timeout. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to debounce. * @param {number} wait The number of milliseconds to delay. * @param {Object} [options] The options object. * @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout. * @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called. * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // avoid costly calculations while the window size is in flux * var lazyLayout = _.debounce(calculateLayout, 150); * jQuery(window).on('resize', lazyLayout); * * // execute `sendMail` when the click event is fired, debouncing subsequent calls * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * }); * * // ensure `batchLog` is executed once after 1 second of debounced calls * var source = new EventSource('/stream'); * source.addEventListener('message', _.debounce(batchLog, 250, { * 'maxWait': 1000 * }, false); */ function debounce(func, wait, options) { var args, maxTimeoutId, result, stamp, thisArg, timeoutId, trailingCall, lastCalled = 0, maxWait = false, trailing = true; if (!isFunction(func)) { throw new TypeError; } wait = nativeMax(0, wait) || 0; if (options === true) { var leading = true; trailing = false; } else if (isObject(options)) { leading = options.leading; maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0); trailing = 'trailing' in options ? options.trailing : trailing; } var delayed = function() { var remaining = wait - (now() - stamp); if (remaining <= 0) { if (maxTimeoutId) { clearTimeout(maxTimeoutId); } var isCalled = trailingCall; maxTimeoutId = timeoutId = trailingCall = undefined; if (isCalled) { lastCalled = now(); result = func.apply(thisArg, args); if (!timeoutId && !maxTimeoutId) { args = thisArg = null; } } } else { timeoutId = setTimeout(delayed, remaining); } }; var maxDelayed = function() { if (timeoutId) { clearTimeout(timeoutId); } maxTimeoutId = timeoutId = trailingCall = undefined; if (trailing || (maxWait !== wait)) { lastCalled = now(); result = func.apply(thisArg, args); if (!timeoutId && !maxTimeoutId) { args = thisArg = null; } } }; return function() { args = arguments; stamp = now(); thisArg = this; trailingCall = trailing && (timeoutId || !leading); if (maxWait === false) { var leadingCall = leading && !timeoutId; } else { if (!maxTimeoutId && !leading) { lastCalled = stamp; } var remaining = maxWait - (stamp - lastCalled), isCalled = remaining <= 0; if (isCalled) { if (maxTimeoutId) { maxTimeoutId = clearTimeout(maxTimeoutId); } lastCalled = stamp; result = func.apply(thisArg, args); } else if (!maxTimeoutId) { maxTimeoutId = setTimeout(maxDelayed, remaining); } } if (isCalled && timeoutId) { timeoutId = clearTimeout(timeoutId); } else if (!timeoutId && wait !== maxWait) { timeoutId = setTimeout(delayed, wait); } if (leadingCall) { isCalled = true; result = func.apply(thisArg, args); } if (isCalled && !timeoutId && !maxTimeoutId) { args = thisArg = null; } return result; }; } /** * Defers executing the `func` function until the current call stack has cleared. * Additional arguments will be provided to `func` when it is invoked. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to defer. * @param {...*} [arg] Arguments to invoke the function with. * @returns {number} Returns the timer id. * @example * * _.defer(function(text) { console.log(text); }, 'deferred'); * // logs 'deferred' after one or more milliseconds */ function defer(func) { if (!isFunction(func)) { throw new TypeError; } var args = slice(arguments, 1); return setTimeout(function() { func.apply(undefined, args); }, 1); } /** * Executes the `func` function after `wait` milliseconds. Additional arguments * will be provided to `func` when it is invoked. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay execution. * @param {...*} [arg] Arguments to invoke the function with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { console.log(text); }, 1000, 'later'); * // => logs 'later' after one second */ function delay(func, wait) { if (!isFunction(func)) { throw new TypeError; } var args = slice(arguments, 2); return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided it will be used to determine the cache key for storing the result * based on the arguments provided to the memoized function. By default, the * first argument provided to the memoized function is used as the cache key. * The `func` is executed with the `this` binding of the memoized function. * The result cache is exposed as the `cache` property on the memoized function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] A function used to resolve the cache key. * @returns {Function} Returns the new memoizing function. * @example * * var fibonacci = _.memoize(function(n) { * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); * }); * * fibonacci(9) * // => 34 * * var data = { * 'fred': { 'name': 'fred', 'age': 40 }, * 'pebbles': { 'name': 'pebbles', 'age': 1 } * }; * * // modifying the result cache * var get = _.memoize(function(name) { return data[name]; }, _.identity); * get('pebbles'); * // => { 'name': 'pebbles', 'age': 1 } * * get.cache.pebbles.name = 'penelope'; * get('pebbles'); * // => { 'name': 'penelope', 'age': 1 } */ function memoize(func, resolver) { if (!isFunction(func)) { throw new TypeError; } var memoized = function() { var cache = memoized.cache, key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0]; return hasOwnProperty.call(cache, key) ? cache[key] : (cache[key] = func.apply(this, arguments)); } memoized.cache = {}; return memoized; } /** * Creates a function that is restricted to execute `func` once. Repeat calls to * the function will return the value of the first call. The `func` is executed * with the `this` binding of the created function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // `initialize` executes `createApplication` once */ function once(func) { var ran, result; if (!isFunction(func)) { throw new TypeError; } return function() { if (ran) { return result; } ran = true; result = func.apply(this, arguments); // clear the `func` variable so the function may be garbage collected func = null; return result; }; } /** * Creates a function that, when called, invokes `func` with any additional * `partial` arguments prepended to those provided to the new function. This * method is similar to `_.bind` except it does **not** alter the `this` binding. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to partially apply arguments to. * @param {...*} [arg] Arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var greet = function(greeting, name) { return greeting + ' ' + name; }; * var hi = _.partial(greet, 'hi'); * hi('fred'); * // => 'hi fred' */ function partial(func) { return createWrapper(func, 16, slice(arguments, 1)); } /** * This method is like `_.partial` except that `partial` arguments are * appended to those provided to the new function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to partially apply arguments to. * @param {...*} [arg] Arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var defaultsDeep = _.partialRight(_.merge, _.defaults); * * var options = { * 'variable': 'data', * 'imports': { 'jq': $ } * }; * * defaultsDeep(options, _.templateSettings); * * options.variable * // => 'data' * * options.imports * // => { '_': _, 'jq': $ } */ function partialRight(func) { return createWrapper(func, 32, null, slice(arguments, 1)); } /** * Creates a function that, when executed, will only call the `func` function * at most once per every `wait` milliseconds. Provide an options object to * indicate that `func` should be invoked on the leading and/or trailing edge * of the `wait` timeout. Subsequent calls to the throttled function will * return the result of the last `func` call. * * Note: If `leading` and `trailing` options are `true` `func` will be called * on the trailing edge of the timeout only if the the throttled function is * invoked more than once during the `wait` timeout. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to throttle. * @param {number} wait The number of milliseconds to throttle executions to. * @param {Object} [options] The options object. * @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout. * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // avoid excessively updating the position while scrolling * var throttled = _.throttle(updatePosition, 100); * jQuery(window).on('scroll', throttled); * * // execute `renewToken` when the click event is fired, but not more than once every 5 minutes * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { * 'trailing': false * })); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (!isFunction(func)) { throw new TypeError; } if (options === false) { leading = false; } else if (isObject(options)) { leading = 'leading' in options ? options.leading : leading; trailing = 'trailing' in options ? options.trailing : trailing; } debounceOptions.leading = leading; debounceOptions.maxWait = wait; debounceOptions.trailing = trailing; return debounce(func, wait, debounceOptions); } /** * Creates a function that provides `value` to the wrapper function as its * first argument. Additional arguments provided to the function are appended * to those provided to the wrapper function. The wrapper is executed with * the `this` binding of the created function. * * @static * @memberOf _ * @category Functions * @param {*} value The value to wrap. * @param {Function} wrapper The wrapper function. * @returns {Function} Returns the new function. * @example * * var p = _.wrap(_.escape, function(func, text) { * return '<p>' + func(text) + '</p>'; * }); * * p('Fred, Wilma, & Pebbles'); * // => '<p>Fred, Wilma, &amp; Pebbles</p>' */ function wrap(value, wrapper) { return createWrapper(wrapper, 16, [value]); } /*--------------------------------------------------------------------------*/ /** * Creates a function that returns `value`. * * @static * @memberOf _ * @category Utilities * @param {*} value The value to return from the new function. * @returns {Function} Returns the new function. * @example * * var object = { 'name': 'fred' }; * var getter = _.constant(object); * getter() === object; * // => true */ function constant(value) { return function() { return value; }; } /** * Produces a callback bound to an optional `thisArg`. If `func` is a property * name the created callback will return the property value for a given element. * If `func` is an object the created callback will return `true` for elements * that contain the equivalent object properties, otherwise it will return `false`. * * @static * @memberOf _ * @category Utilities * @param {*} [func=identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of the created callback. * @param {number} [argCount] The number of arguments the callback accepts. * @returns {Function} Returns a callback function. * @example * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * // wrap to create custom callback shorthands * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) { * var match = /^(.+?)__([gl]t)(.+)$/.exec(callback); * return !match ? func(callback, thisArg) : function(object) { * return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3]; * }; * }); * * _.filter(characters, 'age__gt38'); * // => [{ 'name': 'fred', 'age': 40 }] */ function createCallback(func, thisArg, argCount) { var type = typeof func; if (func == null || type == 'function') { return baseCreateCallback(func, thisArg, argCount); } // handle "_.pluck" style callback shorthands if (type != 'object') { return property(func); } var props = keys(func), key = props[0], a = func[key]; // handle "_.where" style callback shorthands if (props.length == 1 && a === a && !isObject(a)) { // fast path the common case of providing an object with a single // property containing a primitive value return function(object) { var b = object[key]; return a === b && (a !== 0 || (1 / a == 1 / b)); }; } return function(object) { var length = props.length, result = false; while (length--) { if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) { break; } } return result; }; } /** * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their * corresponding HTML entities. * * @static * @memberOf _ * @category Utilities * @param {string} string The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('Fred, Wilma, & Pebbles'); * // => 'Fred, Wilma, &amp; Pebbles' */ function escape(string) { return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar); } /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utilities * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'name': 'fred' }; * _.identity(object) === object; * // => true */ function identity(value) { return value; } /** * Adds function properties of a source object to the destination object. * If `object` is a function methods will be added to its prototype as well. * * @static * @memberOf _ * @category Utilities * @param {Function|Object} [object=lodash] object The destination object. * @param {Object} source The object of functions to add. * @param {Object} [options] The options object. * @param {boolean} [options.chain=true] Specify whether the functions added are chainable. * @example * * function capitalize(string) { * return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); * } * * _.mixin({ 'capitalize': capitalize }); * _.capitalize('fred'); * // => 'Fred' * * _('fred').capitalize().value(); * // => 'Fred' * * _.mixin({ 'capitalize': capitalize }, { 'chain': false }); * _('fred').capitalize(); * // => 'Fred' */ function mixin(object, source, options) { var chain = true, methodNames = source && functions(source); if (!source || (!options && !methodNames.length)) { if (options == null) { options = source; } ctor = lodashWrapper; source = object; object = lodash; methodNames = functions(source); } if (options === false) { chain = false; } else if (isObject(options) && 'chain' in options) { chain = options.chain; } var ctor = object, isFunc = isFunction(ctor); forEach(methodNames, function(methodName) { var func = object[methodName] = source[methodName]; if (isFunc) { ctor.prototype[methodName] = function() { var chainAll = this.__chain__, value = this.__wrapped__, args = [value]; push.apply(args, arguments); var result = func.apply(object, args); if (chain || chainAll) { if (value === result && isObject(result)) { return this; } result = new ctor(result); result.__chain__ = chainAll; } return result; }; } }); } /** * Reverts the '_' variable to its previous value and returns a reference to * the `lodash` function. * * @static * @memberOf _ * @category Utilities * @returns {Function} Returns the `lodash` function. * @example * * var lodash = _.noConflict(); */ function noConflict() { context._ = oldDash; return this; } /** * A no-operation function. * * @static * @memberOf _ * @category Utilities * @example * * var object = { 'name': 'fred' }; * _.noop(object) === undefined; * // => true */ function noop() { // no operation performed } /** * Gets the number of milliseconds that have elapsed since the Unix epoch * (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @category Utilities * @example * * var stamp = _.now(); * _.defer(function() { console.log(_.now() - stamp); }); * // => logs the number of milliseconds it took for the deferred function to be called */ var now = isNative(now = Date.now) && now || function() { return new Date().getTime(); }; /** * Converts the given value into an integer of the specified radix. * If `radix` is `undefined` or `0` a `radix` of `10` is used unless the * `value` is a hexadecimal, in which case a `radix` of `16` is used. * * Note: This method avoids differences in native ES3 and ES5 `parseInt` * implementations. See http://es5.github.io/#E. * * @static * @memberOf _ * @category Utilities * @param {string} value The value to parse. * @param {number} [radix] The radix used to interpret the value to parse. * @returns {number} Returns the new integer value. * @example * * _.parseInt('08'); * // => 8 */ var parseInt = nativeParseInt(whitespace + '08') == 8 ? nativeParseInt : function(value, radix) { // Firefox < 21 and Opera < 15 follow the ES3 specified implementation of `parseInt` return nativeParseInt(isString(value) ? value.replace(reLeadingSpacesAndZeros, '') : value, radix || 0); }; /** * Creates a "_.pluck" style function, which returns the `key` value of a * given object. * * @static * @memberOf _ * @category Utilities * @param {string} key The name of the property to retrieve. * @returns {Function} Returns the new function. * @example * * var characters = [ * { 'name': 'fred', 'age': 40 }, * { 'name': 'barney', 'age': 36 } * ]; * * var getName = _.property('name'); * * _.map(characters, getName); * // => ['barney', 'fred'] * * _.sortBy(characters, getName); * // => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] */ function property(key) { return function(object) { return object[key]; }; } /** * Produces a random number between `min` and `max` (inclusive). If only one * argument is provided a number between `0` and the given number will be * returned. If `floating` is truey or either `min` or `max` are floats a * floating-point number will be returned instead of an integer. * * @static * @memberOf _ * @category Utilities * @param {number} [min=0] The minimum possible value. * @param {number} [max=1] The maximum possible value. * @param {boolean} [floating=false] Specify returning a floating-point number. * @returns {number} Returns a random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(min, max, floating) { var noMin = min == null, noMax = max == null; if (floating == null) { if (typeof min == 'boolean' && noMax) { floating = min; min = 1; } else if (!noMax && typeof max == 'boolean') { floating = max; noMax = true; } } if (noMin && noMax) { max = 1; } min = +min || 0; if (noMax) { max = min; min = 0; } else { max = +max || 0; } if (floating || min % 1 || max % 1) { var rand = nativeRandom(); return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand +'').length - 1)))), max); } return baseRandom(min, max); } /** * Resolves the value of property `key` on `object`. If `key` is a function * it will be invoked with the `this` binding of `object` and its result returned, * else the property value is returned. If `object` is falsey then `undefined` * is returned. * * @static * @memberOf _ * @category Utilities * @param {Object} object The object to inspect. * @param {string} key The name of the property to resolve. * @returns {*} Returns the resolved value. * @example * * var object = { * 'cheese': 'crumpets', * 'stuff': function() { * return 'nonsense'; * } * }; * * _.result(object, 'cheese'); * // => 'crumpets' * * _.result(object, 'stuff'); * // => 'nonsense' */ function result(object, key) { if (object) { var value = object[key]; return isFunction(value) ? object[key]() : value; } } /** * A micro-templating method that handles arbitrary delimiters, preserves * whitespace, and correctly escapes quotes within interpolated code. * * Note: In the development build, `_.template` utilizes sourceURLs for easier * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl * * For more information on precompiling templates see: * http://lodash.com/custom-builds * * For more information on Chrome extension sandboxes see: * http://developer.chrome.com/stable/extensions/sandboxingEval.html * * @static * @memberOf _ * @category Utilities * @param {string} text The template text. * @param {Object} data The data object used to populate the text. * @param {Object} [options] The options object. * @param {RegExp} [options.escape] The "escape" delimiter. * @param {RegExp} [options.evaluate] The "evaluate" delimiter. * @param {Object} [options.imports] An object to import into the template as local variables. * @param {RegExp} [options.interpolate] The "interpolate" delimiter. * @param {string} [sourceURL] The sourceURL of the template's compiled source. * @param {string} [variable] The data object variable name. * @returns {Function|string} Returns a compiled function when no `data` object * is given, else it returns the interpolated text. * @example * * // using the "interpolate" delimiter to create a compiled template * var compiled = _.template('hello <%= name %>'); * compiled({ 'name': 'fred' }); * // => 'hello fred' * * // using the "escape" delimiter to escape HTML in data property values * _.template('<b><%- value %></b>', { 'value': '<script>' }); * // => '<b>&lt;script&gt;</b>' * * // using the "evaluate" delimiter to generate HTML * var list = '<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>'; * _.template(list, { 'people': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // using the ES6 delimiter as an alternative to the default "interpolate" delimiter * _.template('hello ${ name }', { 'name': 'pebbles' }); * // => 'hello pebbles' * * // using the internal `print` function in "evaluate" delimiters * _.template('<% print("hello " + name); %>!', { 'name': 'barney' }); * // => 'hello barney!' * * // using a custom template delimiters * _.templateSettings = { * 'interpolate': /{{([\s\S]+?)}}/g * }; * * _.template('hello {{ name }}!', { 'name': 'mustache' }); * // => 'hello mustache!' * * // using the `imports` option to import jQuery * var list = '<% jq.each(people, function(name) { %><li><%- name %></li><% }); %>'; * _.template(list, { 'people': ['fred', 'barney'] }, { 'imports': { 'jq': jQuery } }); * // => '<li>fred</li><li>barney</li>' * * // using the `sourceURL` option to specify a custom sourceURL for the template * var compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' }); * compiled(data); * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector * * // using the `variable` option to ensure a with-statement isn't used in the compiled template * var compiled = _.template('hi <%= data.name %>!', null, { 'variable': 'data' }); * compiled.source; * // => function(data) { * var __t, __p = '', __e = _.escape; * __p += 'hi ' + ((__t = ( data.name )) == null ? '' : __t) + '!'; * return __p; * } * * // using the `source` property to inline compiled templates for meaningful * // line numbers in error messages and a stack trace * fs.writeFileSync(path.join(cwd, 'jst.js'), '\ * var JST = {\ * "main": ' + _.template(mainText).source + '\ * };\ * '); */ function template(text, data, options) { // based on Mark Resig's `tmpl` implementation // http://eMark.org/blog/javascript-micro-templating/ // and Laura Doktorova's doT.js // https://github.com/olado/doT var settings = lodash.templateSettings; text = String(text || ''); // avoid missing dependencies when `iteratorTemplate` is not defined options = defaults({}, options, settings); var imports = defaults({}, options.imports, settings.imports), importsKeys = keys(imports), importsValues = values(imports); var isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; // compile the regexp to match each delimiter var reDelimiters = RegExp( (options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$' , 'g'); text.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // escape characters that cannot be included in string literals source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar); // replace delimiters with snippets if (escapeValue) { source += "' +\n__e(" + escapeValue + ") +\n'"; } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; // the JS engine embedded in Adobe products requires returning the `match` // string in order to produce the correct `offset` value return match; }); source += "';\n"; // if `variable` is not specified, wrap a with-statement around the generated // code to add the data object to the top of the scope chain var variable = options.variable, hasVariable = variable; if (!hasVariable) { variable = 'obj'; source = 'with (' + variable + ') {\n' + source + '\n}\n'; } // cleanup code by stripping empty strings source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) .replace(reEmptyStringMiddle, '$1') .replace(reEmptyStringTrailing, '$1;'); // frame code as the function body source = 'function(' + variable + ') {\n' + (hasVariable ? '' : variable + ' || (' + variable + ' = {});\n') + "var __t, __p = '', __e = _.escape" + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n' ) + source + 'return __p\n}'; // Use a sourceURL for easier debugging. // http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl var sourceURL = '\n/*\n//# sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']') + '\n*/'; try { var result = Function(importsKeys, 'return ' + source + sourceURL).apply(undefined, importsValues); } catch(e) { e.source = source; throw e; } if (data) { return result(data); } // provide the compiled function's source by its `toString` method, in // supported environments, or the `source` property as a convenience for // inlining compiled templates during the build process result.source = source; return result; } /** * Executes the callback `n` times, returning an array of the results * of each callback execution. The callback is bound to `thisArg` and invoked * with one argument; (index). * * @static * @memberOf _ * @category Utilities * @param {number} n The number of times to execute the callback. * @param {Function} callback The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns an array of the results of each `callback` execution. * @example * * var diceRolls = _.times(3, _.partial(_.random, 1, 6)); * // => [3, 6, 4] * * _.times(3, function(n) { mage.castSpell(n); }); * // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively * * _.times(3, function(n) { this.cast(n); }, mage); * // => also calls `mage.castSpell(n)` three times */ function times(n, callback, thisArg) { n = (n = +n) > -1 ? n : 0; var index = -1, result = Array(n); callback = baseCreateCallback(callback, thisArg, 1); while (++index < n) { result[index] = callback(index); } return result; } /** * The inverse of `_.escape` this method converts the HTML entities * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to their * corresponding characters. * * @static * @memberOf _ * @category Utilities * @param {string} string The string to unescape. * @returns {string} Returns the unescaped string. * @example * * _.unescape('Fred, Barney &amp; Pebbles'); * // => 'Fred, Barney & Pebbles' */ function unescape(string) { return string == null ? '' : String(string).replace(reEscapedHtml, unescapeHtmlChar); } /** * Generates a unique ID. If `prefix` is provided the ID will be appended to it. * * @static * @memberOf _ * @category Utilities * @param {string} [prefix] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return String(prefix == null ? '' : prefix) + id; } /*--------------------------------------------------------------------------*/ /** * Creates a `lodash` object that wraps the given value with explicit * method chaining enabled. * * @static * @memberOf _ * @category Chaining * @param {*} value The value to wrap. * @returns {Object} Returns the wrapper object. * @example * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 }, * { 'name': 'pebbles', 'age': 1 } * ]; * * var youngest = _.chain(characters) * .sortBy('age') * .map(function(chr) { return chr.name + ' is ' + chr.age; }) * .first() * .value(); * // => 'pebbles is 1' */ function chain(value) { value = new lodashWrapper(value); value.__chain__ = true; return value; } /** * Invokes `interceptor` with the `value` as the first argument and then * returns `value`. The purpose of this method is to "tap into" a method * chain in order to perform operations on intermediate results within * the chain. * * @static * @memberOf _ * @category Chaining * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns `value`. * @example * * _([1, 2, 3, 4]) * .tap(function(array) { array.pop(); }) * .reverse() * .value(); * // => [3, 2, 1] */ function tap(value, interceptor) { interceptor(value); return value; } /** * Enables explicit method chaining on the wrapper object. * * @name chain * @memberOf _ * @category Chaining * @returns {*} Returns the wrapper object. * @example * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * // without explicit chaining * _(characters).first(); * // => { 'name': 'barney', 'age': 36 } * * // with explicit chaining * _(characters).chain() * .first() * .pick('age') * .value(); * // => { 'age': 36 } */ function wrapperChain() { this.__chain__ = true; return this; } /** * Produces the `toString` result of the wrapped value. * * @name toString * @memberOf _ * @category Chaining * @returns {string} Returns the string result. * @example * * _([1, 2, 3]).toString(); * // => '1,2,3' */ function wrapperToString() { return String(this.__wrapped__); } /** * Extracts the wrapped value. * * @name valueOf * @memberOf _ * @alias value * @category Chaining * @returns {*} Returns the wrapped value. * @example * * _([1, 2, 3]).valueOf(); * // => [1, 2, 3] */ function wrapperValueOf() { return this.__wrapped__; } /*--------------------------------------------------------------------------*/ // add functions that return wrapped values when chaining lodash.after = after; lodash.assign = assign; lodash.at = at; lodash.bind = bind; lodash.bindAll = bindAll; lodash.bindKey = bindKey; lodash.chain = chain; lodash.compact = compact; lodash.compose = compose; lodash.constant = constant; lodash.countBy = countBy; lodash.create = create; lodash.createCallback = createCallback; lodash.curry = curry; lodash.debounce = debounce; lodash.defaults = defaults; lodash.defer = defer; lodash.delay = delay; lodash.difference = difference; lodash.filter = filter; lodash.flatten = flatten; lodash.forEach = forEach; lodash.forEachRight = forEachRight; lodash.forIn = forIn; lodash.forInRight = forInRight; lodash.forOwn = forOwn; lodash.forOwnRight = forOwnRight; lodash.functions = functions; lodash.groupBy = groupBy; lodash.indexBy = indexBy; lodash.initial = initial; lodash.intersection = intersection; lodash.invert = invert; lodash.invoke = invoke; lodash.keys = keys; lodash.map = map; lodash.mapValues = mapValues; lodash.max = max; lodash.memoize = memoize; lodash.merge = merge; lodash.min = min; lodash.omit = omit; lodash.once = once; lodash.pairs = pairs; lodash.partial = partial; lodash.partialRight = partialRight; lodash.pick = pick; lodash.pluck = pluck; lodash.property = property; lodash.pull = pull; lodash.range = range; lodash.reject = reject; lodash.remove = remove; lodash.rest = rest; lodash.shuffle = shuffle; lodash.sortBy = sortBy; lodash.tap = tap; lodash.throttle = throttle; lodash.times = times; lodash.toArray = toArray; lodash.transform = transform; lodash.union = union; lodash.uniq = uniq; lodash.values = values; lodash.where = where; lodash.without = without; lodash.wrap = wrap; lodash.xor = xor; lodash.zip = zip; lodash.zipObject = zipObject; // add aliases lodash.collect = map; lodash.drop = rest; lodash.each = forEach; lodash.eachRight = forEachRight; lodash.extend = assign; lodash.methods = functions; lodash.object = zipObject; lodash.select = filter; lodash.tail = rest; lodash.unique = uniq; lodash.unzip = zip; // add functions to `lodash.prototype` mixin(lodash); /*--------------------------------------------------------------------------*/ // add functions that return unwrapped values when chaining lodash.clone = clone; lodash.cloneDeep = cloneDeep; lodash.contains = contains; lodash.escape = escape; lodash.every = every; lodash.find = find; lodash.findIndex = findIndex; lodash.findKey = findKey; lodash.findLast = findLast; lodash.findLastIndex = findLastIndex; lodash.findLastKey = findLastKey; lodash.has = has; lodash.identity = identity; lodash.indexOf = indexOf; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isBoolean = isBoolean; lodash.isDate = isDate; lodash.isElement = isElement; lodash.isEmpty = isEmpty; lodash.isEqual = isEqual; lodash.isFinite = isFinite; lodash.isFunction = isFunction; lodash.isNaN = isNaN; lodash.isNull = isNull; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isPlainObject = isPlainObject; lodash.isRegExp = isRegExp; lodash.isString = isString; lodash.isUndefined = isUndefined; lodash.lastIndexOf = lastIndexOf; lodash.mixin = mixin; lodash.noConflict = noConflict; lodash.noop = noop; lodash.now = now; lodash.parseInt = parseInt; lodash.random = random; lodash.reduce = reduce; lodash.reduceRight = reduceRight; lodash.result = result; lodash.runInContext = runInContext; lodash.size = size; lodash.some = some; lodash.sortedIndex = sortedIndex; lodash.template = template; lodash.unescape = unescape; lodash.uniqueId = uniqueId; // add aliases lodash.all = every; lodash.any = some; lodash.detect = find; lodash.findWhere = find; lodash.foldl = reduce; lodash.foldr = reduceRight; lodash.include = contains; lodash.inject = reduce; mixin(function() { var source = {} forOwn(lodash, function(func, methodName) { if (!lodash.prototype[methodName]) { source[methodName] = func; } }); return source; }(), false); /*--------------------------------------------------------------------------*/ // add functions capable of returning wrapped and unwrapped values when chaining lodash.first = first; lodash.last = last; lodash.sample = sample; // add aliases lodash.take = first; lodash.head = first; forOwn(lodash, function(func, methodName) { var callbackable = methodName !== 'sample'; if (!lodash.prototype[methodName]) { lodash.prototype[methodName]= function(n, guard) { var chainAll = this.__chain__, result = func(this.__wrapped__, n, guard); return !chainAll && (n == null || (guard && !(callbackable && typeof n == 'function'))) ? result : new lodashWrapper(result, chainAll); }; } }); /*--------------------------------------------------------------------------*/ /** * The semantic version number. * * @static * @memberOf _ * @type string */ lodash.VERSION = '2.4.1'; // add "Chaining" functions to the wrapper lodash.prototype.chain = wrapperChain; lodash.prototype.toString = wrapperToString; lodash.prototype.value = wrapperValueOf; lodash.prototype.valueOf = wrapperValueOf; // add `Array` functions that return unwrapped values baseEach(['join', 'pop', 'shift'], function(methodName) { var func = arrayRef[methodName]; lodash.prototype[methodName] = function() { var chainAll = this.__chain__, result = func.apply(this.__wrapped__, arguments); return chainAll ? new lodashWrapper(result, chainAll) : result; }; }); // add `Array` functions that return the existing wrapped value baseEach(['push', 'reverse', 'sort', 'unshift'], function(methodName) { var func = arrayRef[methodName]; lodash.prototype[methodName] = function() { func.apply(this.__wrapped__, arguments); return this; }; }); // add `Array` functions that return new wrapped values baseEach(['concat', 'slice', 'splice'], function(methodName) { var func = arrayRef[methodName]; lodash.prototype[methodName] = function() { return new lodashWrapper(func.apply(this.__wrapped__, arguments), this.__chain__); }; }); // avoid array-like object bugs with `Array#shift` and `Array#splice` // in IE < 9, Firefox < 10, Narwhal, and RingoJS if (!support.spliceObjects) { baseEach(['pop', 'shift', 'splice'], function(methodName) { var func = arrayRef[methodName], isSplice = methodName == 'splice'; lodash.prototype[methodName] = function() { var chainAll = this.__chain__, value = this.__wrapped__, result = func.apply(value, arguments); if (value.length === 0) { delete value[0]; } return (chainAll || isSplice) ? new lodashWrapper(result, chainAll) : result; }; }); } return lodash; } /*--------------------------------------------------------------------------*/ // expose Lo-Dash var _ = runInContext(); // some AMD build optimizers like r.js check for condition patterns like the following: if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { // Expose Lo-Dash to the global object even when an AMD loader is present in // case Lo-Dash is loaded with a RequireJS shim config. // See http://requirejs.org/docs/api.html#config-shim root._ = _; // define as an anonymous module so, through path mapping, it can be // referenced as the "underscore" module define(function() { return _; }); } // check for `exports` after `define` in case a build optimizer adds an `exports` object else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = _)._ = _; } // in Narwhal or Rhino -require else { freeExports._ = _; } } else { // in a browser or Rhino root._ = _; } }.call(this));
var powerSaveBlocker; powerSaveBlocker = process.atomBinding('power_save_blocker').powerSaveBlocker; module.exports = powerSaveBlocker;
const fs = require(`fs`) const fetchData = require(`../fetch`) // Fetch data from our sample site and save it to disk. const typePrefix = `wordpress__` const refactoredEntityTypes = { post: `${typePrefix}POST`, page: `${typePrefix}PAGE`, tag: `${typePrefix}TAG`, category: `${typePrefix}CATEGORY`, } fetchData({ _verbose: false, _siteURL: `http://dev-gatbsyjswp.pantheonsite.io`, baseUrl: `dev-gatbsyjswp.pantheonsite.io`, _useACF: true, _hostingWPCOM: false, _perPage: 100, typePrefix, refactoredEntityTypes, }).then(data => { fs.writeFileSync( `${__dirname}/../__tests__/data.json`, JSON.stringify(data, null, 4) ) })
requirejs.config({ "paths": { "jquery": "https://code.jquery.com/jquery-1.11.3.min", "moment": "../../moment", "daterangepicker": "../../daterangepicker" } }); requirejs(['jquery', 'moment', 'daterangepicker'] , function ($, moment) { $(document).ready(function() { $('#config-text').keyup(function() { eval($(this).val()); }); $('.configurator input, .configurator select').change(function() { updateConfig(); }); $('.demo i').click(function() { $(this).parent().find('input').click(); }); $('#startDate').daterangepicker({ singleDatePicker: true, startDate: moment().subtract(6, 'days') }); $('#endDate').daterangepicker({ singleDatePicker: true, startDate: moment() }); updateConfig(); function updateConfig() { var options = {}; if ($('#singleDatePicker').is(':checked')) options.singleDatePicker = true; if ($('#showDropdowns').is(':checked')) options.showDropdowns = true; if ($('#showWeekNumbers').is(':checked')) options.showWeekNumbers = true; if ($('#showISOWeekNumbers').is(':checked')) options.showISOWeekNumbers = true; if ($('#timePicker').is(':checked')) options.timePicker = true; if ($('#timePicker24Hour').is(':checked')) options.timePicker24Hour = true; if ($('#timePickerIncrement').val().length && $('#timePickerIncrement').val() != 1) options.timePickerIncrement = parseInt($('#timePickerIncrement').val(), 10); if ($('#timePickerSeconds').is(':checked')) options.timePickerSeconds = true; if ($('#autoApply').is(':checked')) options.autoApply = true; if ($('#dateLimit').is(':checked')) options.dateLimit = { days: 7 }; if ($('#ranges').is(':checked')) { options.ranges = { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] }; } if ($('#locale').is(':checked')) { options.locale = { format: 'MM/DD/YYYY HH:mm', separator: ' - ', applyLabel: 'Apply', cancelLabel: 'Cancel', fromLabel: 'From', toLabel: 'To', customRangeLabel: 'Custom', daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr','Sa'], monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], firstDay: 1 }; } if (!$('#linkedCalendars').is(':checked')) options.linkedCalendars = false; if (!$('#autoUpdateInput').is(':checked')) options.autoUpdateInput = false; if ($('#alwaysShowCalendars').is(':checked')) options.alwaysShowCalendars = true; if ($('#parentEl').val().length) options.parentEl = $('#parentEl').val(); if ($('#startDate').val().length) options.startDate = $('#startDate').val(); if ($('#endDate').val().length) options.endDate = $('#endDate').val(); if ($('#minDate').val().length) options.minDate = $('#minDate').val(); if ($('#maxDate').val().length) options.maxDate = $('#maxDate').val(); if ($('#opens').val().length && $('#opens').val() != 'right') options.opens = $('#opens').val(); if ($('#drops').val().length && $('#drops').val() != 'down') options.drops = $('#drops').val(); if ($('#buttonClasses').val().length && $('#buttonClasses').val() != 'btn btn-sm') options.buttonClasses = $('#buttonClasses').val(); if ($('#applyClass').val().length && $('#applyClass').val() != 'btn-success') options.applyClass = $('#applyClass').val(); if ($('#cancelClass').val().length && $('#cancelClass').val() != 'btn-default') options.cancelClass = $('#cancelClass').val(); $('#config-text').val("$('#demo').daterangepicker(" + JSON.stringify(options, null, ' ') + ", function(start, end, label) {\n console.log(\"New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')\");\n});"); $('#config-demo').daterangepicker(options, function(start, end, label) { console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')'); }); } }); });
describe('[Regression](GH-1424)', function () { it('Should raise click event on a button after "enter" key is pressed', function () { return runTests('testcafe-fixtures/index-test.js', 'Press enter'); }); });
/*! * Ext JS Library 3.3.1 * Copyright(c) 2006-2010 Sencha Inc. * [email protected] * http://www.sencha.com/license */ /*! * Ext JS Library 3.3.0 * Copyright(c) 2006-2010 Ext JS, Inc. * [email protected] * http://www.extjs.com/license */ Ext.ns('Ext.ux.grid'); Ext.ux.grid.LockingGridView = Ext.extend(Ext.grid.GridView, { lockText : 'Lock', unlockText : 'Unlock', rowBorderWidth : 1, lockedBorderWidth : 1, /* * This option ensures that height between the rows is synchronized * between the locked and unlocked sides. This option only needs to be used * when the row heights aren't predictable. */ syncHeights: false, initTemplates : function(){ var ts = this.templates || {}; if (!ts.masterTpl) { ts.masterTpl = new Ext.Template( '<div class="x-grid3" hidefocus="true">', '<div class="x-grid3-locked">', '<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset" style="{lstyle}">{lockedHeader}</div></div><div class="x-clear"></div></div>', '<div class="x-grid3-scroller"><div class="x-grid3-body" style="{lstyle}">{lockedBody}</div><div class="x-grid3-scroll-spacer"></div></div>', '</div>', '<div class="x-grid3-viewport x-grid3-unlocked">', '<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset" style="{ostyle}">{header}</div></div><div class="x-clear"></div></div>', '<div class="x-grid3-scroller"><div class="x-grid3-body" style="{bstyle}">{body}</div><a href="#" class="x-grid3-focus" tabIndex="-1"></a></div>', '</div>', '<div class="x-grid3-resize-marker">&#160;</div>', '<div class="x-grid3-resize-proxy">&#160;</div>', '</div>' ); } this.templates = ts; Ext.ux.grid.LockingGridView.superclass.initTemplates.call(this); }, getEditorParent : function(ed){ return this.el.dom; }, initElements : function(){ var el = Ext.get(this.grid.getGridEl().dom.firstChild), lockedWrap = el.child('div.x-grid3-locked'), lockedHd = lockedWrap.child('div.x-grid3-header'), lockedScroller = lockedWrap.child('div.x-grid3-scroller'), mainWrap = el.child('div.x-grid3-viewport'), mainHd = mainWrap.child('div.x-grid3-header'), scroller = mainWrap.child('div.x-grid3-scroller'); if (this.grid.hideHeaders) { lockedHd.setDisplayed(false); mainHd.setDisplayed(false); } if(this.forceFit){ scroller.setStyle('overflow-x', 'hidden'); } Ext.apply(this, { el : el, mainWrap: mainWrap, mainHd : mainHd, innerHd : mainHd.dom.firstChild, scroller: scroller, mainBody: scroller.child('div.x-grid3-body'), focusEl : scroller.child('a'), resizeMarker: el.child('div.x-grid3-resize-marker'), resizeProxy : el.child('div.x-grid3-resize-proxy'), lockedWrap: lockedWrap, lockedHd: lockedHd, lockedScroller: lockedScroller, lockedBody: lockedScroller.child('div.x-grid3-body'), lockedInnerHd: lockedHd.child('div.x-grid3-header-inner', true) }); this.focusEl.swallowEvent('click', true); }, getLockedRows : function(){ return this.hasRows() ? this.lockedBody.dom.childNodes : []; }, getLockedRow : function(row){ return this.getLockedRows()[row]; }, getCell : function(row, col){ var lockedLen = this.cm.getLockedCount(); if(col < lockedLen){ return this.getLockedRow(row).getElementsByTagName('td')[col]; } return Ext.ux.grid.LockingGridView.superclass.getCell.call(this, row, col - lockedLen); }, getHeaderCell : function(index){ var lockedLen = this.cm.getLockedCount(); if(index < lockedLen){ return this.lockedHd.dom.getElementsByTagName('td')[index]; } return Ext.ux.grid.LockingGridView.superclass.getHeaderCell.call(this, index - lockedLen); }, addRowClass : function(row, cls){ var lockedRow = this.getLockedRow(row); if(lockedRow){ this.fly(lockedRow).addClass(cls); } Ext.ux.grid.LockingGridView.superclass.addRowClass.call(this, row, cls); }, removeRowClass : function(row, cls){ var lockedRow = this.getLockedRow(row); if(lockedRow){ this.fly(lockedRow).removeClass(cls); } Ext.ux.grid.LockingGridView.superclass.removeRowClass.call(this, row, cls); }, removeRow : function(row) { Ext.removeNode(this.getLockedRow(row)); Ext.ux.grid.LockingGridView.superclass.removeRow.call(this, row); }, removeRows : function(firstRow, lastRow){ var lockedBody = this.lockedBody.dom, rowIndex = firstRow; for(; rowIndex <= lastRow; rowIndex++){ Ext.removeNode(lockedBody.childNodes[firstRow]); } Ext.ux.grid.LockingGridView.superclass.removeRows.call(this, firstRow, lastRow); }, syncScroll : function(e){ this.lockedScroller.dom.scrollTop = this.scroller.dom.scrollTop; Ext.ux.grid.LockingGridView.superclass.syncScroll.call(this, e); }, updateSortIcon : function(col, dir){ var sortClasses = this.sortClasses, lockedHeaders = this.lockedHd.select('td').removeClass(sortClasses), headers = this.mainHd.select('td').removeClass(sortClasses), lockedLen = this.cm.getLockedCount(), cls = sortClasses[dir == 'DESC' ? 1 : 0]; if(col < lockedLen){ lockedHeaders.item(col).addClass(cls); }else{ headers.item(col - lockedLen).addClass(cls); } }, updateAllColumnWidths : function(){ var tw = this.getTotalWidth(), clen = this.cm.getColumnCount(), lw = this.getLockedWidth(), llen = this.cm.getLockedCount(), ws = [], len, i; this.updateLockedWidth(); for(i = 0; i < clen; i++){ ws[i] = this.getColumnWidth(i); var hd = this.getHeaderCell(i); hd.style.width = ws[i]; } var lns = this.getLockedRows(), ns = this.getRows(), row, trow, j; for(i = 0, len = ns.length; i < len; i++){ row = lns[i]; row.style.width = lw; if(row.firstChild){ row.firstChild.style.width = lw; trow = row.firstChild.rows[0]; for (j = 0; j < llen; j++) { trow.childNodes[j].style.width = ws[j]; } } row = ns[i]; row.style.width = tw; if(row.firstChild){ row.firstChild.style.width = tw; trow = row.firstChild.rows[0]; for (j = llen; j < clen; j++) { trow.childNodes[j - llen].style.width = ws[j]; } } } this.onAllColumnWidthsUpdated(ws, tw); this.syncHeaderHeight(); }, updateColumnWidth : function(col, width){ var w = this.getColumnWidth(col), llen = this.cm.getLockedCount(), ns, rw, c, row; this.updateLockedWidth(); if(col < llen){ ns = this.getLockedRows(); rw = this.getLockedWidth(); c = col; }else{ ns = this.getRows(); rw = this.getTotalWidth(); c = col - llen; } var hd = this.getHeaderCell(col); hd.style.width = w; for(var i = 0, len = ns.length; i < len; i++){ row = ns[i]; row.style.width = rw; if(row.firstChild){ row.firstChild.style.width = rw; row.firstChild.rows[0].childNodes[c].style.width = w; } } this.onColumnWidthUpdated(col, w, this.getTotalWidth()); this.syncHeaderHeight(); }, updateColumnHidden : function(col, hidden){ var llen = this.cm.getLockedCount(), ns, rw, c, row, display = hidden ? 'none' : ''; this.updateLockedWidth(); if(col < llen){ ns = this.getLockedRows(); rw = this.getLockedWidth(); c = col; }else{ ns = this.getRows(); rw = this.getTotalWidth(); c = col - llen; } var hd = this.getHeaderCell(col); hd.style.display = display; for(var i = 0, len = ns.length; i < len; i++){ row = ns[i]; row.style.width = rw; if(row.firstChild){ row.firstChild.style.width = rw; row.firstChild.rows[0].childNodes[c].style.display = display; } } this.onColumnHiddenUpdated(col, hidden, this.getTotalWidth()); delete this.lastViewWidth; this.layout(); }, doRender : function(cs, rs, ds, startRow, colCount, stripe){ var ts = this.templates, ct = ts.cell, rt = ts.row, last = colCount-1, tstyle = 'width:'+this.getTotalWidth()+';', lstyle = 'width:'+this.getLockedWidth()+';', buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r; for(var j = 0, len = rs.length; j < len; j++){ r = rs[j]; cb = []; lcb = []; var rowIndex = (j+startRow); for(var i = 0; i < colCount; i++){ c = cs[i]; p.id = c.id; p.css = (i === 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : '')) + (this.cm.config[i].cellCls ? ' ' + this.cm.config[i].cellCls : ''); p.attr = p.cellAttr = ''; p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds); p.style = c.style; if(Ext.isEmpty(p.value)){ p.value = '&#160;'; } if(this.markDirty && r.dirty && Ext.isDefined(r.modified[c.name])){ p.css += ' x-grid3-dirty-cell'; } if(c.locked){ lcb[lcb.length] = ct.apply(p); }else{ cb[cb.length] = ct.apply(p); } } var alt = []; if(stripe && ((rowIndex+1) % 2 === 0)){ alt[0] = 'x-grid3-row-alt'; } if(r.dirty){ alt[1] = ' x-grid3-dirty-row'; } rp.cols = colCount; if(this.getRowClass){ alt[2] = this.getRowClass(r, rowIndex, rp, ds); } rp.alt = alt.join(' '); rp.cells = cb.join(''); rp.tstyle = tstyle; buf[buf.length] = rt.apply(rp); rp.cells = lcb.join(''); rp.tstyle = lstyle; lbuf[lbuf.length] = rt.apply(rp); } return [buf.join(''), lbuf.join('')]; }, processRows : function(startRow, skipStripe){ if(!this.ds || this.ds.getCount() < 1){ return; } var rows = this.getRows(), lrows = this.getLockedRows(), row, lrow; skipStripe = skipStripe || !this.grid.stripeRows; startRow = startRow || 0; for(var i = 0, len = rows.length; i < len; ++i){ row = rows[i]; lrow = lrows[i]; row.rowIndex = i; lrow.rowIndex = i; if(!skipStripe){ row.className = row.className.replace(this.rowClsRe, ' '); lrow.className = lrow.className.replace(this.rowClsRe, ' '); if ((i + 1) % 2 === 0){ row.className += ' x-grid3-row-alt'; lrow.className += ' x-grid3-row-alt'; } } this.syncRowHeights(row, lrow); } if(startRow === 0){ Ext.fly(rows[0]).addClass(this.firstRowCls); Ext.fly(lrows[0]).addClass(this.firstRowCls); } Ext.fly(rows[rows.length - 1]).addClass(this.lastRowCls); Ext.fly(lrows[lrows.length - 1]).addClass(this.lastRowCls); }, syncRowHeights: function(row1, row2){ if(this.syncHeights){ var el1 = Ext.get(row1), el2 = Ext.get(row2), h1 = el1.getHeight(), h2 = el2.getHeight(); if(h1 > h2){ el2.setHeight(h1); }else if(h2 > h1){ el1.setHeight(h2); } } }, afterRender : function(){ if(!this.ds || !this.cm){ return; } var bd = this.renderRows() || ['&#160;', '&#160;']; this.mainBody.dom.innerHTML = bd[0]; this.lockedBody.dom.innerHTML = bd[1]; this.processRows(0, true); if(this.deferEmptyText !== true){ this.applyEmptyText(); } this.grid.fireEvent('viewready', this.grid); }, renderUI : function(){ var templates = this.templates, header = this.renderHeaders(), body = templates.body.apply({rows:'&#160;'}); return templates.masterTpl.apply({ body : body, header: header[0], ostyle: 'width:' + this.getOffsetWidth() + ';', bstyle: 'width:' + this.getTotalWidth() + ';', lockedBody: body, lockedHeader: header[1], lstyle: 'width:'+this.getLockedWidth()+';' }); }, afterRenderUI: function(){ var g = this.grid; this.initElements(); Ext.fly(this.innerHd).on('click', this.handleHdDown, this); Ext.fly(this.lockedInnerHd).on('click', this.handleHdDown, this); this.mainHd.on({ scope: this, mouseover: this.handleHdOver, mouseout: this.handleHdOut, mousemove: this.handleHdMove }); this.lockedHd.on({ scope: this, mouseover: this.handleHdOver, mouseout: this.handleHdOut, mousemove: this.handleHdMove }); this.scroller.on('scroll', this.syncScroll, this); if(g.enableColumnResize !== false){ this.splitZone = new Ext.grid.GridView.SplitDragZone(g, this.mainHd.dom); this.splitZone.setOuterHandleElId(Ext.id(this.lockedHd.dom)); this.splitZone.setOuterHandleElId(Ext.id(this.mainHd.dom)); } if(g.enableColumnMove){ this.columnDrag = new Ext.grid.GridView.ColumnDragZone(g, this.innerHd); this.columnDrag.setOuterHandleElId(Ext.id(this.lockedInnerHd)); this.columnDrag.setOuterHandleElId(Ext.id(this.innerHd)); this.columnDrop = new Ext.grid.HeaderDropZone(g, this.mainHd.dom); } if(g.enableHdMenu !== false){ this.hmenu = new Ext.menu.Menu({id: g.id + '-hctx'}); this.hmenu.add( {itemId: 'asc', text: this.sortAscText, cls: 'xg-hmenu-sort-asc'}, {itemId: 'desc', text: this.sortDescText, cls: 'xg-hmenu-sort-desc'} ); if(this.grid.enableColLock !== false){ this.hmenu.add('-', {itemId: 'lock', text: this.lockText, cls: 'xg-hmenu-lock'}, {itemId: 'unlock', text: this.unlockText, cls: 'xg-hmenu-unlock'} ); } if(g.enableColumnHide !== false){ this.colMenu = new Ext.menu.Menu({id:g.id + '-hcols-menu'}); this.colMenu.on({ scope: this, beforeshow: this.beforeColMenuShow, itemclick: this.handleHdMenuClick }); this.hmenu.add('-', { itemId:'columns', hideOnClick: false, text: this.columnsText, menu: this.colMenu, iconCls: 'x-cols-icon' }); } this.hmenu.on('itemclick', this.handleHdMenuClick, this); } if(g.trackMouseOver){ this.mainBody.on({ scope: this, mouseover: this.onRowOver, mouseout: this.onRowOut }); this.lockedBody.on({ scope: this, mouseover: this.onRowOver, mouseout: this.onRowOut }); } if(g.enableDragDrop || g.enableDrag){ this.dragZone = new Ext.grid.GridDragZone(g, { ddGroup : g.ddGroup || 'GridDD' }); } this.updateHeaderSortState(); }, layout : function(){ if(!this.mainBody){ return; } var g = this.grid; var c = g.getGridEl(); var csize = c.getSize(true); var vw = csize.width; if(!g.hideHeaders && (vw < 20 || csize.height < 20)){ return; } this.syncHeaderHeight(); if(g.autoHeight){ this.scroller.dom.style.overflow = 'visible'; this.lockedScroller.dom.style.overflow = 'visible'; if(Ext.isWebKit){ this.scroller.dom.style.position = 'static'; this.lockedScroller.dom.style.position = 'static'; } }else{ this.el.setSize(csize.width, csize.height); var hdHeight = this.mainHd.getHeight(); var vh = csize.height - (hdHeight); } this.updateLockedWidth(); if(this.forceFit){ if(this.lastViewWidth != vw){ this.fitColumns(false, false); this.lastViewWidth = vw; } }else { this.autoExpand(); this.syncHeaderScroll(); } this.onLayout(vw, vh); }, getOffsetWidth : function() { return (this.cm.getTotalWidth() - this.cm.getTotalLockedWidth() + this.getScrollOffset()) + 'px'; }, renderHeaders : function(){ var cm = this.cm, ts = this.templates, ct = ts.hcell, cb = [], lcb = [], p = {}, len = cm.getColumnCount(), last = len - 1; for(var i = 0; i < len; i++){ p.id = cm.getColumnId(i); p.value = cm.getColumnHeader(i) || ''; p.style = this.getColumnStyle(i, true); p.tooltip = this.getColumnTooltip(i); p.css = (i === 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : '')) + (cm.config[i].headerCls ? ' ' + cm.config[i].headerCls : ''); if(cm.config[i].align == 'right'){ p.istyle = 'padding-right:16px'; } else { delete p.istyle; } if(cm.isLocked(i)){ lcb[lcb.length] = ct.apply(p); }else{ cb[cb.length] = ct.apply(p); } } return [ts.header.apply({cells: cb.join(''), tstyle:'width:'+this.getTotalWidth()+';'}), ts.header.apply({cells: lcb.join(''), tstyle:'width:'+this.getLockedWidth()+';'})]; }, updateHeaders : function(){ var hd = this.renderHeaders(); this.innerHd.firstChild.innerHTML = hd[0]; this.innerHd.firstChild.style.width = this.getOffsetWidth(); this.innerHd.firstChild.firstChild.style.width = this.getTotalWidth(); this.lockedInnerHd.firstChild.innerHTML = hd[1]; var lw = this.getLockedWidth(); this.lockedInnerHd.firstChild.style.width = lw; this.lockedInnerHd.firstChild.firstChild.style.width = lw; }, getResolvedXY : function(resolved){ if(!resolved){ return null; } var c = resolved.cell, r = resolved.row; return c ? Ext.fly(c).getXY() : [this.scroller.getX(), Ext.fly(r).getY()]; }, syncFocusEl : function(row, col, hscroll){ Ext.ux.grid.LockingGridView.superclass.syncFocusEl.call(this, row, col, col < this.cm.getLockedCount() ? false : hscroll); }, ensureVisible : function(row, col, hscroll){ return Ext.ux.grid.LockingGridView.superclass.ensureVisible.call(this, row, col, col < this.cm.getLockedCount() ? false : hscroll); }, insertRows : function(dm, firstRow, lastRow, isUpdate){ var last = dm.getCount() - 1; if(!isUpdate && firstRow === 0 && lastRow >= last){ this.refresh(); }else{ if(!isUpdate){ this.fireEvent('beforerowsinserted', this, firstRow, lastRow); } var html = this.renderRows(firstRow, lastRow), before = this.getRow(firstRow); if(before){ if(firstRow === 0){ this.removeRowClass(0, this.firstRowCls); } Ext.DomHelper.insertHtml('beforeBegin', before, html[0]); before = this.getLockedRow(firstRow); Ext.DomHelper.insertHtml('beforeBegin', before, html[1]); }else{ this.removeRowClass(last - 1, this.lastRowCls); Ext.DomHelper.insertHtml('beforeEnd', this.mainBody.dom, html[0]); Ext.DomHelper.insertHtml('beforeEnd', this.lockedBody.dom, html[1]); } if(!isUpdate){ this.fireEvent('rowsinserted', this, firstRow, lastRow); this.processRows(firstRow); }else if(firstRow === 0 || firstRow >= last){ this.addRowClass(firstRow, firstRow === 0 ? this.firstRowCls : this.lastRowCls); } } this.syncFocusEl(firstRow); }, getColumnStyle : function(col, isHeader){ var style = !isHeader ? this.cm.config[col].cellStyle || this.cm.config[col].css || '' : this.cm.config[col].headerStyle || ''; style += 'width:'+this.getColumnWidth(col)+';'; if(this.cm.isHidden(col)){ style += 'display:none;'; } var align = this.cm.config[col].align; if(align){ style += 'text-align:'+align+';'; } return style; }, getLockedWidth : function() { return this.cm.getTotalLockedWidth() + 'px'; }, getTotalWidth : function() { return (this.cm.getTotalWidth() - this.cm.getTotalLockedWidth()) + 'px'; }, getColumnData : function(){ var cs = [], cm = this.cm, colCount = cm.getColumnCount(); for(var i = 0; i < colCount; i++){ var name = cm.getDataIndex(i); cs[i] = { name : (!Ext.isDefined(name) ? this.ds.fields.get(i).name : name), renderer : cm.getRenderer(i), id : cm.getColumnId(i), style : this.getColumnStyle(i), locked : cm.isLocked(i) }; } return cs; }, renderBody : function(){ var markup = this.renderRows() || ['&#160;', '&#160;']; return [this.templates.body.apply({rows: markup[0]}), this.templates.body.apply({rows: markup[1]})]; }, refreshRow: function(record){ var store = this.ds, colCount = this.cm.getColumnCount(), columns = this.getColumnData(), last = colCount - 1, cls = ['x-grid3-row'], rowParams = { tstyle: String.format("width: {0};", this.getTotalWidth()) }, lockedRowParams = { tstyle: String.format("width: {0};", this.getLockedWidth()) }, colBuffer = [], lockedColBuffer = [], cellTpl = this.templates.cell, rowIndex, row, lockedRow, column, meta, css, i; if (Ext.isNumber(record)) { rowIndex = record; record = store.getAt(rowIndex); } else { rowIndex = store.indexOf(record); } if (!record || rowIndex < 0) { return; } for (i = 0; i < colCount; i++) { column = columns[i]; if (i == 0) { css = 'x-grid3-cell-first'; } else { css = (i == last) ? 'x-grid3-cell-last ' : ''; } meta = { id: column.id, style: column.style, css: css, attr: "", cellAttr: "" }; meta.value = column.renderer.call(column.scope, record.data[column.name], meta, record, rowIndex, i, store); if (Ext.isEmpty(meta.value)) { meta.value = ' '; } if (this.markDirty && record.dirty && typeof record.modified[column.name] != 'undefined') { meta.css += ' x-grid3-dirty-cell'; } if (column.locked) { lockedColBuffer[i] = cellTpl.apply(meta); } else { colBuffer[i] = cellTpl.apply(meta); } } row = this.getRow(rowIndex); row.className = ''; lockedRow = this.getLockedRow(rowIndex); lockedRow.className = ''; if (this.grid.stripeRows && ((rowIndex + 1) % 2 === 0)) { cls.push('x-grid3-row-alt'); } if (this.getRowClass) { rowParams.cols = colCount; cls.push(this.getRowClass(record, rowIndex, rowParams, store)); } // Unlocked rows this.fly(row).addClass(cls).setStyle(rowParams.tstyle); rowParams.cells = colBuffer.join(""); row.innerHTML = this.templates.rowInner.apply(rowParams); // Locked rows this.fly(lockedRow).addClass(cls).setStyle(lockedRowParams.tstyle); lockedRowParams.cells = lockedColBuffer.join(""); lockedRow.innerHTML = this.templates.rowInner.apply(lockedRowParams); lockedRow.rowIndex = rowIndex; this.syncRowHeights(row, lockedRow); this.fireEvent('rowupdated', this, rowIndex, record); }, refresh : function(headersToo){ this.fireEvent('beforerefresh', this); this.grid.stopEditing(true); var result = this.renderBody(); this.mainBody.update(result[0]).setWidth(this.getTotalWidth()); this.lockedBody.update(result[1]).setWidth(this.getLockedWidth()); if(headersToo === true){ this.updateHeaders(); this.updateHeaderSortState(); } this.processRows(0, true); this.layout(); this.applyEmptyText(); this.fireEvent('refresh', this); }, onDenyColumnLock : function(){ }, initData : function(ds, cm){ if(this.cm){ this.cm.un('columnlockchange', this.onColumnLock, this); } Ext.ux.grid.LockingGridView.superclass.initData.call(this, ds, cm); if(this.cm){ this.cm.on('columnlockchange', this.onColumnLock, this); } }, onColumnLock : function(){ this.refresh(true); }, handleHdMenuClick : function(item){ var index = this.hdCtxIndex, cm = this.cm, id = item.getItemId(), llen = cm.getLockedCount(); switch(id){ case 'lock': if(cm.getColumnCount(true) <= llen + 1){ this.onDenyColumnLock(); return undefined; } cm.setLocked(index, true); if(llen != index){ cm.moveColumn(index, llen); this.grid.fireEvent('columnmove', index, llen); } break; case 'unlock': if(llen - 1 != index){ cm.setLocked(index, false, true); cm.moveColumn(index, llen - 1); this.grid.fireEvent('columnmove', index, llen - 1); }else{ cm.setLocked(index, false); } break; default: return Ext.ux.grid.LockingGridView.superclass.handleHdMenuClick.call(this, item); } return true; }, handleHdDown : function(e, t){ Ext.ux.grid.LockingGridView.superclass.handleHdDown.call(this, e, t); if(this.grid.enableColLock !== false){ if(Ext.fly(t).hasClass('x-grid3-hd-btn')){ var hd = this.findHeaderCell(t), index = this.getCellIndex(hd), ms = this.hmenu.items, cm = this.cm; ms.get('lock').setDisabled(cm.isLocked(index)); ms.get('unlock').setDisabled(!cm.isLocked(index)); } } }, syncHeaderHeight: function(){ var hrow = Ext.fly(this.innerHd).child('tr', true), lhrow = Ext.fly(this.lockedInnerHd).child('tr', true); hrow.style.height = 'auto'; lhrow.style.height = 'auto'; var hd = hrow.offsetHeight, lhd = lhrow.offsetHeight, height = Math.max(lhd, hd) + 'px'; hrow.style.height = height; lhrow.style.height = height; }, updateLockedWidth: function(){ var lw = this.cm.getTotalLockedWidth(), tw = this.cm.getTotalWidth() - lw, csize = this.grid.getGridEl().getSize(true), lp = Ext.isBorderBox ? 0 : this.lockedBorderWidth, rp = Ext.isBorderBox ? 0 : this.rowBorderWidth, vw = (csize.width - lw - lp - rp) + 'px', so = this.getScrollOffset(); if(!this.grid.autoHeight){ var vh = (csize.height - this.mainHd.getHeight()) + 'px'; this.lockedScroller.dom.style.height = vh; this.scroller.dom.style.height = vh; } this.lockedWrap.dom.style.width = (lw + rp) + 'px'; this.scroller.dom.style.width = vw; this.mainWrap.dom.style.left = (lw + lp + rp) + 'px'; if(this.innerHd){ this.lockedInnerHd.firstChild.style.width = lw + 'px'; this.lockedInnerHd.firstChild.firstChild.style.width = lw + 'px'; this.innerHd.style.width = vw; this.innerHd.firstChild.style.width = (tw + rp + so) + 'px'; this.innerHd.firstChild.firstChild.style.width = tw + 'px'; } if(this.mainBody){ this.lockedBody.dom.style.width = (lw + rp) + 'px'; this.mainBody.dom.style.width = (tw + rp) + 'px'; } } }); Ext.ux.grid.LockingColumnModel = Ext.extend(Ext.grid.ColumnModel, { /** * Returns true if the given column index is currently locked * @param {Number} colIndex The column index * @return {Boolean} True if the column is locked */ isLocked : function(colIndex){ return this.config[colIndex].locked === true; }, /** * Locks or unlocks a given column * @param {Number} colIndex The column index * @param {Boolean} value True to lock, false to unlock * @param {Boolean} suppressEvent Pass false to cause the columnlockchange event not to fire */ setLocked : function(colIndex, value, suppressEvent){ if (this.isLocked(colIndex) == value) { return; } this.config[colIndex].locked = value; if (!suppressEvent) { this.fireEvent('columnlockchange', this, colIndex, value); } }, /** * Returns the total width of all locked columns * @return {Number} The width of all locked columns */ getTotalLockedWidth : function(){ var totalWidth = 0; for (var i = 0, len = this.config.length; i < len; i++) { if (this.isLocked(i) && !this.isHidden(i)) { totalWidth += this.getColumnWidth(i); } } return totalWidth; }, /** * Returns the total number of locked columns * @return {Number} The number of locked columns */ getLockedCount : function() { var len = this.config.length; for (var i = 0; i < len; i++) { if (!this.isLocked(i)) { return i; } } //if we get to this point all of the columns are locked so we return the total return len; }, /** * Moves a column from one position to another * @param {Number} oldIndex The current column index * @param {Number} newIndex The destination column index */ moveColumn : function(oldIndex, newIndex){ var oldLocked = this.isLocked(oldIndex), newLocked = this.isLocked(newIndex); if (oldIndex < newIndex && oldLocked && !newLocked) { this.setLocked(oldIndex, false, true); } else if (oldIndex > newIndex && !oldLocked && newLocked) { this.setLocked(oldIndex, true, true); } Ext.ux.grid.LockingColumnModel.superclass.moveColumn.apply(this, arguments); } });
import Ember from "ember"; const { Route } = Ember; const set = Ember.set; export default Route.extend({ setupController() { this.controllerFor('mixinStack').set('model', []); let port = this.get('port'); port.on('objectInspector:updateObject', this, this.updateObject); port.on('objectInspector:updateProperty', this, this.updateProperty); port.on('objectInspector:updateErrors', this, this.updateErrors); port.on('objectInspector:droppedObject', this, this.droppedObject); port.on('deprecation:count', this, this.setDeprecationCount); port.send('deprecation:getCount'); }, deactivate() { let port = this.get('port'); port.off('objectInspector:updateObject', this, this.updateObject); port.off('objectInspector:updateProperty', this, this.updateProperty); port.off('objectInspector:updateErrors', this, this.updateErrors); port.off('objectInspector:droppedObject', this, this.droppedObject); port.off('deprecation:count', this, this.setDeprecationCount); }, updateObject(options) { const details = options.details, name = options.name, property = options.property, objectId = options.objectId, errors = options.errors; Ember.NativeArray.apply(details); details.forEach(arrayize); let controller = this.get('controller'); if (options.parentObject) { controller.pushMixinDetails(name, property, objectId, details); } else { controller.activateMixinDetails(name, objectId, details, errors); } this.send('expandInspector'); }, setDeprecationCount(message) { this.controller.set('deprecationCount', message.count); }, updateProperty(options) { const detail = this.controllerFor('mixinDetails').get('model.mixins').objectAt(options.mixinIndex); const property = Ember.get(detail, 'properties').findProperty('name', options.property); set(property, 'value', options.value); }, updateErrors(options) { const mixinDetails = this.controllerFor('mixinDetails'); if (mixinDetails.get('model.objectId') === options.objectId) { mixinDetails.set('model.errors', options.errors); } }, droppedObject(message) { let controller = this.get('controller'); controller.droppedObject(message.objectId); }, actions: { expandInspector() { this.set("controller.inspectorExpanded", true); }, toggleInspector() { this.toggleProperty("controller.inspectorExpanded"); }, inspectObject(objectId) { if (objectId) { this.get('port').send('objectInspector:inspectById', { objectId: objectId }); } }, setIsDragging(isDragging) { this.set('controller.isDragging', isDragging); }, refreshPage() { // If the adapter defined a `reloadTab` method, it means // they prefer to handle the reload themselves if (typeof this.get('adapter').reloadTab === 'function') { this.get('adapter').reloadTab(); } else { // inject ember_debug as quickly as possible in chrome // so that promises created on dom ready are caught this.get('port').send('general:refresh'); this.get('adapter').willReload(); } } } }); function arrayize(mixin) { Ember.NativeArray.apply(mixin.properties); }
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.Inferno = global.Inferno || {}))); }(this, (function (exports) { 'use strict'; var NO_OP = '$NO_OP'; var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.'; // This should be boolean and not reference to window.document var isBrowser = !!(typeof window !== 'undefined' && window.document); // this is MUCH faster than .constructor === Array and instanceof Array // in Node 7 and the later versions of V8, slower in older versions though var isArray = Array.isArray; function isStringOrNumber(o) { var type = typeof o; return type === 'string' || type === 'number'; } function isNullOrUndef(o) { return isUndefined(o) || isNull(o); } function isInvalid(o) { return isNull(o) || o === false || isTrue(o) || isUndefined(o); } function isFunction(o) { return typeof o === 'function'; } function isString(o) { return typeof o === 'string'; } function isNumber(o) { return typeof o === 'number'; } function isNull(o) { return o === null; } function isTrue(o) { return o === true; } function isUndefined(o) { return o === void 0; } function isDefined(o) { return o !== void 0; } function isObject(o) { return typeof o === 'object'; } function throwError(message) { if (!message) { message = ERROR_MSG; } throw new Error(("Inferno Error: " + message)); } function warning(message) { // tslint:disable-next-line:no-console console.error(message); } function combineFrom(first, second) { var out = {}; if (first) { for (var key in first) { out[key] = first[key]; } } if (second) { for (var key$1 in second) { out[key$1] = second[key$1]; } } return out; } function getTagName(input) { var tagName; if (isArray(input)) { var arrayText = input.length > 3 ? input.slice(0, 3).toString() + ',...' : input.toString(); tagName = 'Array(' + arrayText + ')'; } else if (isStringOrNumber(input)) { tagName = 'Text(' + input + ')'; } else if (isInvalid(input)) { tagName = 'InvalidVNode(' + input + ')'; } else { var flags = input.flags; if (flags & 481 /* Element */) { tagName = "<" + (input.type) + (input.className ? ' class="' + input.className + '"' : '') + ">"; } else if (flags & 16 /* Text */) { tagName = "Text(" + (input.children) + ")"; } else if (flags & 1024 /* Portal */) { tagName = "Portal*"; } else { var type = input.type; // Fallback for IE var componentName = type.name || type.displayName || type.constructor.name || (type.toString().match(/^function\s*([^\s(]+)/) || [])[1]; tagName = "<" + componentName + " />"; } } return '>> ' + tagName + '\n'; } function DEV_ValidateKeys(vNodeTree, vNode, forceKeyed) { var foundKeys = []; for (var i = 0, len = vNodeTree.length; i < len; i++) { var childNode = vNodeTree[i]; if (isArray(childNode)) { return 'Encountered ARRAY in mount, array must be flattened, or normalize used. Location: \n' + getTagName(childNode); } if (isInvalid(childNode)) { if (forceKeyed) { return 'Encountered invalid node when preparing to keyed algorithm. Location: \n' + getTagName(childNode); } else if (foundKeys.length !== 0) { return 'Encountered invalid node with mixed keys. Location: \n' + getTagName(childNode); } continue; } if (typeof childNode === 'object') { childNode.isValidated = true; } var key = childNode.key; if (!isNullOrUndef(key) && !isStringOrNumber(key)) { return 'Encountered child vNode where key property is not string or number. Location: \n' + getTagName(childNode); } var children = childNode.children; var childFlags = childNode.childFlags; if (!isInvalid(children)) { var val = (void 0); if (childFlags & 12 /* MultipleChildren */) { val = DEV_ValidateKeys(children, childNode, childNode.childFlags & 8 /* HasKeyedChildren */); } else if (childFlags === 2 /* HasVNodeChildren */) { val = DEV_ValidateKeys([children], childNode, childNode.childFlags & 8 /* HasKeyedChildren */); } if (val) { val += getTagName(childNode); return val; } } if (forceKeyed && isNullOrUndef(key)) { return ('Encountered child without key during keyed algorithm. If this error points to Array make sure children is flat list. Location: \n' + getTagName(childNode)); } else if (!forceKeyed && isNullOrUndef(key)) { if (foundKeys.length !== 0) { return 'Encountered children with key missing. Location: \n' + getTagName(childNode); } continue; } if (foundKeys.indexOf(key) > -1) { return 'Encountered two children with same key: {' + key + '}. Location: \n' + getTagName(childNode); } foundKeys.push(key); } } function validateVNodeElementChildren(vNode) { { if (vNode.childFlags & 1 /* HasInvalidChildren */) { return; } if (vNode.flags & 64 /* InputElement */) { throwError("input elements can't have children."); } if (vNode.flags & 128 /* TextareaElement */) { throwError("textarea elements can't have children."); } if (vNode.flags & 481 /* Element */) { var voidTypes = ['area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr']; var tag = vNode.type.toLowerCase(); if (tag === 'media') { throwError("media elements can't have children."); } var idx = voidTypes.indexOf(tag); if (idx !== -1) { throwError(((voidTypes[idx]) + " elements can't have children.")); } } } } function validateKeys(vNode) { { // Checks if there is any key missing or duplicate keys if (vNode.isValidated === false && vNode.children && vNode.flags & 481 /* Element */) { var error = DEV_ValidateKeys(Array.isArray(vNode.children) ? vNode.children : [vNode.children], vNode, (vNode.childFlags & 8 /* HasKeyedChildren */) > 0); if (error) { throwError(error + getTagName(vNode)); } } vNode.isValidated = true; } } var keyPrefix = '$'; function getVNode(childFlags, children, className, flags, key, props, ref, type) { { return { childFlags: childFlags, children: children, className: className, dom: null, flags: flags, isValidated: false, key: key === void 0 ? null : key, parentVNode: null, props: props === void 0 ? null : props, ref: ref === void 0 ? null : ref, type: type }; } return { childFlags: childFlags, children: children, className: className, dom: null, flags: flags, key: key === void 0 ? null : key, parentVNode: null, props: props === void 0 ? null : props, ref: ref === void 0 ? null : ref, type: type }; } function createVNode(flags, type, className, children, childFlags, props, key, ref) { { if (flags & 14 /* Component */) { throwError('Creating Component vNodes using createVNode is not allowed. Use Inferno.createComponentVNode method.'); } } var childFlag = childFlags === void 0 ? 1 /* HasInvalidChildren */ : childFlags; var vNode = getVNode(childFlag, children, className, flags, key, props, ref, type); var optsVNode = options.createVNode; if (typeof optsVNode === 'function') { optsVNode(vNode); } if (childFlag === 0 /* UnknownChildren */) { normalizeChildren(vNode, vNode.children); } { validateVNodeElementChildren(vNode); } return vNode; } function createComponentVNode(flags, type, props, key, ref) { { if (flags & 1 /* HtmlElement */) { throwError('Creating element vNodes using createComponentVNode is not allowed. Use Inferno.createVNode method.'); } } if ((flags & 2 /* ComponentUnknown */) > 0) { flags = isDefined(type.prototype) && isFunction(type.prototype.render) ? 4 /* ComponentClass */ : 8 /* ComponentFunction */; } // set default props var defaultProps = type.defaultProps; if (!isNullOrUndef(defaultProps)) { if (!props) { props = {}; // Props can be referenced and modified at application level so always create new object } for (var prop in defaultProps) { if (isUndefined(props[prop])) { props[prop] = defaultProps[prop]; } } } if ((flags & 8 /* ComponentFunction */) > 0) { var defaultHooks = type.defaultHooks; if (!isNullOrUndef(defaultHooks)) { if (!ref) { // As ref cannot be referenced from application level, we can use the same refs object ref = defaultHooks; } else { for (var prop$1 in defaultHooks) { if (isUndefined(ref[prop$1])) { ref[prop$1] = defaultHooks[prop$1]; } } } } } var vNode = getVNode(1 /* HasInvalidChildren */, null, null, flags, key, props, ref, type); var optsVNode = options.createVNode; if (isFunction(optsVNode)) { optsVNode(vNode); } return vNode; } function createTextVNode(text, key) { return getVNode(1 /* HasInvalidChildren */, isNullOrUndef(text) ? '' : text, null, 16 /* Text */, key, null, null, null); } function normalizeProps(vNode) { var props = vNode.props; if (props) { var flags = vNode.flags; if (flags & 481 /* Element */) { if (isDefined(props.children) && isNullOrUndef(vNode.children)) { normalizeChildren(vNode, props.children); } if (isDefined(props.className)) { vNode.className = props.className || null; props.className = undefined; } } if (isDefined(props.key)) { vNode.key = props.key; props.key = undefined; } if (isDefined(props.ref)) { if (flags & 8 /* ComponentFunction */) { vNode.ref = combineFrom(vNode.ref, props.ref); } else { vNode.ref = props.ref; } props.ref = undefined; } } return vNode; } function directClone(vNodeToClone) { var newVNode; var flags = vNodeToClone.flags; if (flags & 14 /* Component */) { var props; var propsToClone = vNodeToClone.props; if (!isNull(propsToClone)) { props = {}; for (var key in propsToClone) { props[key] = propsToClone[key]; } } newVNode = createComponentVNode(flags, vNodeToClone.type, props, vNodeToClone.key, vNodeToClone.ref); } else if (flags & 481 /* Element */) { var children = vNodeToClone.children; newVNode = createVNode(flags, vNodeToClone.type, vNodeToClone.className, children, 0 /* UnknownChildren */, vNodeToClone.props, vNodeToClone.key, vNodeToClone.ref); } else if (flags & 16 /* Text */) { newVNode = createTextVNode(vNodeToClone.children, vNodeToClone.key); } else if (flags & 1024 /* Portal */) { newVNode = vNodeToClone; } return newVNode; } function createVoidVNode() { return createTextVNode('', null); } function _normalizeVNodes(nodes, result, index, currentKey) { for (var len = nodes.length; index < len; index++) { var n = nodes[index]; if (!isInvalid(n)) { var newKey = currentKey + keyPrefix + index; if (isArray(n)) { _normalizeVNodes(n, result, 0, newKey); } else { if (isStringOrNumber(n)) { n = createTextVNode(n, newKey); } else { var oldKey = n.key; var isPrefixedKey = isString(oldKey) && oldKey[0] === keyPrefix; if (!isNull(n.dom) || isPrefixedKey) { n = directClone(n); } if (isNull(oldKey) || isPrefixedKey) { n.key = newKey; } else { n.key = currentKey + oldKey; } } result.push(n); } } } } function getFlagsForElementVnode(type) { if (type === 'svg') { return 32 /* SvgElement */; } if (type === 'input') { return 64 /* InputElement */; } if (type === 'select') { return 256 /* SelectElement */; } if (type === 'textarea') { return 128 /* TextareaElement */; } return 1 /* HtmlElement */; } function normalizeChildren(vNode, children) { var newChildren; var newChildFlags = 1 /* HasInvalidChildren */; // Don't change children to match strict equal (===) true in patching if (isInvalid(children)) { newChildren = children; } else if (isString(children)) { newChildFlags = 2 /* HasVNodeChildren */; newChildren = createTextVNode(children); } else if (isNumber(children)) { newChildFlags = 2 /* HasVNodeChildren */; newChildren = createTextVNode(children + ''); } else if (isArray(children)) { var len = children.length; if (len === 0) { newChildren = null; newChildFlags = 1 /* HasInvalidChildren */; } else { // we assign $ which basically means we've flagged this array for future note // if it comes back again, we need to clone it, as people are using it // in an immutable way // tslint:disable-next-line if (Object.isFrozen(children) || children['$'] === true) { children = children.slice(); } newChildFlags = 8 /* HasKeyedChildren */; for (var i = 0; i < len; i++) { var n = children[i]; if (isInvalid(n) || isArray(n)) { newChildren = newChildren || children.slice(0, i); _normalizeVNodes(children, newChildren, i, ''); break; } else if (isStringOrNumber(n)) { newChildren = newChildren || children.slice(0, i); newChildren.push(createTextVNode(n, keyPrefix + i)); } else { var key = n.key; var isNullDom = isNull(n.dom); var isNullKey = isNull(key); var isPrefixed = !isNullKey && key[0] === keyPrefix; if (!isNullDom || isNullKey || isPrefixed) { newChildren = newChildren || children.slice(0, i); if (!isNullDom || isPrefixed) { n = directClone(n); } if (isNullKey || isPrefixed) { n.key = keyPrefix + i; } newChildren.push(n); } else if (newChildren) { newChildren.push(n); } } } newChildren = newChildren || children; newChildren.$ = true; } } else { newChildren = children; if (!isNull(children.dom)) { newChildren = directClone(children); } newChildFlags = 2 /* HasVNodeChildren */; } vNode.children = newChildren; vNode.childFlags = newChildFlags; { validateVNodeElementChildren(vNode); } return vNode; } var options = { afterMount: null, afterRender: null, afterUpdate: null, beforeRender: null, beforeUnmount: null, createVNode: null, roots: [] }; /** * Links given data to event as first parameter * @param {*} data data to be linked, it will be available in function as first parameter * @param {Function} event Function to be called when event occurs * @returns {{data: *, event: Function}} */ function linkEvent(data, event) { if (isFunction(event)) { return { data: data, event: event }; } return null; // Return null when event is invalid, to avoid creating unnecessary event handlers } var xlinkNS = 'http://www.w3.org/1999/xlink'; var xmlNS = 'http://www.w3.org/XML/1998/namespace'; var svgNS = 'http://www.w3.org/2000/svg'; var namespaces = { 'xlink:actuate': xlinkNS, 'xlink:arcrole': xlinkNS, 'xlink:href': xlinkNS, 'xlink:role': xlinkNS, 'xlink:show': xlinkNS, 'xlink:title': xlinkNS, 'xlink:type': xlinkNS, 'xml:base': xmlNS, 'xml:lang': xmlNS, 'xml:space': xmlNS }; // We need EMPTY_OBJ defined in one place. // Its used for comparison so we cant inline it into shared var EMPTY_OBJ = {}; var LIFECYCLE = []; { Object.freeze(EMPTY_OBJ); } function appendChild(parentDom, dom) { parentDom.appendChild(dom); } function insertOrAppend(parentDom, newNode, nextNode) { if (isNullOrUndef(nextNode)) { appendChild(parentDom, newNode); } else { parentDom.insertBefore(newNode, nextNode); } } function documentCreateElement(tag, isSVG) { if (isSVG === true) { return document.createElementNS(svgNS, tag); } return document.createElement(tag); } function replaceChild(parentDom, newDom, lastDom) { parentDom.replaceChild(newDom, lastDom); } function removeChild(parentDom, dom) { parentDom.removeChild(dom); } function callAll(arrayFn) { var listener; while ((listener = arrayFn.shift()) !== undefined) { listener(); } } var attachedEventCounts = {}; var attachedEvents = {}; function handleEvent(name, nextEvent, dom) { var eventsLeft = attachedEventCounts[name]; var eventsObject = dom.$EV; if (nextEvent) { if (!eventsLeft) { attachedEvents[name] = attachEventToDocument(name); attachedEventCounts[name] = 0; } if (!eventsObject) { eventsObject = dom.$EV = {}; } if (!eventsObject[name]) { attachedEventCounts[name]++; } eventsObject[name] = nextEvent; } else if (eventsObject && eventsObject[name]) { attachedEventCounts[name]--; if (eventsLeft === 1) { document.removeEventListener(normalizeEventName(name), attachedEvents[name]); attachedEvents[name] = null; } eventsObject[name] = nextEvent; } } function dispatchEvents(event, target, isClick, name, eventData) { var dom = target; while (!isNull(dom)) { // Html Nodes can be nested fe: span inside button in that scenario browser does not handle disabled attribute on parent, // because the event listener is on document.body // Don't process clicks on disabled elements if (isClick && dom.disabled) { return; } var eventsObject = dom.$EV; if (eventsObject) { var currentEvent = eventsObject[name]; if (currentEvent) { // linkEvent object eventData.dom = dom; if (currentEvent.event) { currentEvent.event(currentEvent.data, event); } else { currentEvent(event); } if (event.cancelBubble) { return; } } } dom = dom.parentNode; } } function normalizeEventName(name) { return name.substr(2).toLowerCase(); } function stopPropagation() { this.cancelBubble = true; this.stopImmediatePropagation(); } function attachEventToDocument(name) { var docEvent = function (event) { var type = event.type; var isClick = type === 'click' || type === 'dblclick'; if (isClick && event.button !== 0) { // Firefox incorrectly triggers click event for mid/right mouse buttons. // This bug has been active for 12 years. // https://bugzilla.mozilla.org/show_bug.cgi?id=184051 event.preventDefault(); event.stopPropagation(); return false; } event.stopPropagation = stopPropagation; // Event data needs to be object to save reference to currentTarget getter var eventData = { dom: document }; try { Object.defineProperty(event, 'currentTarget', { configurable: true, get: function get() { return eventData.dom; } }); } catch (e) { /* safari7 and phantomJS will crash */ } dispatchEvents(event, event.target, isClick, name, eventData); }; document.addEventListener(normalizeEventName(name), docEvent); return docEvent; } function isSameInnerHTML(dom, innerHTML) { var tempdom = document.createElement('i'); tempdom.innerHTML = innerHTML; return tempdom.innerHTML === dom.innerHTML; } function isSamePropsInnerHTML(dom, props) { return Boolean(props && props.dangerouslySetInnerHTML && props.dangerouslySetInnerHTML.__html && isSameInnerHTML(dom, props.dangerouslySetInnerHTML.__html)); } function triggerEventListener(props, methodName, e) { if (props[methodName]) { var listener = props[methodName]; if (listener.event) { listener.event(listener.data, e); } else { listener(e); } } else { var nativeListenerName = methodName.toLowerCase(); if (props[nativeListenerName]) { props[nativeListenerName](e); } } } function createWrappedFunction(methodName, applyValue) { var fnMethod = function (e) { e.stopPropagation(); var vNode = this.$V; // If vNode is gone by the time event fires, no-op if (!vNode) { return; } var props = vNode.props || EMPTY_OBJ; var dom = vNode.dom; if (isString(methodName)) { triggerEventListener(props, methodName, e); } else { for (var i = 0; i < methodName.length; i++) { triggerEventListener(props, methodName[i], e); } } if (isFunction(applyValue)) { var newVNode = this.$V; var newProps = newVNode.props || EMPTY_OBJ; applyValue(newProps, dom, false, newVNode); } }; Object.defineProperty(fnMethod, 'wrapped', { configurable: false, enumerable: false, value: true, writable: false }); return fnMethod; } function isCheckedType(type) { return type === 'checkbox' || type === 'radio'; } var onTextInputChange = createWrappedFunction('onInput', applyValueInput); var wrappedOnChange = createWrappedFunction(['onClick', 'onChange'], applyValueInput); /* tslint:disable-next-line:no-empty */ function emptywrapper(event) { event.stopPropagation(); } emptywrapper.wrapped = true; function inputEvents(dom, nextPropsOrEmpty) { if (isCheckedType(nextPropsOrEmpty.type)) { dom.onchange = wrappedOnChange; dom.onclick = emptywrapper; } else { dom.oninput = onTextInputChange; } } function applyValueInput(nextPropsOrEmpty, dom) { var type = nextPropsOrEmpty.type; var value = nextPropsOrEmpty.value; var checked = nextPropsOrEmpty.checked; var multiple = nextPropsOrEmpty.multiple; var defaultValue = nextPropsOrEmpty.defaultValue; var hasValue = !isNullOrUndef(value); if (type && type !== dom.type) { dom.setAttribute('type', type); } if (!isNullOrUndef(multiple) && multiple !== dom.multiple) { dom.multiple = multiple; } if (!isNullOrUndef(defaultValue) && !hasValue) { dom.defaultValue = defaultValue + ''; } if (isCheckedType(type)) { if (hasValue) { dom.value = value; } if (!isNullOrUndef(checked)) { dom.checked = checked; } } else { if (hasValue && dom.value !== value) { dom.defaultValue = value; dom.value = value; } else if (!isNullOrUndef(checked)) { dom.checked = checked; } } } function updateChildOptionGroup(vNode, value) { var type = vNode.type; if (type === 'optgroup') { var children = vNode.children; var childFlags = vNode.childFlags; if (childFlags & 12 /* MultipleChildren */) { for (var i = 0, len = children.length; i < len; i++) { updateChildOption(children[i], value); } } else if (childFlags === 2 /* HasVNodeChildren */) { updateChildOption(children, value); } } else { updateChildOption(vNode, value); } } function updateChildOption(vNode, value) { var props = vNode.props || EMPTY_OBJ; var dom = vNode.dom; // we do this as multiple may have changed dom.value = props.value; if ((isArray(value) && value.indexOf(props.value) !== -1) || props.value === value) { dom.selected = true; } else if (!isNullOrUndef(value) || !isNullOrUndef(props.selected)) { dom.selected = props.selected || false; } } var onSelectChange = createWrappedFunction('onChange', applyValueSelect); function selectEvents(dom) { dom.onchange = onSelectChange; } function applyValueSelect(nextPropsOrEmpty, dom, mounting, vNode) { var multiplePropInBoolean = Boolean(nextPropsOrEmpty.multiple); if (!isNullOrUndef(nextPropsOrEmpty.multiple) && multiplePropInBoolean !== dom.multiple) { dom.multiple = multiplePropInBoolean; } var childFlags = vNode.childFlags; if ((childFlags & 1 /* HasInvalidChildren */) === 0) { var children = vNode.children; var value = nextPropsOrEmpty.value; if (mounting && isNullOrUndef(value)) { value = nextPropsOrEmpty.defaultValue; } if (childFlags & 12 /* MultipleChildren */) { for (var i = 0, len = children.length; i < len; i++) { updateChildOptionGroup(children[i], value); } } else if (childFlags === 2 /* HasVNodeChildren */) { updateChildOptionGroup(children, value); } } } var onTextareaInputChange = createWrappedFunction('onInput', applyValueTextArea); var wrappedOnChange$1 = createWrappedFunction('onChange'); function textAreaEvents(dom, nextPropsOrEmpty) { dom.oninput = onTextareaInputChange; if (nextPropsOrEmpty.onChange) { dom.onchange = wrappedOnChange$1; } } function applyValueTextArea(nextPropsOrEmpty, dom, mounting) { var value = nextPropsOrEmpty.value; var domValue = dom.value; if (isNullOrUndef(value)) { if (mounting) { var defaultValue = nextPropsOrEmpty.defaultValue; if (!isNullOrUndef(defaultValue) && defaultValue !== domValue) { dom.defaultValue = defaultValue; dom.value = defaultValue; } } } else if (domValue !== value) { /* There is value so keep it controlled */ dom.defaultValue = value; dom.value = value; } } /** * There is currently no support for switching same input between controlled and nonControlled * If that ever becomes a real issue, then re design controlled elements * Currently user must choose either controlled or non-controlled and stick with that */ function processElement(flags, vNode, dom, nextPropsOrEmpty, mounting, isControlled) { if (flags & 64 /* InputElement */) { applyValueInput(nextPropsOrEmpty, dom); } else if (flags & 256 /* SelectElement */) { applyValueSelect(nextPropsOrEmpty, dom, mounting, vNode); } else if (flags & 128 /* TextareaElement */) { applyValueTextArea(nextPropsOrEmpty, dom, mounting); } if (isControlled) { dom.$V = vNode; } } function addFormElementEventHandlers(flags, dom, nextPropsOrEmpty) { if (flags & 64 /* InputElement */) { inputEvents(dom, nextPropsOrEmpty); } else if (flags & 256 /* SelectElement */) { selectEvents(dom); } else if (flags & 128 /* TextareaElement */) { textAreaEvents(dom, nextPropsOrEmpty); } } function isControlledFormElement(nextPropsOrEmpty) { return nextPropsOrEmpty.type && isCheckedType(nextPropsOrEmpty.type) ? !isNullOrUndef(nextPropsOrEmpty.checked) : !isNullOrUndef(nextPropsOrEmpty.value); } function remove(vNode, parentDom) { unmount(vNode); if (!isNull(parentDom)) { removeChild(parentDom, vNode.dom); // Let carbage collector free memory vNode.dom = null; } } function unmount(vNode) { var flags = vNode.flags; if (flags & 481 /* Element */) { var ref = vNode.ref; var props = vNode.props; if (isFunction(ref)) { ref(null); } var children = vNode.children; var childFlags = vNode.childFlags; if (childFlags & 12 /* MultipleChildren */) { unmountAllChildren(children); } else if (childFlags === 2 /* HasVNodeChildren */) { unmount(children); } if (!isNull(props)) { for (var name in props) { switch (name) { case 'onClick': case 'onDblClick': case 'onFocusIn': case 'onFocusOut': case 'onKeyDown': case 'onKeyPress': case 'onKeyUp': case 'onMouseDown': case 'onMouseMove': case 'onMouseUp': case 'onSubmit': case 'onTouchEnd': case 'onTouchMove': case 'onTouchStart': handleEvent(name, null, vNode.dom); break; default: break; } } } } else if (flags & 14 /* Component */) { var instance = vNode.children; var ref$1 = vNode.ref; if (flags & 4 /* ComponentClass */) { if (isFunction(options.beforeUnmount)) { options.beforeUnmount(vNode); } if (isFunction(instance.componentWillUnmount)) { instance.componentWillUnmount(); } if (isFunction(ref$1)) { ref$1(null); } instance.$UN = true; unmount(instance.$LI); } else { if (!isNullOrUndef(ref$1) && isFunction(ref$1.onComponentWillUnmount)) { ref$1.onComponentWillUnmount(vNode.dom, vNode.props || EMPTY_OBJ); } unmount(instance); } } else if (flags & 1024 /* Portal */) { var children$1 = vNode.children; if (!isNull(children$1) && isObject(children$1)) { remove(children$1, vNode.type); } } } function unmountAllChildren(children) { for (var i = 0, len = children.length; i < len; i++) { unmount(children[i]); } } function removeAllChildren(dom, children) { unmountAllChildren(children); dom.textContent = ''; } function createLinkEvent(linkEvent, nextValue) { return function (e) { linkEvent(nextValue.data, e); }; } function patchEvent(name, lastValue, nextValue, dom) { var nameLowerCase = name.toLowerCase(); if (!isFunction(nextValue) && !isNullOrUndef(nextValue)) { var linkEvent = nextValue.event; if (linkEvent && isFunction(linkEvent)) { dom[nameLowerCase] = createLinkEvent(linkEvent, nextValue); } else { // Development warning { throwError(("an event on a VNode \"" + name + "\". was not a function or a valid linkEvent.")); } } } else { var domEvent = dom[nameLowerCase]; // if the function is wrapped, that means it's been controlled by a wrapper if (!domEvent || !domEvent.wrapped) { dom[nameLowerCase] = nextValue; } } } function getNumberStyleValue(style, value) { switch (style) { case 'animationIterationCount': case 'borderImageOutset': case 'borderImageSlice': case 'borderImageWidth': case 'boxFlex': case 'boxFlexGroup': case 'boxOrdinalGroup': case 'columnCount': case 'fillOpacity': case 'flex': case 'flexGrow': case 'flexNegative': case 'flexOrder': case 'flexPositive': case 'flexShrink': case 'floodOpacity': case 'fontWeight': case 'gridColumn': case 'gridRow': case 'lineClamp': case 'lineHeight': case 'opacity': case 'order': case 'orphans': case 'stopOpacity': case 'strokeDasharray': case 'strokeDashoffset': case 'strokeMiterlimit': case 'strokeOpacity': case 'strokeWidth': case 'tabSize': case 'widows': case 'zIndex': case 'zoom': return value; default: return value + 'px'; } } // We are assuming here that we come from patchProp routine // -nextAttrValue cannot be null or undefined function patchStyle(lastAttrValue, nextAttrValue, dom) { var domStyle = dom.style; var style; var value; if (isString(nextAttrValue)) { domStyle.cssText = nextAttrValue; return; } if (!isNullOrUndef(lastAttrValue) && !isString(lastAttrValue)) { for (style in nextAttrValue) { // do not add a hasOwnProperty check here, it affects performance value = nextAttrValue[style]; if (value !== lastAttrValue[style]) { domStyle[style] = isNumber(value) ? getNumberStyleValue(style, value) : value; } } for (style in lastAttrValue) { if (isNullOrUndef(nextAttrValue[style])) { domStyle[style] = ''; } } } else { for (style in nextAttrValue) { value = nextAttrValue[style]; domStyle[style] = isNumber(value) ? getNumberStyleValue(style, value) : value; } } } function patchProp(prop, lastValue, nextValue, dom, isSVG, hasControlledValue, lastVNode) { switch (prop) { case 'onClick': case 'onDblClick': case 'onFocusIn': case 'onFocusOut': case 'onKeyDown': case 'onKeyPress': case 'onKeyUp': case 'onMouseDown': case 'onMouseMove': case 'onMouseUp': case 'onSubmit': case 'onTouchEnd': case 'onTouchMove': case 'onTouchStart': handleEvent(prop, nextValue, dom); break; case 'children': case 'childrenType': case 'className': case 'defaultValue': case 'key': case 'multiple': case 'ref': return; case 'allowfullscreen': case 'autoFocus': case 'autoplay': case 'capture': case 'checked': case 'controls': case 'default': case 'disabled': case 'hidden': case 'indeterminate': case 'loop': case 'muted': case 'novalidate': case 'open': case 'readOnly': case 'required': case 'reversed': case 'scoped': case 'seamless': case 'selected': prop = prop === 'autoFocus' ? prop.toLowerCase() : prop; dom[prop] = !!nextValue; break; case 'defaultChecked': case 'value': case 'volume': if (hasControlledValue && prop === 'value') { return; } var value = isNullOrUndef(nextValue) ? '' : nextValue; if (dom[prop] !== value) { dom[prop] = value; } break; case 'dangerouslySetInnerHTML': var lastHtml = (lastValue && lastValue.__html) || ''; var nextHtml = (nextValue && nextValue.__html) || ''; if (lastHtml !== nextHtml) { if (!isNullOrUndef(nextHtml) && !isSameInnerHTML(dom, nextHtml)) { if (!isNull(lastVNode)) { if (lastVNode.childFlags & 12 /* MultipleChildren */) { unmountAllChildren(lastVNode.children); } else if (lastVNode.childFlags === 2 /* HasVNodeChildren */) { unmount(lastVNode.children); } lastVNode.children = null; lastVNode.childFlags = 1 /* HasInvalidChildren */; } dom.innerHTML = nextHtml; } } break; default: if (prop[0] === 'o' && prop[1] === 'n') { patchEvent(prop, lastValue, nextValue, dom); } else if (isNullOrUndef(nextValue)) { dom.removeAttribute(prop); } else if (prop === 'style') { patchStyle(lastValue, nextValue, dom); } else if (isSVG && namespaces[prop]) { // We optimize for NS being boolean. Its 99.9% time false // If we end up in this path we can read property again dom.setAttributeNS(namespaces[prop], prop, nextValue); } else { dom.setAttribute(prop, nextValue); } break; } } function mountProps(vNode, flags, props, dom, isSVG) { var hasControlledValue = false; var isFormElement = (flags & 448 /* FormElement */) > 0; if (isFormElement) { hasControlledValue = isControlledFormElement(props); if (hasControlledValue) { addFormElementEventHandlers(flags, dom, props); } } for (var prop in props) { // do not add a hasOwnProperty check here, it affects performance patchProp(prop, null, props[prop], dom, isSVG, hasControlledValue, null); } if (isFormElement) { processElement(flags, vNode, dom, props, true, hasControlledValue); } } function createClassComponentInstance(vNode, Component, props, context) { var instance = new Component(props, context); vNode.children = instance; instance.$V = vNode; instance.$BS = false; instance.context = context; if (instance.props === EMPTY_OBJ) { instance.props = props; } instance.$UN = false; if (isFunction(instance.componentWillMount)) { instance.$BR = true; instance.componentWillMount(); if (instance.$PSS) { var state = instance.state; var pending = instance.$PS; if (isNull(state)) { instance.state = pending; } else { for (var key in pending) { state[key] = pending[key]; } } instance.$PSS = false; instance.$PS = null; } instance.$BR = false; } if (isFunction(options.beforeRender)) { options.beforeRender(instance); } var input = handleComponentInput(instance.render(props, instance.state, context), vNode); var childContext; if (isFunction(instance.getChildContext)) { childContext = instance.getChildContext(); } if (isNullOrUndef(childContext)) { instance.$CX = context; } else { instance.$CX = combineFrom(context, childContext); } if (isFunction(options.afterRender)) { options.afterRender(instance); } instance.$LI = input; return instance; } function handleComponentInput(input, componentVNode) { // Development validation { if (isArray(input)) { throwError('a valid Inferno VNode (or null) must be returned from a component render. You may have returned an array or an invalid object.'); } } if (isInvalid(input)) { input = createVoidVNode(); } else if (isStringOrNumber(input)) { input = createTextVNode(input, null); } else { if (input.dom) { input = directClone(input); } if (input.flags & 14 /* Component */) { // if we have an input that is also a component, we run into a tricky situation // where the root vNode needs to always have the correct DOM entry // we can optimise this in the future, but this gets us out of a lot of issues input.parentVNode = componentVNode; } } return input; } function mount(vNode, parentDom, lifecycle, context, isSVG) { var flags = vNode.flags; if (flags & 481 /* Element */) { return mountElement(vNode, parentDom, lifecycle, context, isSVG); } if (flags & 14 /* Component */) { return mountComponent(vNode, parentDom, lifecycle, context, isSVG, (flags & 4 /* ComponentClass */) > 0); } if (flags & 512 /* Void */ || flags & 16 /* Text */) { return mountText(vNode, parentDom); } if (flags & 1024 /* Portal */) { mount(vNode.children, vNode.type, lifecycle, context, false); return (vNode.dom = mountText(createVoidVNode(), parentDom)); } // Development validation, in production we don't need to throw because it crashes anyway { if (typeof vNode === 'object') { throwError(("mount() received an object that's not a valid VNode, you should stringify it first, fix createVNode flags or call normalizeChildren. Object: \"" + (JSON.stringify(vNode)) + "\".")); } else { throwError(("mount() expects a valid VNode, instead it received an object with the type \"" + (typeof vNode) + "\".")); } } } function mountText(vNode, parentDom) { var dom = (vNode.dom = document.createTextNode(vNode.children)); if (!isNull(parentDom)) { appendChild(parentDom, dom); } return dom; } function mountElement(vNode, parentDom, lifecycle, context, isSVG) { var flags = vNode.flags; var children = vNode.children; var props = vNode.props; var className = vNode.className; var ref = vNode.ref; var childFlags = vNode.childFlags; isSVG = isSVG || (flags & 32 /* SvgElement */) > 0; var dom = documentCreateElement(vNode.type, isSVG); vNode.dom = dom; if (!isNullOrUndef(className) && className !== '') { if (isSVG) { dom.setAttribute('class', className); } else { dom.className = className; } } { validateKeys(vNode); } if (!isNull(parentDom)) { appendChild(parentDom, dom); } if ((childFlags & 1 /* HasInvalidChildren */) === 0) { var childrenIsSVG = isSVG === true && vNode.type !== 'foreignObject'; if (childFlags === 2 /* HasVNodeChildren */) { mount(children, dom, lifecycle, context, childrenIsSVG); } else if (childFlags & 12 /* MultipleChildren */) { mountArrayChildren(children, dom, lifecycle, context, childrenIsSVG); } } if (!isNull(props)) { mountProps(vNode, flags, props, dom, isSVG); } { if (isString(ref)) { throwError('string "refs" are not supported in Inferno 1.0. Use callback "refs" instead.'); } } if (isFunction(ref)) { mountRef(dom, ref, lifecycle); } return dom; } function mountArrayChildren(children, dom, lifecycle, context, isSVG) { for (var i = 0, len = children.length; i < len; i++) { var child = children[i]; if (!isNull(child.dom)) { children[i] = child = directClone(child); } mount(child, dom, lifecycle, context, isSVG); } } function mountComponent(vNode, parentDom, lifecycle, context, isSVG, isClass) { var dom; var type = vNode.type; var props = vNode.props || EMPTY_OBJ; var ref = vNode.ref; if (isClass) { var instance = createClassComponentInstance(vNode, type, props, context); vNode.dom = dom = mount(instance.$LI, null, lifecycle, instance.$CX, isSVG); mountClassComponentCallbacks(vNode, ref, instance, lifecycle); instance.$UPD = false; } else { var input = handleComponentInput(type(props, context), vNode); vNode.children = input; vNode.dom = dom = mount(input, null, lifecycle, context, isSVG); mountFunctionalComponentCallbacks(props, ref, dom, lifecycle); } if (!isNull(parentDom)) { appendChild(parentDom, dom); } return dom; } function createClassMountCallback(instance, hasAfterMount, afterMount, vNode, hasDidMount) { return function () { instance.$UPD = true; if (hasAfterMount) { afterMount(vNode); } if (hasDidMount) { instance.componentDidMount(); } instance.$UPD = false; }; } function mountClassComponentCallbacks(vNode, ref, instance, lifecycle) { if (isFunction(ref)) { ref(instance); } else { { if (isStringOrNumber(ref)) { throwError('string "refs" are not supported in Inferno 1.0. Use callback "refs" instead.'); } else if (!isNullOrUndef(ref) && isObject(ref) && vNode.flags & 4 /* ComponentClass */) { throwError('functional component lifecycle events are not supported on ES2015 class components.'); } } } var hasDidMount = isFunction(instance.componentDidMount); var afterMount = options.afterMount; var hasAfterMount = isFunction(afterMount); if (hasDidMount || hasAfterMount) { lifecycle.push(createClassMountCallback(instance, hasAfterMount, afterMount, vNode, hasDidMount)); } } // Create did mount callback lazily to avoid creating function context if not needed function createOnMountCallback(ref, dom, props) { return function () { return ref.onComponentDidMount(dom, props); }; } function mountFunctionalComponentCallbacks(props, ref, dom, lifecycle) { if (!isNullOrUndef(ref)) { if (isFunction(ref.onComponentWillMount)) { ref.onComponentWillMount(props); } if (isFunction(ref.onComponentDidMount)) { lifecycle.push(createOnMountCallback(ref, dom, props)); } } } function mountRef(dom, value, lifecycle) { lifecycle.push(function () { return value(dom); }); } function hydrateComponent(vNode, dom, lifecycle, context, isSVG, isClass) { var type = vNode.type; var ref = vNode.ref; var props = vNode.props || EMPTY_OBJ; if (isClass) { var instance = createClassComponentInstance(vNode, type, props, context); var input = instance.$LI; hydrateVNode(input, dom, lifecycle, instance.$CX, isSVG); vNode.dom = input.dom; mountClassComponentCallbacks(vNode, ref, instance, lifecycle); instance.$UPD = false; // Mount finished allow going sync } else { var input$1 = handleComponentInput(type(props, context), vNode); hydrateVNode(input$1, dom, lifecycle, context, isSVG); vNode.children = input$1; vNode.dom = input$1.dom; mountFunctionalComponentCallbacks(props, ref, dom, lifecycle); } } function hydrateElement(vNode, dom, lifecycle, context, isSVG) { var children = vNode.children; var props = vNode.props; var className = vNode.className; var flags = vNode.flags; var ref = vNode.ref; isSVG = isSVG || (flags & 32 /* SvgElement */) > 0; if (dom.nodeType !== 1 || dom.tagName.toLowerCase() !== vNode.type) { { warning("Inferno hydration: Server-side markup doesn't match client-side markup or Initial render target is not empty"); } var newDom = mountElement(vNode, null, lifecycle, context, isSVG); vNode.dom = newDom; replaceChild(dom.parentNode, newDom, dom); } else { vNode.dom = dom; var childNode = dom.firstChild; var childFlags = vNode.childFlags; if ((childFlags & 1 /* HasInvalidChildren */) === 0) { var nextSibling = null; while (childNode) { nextSibling = childNode.nextSibling; if (childNode.nodeType === 8) { if (childNode.data === '!') { dom.replaceChild(document.createTextNode(''), childNode); } else { dom.removeChild(childNode); } } childNode = nextSibling; } childNode = dom.firstChild; if (childFlags === 2 /* HasVNodeChildren */) { if (isNull(childNode)) { mount(children, dom, lifecycle, context, isSVG); } else { nextSibling = childNode.nextSibling; hydrateVNode(children, childNode, lifecycle, context, isSVG); childNode = nextSibling; } } else if (childFlags & 12 /* MultipleChildren */) { for (var i = 0, len = children.length; i < len; i++) { var child = children[i]; if (isNull(childNode)) { mount(child, dom, lifecycle, context, isSVG); } else { nextSibling = childNode.nextSibling; hydrateVNode(child, childNode, lifecycle, context, isSVG); childNode = nextSibling; } } } // clear any other DOM nodes, there should be only a single entry for the root while (childNode) { nextSibling = childNode.nextSibling; dom.removeChild(childNode); childNode = nextSibling; } } else if (!isNull(dom.firstChild) && !isSamePropsInnerHTML(dom, props)) { dom.textContent = ''; // dom has content, but VNode has no children remove everything from DOM if (flags & 448 /* FormElement */) { // If element is form element, we need to clear defaultValue also dom.defaultValue = ''; } } if (!isNull(props)) { mountProps(vNode, flags, props, dom, isSVG); } if (isNullOrUndef(className)) { if (dom.className !== '') { dom.removeAttribute('class'); } } else if (isSVG) { dom.setAttribute('class', className); } else { dom.className = className; } if (isFunction(ref)) { mountRef(dom, ref, lifecycle); } else { { if (isString(ref)) { throwError('string "refs" are not supported in Inferno 1.0. Use callback "refs" instead.'); } } } } } function hydrateText(vNode, dom) { if (dom.nodeType !== 3) { var newDom = mountText(vNode, null); vNode.dom = newDom; replaceChild(dom.parentNode, newDom, dom); } else { var text = vNode.children; if (dom.nodeValue !== text) { dom.nodeValue = text; } vNode.dom = dom; } } function hydrateVNode(vNode, dom, lifecycle, context, isSVG) { var flags = vNode.flags; if (flags & 14 /* Component */) { hydrateComponent(vNode, dom, lifecycle, context, isSVG, (flags & 4 /* ComponentClass */) > 0); } else if (flags & 481 /* Element */) { hydrateElement(vNode, dom, lifecycle, context, isSVG); } else if (flags & 16 /* Text */) { hydrateText(vNode, dom); } else if (flags & 512 /* Void */) { vNode.dom = dom; } else { { throwError(("hydrate() expects a valid VNode, instead it received an object with the type \"" + (typeof vNode) + "\".")); } throwError(); } } function hydrate(input, parentDom, callback) { var dom = parentDom.firstChild; if (!isNull(dom)) { if (!isInvalid(input)) { hydrateVNode(input, dom, LIFECYCLE, EMPTY_OBJ, false); } dom = parentDom.firstChild; // clear any other DOM nodes, there should be only a single entry for the root while ((dom = dom.nextSibling)) { parentDom.removeChild(dom); } } if (LIFECYCLE.length > 0) { callAll(LIFECYCLE); } if (!parentDom.$V) { options.roots.push(parentDom); } parentDom.$V = input; if (isFunction(callback)) { callback(); } } function replaceWithNewNode(lastNode, nextNode, parentDom, lifecycle, context, isSVG) { unmount(lastNode); replaceChild(parentDom, mount(nextNode, null, lifecycle, context, isSVG), lastNode.dom); } function patch(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG) { if (lastVNode !== nextVNode) { var nextFlags = nextVNode.flags | 0; if (lastVNode.flags !== nextFlags || nextFlags & 2048 /* ReCreate */) { replaceWithNewNode(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG); } else if (nextFlags & 481 /* Element */) { patchElement(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG); } else if (nextFlags & 14 /* Component */) { patchComponent(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG, (nextFlags & 4 /* ComponentClass */) > 0); } else if (nextFlags & 16 /* Text */) { patchText(lastVNode, nextVNode, parentDom); } else if (nextFlags & 512 /* Void */) { nextVNode.dom = lastVNode.dom; } else { // Portal patchPortal(lastVNode, nextVNode, lifecycle, context); } } } function patchPortal(lastVNode, nextVNode, lifecycle, context) { var lastContainer = lastVNode.type; var nextContainer = nextVNode.type; var nextChildren = nextVNode.children; patchChildren(lastVNode.childFlags, nextVNode.childFlags, lastVNode.children, nextChildren, lastContainer, lifecycle, context, false); nextVNode.dom = lastVNode.dom; if (lastContainer !== nextContainer && !isInvalid(nextChildren)) { var node = nextChildren.dom; lastContainer.removeChild(node); nextContainer.appendChild(node); } } function patchElement(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG) { var nextTag = nextVNode.type; if (lastVNode.type !== nextTag) { replaceWithNewNode(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG); } else { var dom = lastVNode.dom; var nextFlags = nextVNode.flags; var lastProps = lastVNode.props; var nextProps = nextVNode.props; var isFormElement = false; var hasControlledValue = false; var nextPropsOrEmpty; nextVNode.dom = dom; isSVG = isSVG || (nextFlags & 32 /* SvgElement */) > 0; // inlined patchProps -- starts -- if (lastProps !== nextProps) { var lastPropsOrEmpty = lastProps || EMPTY_OBJ; nextPropsOrEmpty = nextProps || EMPTY_OBJ; if (nextPropsOrEmpty !== EMPTY_OBJ) { isFormElement = (nextFlags & 448 /* FormElement */) > 0; if (isFormElement) { hasControlledValue = isControlledFormElement(nextPropsOrEmpty); } for (var prop in nextPropsOrEmpty) { var lastValue = lastPropsOrEmpty[prop]; var nextValue = nextPropsOrEmpty[prop]; if (lastValue !== nextValue) { patchProp(prop, lastValue, nextValue, dom, isSVG, hasControlledValue, lastVNode); } } } if (lastPropsOrEmpty !== EMPTY_OBJ) { for (var prop$1 in lastPropsOrEmpty) { // do not add a hasOwnProperty check here, it affects performance if (!nextPropsOrEmpty.hasOwnProperty(prop$1) && !isNullOrUndef(lastPropsOrEmpty[prop$1])) { patchProp(prop$1, lastPropsOrEmpty[prop$1], null, dom, isSVG, hasControlledValue, lastVNode); } } } } var lastChildren = lastVNode.children; var nextChildren = nextVNode.children; var nextRef = nextVNode.ref; var lastClassName = lastVNode.className; var nextClassName = nextVNode.className; if (lastChildren !== nextChildren) { { validateKeys(nextVNode); } patchChildren(lastVNode.childFlags, nextVNode.childFlags, lastChildren, nextChildren, dom, lifecycle, context, isSVG && nextTag !== 'foreignObject'); } if (isFormElement) { processElement(nextFlags, nextVNode, dom, nextPropsOrEmpty, false, hasControlledValue); } // inlined patchProps -- ends -- if (lastClassName !== nextClassName) { if (isNullOrUndef(nextClassName)) { dom.removeAttribute('class'); } else if (isSVG) { dom.setAttribute('class', nextClassName); } else { dom.className = nextClassName; } } if (isFunction(nextRef) && lastVNode.ref !== nextRef) { mountRef(dom, nextRef, lifecycle); } else { { if (isString(nextRef)) { throwError('string "refs" are not supported in Inferno 1.0. Use callback "refs" instead.'); } } } } } function patchChildren(lastChildFlags, nextChildFlags, lastChildren, nextChildren, parentDOM, lifecycle, context, isSVG) { switch (lastChildFlags) { case 2 /* HasVNodeChildren */: switch (nextChildFlags) { case 2 /* HasVNodeChildren */: patch(lastChildren, nextChildren, parentDOM, lifecycle, context, isSVG); break; case 1 /* HasInvalidChildren */: remove(lastChildren, parentDOM); break; default: remove(lastChildren, parentDOM); mountArrayChildren(nextChildren, parentDOM, lifecycle, context, isSVG); break; } break; case 1 /* HasInvalidChildren */: switch (nextChildFlags) { case 2 /* HasVNodeChildren */: mount(nextChildren, parentDOM, lifecycle, context, isSVG); break; case 1 /* HasInvalidChildren */: break; default: mountArrayChildren(nextChildren, parentDOM, lifecycle, context, isSVG); break; } break; default: if (nextChildFlags & 12 /* MultipleChildren */) { var lastLength = lastChildren.length; var nextLength = nextChildren.length; // Fast path's for both algorithms if (lastLength === 0) { if (nextLength > 0) { mountArrayChildren(nextChildren, parentDOM, lifecycle, context, isSVG); } } else if (nextLength === 0) { removeAllChildren(parentDOM, lastChildren); } else if (nextChildFlags === 8 /* HasKeyedChildren */ && lastChildFlags === 8 /* HasKeyedChildren */) { patchKeyedChildren(lastChildren, nextChildren, parentDOM, lifecycle, context, isSVG, lastLength, nextLength); } else { patchNonKeyedChildren(lastChildren, nextChildren, parentDOM, lifecycle, context, isSVG, lastLength, nextLength); } } else if (nextChildFlags === 1 /* HasInvalidChildren */) { removeAllChildren(parentDOM, lastChildren); } else { removeAllChildren(parentDOM, lastChildren); mount(nextChildren, parentDOM, lifecycle, context, isSVG); } break; } } function updateClassComponent(instance, nextState, nextVNode, nextProps, parentDom, lifecycle, context, isSVG, force, fromSetState) { var lastState = instance.state; var lastProps = instance.props; nextVNode.children = instance; var lastInput = instance.$LI; var renderOutput; if (instance.$UN) { { throwError('Inferno Error: Can only update a mounted or mounting component. This usually means you called setState() or forceUpdate() on an unmounted component. This is a no-op.'); } return; } if (lastProps !== nextProps || nextProps === EMPTY_OBJ) { if (!fromSetState && isFunction(instance.componentWillReceiveProps)) { instance.$BR = true; instance.componentWillReceiveProps(nextProps, context); // If instance component was removed during its own update do nothing... if (instance.$UN) { return; } instance.$BR = false; } if (instance.$PSS) { nextState = combineFrom(nextState, instance.$PS); instance.$PSS = false; instance.$PS = null; } } /* Update if scu is not defined, or it returns truthy value or force */ var hasSCU = isFunction(instance.shouldComponentUpdate); if (force || !hasSCU || (hasSCU && instance.shouldComponentUpdate(nextProps, nextState, context))) { if (isFunction(instance.componentWillUpdate)) { instance.$BS = true; instance.componentWillUpdate(nextProps, nextState, context); instance.$BS = false; } instance.props = nextProps; instance.state = nextState; instance.context = context; if (isFunction(options.beforeRender)) { options.beforeRender(instance); } renderOutput = instance.render(nextProps, nextState, context); if (isFunction(options.afterRender)) { options.afterRender(instance); } var didUpdate = renderOutput !== NO_OP; var childContext; if (isFunction(instance.getChildContext)) { childContext = instance.getChildContext(); } if (isNullOrUndef(childContext)) { childContext = context; } else { childContext = combineFrom(context, childContext); } instance.$CX = childContext; if (didUpdate) { var nextInput = (instance.$LI = handleComponentInput(renderOutput, nextVNode)); patch(lastInput, nextInput, parentDom, lifecycle, childContext, isSVG); if (isFunction(instance.componentDidUpdate)) { instance.componentDidUpdate(lastProps, lastState); } if (isFunction(options.afterUpdate)) { options.afterUpdate(nextVNode); } } } else { instance.props = nextProps; instance.state = nextState; instance.context = context; } nextVNode.dom = instance.$LI.dom; } function patchComponent(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG, isClass) { var nextType = nextVNode.type; var lastKey = lastVNode.key; var nextKey = nextVNode.key; if (lastVNode.type !== nextType || lastKey !== nextKey) { replaceWithNewNode(lastVNode, nextVNode, parentDom, lifecycle, context, isSVG); } else { var nextProps = nextVNode.props || EMPTY_OBJ; if (isClass) { var instance = lastVNode.children; instance.$UPD = true; updateClassComponent(instance, instance.state, nextVNode, nextProps, parentDom, lifecycle, context, isSVG, false, false); instance.$V = nextVNode; instance.$UPD = false; } else { var shouldUpdate = true; var lastProps = lastVNode.props; var nextHooks = nextVNode.ref; var nextHooksDefined = !isNullOrUndef(nextHooks); var lastInput = lastVNode.children; nextVNode.dom = lastVNode.dom; nextVNode.children = lastInput; if (nextHooksDefined && isFunction(nextHooks.onComponentShouldUpdate)) { shouldUpdate = nextHooks.onComponentShouldUpdate(lastProps, nextProps); } if (shouldUpdate !== false) { if (nextHooksDefined && isFunction(nextHooks.onComponentWillUpdate)) { nextHooks.onComponentWillUpdate(lastProps, nextProps); } var nextInput = nextType(nextProps, context); if (nextInput !== NO_OP) { nextInput = handleComponentInput(nextInput, nextVNode); patch(lastInput, nextInput, parentDom, lifecycle, context, isSVG); nextVNode.children = nextInput; nextVNode.dom = nextInput.dom; if (nextHooksDefined && isFunction(nextHooks.onComponentDidUpdate)) { nextHooks.onComponentDidUpdate(lastProps, nextProps); } } } else if (lastInput.flags & 14 /* Component */) { lastInput.parentVNode = nextVNode; } } } } function patchText(lastVNode, nextVNode, parentDom) { var nextText = nextVNode.children; var textNode = parentDom.firstChild; var dom; // Guard against external change on DOM node. if (isNull(textNode)) { parentDom.textContent = nextText; dom = parentDom.firstChild; } else { dom = lastVNode.dom; if (nextText !== lastVNode.children) { dom.nodeValue = nextText; } } nextVNode.dom = dom; } function patchNonKeyedChildren(lastChildren, nextChildren, dom, lifecycle, context, isSVG, lastChildrenLength, nextChildrenLength) { var commonLength = lastChildrenLength > nextChildrenLength ? nextChildrenLength : lastChildrenLength; var i = 0; for (; i < commonLength; i++) { var nextChild = nextChildren[i]; if (nextChild.dom) { nextChild = nextChildren[i] = directClone(nextChild); } patch(lastChildren[i], nextChild, dom, lifecycle, context, isSVG); } if (lastChildrenLength < nextChildrenLength) { for (i = commonLength; i < nextChildrenLength; i++) { var nextChild$1 = nextChildren[i]; if (nextChild$1.dom) { nextChild$1 = nextChildren[i] = directClone(nextChild$1); } mount(nextChild$1, dom, lifecycle, context, isSVG); } } else if (lastChildrenLength > nextChildrenLength) { for (i = commonLength; i < lastChildrenLength; i++) { remove(lastChildren[i], dom); } } } function patchKeyedChildren(a, b, dom, lifecycle, context, isSVG, aLength, bLength) { var aEnd = aLength - 1; var bEnd = bLength - 1; var aStart = 0; var bStart = 0; var i; var j; var aNode; var bNode; var nextNode; var nextPos; var node; var aStartNode = a[aStart]; var bStartNode = b[bStart]; var aEndNode = a[aEnd]; var bEndNode = b[bEnd]; if (bStartNode.dom) { b[bStart] = bStartNode = directClone(bStartNode); } if (bEndNode.dom) { b[bEnd] = bEndNode = directClone(bEndNode); } // Step 1 // tslint:disable-next-line outer: { // Sync nodes with the same key at the beginning. while (aStartNode.key === bStartNode.key) { patch(aStartNode, bStartNode, dom, lifecycle, context, isSVG); aStart++; bStart++; if (aStart > aEnd || bStart > bEnd) { break outer; } aStartNode = a[aStart]; bStartNode = b[bStart]; if (bStartNode.dom) { b[bStart] = bStartNode = directClone(bStartNode); } } // Sync nodes with the same key at the end. while (aEndNode.key === bEndNode.key) { patch(aEndNode, bEndNode, dom, lifecycle, context, isSVG); aEnd--; bEnd--; if (aStart > aEnd || bStart > bEnd) { break outer; } aEndNode = a[aEnd]; bEndNode = b[bEnd]; if (bEndNode.dom) { b[bEnd] = bEndNode = directClone(bEndNode); } } } if (aStart > aEnd) { if (bStart <= bEnd) { nextPos = bEnd + 1; nextNode = nextPos < bLength ? b[nextPos].dom : null; while (bStart <= bEnd) { node = b[bStart]; if (node.dom) { b[bStart] = node = directClone(node); } bStart++; insertOrAppend(dom, mount(node, null, lifecycle, context, isSVG), nextNode); } } } else if (bStart > bEnd) { while (aStart <= aEnd) { remove(a[aStart++], dom); } } else { var aLeft = aEnd - aStart + 1; var bLeft = bEnd - bStart + 1; var sources = new Array(bLeft); for (i = 0; i < bLeft; i++) { sources[i] = -1; } var moved = false; var pos = 0; var patched = 0; // When sizes are small, just loop them through if (bLeft <= 4 || aLeft * bLeft <= 16) { for (i = aStart; i <= aEnd; i++) { aNode = a[i]; if (patched < bLeft) { for (j = bStart; j <= bEnd; j++) { bNode = b[j]; if (aNode.key === bNode.key) { sources[j - bStart] = i; if (pos > j) { moved = true; } else { pos = j; } if (bNode.dom) { b[j] = bNode = directClone(bNode); } patch(aNode, bNode, dom, lifecycle, context, isSVG); patched++; a[i] = null; break; } } } } } else { var keyIndex = {}; // Map keys by their index in array for (i = bStart; i <= bEnd; i++) { keyIndex[b[i].key] = i; } // Try to patch same keys for (i = aStart; i <= aEnd; i++) { aNode = a[i]; if (patched < bLeft) { j = keyIndex[aNode.key]; if (isDefined(j)) { bNode = b[j]; sources[j - bStart] = i; if (pos > j) { moved = true; } else { pos = j; } if (bNode.dom) { b[j] = bNode = directClone(bNode); } patch(aNode, bNode, dom, lifecycle, context, isSVG); patched++; a[i] = null; } } } } // fast-path: if nothing patched remove all old and add all new if (aLeft === aLength && patched === 0) { removeAllChildren(dom, a); mountArrayChildren(b, dom, lifecycle, context, isSVG); } else { i = aLeft - patched; while (i > 0) { aNode = a[aStart++]; if (!isNull(aNode)) { remove(aNode, dom); i--; } } if (moved) { var seq = lis_algorithm(sources); j = seq.length - 1; for (i = bLeft - 1; i >= 0; i--) { if (sources[i] === -1) { pos = i + bStart; node = b[pos]; if (node.dom) { b[pos] = node = directClone(node); } nextPos = pos + 1; insertOrAppend(dom, mount(node, null, lifecycle, context, isSVG), nextPos < bLength ? b[nextPos].dom : null); } else if (j < 0 || i !== seq[j]) { pos = i + bStart; node = b[pos]; nextPos = pos + 1; insertOrAppend(dom, node.dom, nextPos < bLength ? b[nextPos].dom : null); } else { j--; } } } else if (patched !== bLeft) { // when patched count doesn't match b length we need to insert those new ones // loop backwards so we can use insertBefore for (i = bLeft - 1; i >= 0; i--) { if (sources[i] === -1) { pos = i + bStart; node = b[pos]; if (node.dom) { b[pos] = node = directClone(node); } nextPos = pos + 1; insertOrAppend(dom, mount(node, null, lifecycle, context, isSVG), nextPos < bLength ? b[nextPos].dom : null); } } } } } } // // https://en.wikipedia.org/wiki/Longest_increasing_subsequence function lis_algorithm(arr) { var p = arr.slice(); var result = [0]; var i; var j; var u; var v; var c; var len = arr.length; for (i = 0; i < len; i++) { var arrI = arr[i]; if (arrI !== -1) { j = result[result.length - 1]; if (arr[j] < arrI) { p[i] = j; result.push(i); continue; } u = 0; v = result.length - 1; while (u < v) { c = ((u + v) / 2) | 0; if (arr[result[c]] < arrI) { u = c + 1; } else { v = c; } } if (arrI < arr[result[u]]) { if (u > 0) { p[i] = result[u - 1]; } result[u] = i; } } } u = result.length; v = result[u - 1]; while (u-- > 0) { result[u] = v; v = p[v]; } return result; } var roots = options.roots; { if (isBrowser && document.body === null) { warning('Inferno warning: you cannot initialize inferno without "document.body". Wait on "DOMContentLoaded" event, add script to bottom of body, or use async/defer attributes on script tag.'); } } var documentBody = isBrowser ? document.body : null; function render(input, parentDom, callback) { // Development warning { if (documentBody === parentDom) { throwError('you cannot render() to the "document.body". Use an empty element as a container instead.'); } } if (input === NO_OP) { return; } var rootLen = roots.length; var rootInput; var index; for (index = 0; index < rootLen; index++) { if (roots[index] === parentDom) { rootInput = parentDom.$V; break; } } if (isUndefined(rootInput)) { if (!isInvalid(input)) { if (input.dom) { input = directClone(input); } if (isNull(parentDom.firstChild)) { mount(input, parentDom, LIFECYCLE, EMPTY_OBJ, false); parentDom.$V = input; roots.push(parentDom); } else { hydrate(input, parentDom); } rootInput = input; } } else { if (isNullOrUndef(input)) { remove(rootInput, parentDom); roots.splice(index, 1); } else { if (input.dom) { input = directClone(input); } patch(rootInput, input, parentDom, LIFECYCLE, EMPTY_OBJ, false); rootInput = parentDom.$V = input; } } if (LIFECYCLE.length > 0) { callAll(LIFECYCLE); } if (isFunction(callback)) { callback(); } if (rootInput && rootInput.flags & 14 /* Component */) { return rootInput.children; } } function createRenderer(parentDom) { return function renderer(lastInput, nextInput) { if (!parentDom) { parentDom = lastInput; } render(nextInput, parentDom); }; } function createPortal(children, container) { return createVNode(1024 /* Portal */, container, null, children, 0 /* UnknownChildren */, null, isInvalid(children) ? null : children.key, null); } var resolvedPromise = typeof Promise === 'undefined' ? null : Promise.resolve(); var fallbackMethod = typeof requestAnimationFrame === 'undefined' ? setTimeout : requestAnimationFrame; function nextTick(fn) { if (resolvedPromise) { return resolvedPromise.then(fn); } return fallbackMethod(fn); } function queueStateChanges(component, newState, callback) { if (isFunction(newState)) { newState = newState(component.state, component.props, component.context); } var pending = component.$PS; if (isNullOrUndef(pending)) { component.$PS = newState; } else { for (var stateKey in newState) { pending[stateKey] = newState[stateKey]; } } if (!component.$PSS && !component.$BR) { if (!component.$UPD) { component.$PSS = true; component.$UPD = true; applyState(component, false, callback); component.$UPD = false; } else { // Async var queue = component.$QU; if (isNull(queue)) { queue = component.$QU = []; nextTick(promiseCallback(component, queue)); } if (isFunction(callback)) { queue.push(callback); } } } else { component.$PSS = true; if (component.$BR && isFunction(callback)) { LIFECYCLE.push(callback.bind(component)); } } } function promiseCallback(component, queue) { return function () { component.$QU = null; component.$UPD = true; applyState(component, false, function () { for (var i = 0, len = queue.length; i < len; i++) { queue[i].call(component); } }); component.$UPD = false; }; } function applyState(component, force, callback) { if (component.$UN) { return; } if (force || !component.$BR) { component.$PSS = false; var pendingState = component.$PS; var prevState = component.state; var nextState = combineFrom(prevState, pendingState); var props = component.props; var context = component.context; component.$PS = null; var vNode = component.$V; var lastInput = component.$LI; var parentDom = lastInput.dom && lastInput.dom.parentNode; updateClassComponent(component, nextState, vNode, props, parentDom, LIFECYCLE, context, (vNode.flags & 32 /* SvgElement */) > 0, force, true); if (component.$UN) { return; } if ((component.$LI.flags & 1024 /* Portal */) === 0) { var dom = component.$LI.dom; while (!isNull((vNode = vNode.parentVNode))) { if ((vNode.flags & 14 /* Component */) > 0) { vNode.dom = dom; } } } if (LIFECYCLE.length > 0) { callAll(LIFECYCLE); } } else { component.state = component.$PS; component.$PS = null; } if (isFunction(callback)) { callback.call(component); } } var Component = function Component(props, context) { this.state = null; // Internal properties this.$BR = false; // BLOCK RENDER this.$BS = true; // BLOCK STATE this.$PSS = false; // PENDING SET STATE this.$PS = null; // PENDING STATE (PARTIAL or FULL) this.$LI = null; // LAST INPUT this.$V = null; // VNODE this.$UN = false; // UNMOUNTED this.$CX = null; // CHILDCONTEXT this.$UPD = true; // UPDATING this.$QU = null; // QUEUE /** @type {object} */ this.props = props || EMPTY_OBJ; /** @type {object} */ this.context = context || EMPTY_OBJ; // context should not be mutable }; Component.prototype.forceUpdate = function forceUpdate (callback) { if (this.$UN) { return; } applyState(this, true, callback); }; Component.prototype.setState = function setState (newState, callback) { if (this.$UN) { return; } if (!this.$BS) { queueStateChanges(this, newState, callback); } else { // Development warning { throwError('cannot update state via setState() in componentWillUpdate() or constructor.'); } return; } }; // tslint:disable-next-line:no-empty Component.prototype.render = function render (nextProps, nextState, nextContext) { }; // Public Component.defaultProps = null; { /* tslint:disable-next-line:no-empty */ var testFunc = function testFn() { }; if ((testFunc.name || testFunc.toString()).indexOf('testFn') === -1) { warning("It looks like you're using a minified copy of the development build " + 'of Inferno. When deploying Inferno apps to production, make sure to use ' + 'the production build which skips development warnings and is faster. ' + 'See http://infernojs.org for more details.'); } } var version = "4.0.8"; exports.Component = Component; exports.EMPTY_OBJ = EMPTY_OBJ; exports.NO_OP = NO_OP; exports.createComponentVNode = createComponentVNode; exports.createPortal = createPortal; exports.createRenderer = createRenderer; exports.createTextVNode = createTextVNode; exports.createVNode = createVNode; exports.directClone = directClone; exports.getFlagsForElementVnode = getFlagsForElementVnode; exports.getNumberStyleValue = getNumberStyleValue; exports.hydrate = hydrate; exports.linkEvent = linkEvent; exports.normalizeProps = normalizeProps; exports.options = options; exports.render = render; exports.version = version; Object.defineProperty(exports, '__esModule', { value: true }); })));
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license @product.name@ JS [email protected]@ (@product.date@) * * (c) 2009-2014 Torstein Honsi * * License: www.highcharts.com/license */ (function (root, factory) { if (typeof module === 'object' && module.exports) { module.exports = root.document ? factory(root) : function (w) { return factory(w); }; } else { root.Highcharts = factory(); } }(typeof window !== 'undefined' ? window : this, function (w) {
const debug = require('ghost-ignition').debug('api:v2:utils:serializers:output:actions'); const mapper = require('./utils/mapper'); module.exports = { browse(models, apiConfig, frame) { debug('browse'); frame.response = { actions: models.data.map(model => mapper.mapAction(model, frame)), meta: models.meta }; } };
var fnObj = {}; var ACTIONS = axboot.actionExtend(fnObj, { PAGE_SEARCH: function (caller, act, data) { axboot.ajax({ type: "GET", url: ["samples", "parent"], data: caller.searchView.getData(), callback: function (res) { caller.gridView01.setData(res); }, options: { // axboot.ajax 함수에 2번째 인자는 필수가 아닙니다. ajax의 옵션을 전달하고자 할때 사용합니다. onError: function (err) { console.log(err); } } }); return false; }, PAGE_SAVE: function (caller, act, data) { var saveList = [].concat(caller.gridView01.getData("modified")); saveList = saveList.concat(caller.gridView01.getData("deleted")); axboot.ajax({ type: "PUT", url: ["samples", "parent"], data: JSON.stringify(saveList), callback: function (res) { ACTIONS.dispatch(ACTIONS.PAGE_SEARCH); axToast.push("저장 되었습니다"); } }); }, ITEM_CLICK: function (caller, act, data) { }, ITEM_ADD: function (caller, act, data) { caller.gridView01.addRow(); }, ITEM_DEL: function (caller, act, data) { caller.gridView01.delRow("selected"); } }); // fnObj 기본 함수 스타트와 리사이즈 fnObj.pageStart = function () { this.pageButtonView.initView(); this.searchView.initView(); this.gridView01.initView(); ACTIONS.dispatch(ACTIONS.PAGE_SEARCH); }; fnObj.pageResize = function () { }; fnObj.pageButtonView = axboot.viewExtend({ initView: function () { axboot.buttonClick(this, "data-page-btn", { "search": function () { ACTIONS.dispatch(ACTIONS.PAGE_SEARCH); }, "save": function () { ACTIONS.dispatch(ACTIONS.PAGE_SAVE); }, "excel": function () { } }); } }); //== view 시작 /** * searchView */ fnObj.searchView = axboot.viewExtend(axboot.searchView, { initView: function () { this.target = $(document["searchView0"]); this.target.attr("onsubmit", "return ACTIONS.dispatch(ACTIONS.PAGE_SEARCH);"); this.filter = $("#filter"); }, getData: function () { return { pageNumber: this.pageNumber, pageSize: this.pageSize, filter: this.filter.val() } } }); /** * gridView */ fnObj.gridView01 = axboot.viewExtend(axboot.gridView, { initView: function () { var _this = this; this.target = axboot.gridBuilder({ showRowSelector: true, frozenColumnIndex: 0, multipleSelect: true, target: $('[data-ax5grid="grid-view-01"]'), columns: [ {key: "key", label: "KEY", width: 160, align: "left", editor: "text"}, {key: "value", label: "VALUE", width: 350, align: "left", editor: "text"}, {key: "etc1", label: "ETC1", width: 100, align: "center", editor: "text"}, {key: "etc2", label: "ETC2", width: 100, align: "center", editor: "text"}, {key: "etc3", label: "ETC3", width: 100, align: "center", editor: "text"}, {key: "etc4", label: "ETC4", width: 100, align: "center", editor: "text"} ], body: { onClick: function () { this.self.select(this.dindex, {selectedClear: true}); } } }); axboot.buttonClick(this, "data-grid-view-01-btn", { "add": function () { ACTIONS.dispatch(ACTIONS.ITEM_ADD); }, "delete": function () { ACTIONS.dispatch(ACTIONS.ITEM_DEL); } }); }, getData: function (_type) { var list = []; var _list = this.target.getList(_type); if (_type == "modified" || _type == "deleted") { list = ax5.util.filter(_list, function () { delete this.deleted; return this.key; }); } else { list = _list; } return list; }, addRow: function () { this.target.addRow({__created__: true}, "last"); } });
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require_tree .
import React, {Component, PropTypes} from 'react' import style from './style.js' import ErrorStackParser from 'error-stack-parser' import assign from 'object-assign' import {isFilenameAbsolute, makeUrl, makeLinkText} from './lib' export default class RedBox extends Component { static propTypes = { error: PropTypes.instanceOf(Error).isRequired, filename: PropTypes.string, editorScheme: PropTypes.string, useLines: PropTypes.bool, useColumns: PropTypes.bool } static displayName = 'RedBox' static defaultProps = { useLines: true, useColumns: true } render () { const {error, filename, editorScheme, useLines, useColumns} = this.props const {redbox, message, stack, frame, file, linkToFile} = assign({}, style, this.props.style) const frames = ErrorStackParser.parse(error).map((f, index) => { let text let url if (index === 0 && filename && !isFilenameAbsolute(f.fileName)) { url = makeUrl(filename, editorScheme) text = makeLinkText(filename) } else { let lines = useLines ? f.lineNumber : null let columns = useColumns ? f.columnNumber : null url = makeUrl(f.fileName, editorScheme, lines, columns) text = makeLinkText(f.fileName, lines, columns) } return ( <div style={frame} key={index}> <div>{f.functionName}</div> <div style={file}> <a href={url} style={linkToFile}>{text}</a> </div> </div> ) }) return ( <div style={redbox}> <div style={message}>{error.name}: {error.message}</div> <div style={stack}>{frames}</div> </div> ) } }
/** * Themes: Velonic Admin theme * **/ ! function($) { "use strict"; /** Sidebar Module */ var SideBar = function() { this.$body = $("body"), this.$sideBar = $('aside.left-panel'), this.$navbarToggle = $(".navbar-toggle"), this.$navbarItem = $("aside.left-panel nav.navigation > ul > li:has(ul) > a") }; //initilizing SideBar.prototype.init = function() { //on toggle side menu bar var $this = this; $(document).on('click', '.navbar-toggle', function () { $this.$sideBar.toggleClass('collapsed'); }); //on menu item clicking this.$navbarItem.click(function () { if ($this.$sideBar.hasClass('collapsed') == false || $(window).width() < 768) { $("aside.left-panel nav.navigation > ul > li > ul").slideUp(300); $("aside.left-panel nav.navigation > ul > li").removeClass('active'); if (!$(this).next().is(":visible")) { $(this).next().slideToggle(300, function () { $("aside.left-panel:not(.collapsed)").getNiceScroll().resize(); }); $(this).closest('li').addClass('active'); } return false; } }); //adding nicescroll to sidebar if ($.isFunction($.fn.niceScroll)) { $("aside.left-panel:not(.collapsed)").niceScroll({ cursorcolor: '#8e909a', cursorborder: '0px solid #fff', cursoropacitymax: '0.5', cursorborderradius: '0px' }); } }, //exposing the sidebar module $.SideBar = new SideBar, $.SideBar.Constructor = SideBar }(window.jQuery), //portlets function($) { "use strict"; /** Portlet Widget */ var Portlet = function() { this.$body = $("body"), this.$portletIdentifier = ".portlet", this.$portletCloser = '.portlet a[data-toggle="remove"]', this.$portletRefresher = '.portlet a[data-toggle="reload"]' }; //on init Portlet.prototype.init = function() { // Panel closest var $this = this; $(document).on("click",this.$portletCloser, function (ev) { ev.preventDefault(); var $portlet = $(this).closest($this.$portletIdentifier); var $portlet_parent = $portlet.parent(); $portlet.remove(); if ($portlet_parent.children().length == 0) { $portlet_parent.remove(); } }); // Panel Reload $(document).on("click",this.$portletRefresher, function (ev) { ev.preventDefault(); var $portlet = $(this).closest($this.$portletIdentifier); // This is just a simulation, nothing is going to be reloaded $portlet.append('<div class="panel-disabled"><div class="loader-1"></div></div>'); var $pd = $portlet.find('.panel-disabled'); setTimeout(function () { $pd.fadeOut('fast', function () { $pd.remove(); }); }, 500 + 300 * (Math.random() * 5)); }); }, // $.Portlet = new Portlet, $.Portlet.Constructor = Portlet }(window.jQuery), //main app module function($) { "use strict"; var VelonicApp = function() { this.VERSION = "1.0.0", this.AUTHOR = "Coderthemes", this.SUPPORT = "[email protected]", this.pageScrollElement = "html, body", this.$body = $("body") }; //initializing tooltip VelonicApp.prototype.initTooltipPlugin = function() { $.fn.tooltip && $('[data-toggle="tooltip"]').tooltip() }, //initializing popover VelonicApp.prototype.initPopoverPlugin = function() { $.fn.popover && $('[data-toggle="popover"]').popover() }, //initializing nicescroll VelonicApp.prototype.initNiceScrollPlugin = function() { //You can change the color of scroll bar here $.fn.niceScroll && $(".nicescroll").niceScroll({ cursorcolor: '#9d9ea5', cursorborderradius: '0px'}); }, //initializing knob VelonicApp.prototype.initKnob = function() { if ($(".knob").length > 0) { $(".knob").knob(); } }, //initilizing VelonicApp.prototype.init = function() { this.initTooltipPlugin(), this.initPopoverPlugin(), this.initNiceScrollPlugin(), this.initKnob(), //creating side bar $.SideBar.init(), //creating portles $.Portlet.init(); }, $.VelonicApp = new VelonicApp, $.VelonicApp.Constructor = VelonicApp }(window.jQuery), //initializing main application module function($) { "use strict"; $.VelonicApp.init() }(window.jQuery); /* ============================================== 7.WOW plugin triggers animate.css on scroll =============================================== */ var wow = new WOW( { boxClass: 'wow', // animated element css class (default is wow) animateClass: 'animated', // animation css class (default is animated) offset: 50, // distance to the element when triggering the animation (default is 0) mobile: false // trigger animations on mobile devices (true is default) } ); wow.init();
"use strict"; var Client = require("./../lib/index"); var testAuth = require("./../testAuth.json"); var github = new Client({ debug: true }); github.authenticate({ type: "oauth", token: testAuth["token"] }); github.repos.createFile({ owner: "kaizensoze", repo: "misc-scripts", path: "blah.txt", message: "blah blah", content: "YmxlZXAgYmxvb3A=" }, function(err, res) { console.log(err, res); });
define("ace/snippets/sass",["require","exports","module"], function(require, exports, module) { "use strict"; exports.snippetText = ""; exports.scope = "sass"; }); (function() { window.require(["ace/snippets/sass"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
/* * Keeps track of items being created or deleted in a list * - emits events about changes when .poll is called * - events are: delete, create * * Usage: * * var tracker = changeTracker.create(updateItems, items); * * - updateItems is a function to fetch the current state of the items you want * to watch. It should return a list of objects with a unique 'name'. * * - items is the current list, as given by running updateItems now * * tracker.on("create", createListener); * tracker.on("delete", deleteListener); * tracker.poll(); * * When calling poll, updateItems is called, the result is compared to the old * list, and events are emitted. * */ var EventEmitter = require("events").EventEmitter; var when = require("when"); function create(updateItems, items) { var instance = Object.create(this); instance.updateItems = updateItems; instance.items = items; return instance; } function eq(item1) { return function (item2) { return item1.name === item2.name; }; } function notIn(coll) { return function (item) { return !coll.some(eq(item)); }; } function poll() { var d = when.defer(); this.updateItems(function (err, after) { if (err) { return d.reject(err); } var before = this.items; var created = after.filter(notIn(before)); var deleted = before.filter(notIn(after)); created.forEach(this.emit.bind(this, "create")); deleted.forEach(this.emit.bind(this, "delete")); this.items = after; d.resolve(); }.bind(this)); return d.promise; } module.exports = new EventEmitter(); module.exports.create = create; module.exports.poll = poll;
export default { plurals: [[/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status|bonus)$/i, '$1es'], [/(bu)s$/i, '$1ses'], [/(buffal|tomat)o$/i, '$1oes'], [/([ti])um$/i, '$1a'], [/([ti])a$/i, '$1a'], [/sis$/i, 'ses'], [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], [/(hive)$/i, '$1s'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/(x|ch|ss|sh)$/i, '$1es'], [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'], [/^(m|l)ouse$/i, '$1ice'], [/^(m|l)ice$/i, '$1ice'], [/^(ox)$/i, '$1en'], [/^(oxen)$/i, '$1'], [/(quiz)$/i, '$1zes']], singular: [[/s$/i, ''], [/(ss)$/i, '$1'], [/(n)ews$/i, '$1ews'], [/([ti])a$/i, '$1um'], [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'], [/(^analy)(sis|ses)$/i, '$1sis'], [/([^f])ves$/i, '$1fe'], [/(hive)s$/i, '$1'], [/(tive)s$/i, '$1'], [/([lr])ves$/i, '$1f'], [/([^aeiouy]|qu)ies$/i, '$1y'], [/(s)eries$/i, '$1eries'], [/(m)ovies$/i, '$1ovie'], [/(x|ch|ss|sh)es$/i, '$1'], [/^(m|l)ice$/i, '$1ouse'], [/(bus)(es)?$/i, '$1'], [/(o)es$/i, '$1'], [/(shoe)s$/i, '$1'], [/(cris|test)(is|es)$/i, '$1is'], [/^(a)x[ie]s$/i, '$1xis'], [/(octop|vir)(us|i)$/i, '$1us'], [/(alias|status|bonus)(es)?$/i, '$1'], [/^(ox)en/i, '$1'], [/(vert|ind)ices$/i, '$1ex'], [/(matr)ices$/i, '$1ix'], [/(quiz)zes$/i, '$1'], [/(database)s$/i, '$1']], irregularPairs: [['person', 'people'], ['man', 'men'], ['child', 'children'], ['sex', 'sexes'], ['move', 'moves'], ['cow', 'kine'], ['zombie', 'zombies']], uncountable: ['equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police'] };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function () {}; exports.default = foo; exports.default = 42; exports.default = {}; exports.default = []; exports.default = foo; exports.default = class {}; function foo() {} class Foo {} exports.default = Foo; exports.default = foo; exports.default = (function () { return "foo"; })();
// Copyright 2009 the V8 project authors. 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** * Constructs a mapper that maps addresses into code entries. * * @constructor */ function CodeMap() { /** * Dynamic code entries. Used for JIT compiled code. */ this.dynamics_ = new SplayTree(); /** * Name generator for entries having duplicate names. */ this.dynamicsNameGen_ = new CodeMap.NameGenerator(); /** * Static code entries. Used for statically compiled code. */ this.statics_ = new SplayTree(); /** * Libraries entries. Used for the whole static code libraries. */ this.libraries_ = new SplayTree(); /** * Map of memory pages occupied with static code. */ this.pages_ = []; }; /** * The number of alignment bits in a page address. */ CodeMap.PAGE_ALIGNMENT = 12; /** * Page size in bytes. */ CodeMap.PAGE_SIZE = 1 << CodeMap.PAGE_ALIGNMENT; /** * Adds a dynamic (i.e. moveable and discardable) code entry. * * @param {number} start The starting address. * @param {CodeMap.CodeEntry} codeEntry Code entry object. */ CodeMap.prototype.addCode = function(start, codeEntry) { this.deleteAllCoveredNodes_(this.dynamics_, start, start + codeEntry.size); this.dynamics_.insert(start, codeEntry); }; /** * Moves a dynamic code entry. Throws an exception if there is no dynamic * code entry with the specified starting address. * * @param {number} from The starting address of the entry being moved. * @param {number} to The destination address. */ CodeMap.prototype.moveCode = function(from, to) { var removedNode = this.dynamics_.remove(from); this.deleteAllCoveredNodes_(this.dynamics_, to, to + removedNode.value.size); this.dynamics_.insert(to, removedNode.value); }; /** * Discards a dynamic code entry. Throws an exception if there is no dynamic * code entry with the specified starting address. * * @param {number} start The starting address of the entry being deleted. */ CodeMap.prototype.deleteCode = function(start) { var removedNode = this.dynamics_.remove(start); }; /** * Adds a library entry. * * @param {number} start The starting address. * @param {CodeMap.CodeEntry} codeEntry Code entry object. */ CodeMap.prototype.addLibrary = function( start, codeEntry) { this.markPages_(start, start + codeEntry.size); this.libraries_.insert(start, codeEntry); }; /** * Adds a static code entry. * * @param {number} start The starting address. * @param {CodeMap.CodeEntry} codeEntry Code entry object. */ CodeMap.prototype.addStaticCode = function( start, codeEntry) { this.statics_.insert(start, codeEntry); }; /** * @private */ CodeMap.prototype.markPages_ = function(start, end) { for (var addr = start; addr <= end; addr += CodeMap.PAGE_SIZE) { this.pages_[addr >>> CodeMap.PAGE_ALIGNMENT] = 1; } }; /** * @private */ CodeMap.prototype.deleteAllCoveredNodes_ = function(tree, start, end) { var to_delete = []; var addr = end - 1; while (addr >= start) { var node = tree.findGreatestLessThan(addr); if (!node) break; var start2 = node.key, end2 = start2 + node.value.size; if (start2 < end && start < end2) to_delete.push(start2); addr = start2 - 1; } for (var i = 0, l = to_delete.length; i < l; ++i) tree.remove(to_delete[i]); }; /** * @private */ CodeMap.prototype.isAddressBelongsTo_ = function(addr, node) { return addr >= node.key && addr < (node.key + node.value.size); }; /** * @private */ CodeMap.prototype.findInTree_ = function(tree, addr) { var node = tree.findGreatestLessThan(addr); return node && this.isAddressBelongsTo_(addr, node) ? node : null; }; /** * Finds a code entry that contains the specified address. Both static and * dynamic code entries are considered. Returns the code entry and the offset * within the entry. * * @param {number} addr Address. */ CodeMap.prototype.findAddress = function(addr) { var pageAddr = addr >>> CodeMap.PAGE_ALIGNMENT; if (pageAddr in this.pages_) { // Static code entries can contain "holes" of unnamed code. // In this case, the whole library is assigned to this address. var result = this.findInTree_(this.statics_, addr); if (!result) { result = this.findInTree_(this.libraries_, addr); if (!result) return null; } return { entry : result.value, offset : addr - result.key }; } var min = this.dynamics_.findMin(); var max = this.dynamics_.findMax(); if (max != null && addr < (max.key + max.value.size) && addr >= min.key) { var dynaEntry = this.findInTree_(this.dynamics_, addr); if (dynaEntry == null) return null; // Dedupe entry name. var entry = dynaEntry.value; if (!entry.nameUpdated_) { entry.name = this.dynamicsNameGen_.getName(entry.name); entry.nameUpdated_ = true; } return { entry : entry, offset : addr - dynaEntry.key }; } return null; }; /** * Finds a code entry that contains the specified address. Both static and * dynamic code entries are considered. * * @param {number} addr Address. */ CodeMap.prototype.findEntry = function(addr) { var result = this.findAddress(addr); return result ? result.entry : null; }; /** * Returns a dynamic code entry using its starting address. * * @param {number} addr Address. */ CodeMap.prototype.findDynamicEntryByStartAddress = function(addr) { var node = this.dynamics_.find(addr); return node ? node.value : null; }; /** * Returns an array of all dynamic code entries. */ CodeMap.prototype.getAllDynamicEntries = function() { return this.dynamics_.exportValues(); }; /** * Returns an array of pairs of all dynamic code entries and their addresses. */ CodeMap.prototype.getAllDynamicEntriesWithAddresses = function() { return this.dynamics_.exportKeysAndValues(); }; /** * Returns an array of all static code entries. */ CodeMap.prototype.getAllStaticEntries = function() { return this.statics_.exportValues(); }; /** * Returns an array of pairs of all static code entries and their addresses. */ CodeMap.prototype.getAllStaticEntriesWithAddresses = function() { return this.statics_.exportKeysAndValues(); }; /** * Returns an array of all libraries entries. */ CodeMap.prototype.getAllLibrariesEntries = function() { return this.libraries_.exportValues(); }; /** * Creates a code entry object. * * @param {number} size Code entry size in bytes. * @param {string} opt_name Code entry name. * @param {string} opt_type Code entry type, e.g. SHARED_LIB, CPP. * @constructor */ CodeMap.CodeEntry = function(size, opt_name, opt_type) { this.size = size; this.name = opt_name || ''; this.type = opt_type || ''; this.nameUpdated_ = false; }; CodeMap.CodeEntry.prototype.getName = function() { return this.name; }; CodeMap.CodeEntry.prototype.toString = function() { return this.name + ': ' + this.size.toString(16); }; CodeMap.NameGenerator = function() { this.knownNames_ = {}; }; CodeMap.NameGenerator.prototype.getName = function(name) { if (!(name in this.knownNames_)) { this.knownNames_[name] = 0; return name; } var count = ++this.knownNames_[name]; return name + ' {' + count + '}'; };
module.exports={A:{A:{"1":"J C UB","129":"G E B A"},B:{"1":"D X g H L"},C:{"2":"0 1 2 4 5 SB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s QB PB"},D:{"1":"0 1 4 5 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s EB BB TB CB"},E:{"1":"F I J C G E B A FB GB HB IB JB KB","2":"9 DB"},F:{"1":"H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r","2":"6 7 E A D LB MB NB OB RB y"},G:{"1":"3 G A AB VB WB XB YB ZB aB bB cB","2":"9"},H:{"2":"dB"},I:{"1":"2 3 F s eB fB gB hB iB jB"},J:{"1":"C B"},K:{"1":"K","2":"6 7 B A D y"},L:{"1":"8"},M:{"2":"t"},N:{"129":"B A"},O:{"1":"kB"},P:{"1":"F I"},Q:{"1":"lB"},R:{"1":"mB"}},B:7,C:"CSS zoom"};
import r from 'restructure'; import Entity from '../entity'; import StringRef from '../string-ref'; export default Entity({ id: r.uint32le, name: StringRef, });
module.exports={A:{A:{"2":"I C G E A B SB"},B:{"1":"K","2":"D g q"},C:{"1":"0 1 2 e f J h i j k l m n o p u v w t y r W","2":"3 QB F H I C G E A B D g q K L M N O P Q R S T U V s X Y Z a b c d OB NB"},D:{"1":"0 1 2 6 9 k l m n o p u v w t y r W CB RB AB","2":"F H I C G E A B D g q K L M N O P Q R S T U V s X Y Z a b c d e f J h i j"},E:{"1":"E A GB HB IB","2":"7 F H I C G BB DB EB FB"},F:{"1":"X Y Z a b c d e f J h i j k l m n o p","2":"4 5 E B D K L M N O P Q R S T U V s JB KB LB MB PB z"},G:{"1":"XB YB ZB aB","2":"7 8 G x TB UB VB WB"},H:{"2":"bB"},I:{"1":"W","2":"3 F cB dB eB fB x gB hB"},J:{"2":"C A"},K:{"1":"J","2":"4 5 A B D z"},L:{"1":"6"},M:{"1":"r"},N:{"2":"A B"},O:{"2":"iB"},P:{"1":"H","2":"F"},Q:{"2":"jB"},R:{"1":"kB"}},B:1,C:"Element.closest()"};
(function (global, factory) { if (typeof define === "function" && define.amd) { define('element/locale/it', ['module', 'exports'], factory); } else if (typeof exports !== "undefined") { factory(module, exports); } else { var mod = { exports: {} }; factory(mod, mod.exports); global.ELEMENT.lang = global.ELEMENT.lang || {}; global.ELEMENT.lang.it = mod.exports; } })(this, function (module, exports) { 'use strict'; exports.__esModule = true; exports.default = { el: { colorpicker: { confirm: 'OK', clear: 'Pulisci' }, datepicker: { now: 'Ora', today: 'Oggi', cancel: 'Cancella', clear: 'Pulisci', confirm: 'OK', selectDate: 'Seleziona data', selectTime: 'Seleziona ora', startDate: 'Data inizio', startTime: 'Ora inizio', endDate: 'Data fine', endTime: 'Ora fine', prevYear: 'Anno precedente', nextYear: 'Anno successivo', prevMonth: 'Mese precedente', nextMonth: 'Mese successivo', year: '', month1: 'Gennaio', month2: 'Febbraio', month3: 'Marzo', month4: 'Aprile', month5: 'Maggio', month6: 'Giugno', month7: 'Luglio', month8: 'Agosto', month9: 'Settembre', month10: 'Ottobre', month11: 'Novembre', month12: 'Dicembre', // week: 'settimana', weeks: { sun: 'Dom', mon: 'Lun', tue: 'Mar', wed: 'Mer', thu: 'Gio', fri: 'Ven', sat: 'Sab' }, months: { jan: 'Gen', feb: 'Feb', mar: 'Mar', apr: 'Apr', may: 'Mag', jun: 'Giu', jul: 'Lug', aug: 'Ago', sep: 'Set', oct: 'Ott', nov: 'Nov', dec: 'Dic' } }, select: { loading: 'Caricamento', noMatch: 'Nessuna corrispondenza', noData: 'Nessun dato', placeholder: 'Seleziona' }, cascader: { noMatch: 'Nessuna corrispondenza', loading: 'Caricamento', placeholder: 'Seleziona' }, pagination: { goto: 'Vai a', pagesize: '/page', total: 'Totale {total}', pageClassifier: '' }, messagebox: { confirm: 'OK', cancel: 'Cancella', error: 'Input non valido' }, upload: { deleteTip: 'Premi cancella per rimuovere', delete: 'Cancella', preview: 'Anteprima', continue: 'Continua' }, table: { emptyText: 'Nessun dato', confirmFilter: 'Conferma', resetFilter: 'Reset', clearFilter: 'Tutti', sumText: 'Somma' }, tree: { emptyText: 'Nessun dato' }, transfer: { noMatch: 'Nessuna corrispondenza', noData: 'Nessun dato', titles: ['Lista 1', 'Lista 2'], filterPlaceholder: 'Inserisci filtro', noCheckedFormat: '{total} elementi', hasCheckedFormat: '{checked}/{total} selezionati' }, image: { error: 'FAILED' // to be translated } } }; module.exports = exports['default']; });
module.exports = function() { return { modulePrefix: 'some-cool-app', EmberENV: { asdflkmawejf: ';jlnu3yr23' }, APP: { autoboot: false } }; };
console.warn("warn -",`Imports like "const buddy = require('simple-icons/icons/buddy');" have been deprecated in v6.0.0 and will no longer work from v7.0.0, use "const { siBuddy } = require('simple-icons/icons');" instead`),module.exports={title:"Buddy",slug:"buddy",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Buddy</title><path d="'+this.path+'"/></svg>'},path:"M21.7 5.307L12.945.253a1.892 1.892 0 00-1.891 0L2.299 5.306a1.892 1.892 0 00-.945 1.638v10.11c0 .675.36 1.3.945 1.637l8.756 5.056a1.892 1.892 0 001.89 0l8.756-5.055c.585-.338.945-.962.945-1.638V6.945c0-.675-.36-1.3-.945-1.638zm-7.45 7.753l-3.805 3.804-1.351-1.351 3.804-3.805-3.804-3.806 1.35-1.35 3.805 3.805 1.351 1.35-1.35 1.353z",source:"https://buddy.works/about",hex:"1A86FD",guidelines:void 0,license:void 0};
module('system/props/events_test'); test('listener should receive event - removing should remove', function() { var obj = {}, count = 0; var F = function() { count++; }; Ember.addListener(obj, 'event!', F); equal(count, 0, 'nothing yet'); Ember.sendEvent(obj, 'event!'); equal(count, 1, 'received event'); Ember.removeListener(obj, 'event!', F); count = 0; Ember.sendEvent(obj, 'event!'); equal(count, 0, 'received event'); }); test('listeners should be inherited', function() { var obj = {}, count = 0; var F = function() { count++; }; Ember.addListener(obj, 'event!', F); var obj2 = Ember.create(obj); equal(count, 0, 'nothing yet'); Ember.sendEvent(obj2, 'event!'); equal(count, 1, 'received event'); Ember.removeListener(obj2, 'event!', F); count = 0; Ember.sendEvent(obj2, 'event!'); equal(count, 0, 'did not receive event'); Ember.sendEvent(obj, 'event!'); equal(count, 1, 'should still invoke on parent'); }); test('adding a listener more than once should only invoke once', function() { var obj = {}, count = 0; var F = function() { count++; }; Ember.addListener(obj, 'event!', F); Ember.addListener(obj, 'event!', F); Ember.sendEvent(obj, 'event!'); equal(count, 1, 'should only invoke once'); }); test('adding a listener with a target should invoke with target', function() { var obj = {}, target; target = { count: 0, method: function() { this.count++; } }; Ember.addListener(obj, 'event!', target, target.method); Ember.sendEvent(obj, 'event!'); equal(target.count, 1, 'should invoke'); }); test('suspending a listener should not invoke during callback', function() { var obj = {}, target, otherTarget; target = { count: 0, method: function() { this.count++; } }; otherTarget = { count: 0, method: function() { this.count++; } }; Ember.addListener(obj, 'event!', target, target.method); Ember.addListener(obj, 'event!', otherTarget, otherTarget.method); function callback() { equal(this, target); Ember.sendEvent(obj, 'event!'); return 'result'; } Ember.sendEvent(obj, 'event!'); equal(Ember._suspendListener(obj, 'event!', target, target.method, callback), 'result'); Ember.sendEvent(obj, 'event!'); equal(target.count, 2, 'should invoke'); equal(otherTarget.count, 3, 'should invoke'); }); test('adding a listener with string method should lookup method on event delivery', function() { var obj = {}, target; target = { count: 0, method: function() {} }; Ember.addListener(obj, 'event!', target, 'method'); Ember.sendEvent(obj, 'event!'); equal(target.count, 0, 'should invoke but do nothing'); target.method = function() { this.count++; }; Ember.sendEvent(obj, 'event!'); equal(target.count, 1, 'should invoke now'); }); test('calling sendEvent with extra params should be passed to listeners', function() { var obj = {}, params = null; Ember.addListener(obj, 'event!', function() { params = Array.prototype.slice.call(arguments); }); Ember.sendEvent(obj, 'event!', ['foo', 'bar']); deepEqual(params, ['foo', 'bar'], 'params should be saved'); }); test('implementing sendEvent on object should invoke', function() { var obj = { sendEvent: function(eventName, params) { equal(eventName, 'event!', 'eventName'); deepEqual(params, ['foo', 'bar']); this.count++; }, count: 0 }; Ember.addListener(obj, 'event!', obj, function() { this.count++; }); Ember.sendEvent(obj, 'event!', ['foo', 'bar']); equal(obj.count, 2, 'should have invoked method & listener'); }); test('hasListeners tells you if there are listeners for a given event', function() { var obj = {}, F = function() {}, F2 = function() {}; equal(Ember.hasListeners(obj, 'event!'), false, 'no listeners at first'); Ember.addListener(obj, 'event!', F); Ember.addListener(obj, 'event!', F2); equal(Ember.hasListeners(obj, 'event!'), true, 'has listeners'); Ember.removeListener(obj, 'event!', F); equal(Ember.hasListeners(obj, 'event!'), true, 'has listeners'); Ember.removeListener(obj, 'event!', F2); equal(Ember.hasListeners(obj, 'event!'), false, 'has no more listeners'); Ember.addListener(obj, 'event!', F); equal(Ember.hasListeners(obj, 'event!'), true, 'has listeners'); }); test('calling removeListener without method should remove all listeners', function() { var obj = {}, F = function() {}, F2 = function() {}; equal(Ember.hasListeners(obj, 'event!'), false, 'no listeners at first'); Ember.addListener(obj, 'event!', F); Ember.addListener(obj, 'event!', F2); equal(Ember.hasListeners(obj, 'event!'), true, 'has listeners'); Ember.removeListener(obj, 'event!'); equal(Ember.hasListeners(obj, 'event!'), false, 'has no more listeners'); }); test('while suspended, it should not be possible to add a duplicate listener', function() { var obj = {}, target; target = { count: 0, method: function() { this.count++; } }; Ember.addListener(obj, 'event!', target, target.method); function callback() { Ember.addListener(obj, 'event!', target, target.method); } Ember.sendEvent(obj, 'event!'); Ember._suspendListener(obj, 'event!', target, target.method, callback); equal(target.count, 1, 'should invoke'); equal(Ember.meta(obj).listeners['event!'].length, 1, "a duplicate listener wasn't added"); // now test _suspendListeners... Ember.sendEvent(obj, 'event!'); Ember._suspendListeners(obj, ['event!'], target, target.method, callback); equal(target.count, 2, 'should have invoked again'); equal(Ember.meta(obj).listeners['event!'].length, 1, "a duplicate listener wasn't added"); });
(function (Prism) { Prism.languages.puppet = { 'heredoc': [ // Matches the content of a quoted heredoc string (subject to interpolation) { pattern: /(@\("([^"\r\n\/):]+)"(?:\/[nrts$uL]*)?\).*(?:\r?\n|\r))(?:.*(?:\r?\n|\r))*?[ \t]*\|?[ \t]*-?[ \t]*\2/, lookbehind: true, alias: 'string', inside: { // Matches the end tag 'punctuation': /(?=\S).*\S(?= *$)/ // See interpolation below } }, // Matches the content of an unquoted heredoc string (no interpolation) { pattern: /(@\(([^"\r\n\/):]+)(?:\/[nrts$uL]*)?\).*(?:\r?\n|\r))(?:.*(?:\r?\n|\r))*?[ \t]*\|?[ \t]*-?[ \t]*\2/, lookbehind: true, alias: 'string', inside: { // Matches the end tag 'punctuation': /(?=\S).*\S(?= *$)/ } }, // Matches the start tag of heredoc strings { pattern: /@\("?(?:[^"\r\n\/):]+)"?(?:\/[nrts$uL]*)?\)/, alias: 'string', inside: { 'punctuation': { pattern: /(\().+?(?=\))/, lookbehind: true } } } ], 'multiline-comment': { pattern: /(^|[^\\])\/\*[\s\S]*?\*\//, lookbehind: true, alias: 'comment' }, 'regex': { // Must be prefixed with the keyword "node" or a non-word char pattern: /((?:\bnode\s+|[~=\(\[\{,]\s*|[=+]>\s*|^\s*))\/(?:[^\/\\]|\\[\s\S])+\/(?:[imx]+\b|\B)/, lookbehind: true, inside: { // Extended regexes must have the x flag. They can contain single-line comments. 'extended-regex': { pattern: /^\/(?:[^\/\\]|\\[\s\S])+\/[im]*x[im]*$/, inside: { 'comment': /#.*/ } } } }, 'comment': { pattern: /(^|[^\\])#.*/, lookbehind: true }, 'string': { // Allow for one nested level of double quotes inside interpolation pattern: /(["'])(?:\$\{(?:[^'"}]|(["'])(?:(?!\2)[^\\]|\\[\s\S])*\2)+\}|(?!\1)[^\\]|\\[\s\S])*\1/, inside: { 'double-quoted': { pattern: /^"[\s\S]*"$/, inside: { // See interpolation below } } } }, 'variable': { pattern: /\$(?:::)?\w+(?:::\w+)*/, inside: { 'punctuation': /::/ } }, 'attr-name': /(?:\w+|\*)(?=\s*=>)/, 'function': [ { pattern: /(\.)(?!\d)\w+/, lookbehind: true }, /\b(?:contain|debug|err|fail|include|info|notice|realize|require|tag|warning)\b|\b(?!\d)\w+(?=\()/ ], 'number': /\b(?:0x[a-f\d]+|\d+(?:\.\d+)?(?:e-?\d+)?)\b/i, 'boolean': /\b(?:true|false)\b/, // Includes words reserved for future use 'keyword': /\b(?:application|attr|case|class|consumes|default|define|else|elsif|function|if|import|inherits|node|private|produces|type|undef|unless)\b/, 'datatype': { pattern: /\b(?:Any|Array|Boolean|Callable|Catalogentry|Class|Collection|Data|Default|Enum|Float|Hash|Integer|NotUndef|Numeric|Optional|Pattern|Regexp|Resource|Runtime|Scalar|String|Struct|Tuple|Type|Undef|Variant)\b/, alias: 'symbol' }, 'operator': /=[=~>]?|![=~]?|<(?:<\|?|[=~|-])?|>[>=]?|->?|~>|\|>?>?|[*\/%+?]|\b(?:and|in|or)\b/, 'punctuation': /[\[\]{}().,;]|:+/ }; var interpolation = [ { // Allow for one nested level of braces inside interpolation pattern: /(^|[^\\])\$\{(?:[^'"{}]|\{[^}]*\}|(["'])(?:(?!\2)[^\\]|\\[\s\S])*\2)+\}/, lookbehind: true, inside: { 'short-variable': { // Negative look-ahead prevent wrong highlighting of functions pattern: /(^\$\{)(?!\w+\()(?:::)?\w+(?:::\w+)*/, lookbehind: true, alias: 'variable', inside: { 'punctuation': /::/ } }, 'delimiter': { pattern: /^\$/, alias: 'variable' }, rest: Prism.languages.puppet } }, { pattern: /(^|[^\\])\$(?:::)?\w+(?:::\w+)*/, lookbehind: true, alias: 'variable', inside: { 'punctuation': /::/ } } ]; Prism.languages.puppet['heredoc'][0].inside.interpolation = interpolation; Prism.languages.puppet['string'].inside['double-quoted'].inside.interpolation = interpolation; }(Prism));
var assert = require('assert'); var Helpers = require('../../lib/Helpers'); var common = require('../common'); var Dialect = common.getDialect('mysql'); assert.equal( Helpers.escapeQuery(Dialect, "SELECT * FROM abc WHERE LOWER(abc.`stuff`) LIKE 'peaches'"), "SELECT * FROM abc WHERE LOWER(abc.`stuff`) LIKE 'peaches'" ); assert.equal( Helpers.escapeQuery(Dialect, "SELECT * FROM abc WHERE LOWER(abc.`stuff`) LIKE ?", ['peaches']), "SELECT * FROM abc WHERE LOWER(abc.`stuff`) LIKE 'peaches'" ); assert.equal( Helpers.escapeQuery(Dialect, "SELECT * FROM abc WHERE LOWER(abc.`stuff`) LIKE ? AND `number` > ?", ['peaches', 12]), "SELECT * FROM abc WHERE LOWER(abc.`stuff`) LIKE 'peaches' AND `number` > 12" ); assert.equal( Helpers.escapeQuery(Dialect, "SELECT * FROM abc WHERE LOWER(abc.`stuff`) LIKE ? AND `number` == ?", ['peaches']), "SELECT * FROM abc WHERE LOWER(abc.`stuff`) LIKE 'peaches' AND `number` == NULL" ); assert.equal( Helpers.escapeQuery(Dialect, "SELECT * FROM abc WHERE LOWER(abc.??) LIKE ? AND abc.?? > ?", ['stuff', 'peaches', 'number', 12]), "SELECT * FROM abc WHERE LOWER(abc.`stuff`) LIKE 'peaches' AND abc.`number` > 12" ); assert.equal( Helpers.escapeQuery(Dialect, "SELECT * FROM abc WHERE LOWER(abc.??) LIKE ? AND ?? == ?", ['stuff', 'peaches', 'number']), "SELECT * FROM abc WHERE LOWER(abc.`stuff`) LIKE 'peaches' AND `number` == NULL" ); // Should match at most 2 '?' at a time assert.equal( Helpers.escapeQuery(Dialect, "?????", ['a', 'b', 'c']), "`a``b`'c'" ); // Should not modify provided array var arr = ['a', 'b', 'c']; assert.equal( arr.join(','), 'a,b,c' )
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * Facebook, Inc. ("Facebook") owns all right, title and interest, including * all intellectual property and other proprietary rights, in and to the React * Native CustomComponents software (the "Software"). Subject to your * compliance with these terms, you are hereby granted a non-exclusive, * worldwide, royalty-free copyright license to (1) use and copy the Software; * and (2) reproduce and distribute the Software as part of your own software * ("Your Software"). Facebook reserves all rights not expressly granted to * you in this license agreement. * * THE SOFTWARE AND DOCUMENTATION, IF ANY, ARE PROVIDED "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 FACEBOOK OR ITS AFFILIATES, OFFICERS, DIRECTORS OR * EMPLOYEES 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 THE SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @providesModule NavigationHeader * @flow */ 'use strict'; const React = require('React'); const ReactNative = require('react-native'); const NavigationHeaderTitle = require('NavigationHeaderTitle'); const NavigationHeaderBackButton = require('NavigationHeaderBackButton'); const NavigationPropTypes = require('NavigationPropTypes'); const NavigationHeaderStyleInterpolator = require('NavigationHeaderStyleInterpolator'); const ReactComponentWithPureRenderMixin = require('react/lib/ReactComponentWithPureRenderMixin'); const { Animated, Platform, StyleSheet, View, } = ReactNative; import type { NavigationSceneRendererProps, NavigationStyleInterpolator, } from 'NavigationTypeDefinition'; type SubViewProps = NavigationSceneRendererProps & { onNavigateBack: ?Function, }; type SubViewRenderer = (subViewProps: SubViewProps) => ?React.Element<any>; type DefaultProps = { renderLeftComponent: SubViewRenderer, renderRightComponent: SubViewRenderer, renderTitleComponent: SubViewRenderer, statusBarHeight: number | Animated.Value, }; type Props = NavigationSceneRendererProps & { onNavigateBack: ?Function, renderLeftComponent: SubViewRenderer, renderRightComponent: SubViewRenderer, renderTitleComponent: SubViewRenderer, style?: any, viewProps?: any, statusBarHeight: number | Animated.Value, }; type SubViewName = 'left' | 'title' | 'right'; const APPBAR_HEIGHT = Platform.OS === 'ios' ? 44 : 56; const STATUSBAR_HEIGHT = Platform.OS === 'ios' ? 20 : 0; const {PropTypes} = React; class NavigationHeader extends React.Component<DefaultProps, Props, any> { props: Props; static defaultProps = { renderTitleComponent: (props: SubViewProps) => { const title = String(props.scene.route.title || ''); return <NavigationHeaderTitle>{title}</NavigationHeaderTitle>; }, renderLeftComponent: (props: SubViewProps) => { if (props.scene.index === 0 || !props.onNavigateBack) { return null; } return ( <NavigationHeaderBackButton onPress={props.onNavigateBack} /> ); }, renderRightComponent: (props: SubViewProps) => { return null; }, statusBarHeight: STATUSBAR_HEIGHT, }; static propTypes = { ...NavigationPropTypes.SceneRendererProps, onNavigateBack: PropTypes.func, renderLeftComponent: PropTypes.func, renderRightComponent: PropTypes.func, renderTitleComponent: PropTypes.func, style: View.propTypes.style, statusBarHeight: PropTypes.number, viewProps: PropTypes.shape(View.propTypes), }; shouldComponentUpdate(nextProps: Props, nextState: any): boolean { return ReactComponentWithPureRenderMixin.shouldComponentUpdate.call( this, nextProps, nextState ); } render(): React.Element<any> { const { scenes, style, viewProps } = this.props; const scenesProps = scenes.map(scene => { const props = NavigationPropTypes.extractSceneRendererProps(this.props); props.scene = scene; return props; }); const barHeight = (this.props.statusBarHeight instanceof Animated.Value) ? Animated.add(this.props.statusBarHeight, new Animated.Value(APPBAR_HEIGHT)) : APPBAR_HEIGHT + this.props.statusBarHeight; return ( <Animated.View style={[ styles.appbar, { height: barHeight }, style ]} {...viewProps} > {scenesProps.map(this._renderLeft, this)} {scenesProps.map(this._renderTitle, this)} {scenesProps.map(this._renderRight, this)} </Animated.View> ); } _renderLeft(props: NavigationSceneRendererProps): ?React.Element<any> { return this._renderSubView( props, 'left', this.props.renderLeftComponent, NavigationHeaderStyleInterpolator.forLeft, ); } _renderTitle(props: NavigationSceneRendererProps): ?React.Element<any> { return this._renderSubView( props, 'title', this.props.renderTitleComponent, NavigationHeaderStyleInterpolator.forCenter, ); } _renderRight(props: NavigationSceneRendererProps): ?React.Element<any> { return this._renderSubView( props, 'right', this.props.renderRightComponent, NavigationHeaderStyleInterpolator.forRight, ); } _renderSubView( props: NavigationSceneRendererProps, name: SubViewName, renderer: SubViewRenderer, styleInterpolator: NavigationStyleInterpolator, ): ?React.Element<any> { const { scene, navigationState, } = props; const { index, isStale, key, } = scene; const offset = navigationState.index - index; if (Math.abs(offset) > 2) { // Scene is far away from the active scene. Hides it to avoid unnecessary // rendering. return null; } const subViewProps = {...props, onNavigateBack: this.props.onNavigateBack}; const subView = renderer(subViewProps); if (subView === null) { return null; } const pointerEvents = offset !== 0 || isStale ? 'none' : 'box-none'; return ( <Animated.View pointerEvents={pointerEvents} key={name + '_' + key} style={[ styles[name], { marginTop: this.props.statusBarHeight }, styleInterpolator(props), ]}> {subView} </Animated.View> ); } static HEIGHT = APPBAR_HEIGHT + STATUSBAR_HEIGHT; static Title = NavigationHeaderTitle; static BackButton = NavigationHeaderBackButton; } const styles = StyleSheet.create({ appbar: { alignItems: 'center', backgroundColor: Platform.OS === 'ios' ? '#EFEFF2' : '#FFF', borderBottomColor: 'rgba(0, 0, 0, .15)', borderBottomWidth: Platform.OS === 'ios' ? StyleSheet.hairlineWidth : 0, elevation: 4, flexDirection: 'row', justifyContent: 'flex-start', }, title: { bottom: 0, left: APPBAR_HEIGHT, position: 'absolute', right: APPBAR_HEIGHT, top: 0, }, left: { bottom: 0, left: 0, position: 'absolute', top: 0, }, right: { bottom: 0, position: 'absolute', right: 0, top: 0, }, }); module.exports = NavigationHeader;
/* * blueimp Gallery JS * https://github.com/blueimp/Gallery * * Copyright 2013, Sebastian Tschan * https://blueimp.net * * Swipe implementation based on * https://github.com/bradbirdsall/Swipe * * Licensed under the MIT license: * https://opensource.org/licenses/MIT */ /* global define, DocumentTouch */ /* eslint-disable no-param-reassign */ ;(function (factory) { 'use strict' if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['./blueimp-helper'], factory) } else { // Browser globals: window.blueimp = window.blueimp || {} window.blueimp.Gallery = factory(window.blueimp.helper || window.jQuery) } })(function ($) { 'use strict' /** * Gallery constructor * * @class * @param {Array|NodeList} list Gallery content * @param {object} [options] Gallery options * @returns {object} Gallery object */ function Gallery(list, options) { if (document.body.style.maxHeight === undefined) { // document.body.style.maxHeight is undefined on IE6 and lower return null } if (!this || this.options !== Gallery.prototype.options) { // Called as function instead of as constructor, // so we simply return a new instance: return new Gallery(list, options) } if (!list || !list.length) { this.console.log( 'blueimp Gallery: No or empty list provided as first argument.', list ) return } this.list = list this.num = list.length this.initOptions(options) this.initialize() } $.extend(Gallery.prototype, { options: { // The Id, element or querySelector of the gallery widget: container: '#blueimp-gallery', // The tag name, Id, element or querySelector of the slides container: slidesContainer: 'div', // The tag name, Id, element or querySelector of the title element: titleElement: 'h3', // The class to add when the gallery is visible: displayClass: 'blueimp-gallery-display', // The class to add when the gallery controls are visible: controlsClass: 'blueimp-gallery-controls', // The class to add when the gallery only displays one element: singleClass: 'blueimp-gallery-single', // The class to add when the left edge has been reached: leftEdgeClass: 'blueimp-gallery-left', // The class to add when the right edge has been reached: rightEdgeClass: 'blueimp-gallery-right', // The class to add when the automatic slideshow is active: playingClass: 'blueimp-gallery-playing', // The class to add when the browser supports SVG as img (or background): svgasimgClass: 'blueimp-gallery-svgasimg', // The class to add when the browser supports SMIL (animated SVGs): smilClass: 'blueimp-gallery-smil', // The class for all slides: slideClass: 'slide', // The slide class for the active (current index) slide: slideActiveClass: 'slide-active', // The slide class for the previous (before current index) slide: slidePrevClass: 'slide-prev', // The slide class for the next (after current index) slide: slideNextClass: 'slide-next', // The slide class for loading elements: slideLoadingClass: 'slide-loading', // The slide class for elements that failed to load: slideErrorClass: 'slide-error', // The class for the content element loaded into each slide: slideContentClass: 'slide-content', // The class for the "toggle" control: toggleClass: 'toggle', // The class for the "prev" control: prevClass: 'prev', // The class for the "next" control: nextClass: 'next', // The class for the "close" control: closeClass: 'close', // The class for the "play-pause" toggle control: playPauseClass: 'play-pause', // The list object property (or data attribute) with the object type: typeProperty: 'type', // The list object property (or data attribute) with the object title: titleProperty: 'title', // The list object property (or data attribute) with the object alt text: altTextProperty: 'alt', // The list object property (or data attribute) with the object URL: urlProperty: 'href', // The list object property (or data attribute) with the object srcset: srcsetProperty: 'srcset', // The list object property (or data attribute) with the object sizes: sizesProperty: 'sizes', // The list object property (or data attribute) with the object sources: sourcesProperty: 'sources', // The gallery listens for transitionend events before triggering the // opened and closed events, unless the following option is set to false: displayTransition: true, // Defines if the gallery slides are cleared from the gallery modal, // or reused for the next gallery initialization: clearSlides: true, // Toggle the controls on pressing the Enter key: toggleControlsOnEnter: true, // Toggle the controls on slide click: toggleControlsOnSlideClick: true, // Toggle the automatic slideshow interval on pressing the Space key: toggleSlideshowOnSpace: true, // Navigate the gallery by pressing the ArrowLeft and ArrowRight keys: enableKeyboardNavigation: true, // Close the gallery on pressing the Escape key: closeOnEscape: true, // Close the gallery when clicking on an empty slide area: closeOnSlideClick: true, // Close the gallery by swiping up or down: closeOnSwipeUpOrDown: true, // Close the gallery when the URL hash changes: closeOnHashChange: true, // Emulate touch events on mouse-pointer devices such as desktop browsers: emulateTouchEvents: true, // Stop touch events from bubbling up to ancestor elements of the Gallery: stopTouchEventsPropagation: false, // Hide the page scrollbars: hidePageScrollbars: true, // Stops any touches on the container from scrolling the page: disableScroll: true, // Carousel mode (shortcut for carousel specific options): carousel: false, // Allow continuous navigation, moving from last to first // and from first to last slide: continuous: true, // Remove elements outside of the preload range from the DOM: unloadElements: true, // Start with the automatic slideshow: startSlideshow: false, // Delay in milliseconds between slides for the automatic slideshow: slideshowInterval: 5000, // The direction the slides are moving: ltr=LeftToRight or rtl=RightToLeft slideshowDirection: 'ltr', // The starting index as integer. // Can also be an object of the given list, // or an equal object with the same url property: index: 0, // The number of elements to load around the current index: preloadRange: 2, // The transition duration between slide changes in milliseconds: transitionDuration: 300, // The transition duration for automatic slide changes, set to an integer // greater 0 to override the default transition duration: slideshowTransitionDuration: 500, // The event object for which the default action will be canceled // on Gallery initialization (e.g. the click event to open the Gallery): event: undefined, // Callback function executed when the Gallery is initialized. // Is called with the gallery instance as "this" object: onopen: undefined, // Callback function executed when the Gallery has been initialized // and the initialization transition has been completed. // Is called with the gallery instance as "this" object: onopened: undefined, // Callback function executed on slide change. // Is called with the gallery instance as "this" object and the // current index and slide as arguments: onslide: undefined, // Callback function executed after the slide change transition. // Is called with the gallery instance as "this" object and the // current index and slide as arguments: onslideend: undefined, // Callback function executed on slide content load. // Is called with the gallery instance as "this" object and the // slide index and slide element as arguments: onslidecomplete: undefined, // Callback function executed when the Gallery is about to be closed. // Is called with the gallery instance as "this" object: onclose: undefined, // Callback function executed when the Gallery has been closed // and the closing transition has been completed. // Is called with the gallery instance as "this" object: onclosed: undefined }, carouselOptions: { hidePageScrollbars: false, toggleControlsOnEnter: false, toggleSlideshowOnSpace: false, enableKeyboardNavigation: false, closeOnEscape: false, closeOnSlideClick: false, closeOnSwipeUpOrDown: false, closeOnHashChange: false, disableScroll: false, startSlideshow: true }, console: window.console && typeof window.console.log === 'function' ? window.console : { log: function () {} }, // Detect touch, transition, transform and background-size support: support: (function (element) { var support = { source: !!window.HTMLSourceElement, picture: !!window.HTMLPictureElement, svgasimg: document.implementation.hasFeature( 'http://www.w3.org/TR/SVG11/feature#Image', '1.1' ), smil: !!document.createElementNS && /SVGAnimate/.test( document .createElementNS('http://www.w3.org/2000/svg', 'animate') .toString() ), touch: window.ontouchstart !== undefined || (window.DocumentTouch && document instanceof DocumentTouch) } var transitions = { webkitTransition: { end: 'webkitTransitionEnd', prefix: '-webkit-' }, MozTransition: { end: 'transitionend', prefix: '-moz-' }, OTransition: { end: 'otransitionend', prefix: '-o-' }, transition: { end: 'transitionend', prefix: '' } } var prop for (prop in transitions) { if ( Object.prototype.hasOwnProperty.call(transitions, prop) && element.style[prop] !== undefined ) { support.transition = transitions[prop] support.transition.name = prop break } } /** * Tests browser support */ function elementTests() { var transition = support.transition var prop var translateZ document.body.appendChild(element) if (transition) { prop = transition.name.slice(0, -9) + 'ransform' if (element.style[prop] !== undefined) { element.style[prop] = 'translateZ(0)' translateZ = window .getComputedStyle(element) .getPropertyValue(transition.prefix + 'transform') support.transform = { prefix: transition.prefix, name: prop, translate: true, translateZ: !!translateZ && translateZ !== 'none' } } } document.body.removeChild(element) } if (document.body) { elementTests() } else { $(document).on('DOMContentLoaded', elementTests) } return support // Test element, has to be standard HTML and must not be hidden // for the CSS3 tests using window.getComputedStyle to be applicable: })(document.createElement('div')), requestAnimationFrame: window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame, cancelAnimationFrame: window.cancelAnimationFrame || window.webkitCancelRequestAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame, initialize: function () { this.initStartIndex() if (this.initWidget() === false) { return false } this.initEventListeners() // Load the slide at the given index: this.onslide(this.index) // Manually trigger the slideend event for the initial slide: this.ontransitionend() // Start the automatic slideshow if applicable: if (this.options.startSlideshow) { this.play() } }, slide: function (to, duration) { window.clearTimeout(this.timeout) var index = this.index var direction var naturalDirection var diff if (index === to || this.num === 1) { return } if (!duration) { duration = this.options.transitionDuration } if (this.support.transform) { if (!this.options.continuous) { to = this.circle(to) } // 1: backward, -1: forward: direction = Math.abs(index - to) / (index - to) // Get the actual position of the slide: if (this.options.continuous) { naturalDirection = direction direction = -this.positions[this.circle(to)] / this.slideWidth // If going forward but to < index, use to = slides.length + to // If going backward but to > index, use to = -slides.length + to if (direction !== naturalDirection) { to = -direction * this.num + to } } diff = Math.abs(index - to) - 1 // Move all the slides between index and to in the right direction: while (diff) { diff -= 1 this.move( this.circle((to > index ? to : index) - diff - 1), this.slideWidth * direction, 0 ) } to = this.circle(to) this.move(index, this.slideWidth * direction, duration) this.move(to, 0, duration) if (this.options.continuous) { this.move( this.circle(to - direction), -(this.slideWidth * direction), 0 ) } } else { to = this.circle(to) this.animate(index * -this.slideWidth, to * -this.slideWidth, duration) } this.onslide(to) }, getIndex: function () { return this.index }, getNumber: function () { return this.num }, prev: function () { if (this.options.continuous || this.index) { this.slide(this.index - 1) } }, next: function () { if (this.options.continuous || this.index < this.num - 1) { this.slide(this.index + 1) } }, play: function (time) { var that = this var nextIndex = this.index + (this.options.slideshowDirection === 'rtl' ? -1 : 1) window.clearTimeout(this.timeout) this.interval = time || this.options.slideshowInterval if (this.elements[this.index] > 1) { this.timeout = this.setTimeout( (!this.requestAnimationFrame && this.slide) || function (to, duration) { that.animationFrameId = that.requestAnimationFrame.call( window, function () { that.slide(to, duration) } ) }, [nextIndex, this.options.slideshowTransitionDuration], this.interval ) } this.container.addClass(this.options.playingClass) this.slidesContainer[0].setAttribute('aria-live', 'off') if (this.playPauseElement.length) { this.playPauseElement[0].setAttribute('aria-pressed', 'true') } }, pause: function () { window.clearTimeout(this.timeout) this.interval = null if (this.cancelAnimationFrame) { this.cancelAnimationFrame.call(window, this.animationFrameId) this.animationFrameId = null } this.container.removeClass(this.options.playingClass) this.slidesContainer[0].setAttribute('aria-live', 'polite') if (this.playPauseElement.length) { this.playPauseElement[0].setAttribute('aria-pressed', 'false') } }, add: function (list) { var i if (!list.concat) { // Make a real array out of the list to add: list = Array.prototype.slice.call(list) } if (!this.list.concat) { // Make a real array out of the Gallery list: this.list = Array.prototype.slice.call(this.list) } this.list = this.list.concat(list) this.num = this.list.length if (this.num > 2 && this.options.continuous === null) { this.options.continuous = true this.container.removeClass(this.options.leftEdgeClass) } this.container .removeClass(this.options.rightEdgeClass) .removeClass(this.options.singleClass) for (i = this.num - list.length; i < this.num; i += 1) { this.addSlide(i) this.positionSlide(i) } this.positions.length = this.num this.initSlides(true) }, resetSlides: function () { this.slidesContainer.empty() this.unloadAllSlides() this.slides = [] }, handleClose: function () { var options = this.options this.destroyEventListeners() // Cancel the slideshow: this.pause() this.container[0].style.display = 'none' this.container .removeClass(options.displayClass) .removeClass(options.singleClass) .removeClass(options.leftEdgeClass) .removeClass(options.rightEdgeClass) if (options.hidePageScrollbars) { document.body.style.overflow = this.bodyOverflowStyle } if (this.options.clearSlides) { this.resetSlides() } if (this.options.onclosed) { this.options.onclosed.call(this) } }, close: function () { var that = this /** * Close handler * * @param {event} event Close event */ function closeHandler(event) { if (event.target === that.container[0]) { that.container.off(that.support.transition.end, closeHandler) that.handleClose() } } if (this.options.onclose) { this.options.onclose.call(this) } if (this.support.transition && this.options.displayTransition) { this.container.on(this.support.transition.end, closeHandler) this.container.removeClass(this.options.displayClass) } else { this.handleClose() } }, circle: function (index) { // Always return a number inside of the slides index range: return (this.num + (index % this.num)) % this.num }, move: function (index, dist, duration) { this.translateX(index, dist, duration) this.positions[index] = dist }, translate: function (index, x, y, duration) { if (!this.slides[index]) return var style = this.slides[index].style var transition = this.support.transition var transform = this.support.transform style[transition.name + 'Duration'] = duration + 'ms' style[transform.name] = 'translate(' + x + 'px, ' + y + 'px)' + (transform.translateZ ? ' translateZ(0)' : '') }, translateX: function (index, x, duration) { this.translate(index, x, 0, duration) }, translateY: function (index, y, duration) { this.translate(index, 0, y, duration) }, animate: function (from, to, duration) { if (!duration) { this.slidesContainer[0].style.left = to + 'px' return } var that = this var start = new Date().getTime() var timer = window.setInterval(function () { var timeElap = new Date().getTime() - start if (timeElap > duration) { that.slidesContainer[0].style.left = to + 'px' that.ontransitionend() window.clearInterval(timer) return } that.slidesContainer[0].style.left = (to - from) * (Math.floor((timeElap / duration) * 100) / 100) + from + 'px' }, 4) }, preventDefault: function (event) { if (event.preventDefault) { event.preventDefault() } else { event.returnValue = false } }, stopPropagation: function (event) { if (event.stopPropagation) { event.stopPropagation() } else { event.cancelBubble = true } }, onresize: function () { this.initSlides(true) }, onhashchange: function () { if (this.options.closeOnHashChange) { this.close() } }, onmousedown: function (event) { // Trigger on clicks of the left mouse button only // and exclude video & audio elements: if ( event.which && event.which === 1 && event.target.nodeName !== 'VIDEO' && event.target.nodeName !== 'AUDIO' ) { // Preventing the default mousedown action is required // to make touch emulation work with Firefox: event.preventDefault() ;(event.originalEvent || event).touches = [ { pageX: event.pageX, pageY: event.pageY } ] this.ontouchstart(event) } }, onmousemove: function (event) { if (this.touchStart) { ;(event.originalEvent || event).touches = [ { pageX: event.pageX, pageY: event.pageY } ] this.ontouchmove(event) } }, onmouseup: function (event) { if (this.touchStart) { this.ontouchend(event) delete this.touchStart } }, onmouseout: function (event) { if (this.touchStart) { var target = event.target var related = event.relatedTarget if (!related || (related !== target && !$.contains(target, related))) { this.onmouseup(event) } } }, ontouchstart: function (event) { if (this.options.stopTouchEventsPropagation) { this.stopPropagation(event) } // jQuery doesn't copy touch event properties by default, // so we have to access the originalEvent object: var touch = (event.originalEvent || event).touches[0] this.touchStart = { // Remember the initial touch coordinates: x: touch.pageX, y: touch.pageY, // Store the time to determine touch duration: time: Date.now() } // Helper variable to detect scroll movement: this.isScrolling = undefined // Reset delta values: this.touchDelta = {} }, ontouchmove: function (event) { if (this.options.stopTouchEventsPropagation) { this.stopPropagation(event) } // jQuery doesn't copy touch event properties by default, // so we have to access the originalEvent object: var touches = (event.originalEvent || event).touches var touch = touches[0] var scale = (event.originalEvent || event).scale var index = this.index var touchDeltaX var indices // Ensure this is a one touch swipe and not, e.g. a pinch: if (touches.length > 1 || (scale && scale !== 1)) { return } if (this.options.disableScroll) { event.preventDefault() } // Measure change in x and y coordinates: this.touchDelta = { x: touch.pageX - this.touchStart.x, y: touch.pageY - this.touchStart.y } touchDeltaX = this.touchDelta.x // Detect if this is a vertical scroll movement (run only once per touch): if (this.isScrolling === undefined) { this.isScrolling = this.isScrolling || Math.abs(touchDeltaX) < Math.abs(this.touchDelta.y) } if (!this.isScrolling) { // Always prevent horizontal scroll: event.preventDefault() // Stop the slideshow: window.clearTimeout(this.timeout) if (this.options.continuous) { indices = [this.circle(index + 1), index, this.circle(index - 1)] } else { // Increase resistance if first slide and sliding left // or last slide and sliding right: this.touchDelta.x = touchDeltaX = touchDeltaX / ((!index && touchDeltaX > 0) || (index === this.num - 1 && touchDeltaX < 0) ? Math.abs(touchDeltaX) / this.slideWidth + 1 : 1) indices = [index] if (index) { indices.push(index - 1) } if (index < this.num - 1) { indices.unshift(index + 1) } } while (indices.length) { index = indices.pop() this.translateX(index, touchDeltaX + this.positions[index], 0) } } else if (!this.options.carousel) { this.translateY(index, this.touchDelta.y + this.positions[index], 0) } }, ontouchend: function (event) { if (this.options.stopTouchEventsPropagation) { this.stopPropagation(event) } var index = this.index var absTouchDeltaX = Math.abs(this.touchDelta.x) var slideWidth = this.slideWidth var duration = Math.ceil( (this.options.transitionDuration * (1 - absTouchDeltaX / slideWidth)) / 2 ) // Determine if slide attempt triggers next/prev slide: var isValidSlide = absTouchDeltaX > 20 // Determine if slide attempt is past start or end: var isPastBounds = (!index && this.touchDelta.x > 0) || (index === this.num - 1 && this.touchDelta.x < 0) var isValidClose = !isValidSlide && this.options.closeOnSwipeUpOrDown && Math.abs(this.touchDelta.y) > 20 var direction var indexForward var indexBackward var distanceForward var distanceBackward if (this.options.continuous) { isPastBounds = false } // Determine direction of swipe (true: right, false: left): direction = this.touchDelta.x < 0 ? -1 : 1 if (!this.isScrolling) { if (isValidSlide && !isPastBounds) { indexForward = index + direction indexBackward = index - direction distanceForward = slideWidth * direction distanceBackward = -slideWidth * direction if (this.options.continuous) { this.move(this.circle(indexForward), distanceForward, 0) this.move(this.circle(index - 2 * direction), distanceBackward, 0) } else if (indexForward >= 0 && indexForward < this.num) { this.move(indexForward, distanceForward, 0) } this.move(index, this.positions[index] + distanceForward, duration) this.move( this.circle(indexBackward), this.positions[this.circle(indexBackward)] + distanceForward, duration ) index = this.circle(indexBackward) this.onslide(index) } else { // Move back into position if (this.options.continuous) { this.move(this.circle(index - 1), -slideWidth, duration) this.move(index, 0, duration) this.move(this.circle(index + 1), slideWidth, duration) } else { if (index) { this.move(index - 1, -slideWidth, duration) } this.move(index, 0, duration) if (index < this.num - 1) { this.move(index + 1, slideWidth, duration) } } } } else { if (isValidClose) { this.close() } else { // Move back into position this.translateY(index, 0, duration) } } }, ontouchcancel: function (event) { if (this.touchStart) { this.ontouchend(event) delete this.touchStart } }, ontransitionend: function (event) { var slide = this.slides[this.index] if (!event || slide === event.target) { if (this.interval) { this.play() } this.setTimeout(this.options.onslideend, [this.index, slide]) } }, oncomplete: function (event) { var target = event.target || event.srcElement var parent = target && target.parentNode var index if (!target || !parent) { return } index = this.getNodeIndex(parent) $(parent).removeClass(this.options.slideLoadingClass) if (event.type === 'error') { $(parent).addClass(this.options.slideErrorClass) this.elements[index] = 3 // Fail } else { this.elements[index] = 2 // Done } // Fix for IE7's lack of support for percentage max-height: if (target.clientHeight > this.container[0].clientHeight) { target.style.maxHeight = this.container[0].clientHeight } if (this.interval && this.slides[this.index] === parent) { this.play() } this.setTimeout(this.options.onslidecomplete, [index, parent]) }, onload: function (event) { this.oncomplete(event) }, onerror: function (event) { this.oncomplete(event) }, onkeydown: function (event) { switch (event.which || event.keyCode) { case 13: // Enter if (this.options.toggleControlsOnEnter) { this.preventDefault(event) this.toggleControls() } break case 27: // Escape if (this.options.closeOnEscape) { this.close() // prevent Escape from closing other things event.stopImmediatePropagation() } break case 32: // Space if (this.options.toggleSlideshowOnSpace) { this.preventDefault(event) this.toggleSlideshow() } break case 37: // ArrowLeft if (this.options.enableKeyboardNavigation) { this.preventDefault(event) this.prev() } break case 39: // ArrowRight if (this.options.enableKeyboardNavigation) { this.preventDefault(event) this.next() } break } }, handleClick: function (event) { var options = this.options var target = event.target || event.srcElement var parent = target.parentNode /** * Checks if the target from the close has the given class * * @param {string} className Class name * @returns {boolean} Returns true if the target has the class name */ function isTarget(className) { return $(target).hasClass(className) || $(parent).hasClass(className) } if (isTarget(options.toggleClass)) { // Click on "toggle" control this.preventDefault(event) this.toggleControls() } else if (isTarget(options.prevClass)) { // Click on "prev" control this.preventDefault(event) this.prev() } else if (isTarget(options.nextClass)) { // Click on "next" control this.preventDefault(event) this.next() } else if (isTarget(options.closeClass)) { // Click on "close" control this.preventDefault(event) this.close() } else if (isTarget(options.playPauseClass)) { // Click on "play-pause" control this.preventDefault(event) this.toggleSlideshow() } else if (parent === this.slidesContainer[0]) { // Click on slide background if (options.closeOnSlideClick) { this.preventDefault(event) this.close() } else if (options.toggleControlsOnSlideClick) { this.preventDefault(event) this.toggleControls() } } else if ( parent.parentNode && parent.parentNode === this.slidesContainer[0] ) { // Click on displayed element if (options.toggleControlsOnSlideClick) { this.preventDefault(event) this.toggleControls() } } }, onclick: function (event) { if ( this.options.emulateTouchEvents && this.touchDelta && (Math.abs(this.touchDelta.x) > 20 || Math.abs(this.touchDelta.y) > 20) ) { delete this.touchDelta return } return this.handleClick(event) }, updateEdgeClasses: function (index) { if (!index) { this.container.addClass(this.options.leftEdgeClass) } else { this.container.removeClass(this.options.leftEdgeClass) } if (index === this.num - 1) { this.container.addClass(this.options.rightEdgeClass) } else { this.container.removeClass(this.options.rightEdgeClass) } }, updateActiveSlide: function (oldIndex, newIndex) { var slides = this.slides var options = this.options var list = [ { index: newIndex, method: 'addClass', hidden: false }, { index: oldIndex, method: 'removeClass', hidden: true } ] var item, index while (list.length) { item = list.pop() $(slides[item.index])[item.method](options.slideActiveClass) index = this.circle(item.index - 1) if (options.continuous || index < item.index) { $(slides[index])[item.method](options.slidePrevClass) } index = this.circle(item.index + 1) if (options.continuous || index > item.index) { $(slides[index])[item.method](options.slideNextClass) } } this.slides[oldIndex].setAttribute('aria-hidden', 'true') this.slides[newIndex].removeAttribute('aria-hidden') }, handleSlide: function (oldIndex, newIndex) { if (!this.options.continuous) { this.updateEdgeClasses(newIndex) } this.updateActiveSlide(oldIndex, newIndex) this.loadElements(newIndex) if (this.options.unloadElements) { this.unloadElements(oldIndex, newIndex) } this.setTitle(newIndex) }, onslide: function (index) { this.handleSlide(this.index, index) this.index = index this.setTimeout(this.options.onslide, [index, this.slides[index]]) }, setTitle: function (index) { var firstChild = this.slides[index].firstChild var text = firstChild.title || firstChild.alt var titleElement = this.titleElement if (titleElement.length) { this.titleElement.empty() if (text) { titleElement[0].appendChild(document.createTextNode(text)) } } }, setTimeout: function (func, args, wait) { var that = this return ( func && window.setTimeout(function () { func.apply(that, args || []) }, wait || 0) ) }, imageFactory: function (obj, callback) { var options = this.options var that = this var url = obj var img = this.imagePrototype.cloneNode(false) var picture var called var sources var srcset var sizes var title var altText var i /** * Wraps the callback function for the load/error event * * @param {event} event load/error event * @returns {number} timeout ID */ function callbackWrapper(event) { if (!called) { event = { type: event.type, target: picture || img } if (!event.target.parentNode) { // Fix for browsers (e.g. IE7) firing the load event for // cached images before the element could // be added to the DOM: return that.setTimeout(callbackWrapper, [event]) } called = true $(img).off('load error', callbackWrapper) callback(event) } } if (typeof url !== 'string') { url = this.getItemProperty(obj, options.urlProperty) sources = this.support.picture && this.support.source && this.getItemProperty(obj, options.sourcesProperty) srcset = this.getItemProperty(obj, options.srcsetProperty) sizes = this.getItemProperty(obj, options.sizesProperty) title = this.getItemProperty(obj, options.titleProperty) altText = this.getItemProperty(obj, options.altTextProperty) || title } img.draggable = false if (title) { img.title = title } if (altText) { img.alt = altText } $(img).on('load error', callbackWrapper) if (sources && sources.length) { picture = this.picturePrototype.cloneNode(false) for (i = 0; i < sources.length; i += 1) { picture.appendChild( $.extend(this.sourcePrototype.cloneNode(false), sources[i]) ) } picture.appendChild(img) $(picture).addClass(options.toggleClass) } if (srcset) { if (sizes) { img.sizes = sizes } img.srcset = srcset } img.src = url if (picture) return picture return img }, createElement: function (obj, callback) { var type = obj && this.getItemProperty(obj, this.options.typeProperty) var factory = (type && this[type.split('/')[0] + 'Factory']) || this.imageFactory var element = obj && factory.call(this, obj, callback) if (!element) { element = this.elementPrototype.cloneNode(false) this.setTimeout(callback, [ { type: 'error', target: element } ]) } $(element).addClass(this.options.slideContentClass) return element }, iteratePreloadRange: function (index, func) { var num = this.num var options = this.options var limit = Math.min(num, options.preloadRange * 2 + 1) var j = index var i for (i = 0; i < limit; i += 1) { // First iterate to the current index (0), // then the next one (+1), // then the previous one (-1), // then the next after next (+2), // then the one before the previous one (-2), etc.: j += i * (i % 2 === 0 ? -1 : 1) if (j < 0 || j >= num) { if (!options.continuous) continue // Connect the ends of the list to load slide elements for // continuous iteration: j = this.circle(j) } func.call(this, j) } }, loadElement: function (index) { if (!this.elements[index]) { if (this.slides[index].firstChild) { this.elements[index] = $(this.slides[index]).hasClass( this.options.slideErrorClass ) ? 3 : 2 } else { this.elements[index] = 1 // Loading $(this.slides[index]).addClass(this.options.slideLoadingClass) this.slides[index].appendChild( this.createElement(this.list[index], this.proxyListener) ) } } }, loadElements: function (index) { this.iteratePreloadRange(index, this.loadElement) }, unloadElements: function (oldIndex, newIndex) { var preloadRange = this.options.preloadRange this.iteratePreloadRange(oldIndex, function (i) { var diff = Math.abs(i - newIndex) if (diff > preloadRange && diff + preloadRange < this.num) { this.unloadSlide(i) delete this.elements[i] } }) }, addSlide: function (index) { var slide = this.slidePrototype.cloneNode(false) slide.setAttribute('data-index', index) slide.setAttribute('aria-hidden', 'true') this.slidesContainer[0].appendChild(slide) this.slides.push(slide) }, positionSlide: function (index) { var slide = this.slides[index] slide.style.width = this.slideWidth + 'px' if (this.support.transform) { slide.style.left = index * -this.slideWidth + 'px' this.move( index, this.index > index ? -this.slideWidth : this.index < index ? this.slideWidth : 0, 0 ) } }, initSlides: function (reload) { var clearSlides, i if (!reload) { this.positions = [] this.positions.length = this.num this.elements = {} this.picturePrototype = this.support.picture && document.createElement('picture') this.sourcePrototype = this.support.source && document.createElement('source') this.imagePrototype = document.createElement('img') this.elementPrototype = document.createElement('div') this.slidePrototype = this.elementPrototype.cloneNode(false) $(this.slidePrototype).addClass(this.options.slideClass) this.slides = this.slidesContainer[0].children clearSlides = this.options.clearSlides || this.slides.length !== this.num } this.slideWidth = this.container[0].clientWidth this.slideHeight = this.container[0].clientHeight this.slidesContainer[0].style.width = this.num * this.slideWidth + 'px' if (clearSlides) { this.resetSlides() } for (i = 0; i < this.num; i += 1) { if (clearSlides) { this.addSlide(i) } this.positionSlide(i) } // Reposition the slides before and after the given index: if (this.options.continuous && this.support.transform) { this.move(this.circle(this.index - 1), -this.slideWidth, 0) this.move(this.circle(this.index + 1), this.slideWidth, 0) } if (!this.support.transform) { this.slidesContainer[0].style.left = this.index * -this.slideWidth + 'px' } }, unloadSlide: function (index) { var slide, firstChild slide = this.slides[index] firstChild = slide.firstChild if (firstChild !== null) { slide.removeChild(firstChild) } }, unloadAllSlides: function () { var i, len for (i = 0, len = this.slides.length; i < len; i++) { this.unloadSlide(i) } }, toggleControls: function () { var controlsClass = this.options.controlsClass if (this.container.hasClass(controlsClass)) { this.container.removeClass(controlsClass) } else { this.container.addClass(controlsClass) } }, toggleSlideshow: function () { if (!this.interval) { this.play() } else { this.pause() } }, getNodeIndex: function (element) { return parseInt(element.getAttribute('data-index'), 10) }, getNestedProperty: function (obj, property) { property.replace( // Matches native JavaScript notation in a String, // e.g. '["doubleQuoteProp"].dotProp[2]' // eslint-disable-next-line no-useless-escape /\[(?:'([^']+)'|"([^"]+)"|(\d+))\]|(?:(?:^|\.)([^\.\[]+))/g, function (str, singleQuoteProp, doubleQuoteProp, arrayIndex, dotProp) { var prop = dotProp || singleQuoteProp || doubleQuoteProp || (arrayIndex && parseInt(arrayIndex, 10)) if (str && obj) { obj = obj[prop] } } ) return obj }, getDataProperty: function (obj, property) { var key var prop if (obj.dataset) { key = property.replace(/-([a-z])/g, function (_, b) { return b.toUpperCase() }) prop = obj.dataset[key] } else if (obj.getAttribute) { prop = obj.getAttribute( 'data-' + property.replace(/([A-Z])/g, '-$1').toLowerCase() ) } if (typeof prop === 'string') { // eslint-disable-next-line no-useless-escape if ( /^(true|false|null|-?\d+(\.\d+)?|\{[\s\S]*\}|\[[\s\S]*\])$/.test(prop) ) { try { return $.parseJSON(prop) } catch (ignore) { // ignore JSON parsing errors } } return prop } }, getItemProperty: function (obj, property) { var prop = this.getDataProperty(obj, property) if (prop === undefined) { prop = obj[property] } if (prop === undefined) { prop = this.getNestedProperty(obj, property) } return prop }, initStartIndex: function () { var index = this.options.index var urlProperty = this.options.urlProperty var i // Check if the index is given as a list object: if (index && typeof index !== 'number') { for (i = 0; i < this.num; i += 1) { if ( this.list[i] === index || this.getItemProperty(this.list[i], urlProperty) === this.getItemProperty(index, urlProperty) ) { index = i break } } } // Make sure the index is in the list range: this.index = this.circle(parseInt(index, 10) || 0) }, initEventListeners: function () { var that = this var slidesContainer = this.slidesContainer /** * Proxy listener * * @param {event} event original event */ function proxyListener(event) { var type = that.support.transition && that.support.transition.end === event.type ? 'transitionend' : event.type that['on' + type](event) } $(window).on('resize', proxyListener) $(window).on('hashchange', proxyListener) $(document.body).on('keydown', proxyListener) this.container.on('click', proxyListener) if (this.support.touch) { slidesContainer.on( 'touchstart touchmove touchend touchcancel', proxyListener ) } else if (this.options.emulateTouchEvents && this.support.transition) { slidesContainer.on( 'mousedown mousemove mouseup mouseout', proxyListener ) } if (this.support.transition) { slidesContainer.on(this.support.transition.end, proxyListener) } this.proxyListener = proxyListener }, destroyEventListeners: function () { var slidesContainer = this.slidesContainer var proxyListener = this.proxyListener $(window).off('resize', proxyListener) $(document.body).off('keydown', proxyListener) this.container.off('click', proxyListener) if (this.support.touch) { slidesContainer.off( 'touchstart touchmove touchend touchcancel', proxyListener ) } else if (this.options.emulateTouchEvents && this.support.transition) { slidesContainer.off( 'mousedown mousemove mouseup mouseout', proxyListener ) } if (this.support.transition) { slidesContainer.off(this.support.transition.end, proxyListener) } }, handleOpen: function () { if (this.options.onopened) { this.options.onopened.call(this) } }, initWidget: function () { var that = this /** * Open handler * * @param {event} event Gallery open event */ function openHandler(event) { if (event.target === that.container[0]) { that.container.off(that.support.transition.end, openHandler) that.handleOpen() } } this.container = $(this.options.container) if (!this.container.length) { this.console.log( 'blueimp Gallery: Widget container not found.', this.options.container ) return false } this.slidesContainer = this.container .find(this.options.slidesContainer) .first() if (!this.slidesContainer.length) { this.console.log( 'blueimp Gallery: Slides container not found.', this.options.slidesContainer ) return false } this.titleElement = this.container.find(this.options.titleElement).first() this.playPauseElement = this.container .find('.' + this.options.playPauseClass) .first() if (this.num === 1) { this.container.addClass(this.options.singleClass) } if (this.support.svgasimg) { this.container.addClass(this.options.svgasimgClass) } if (this.support.smil) { this.container.addClass(this.options.smilClass) } if (this.options.onopen) { this.options.onopen.call(this) } if (this.support.transition && this.options.displayTransition) { this.container.on(this.support.transition.end, openHandler) } else { this.handleOpen() } if (this.options.hidePageScrollbars) { // Hide the page scrollbars: this.bodyOverflowStyle = document.body.style.overflow document.body.style.overflow = 'hidden' } this.container[0].style.display = 'block' this.initSlides() this.container.addClass(this.options.displayClass) }, initOptions: function (options) { // Create a copy of the prototype options: this.options = $.extend({}, this.options) // Check if carousel mode is enabled: if ( (options && options.carousel) || (this.options.carousel && (!options || options.carousel !== false)) ) { $.extend(this.options, this.carouselOptions) } // Override any given options: $.extend(this.options, options) if (this.num < 3) { // 1 or 2 slides cannot be displayed continuous, // remember the original option by setting to null instead of false: this.options.continuous = this.options.continuous ? null : false } if (!this.support.transition) { this.options.emulateTouchEvents = false } if (this.options.event) { this.preventDefault(this.options.event) } } }) return Gallery })
/** * 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. */ import SyntheticMouseEvent from './SyntheticMouseEvent'; /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ const SyntheticWheelEvent = SyntheticMouseEvent.extend({ deltaX(event) { return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; }, deltaY(event) { return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -event.wheelDelta : 0; }, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: null, }); export default SyntheticWheelEvent;
version https://git-lfs.github.com/spec/v1 oid sha256:a92e0a42b6e55c21f7494e8604852635b90e81170e9f49207a0a68c2174158ee size 877
define({ root: //begin v1.x content { "days-standAlone-short": [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "months-format-narrow": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ], "quarters-standAlone-narrow": [ "1", "2", "3", "4" ], "field-weekday": "Day of the Week", "dateFormatItem-GyMMMEd": "G y MMM d, E", "dateFormatItem-MMMEd": "MMM d, E", "eraNarrow": [ "BE" ], "days-format-short": [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "dateTimeFormats-appendItem-Day-Of-Week": "{0} {1}", "dateFormat-long": "G y MMMM d", "months-format-wide": [ "Month1", "Month2", "Month3", "Month4", "Month5", "Month6", "Month7", "Month8", "Month9", "Month10", "Month11", "Month12" ], "dateFormatItem-yyyyQQQ": "G y QQQ", "dateTimeFormat-medium": "{1} {0}", "dayPeriods-format-wide-pm": "PM", "dateFormat-full": "G y MMMM d, EEEE", "dateFormatItem-yyyyMEd": "GGGGG y-MM-dd, E", "dateFormatItem-Md": "MM-dd", "dayPeriods-format-abbr-am": "AM", "dateTimeFormats-appendItem-Second": "{0} ({2}: {1})", "field-era": "Era", "months-standAlone-wide": [ "Month1", "Month2", "Month3", "Month4", "Month5", "Month6", "Month7", "Month8", "Month9", "Month10", "Month11", "Month12" ], "timeFormat-short": "HH:mm", "quarters-format-wide": [ "Q1", "Q2", "Q3", "Q4" ], "timeFormat-long": "HH:mm:ss z", "field-year": "Year", "dateTimeFormats-appendItem-Era": "{1} {0}", "field-hour": "Hour", "months-format-abbr": [ "Month1", "Month2", "Month3", "Month4", "Month5", "Month6", "Month7", "Month8", "Month9", "Month10", "Month11", "Month12" ], "timeFormat-full": "HH:mm:ss zzzz", "dateTimeFormats-appendItem-Week": "{0} ({2}: {1})", "field-day-relative+0": "Today", "field-day-relative+1": "Tomorrow", "dateFormatItem-GyMMMd": "G y MMM d", "dateFormatItem-H": "HH", "months-standAlone-abbr": [ "Month1", "Month2", "Month3", "Month4", "Month5", "Month6", "Month7", "Month8", "Month9", "Month10", "Month11", "Month12" ], "quarters-format-abbr": [ "Q1", "Q2", "Q3", "Q4" ], "quarters-standAlone-wide": [ "Q1", "Q2", "Q3", "Q4" ], "dateFormatItem-Gy": "G y", "dateFormatItem-yyyyMMMEd": "G y MMM d, E", "dateFormatItem-M": "L", "days-standAlone-wide": [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "dateFormatItem-yyyyMMM": "G y MMM", "dateFormatItem-yyyyMMMd": "G y MMM d", "timeFormat-medium": "HH:mm:ss", "dateFormatItem-Hm": "HH:mm", "quarters-standAlone-abbr": [ "Q1", "Q2", "Q3", "Q4" ], "eraAbbr": [ "BE" ], "field-minute": "Minute", "field-dayperiod": "Dayperiod", "days-standAlone-abbr": [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "dateFormatItem-d": "d", "dateFormatItem-ms": "mm:ss", "quarters-format-narrow": [ "1", "2", "3", "4" ], "field-day-relative+-1": "Yesterday", "dateFormatItem-h": "h a", "dateTimeFormat-long": "{1} {0}", "dayPeriods-format-narrow-am": "AM", "dateFormatItem-MMMd": "MMM d", "dateFormatItem-MEd": "MM-dd, E", "dateTimeFormat-full": "{1} {0}", "field-day": "Day", "days-format-wide": [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "field-zone": "Zone", "dateTimeFormats-appendItem-Day": "{0} ({2}: {1})", "dateFormatItem-y": "G y", "months-standAlone-narrow": [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" ], "dateFormatItem-hm": "h:mm a", "dateTimeFormats-appendItem-Year": "{1} {0}", "dateTimeFormats-appendItem-Hour": "{0} ({2}: {1})", "dayPeriods-format-abbr-pm": "PM", "days-format-abbr": [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "eraNames": [ "BE" ], "days-format-narrow": [ "S", "M", "T", "W", "T", "F", "S" ], "dateFormatItem-yyyyMd": "GGGGG y-MM-dd", "days-standAlone-narrow": [ "S", "M", "T", "W", "T", "F", "S" ], "dateFormatItem-MMM": "LLL", "field-month": "Month", "dateTimeFormats-appendItem-Quarter": "{0} ({2}: {1})", "dayPeriods-format-wide-am": "AM", "dateTimeFormats-appendItem-Month": "{0} ({2}: {1})", "dateTimeFormats-appendItem-Minute": "{0} ({2}: {1})", "dateFormat-short": "GGGGG y-MM-dd", "field-second": "Second", "dateFormatItem-Ed": "d, E", "dateTimeFormats-appendItem-Timezone": "{0} {1}", "field-week": "Week", "dateFormat-medium": "G y MMM d", "dateFormatItem-yyyyM": "GGGGG y-MM", "dayPeriods-format-narrow-pm": "PM", "dateFormatItem-yyyyQQQQ": "G y QQQQ", "dateTimeFormat-short": "{1} {0}", "dateFormatItem-Hms": "HH:mm:ss", "dateFormatItem-hms": "h:mm:ss a", "dateFormatItem-GyMMM": "G y MMM", "dateFormatItem-yyyy": "G y" } //end v1.x content , "ar": true, "ca": true, "cs": true, "da": true, "de": true, "el": true, "en": true, "es": true, "fi": true, "fr": true, "hu": true, "it": true, "ja": true, "ko": true, "nb": true, "nl": true, "pl": true, "pt": true, "pt-pt": true, "ro": true, "ru": true, "sv": true, "th": true, "tr": true, "zh": true, "zh-hant": true });
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var React=_interopRequireWildcard(require("react")),_createSvgIcon=_interopRequireDefault(require("../../utils/createSvgIcon")),_default=(0,_createSvgIcon.default)(React.createElement("path",{d:"M20,12A8,8 0 0,1 12,20A8,8 0 0,1 4,12A8,8 0 0,1 12,4C12.76,4 13.5,4.11 14.2, 4.31L15.77,2.74C14.61,2.26 13.34,2 12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0, 0 22,12M7.91,10.08L6.5,11.5L11,16L21,6L19.59,4.58L11,13.17L7.91,10.08Z"}),"SuccessOutlined");exports.default=_default;
var foo = createReactClass({}); var bar = React.createClass({});